8
8
using System . Text ;
9
9
using System . Text . Json ;
10
10
using System . Text . RegularExpressions ;
11
+ using System . Threading ;
11
12
using System . Threading . Tasks ;
12
13
using Microsoft . Extensions . Logging ;
13
14
using Microsoft . Extensions . Logging . Abstractions ;
@@ -89,23 +90,16 @@ public async Task<string> ExecuteCodeAsync([Description("The valid Python code t
89
90
this . _logger . LogTrace ( "Executing Python code: {Code}" , code ) ;
90
91
91
92
using var httpClient = this . _httpClientFactory . CreateClient ( ) ;
93
+ await this . AddHeadersAsync ( httpClient ) . ConfigureAwait ( false ) ;
92
94
93
95
var requestBody = new SessionsPythonCodeExecutionProperties ( this . _settings , code ) ;
94
96
95
- await this . AddHeadersAsync ( httpClient ) . ConfigureAwait ( false ) ;
96
-
97
97
using var request = new HttpRequestMessage ( HttpMethod . Post , $ "{ this . _poolManagementEndpoint } /executions?identifier={ this . _settings . SessionId } &api-version={ ApiVersion } ")
98
98
{
99
99
Content = new StringContent ( JsonSerializer . Serialize ( requestBody ) , Encoding . UTF8 , "application/json" )
100
100
} ;
101
101
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 ) ;
109
103
110
104
var responseContent = JsonSerializer . Deserialize < JsonElement > ( await response . Content . ReadAsStringAsync ( ) . ConfigureAwait ( false ) ) ;
111
105
@@ -123,16 +117,6 @@ public async Task<string> ExecuteCodeAsync([Description("The valid Python code t
123
117
""" ;
124
118
}
125
119
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
-
136
120
/// <summary>
137
121
/// Uploads a file to the `/mnt/data` directory of the current session.
138
122
/// </summary>
@@ -149,10 +133,9 @@ public async Task<SessionsRemoteFileMetadata> UploadFileAsync(
149
133
Verify . NotNullOrWhiteSpace ( remoteFileName , nameof ( remoteFileName ) ) ;
150
134
Verify . NotNullOrWhiteSpace ( localFilePath , nameof ( localFilePath ) ) ;
151
135
152
- this . _logger . LogInformation ( "Uploading file: {LocalFilePath} to {RemoteFilePath }" , localFilePath , remoteFileName ) ;
136
+ this . _logger . LogInformation ( "Uploading file: {LocalFilePath} to {RemoteFileName }" , localFilePath , remoteFileName ) ;
153
137
154
138
using var httpClient = this . _httpClientFactory . CreateClient ( ) ;
155
-
156
139
await this . AddHeadersAsync ( httpClient ) . ConfigureAwait ( false ) ;
157
140
158
141
using var fileContent = new ByteArrayContent ( File . ReadAllBytes ( localFilePath ) ) ;
@@ -164,13 +147,7 @@ public async Task<SessionsRemoteFileMetadata> UploadFileAsync(
164
147
}
165
148
} ;
166
149
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 ) ;
174
151
175
152
var stringContent = await response . Content . ReadAsStringAsync ( ) . ConfigureAwait ( false ) ;
176
153
@@ -190,17 +167,14 @@ public async Task<byte[]> DownloadFileAsync(
190
167
{
191
168
Verify . NotNullOrWhiteSpace ( remoteFileName , nameof ( remoteFileName ) ) ;
192
169
193
- this . _logger . LogTrace ( "Downloading file: {RemoteFilePath } to {LocalFilePath }" , remoteFileName , localFilePath ) ;
170
+ this . _logger . LogTrace ( "Downloading file: {RemoteFileName } to {LocalFileName }" , remoteFileName , localFilePath ) ;
194
171
195
172
using var httpClient = this . _httpClientFactory . CreateClient ( ) ;
196
173
await this . AddHeadersAsync ( httpClient ) . ConfigureAwait ( false ) ;
197
174
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 ) ;
204
178
205
179
var fileContent = await response . Content . ReadAsByteArrayAsync ( ) . ConfigureAwait ( false ) ;
206
180
@@ -231,12 +205,9 @@ public async Task<IReadOnlyList<SessionsRemoteFileMetadata>> ListFilesAsync()
231
205
using var httpClient = this . _httpClientFactory . CreateClient ( ) ;
232
206
await this . AddHeadersAsync ( httpClient ) . ConfigureAwait ( false ) ;
233
207
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 } ") ;
235
209
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 ) ;
240
211
241
212
var jsonElementResult = JsonSerializer . Deserialize < JsonElement > ( await response . Content . ReadAsStringAsync ( ) . ConfigureAwait ( false ) ) ;
242
213
@@ -277,6 +248,20 @@ private static string SanitizeCodeInput(string code)
277
248
return code ;
278
249
}
279
250
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
+
280
265
#if NET
281
266
[ GeneratedRegex ( @"^(\s|`)*(?i:python)?\s*" , RegexOptions . ExplicitCapture ) ]
282
267
private static partial Regex RemoveLeadingWhitespaceBackticksPython ( ) ;
0 commit comments