Skip to content

Commit 46e5744

Browse files
.Net: Use SendWithSuccessCheck extension methods (#11859)
### Motivation, Context and Description This PR refactors the `SessionsPythonPlugin` to use the `SendWithSuccessCheckAsync` extension methods to align the handling of HTTP requests with the other SK components. Additionally, it fixes minor logging-related issues and moves a private method down the plugin file for better readability. Contributes to: #10070
1 parent 5e6d6bb commit 46e5744

File tree

1 file changed

+25
-40
lines changed

1 file changed

+25
-40
lines changed

dotnet/src/Plugins/Plugins.Core/CodeInterpreter/SessionsPythonPlugin.cs

+25-40
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
using System.Text;
99
using System.Text.Json;
1010
using System.Text.RegularExpressions;
11+
using System.Threading;
1112
using System.Threading.Tasks;
1213
using Microsoft.Extensions.Logging;
1314
using Microsoft.Extensions.Logging.Abstractions;
@@ -89,23 +90,16 @@ public async Task<string> ExecuteCodeAsync([Description("The valid Python code t
8990
this._logger.LogTrace("Executing Python code: {Code}", code);
9091

9192
using var httpClient = this._httpClientFactory.CreateClient();
93+
await this.AddHeadersAsync(httpClient).ConfigureAwait(false);
9294

9395
var requestBody = new SessionsPythonCodeExecutionProperties(this._settings, code);
9496

95-
await this.AddHeadersAsync(httpClient).ConfigureAwait(false);
96-
9797
using var request = new HttpRequestMessage(HttpMethod.Post, $"{this._poolManagementEndpoint}/executions?identifier={this._settings.SessionId}&api-version={ApiVersion}")
9898
{
9999
Content = new StringContent(JsonSerializer.Serialize(requestBody), Encoding.UTF8, "application/json")
100100
};
101101

102-
var response = await httpClient.SendAsync(request).ConfigureAwait(false);
103-
104-
if (!response.IsSuccessStatusCode)
105-
{
106-
var errorBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
107-
throw new HttpRequestException($"Failed to execute python code. Status: {response.StatusCode}. Details: {errorBody}.");
108-
}
102+
using var response = await httpClient.SendWithSuccessCheckAsync(request, CancellationToken.None).ConfigureAwait(false);
109103

110104
var responseContent = JsonSerializer.Deserialize<JsonElement>(await response.Content.ReadAsStringAsync().ConfigureAwait(false));
111105

@@ -123,16 +117,6 @@ public async Task<string> ExecuteCodeAsync([Description("The valid Python code t
123117
""";
124118
}
125119

126-
private async Task AddHeadersAsync(HttpClient httpClient)
127-
{
128-
httpClient.DefaultRequestHeaders.Add("User-Agent", $"{HttpHeaderConstant.Values.UserAgent}/{s_assemblyVersion} (Language=dotnet)");
129-
130-
if (this._authTokenProvider is not null)
131-
{
132-
httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {(await this._authTokenProvider().ConfigureAwait(false))}");
133-
}
134-
}
135-
136120
/// <summary>
137121
/// Uploads a file to the `/mnt/data` directory of the current session.
138122
/// </summary>
@@ -149,10 +133,9 @@ public async Task<SessionsRemoteFileMetadata> UploadFileAsync(
149133
Verify.NotNullOrWhiteSpace(remoteFileName, nameof(remoteFileName));
150134
Verify.NotNullOrWhiteSpace(localFilePath, nameof(localFilePath));
151135

152-
this._logger.LogInformation("Uploading file: {LocalFilePath} to {RemoteFilePath}", localFilePath, remoteFileName);
136+
this._logger.LogInformation("Uploading file: {LocalFilePath} to {RemoteFileName}", localFilePath, remoteFileName);
153137

154138
using var httpClient = this._httpClientFactory.CreateClient();
155-
156139
await this.AddHeadersAsync(httpClient).ConfigureAwait(false);
157140

158141
using var fileContent = new ByteArrayContent(File.ReadAllBytes(localFilePath));
@@ -164,13 +147,7 @@ public async Task<SessionsRemoteFileMetadata> UploadFileAsync(
164147
}
165148
};
166149

167-
var response = await httpClient.SendAsync(request).ConfigureAwait(false);
168-
169-
if (!response.IsSuccessStatusCode)
170-
{
171-
var errorBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
172-
throw new HttpRequestException($"Failed to upload file. Status code: {response.StatusCode}. Details: {errorBody}.");
173-
}
150+
using var response = await httpClient.SendWithSuccessCheckAsync(request, CancellationToken.None).ConfigureAwait(false);
174151

175152
var stringContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
176153

@@ -190,17 +167,14 @@ public async Task<byte[]> DownloadFileAsync(
190167
{
191168
Verify.NotNullOrWhiteSpace(remoteFileName, nameof(remoteFileName));
192169

193-
this._logger.LogTrace("Downloading file: {RemoteFilePath} to {LocalFilePath}", remoteFileName, localFilePath);
170+
this._logger.LogTrace("Downloading file: {RemoteFileName} to {LocalFileName}", remoteFileName, localFilePath);
194171

195172
using var httpClient = this._httpClientFactory.CreateClient();
196173
await this.AddHeadersAsync(httpClient).ConfigureAwait(false);
197174

198-
var response = await httpClient.GetAsync(new Uri($"{this._poolManagementEndpoint}/files/{Uri.EscapeDataString(remoteFileName)}/content?identifier={this._settings.SessionId}&api-version={ApiVersion}")).ConfigureAwait(false);
199-
if (!response.IsSuccessStatusCode)
200-
{
201-
var errorBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
202-
throw new HttpRequestException($"Failed to download file. Status code: {response.StatusCode}. Details: {errorBody}.");
203-
}
175+
using var request = new HttpRequestMessage(HttpMethod.Get, $"{this._poolManagementEndpoint}/files/{Uri.EscapeDataString(remoteFileName)}/content?identifier={this._settings.SessionId}&api-version={ApiVersion}");
176+
177+
using var response = await httpClient.SendWithSuccessCheckAsync(request, CancellationToken.None).ConfigureAwait(false);
204178

205179
var fileContent = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
206180

@@ -231,12 +205,9 @@ public async Task<IReadOnlyList<SessionsRemoteFileMetadata>> ListFilesAsync()
231205
using var httpClient = this._httpClientFactory.CreateClient();
232206
await this.AddHeadersAsync(httpClient).ConfigureAwait(false);
233207

234-
var response = await httpClient.GetAsync(new Uri($"{this._poolManagementEndpoint}/files?identifier={this._settings.SessionId}&api-version={ApiVersion}")).ConfigureAwait(false);
208+
using var request = new HttpRequestMessage(HttpMethod.Get, $"{this._poolManagementEndpoint}/files?identifier={this._settings.SessionId}&api-version={ApiVersion}");
235209

236-
if (!response.IsSuccessStatusCode)
237-
{
238-
throw new HttpRequestException($"Failed to list files. Status code: {response.StatusCode}");
239-
}
210+
using var response = await httpClient.SendWithSuccessCheckAsync(request, CancellationToken.None).ConfigureAwait(false);
240211

241212
var jsonElementResult = JsonSerializer.Deserialize<JsonElement>(await response.Content.ReadAsStringAsync().ConfigureAwait(false));
242213

@@ -277,6 +248,20 @@ private static string SanitizeCodeInput(string code)
277248
return code;
278249
}
279250

251+
/// <summary>
252+
/// Add headers to the HTTP client.
253+
/// </summary>
254+
/// <param name="httpClient">The HTTP client to add headers to.</param>
255+
private async Task AddHeadersAsync(HttpClient httpClient)
256+
{
257+
httpClient.DefaultRequestHeaders.Add("User-Agent", $"{HttpHeaderConstant.Values.UserAgent}/{s_assemblyVersion} (Language=dotnet)");
258+
259+
if (this._authTokenProvider is not null)
260+
{
261+
httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {(await this._authTokenProvider().ConfigureAwait(false))}");
262+
}
263+
}
264+
280265
#if NET
281266
[GeneratedRegex(@"^(\s|`)*(?i:python)?\s*", RegexOptions.ExplicitCapture)]
282267
private static partial Regex RemoveLeadingWhitespaceBackticksPython();

0 commit comments

Comments
 (0)