@@ -26,21 +26,21 @@ public sealed partial class SessionsPythonPlugin
2626 private const string ApiVersion = "2024-10-02-preview" ;
2727 private readonly Uri _poolManagementEndpoint ;
2828 private readonly SessionsPythonSettings _settings ;
29- private readonly Func < Task < string > > ? _authTokenProvider ;
29+ private readonly Func < CancellationToken , Task < string > > ? _authTokenProvider ;
3030 private readonly IHttpClientFactory _httpClientFactory ;
3131 private readonly ILogger _logger ;
3232
3333 /// <summary>
3434 /// Initializes a new instance of the SessionsPythonTool class.
3535 /// </summary>
36- /// <param name="settings">The settings for the Python tool plugin. </param>
37- /// <param name="httpClientFactory">The HTTP client factory. </param>
38- /// <param name="authTokenProvider"> Optional provider for auth token generation. </param>
39- /// <param name="loggerFactory">The logger factory. </param>
36+ /// <param name="settings">The settings for the Python tool plugin.</param>
37+ /// <param name="httpClientFactory">The HTTP client factory.</param>
38+ /// <param name="authTokenProvider">Optional provider for auth token generation.</param>
39+ /// <param name="loggerFactory">The logger factory.</param>
4040 public SessionsPythonPlugin (
4141 SessionsPythonSettings settings ,
4242 IHttpClientFactory httpClientFactory ,
43- Func < Task < string > > ? authTokenProvider = null ,
43+ Func < CancellationToken , Task < string > > ? authTokenProvider = null ,
4444 ILoggerFactory ? loggerFactory = null )
4545 {
4646 Verify . NotNull ( settings , nameof ( settings ) ) ;
@@ -66,7 +66,8 @@ public SessionsPythonPlugin(
6666 /// Keep everything in a single line; the \n sequences will represent line breaks
6767 /// when the string is processed or displayed.
6868 /// </summary>
69- /// <param name="code"> The valid Python code to execute. </param>
69+ /// <param name="code"> The valid Python code to execute.</param>
70+ /// <param name="cancellationToken">The cancellation token.</param>
7071 /// <returns> The result of the Python code execution. </returns>
7172 /// <exception cref="ArgumentNullException"></exception>
7273 /// <exception cref="HttpRequestException"></exception>
@@ -79,7 +80,9 @@ Add spaces directly after \n sequences to replicate indentation.
7980 Keep everything in a single line; the \n sequences will represent line breaks
8081 when the string is processed or displayed.
8182 """ ) ]
82- public async Task < string > ExecuteCodeAsync ( [ Description ( "The valid Python code to execute." ) ] string code )
83+ public async Task < string > ExecuteCodeAsync (
84+ [ Description ( "The valid Python code to execute." ) ] string code ,
85+ CancellationToken cancellationToken = default )
8386 {
8487 Verify . NotNullOrWhiteSpace ( code , nameof ( code ) ) ;
8588
@@ -91,15 +94,14 @@ public async Task<string> ExecuteCodeAsync([Description("The valid Python code t
9194 this . _logger . LogTrace ( "Executing Python code: {Code}" , code ) ;
9295
9396 using var httpClient = this . _httpClientFactory . CreateClient ( ) ;
94- await this . AddHeadersAsync ( httpClient ) . ConfigureAwait ( false ) ;
9597
9698 var requestBody = new SessionsPythonCodeExecutionProperties ( this . _settings , code ) ;
9799
98100 using var content = new StringContent ( JsonSerializer . Serialize ( requestBody ) , Encoding . UTF8 , "application/json" ) ;
99101
100- using var response = await this . SendAsync ( httpClient , HttpMethod . Post , "executions" , content ) . ConfigureAwait ( false ) ;
102+ using var response = await this . SendAsync ( httpClient , HttpMethod . Post , "executions" , cancellationToken , content ) . ConfigureAwait ( false ) ;
101103
102- var responseContent = JsonSerializer . Deserialize < JsonElement > ( await response . Content . ReadAsStringAsync ( ) . ConfigureAwait ( false ) ) ;
104+ var responseContent = JsonSerializer . Deserialize < JsonElement > ( await response . Content . ReadAsStringWithExceptionMappingAsync ( cancellationToken ) . ConfigureAwait ( false ) ) ;
103105
104106 var result = responseContent . GetProperty ( "result" ) ;
105107
@@ -120,21 +122,22 @@ public async Task<string> ExecuteCodeAsync([Description("The valid Python code t
120122 /// </summary>
121123 /// <param name="remoteFileName">The name of the remote file, relative to `/mnt/data`.</param>
122124 /// <param name="localFilePath">The path to the file on the local machine.</param>
125+ /// <param name="cancellationToken">The cancellation token.</param>
123126 /// <returns>The metadata of the uploaded file.</returns>
124127 /// <exception cref="ArgumentNullException"></exception>
125128 /// <exception cref="HttpRequestException"></exception>
126129 [ KernelFunction , Description ( "Uploads a file to the `/mnt/data` directory of the current session." ) ]
127130 public async Task < SessionsRemoteFileMetadata > UploadFileAsync (
128131 [ Description ( "The name of the remote file, relative to `/mnt/data`." ) ] string remoteFileName ,
129- [ Description ( "The path to the file on the local machine." ) ] string localFilePath )
132+ [ Description ( "The path to the file on the local machine." ) ] string localFilePath ,
133+ CancellationToken cancellationToken = default )
130134 {
131135 Verify . NotNullOrWhiteSpace ( remoteFileName , nameof ( remoteFileName ) ) ;
132136 Verify . NotNullOrWhiteSpace ( localFilePath , nameof ( localFilePath ) ) ;
133137
134138 this . _logger . LogInformation ( "Uploading file: {LocalFilePath} to {RemoteFileName}" , localFilePath , remoteFileName ) ;
135139
136140 using var httpClient = this . _httpClientFactory . CreateClient ( ) ;
137- await this . AddHeadersAsync ( httpClient ) . ConfigureAwait ( false ) ;
138141
139142 using var fileContent = new ByteArrayContent ( File . ReadAllBytes ( localFilePath ) ) ;
140143
@@ -143,9 +146,9 @@ public async Task<SessionsRemoteFileMetadata> UploadFileAsync(
143146 { fileContent , "file" , remoteFileName } ,
144147 } ;
145148
146- using var response = await this . SendAsync ( httpClient , HttpMethod . Post , "files" , multipartFormDataContent ) . ConfigureAwait ( false ) ;
149+ using var response = await this . SendAsync ( httpClient , HttpMethod . Post , "files" , cancellationToken , multipartFormDataContent ) . ConfigureAwait ( false ) ;
147150
148- var stringContent = await response . Content . ReadAsStringAsync ( ) . ConfigureAwait ( false ) ;
151+ var stringContent = await response . Content . ReadAsStringWithExceptionMappingAsync ( cancellationToken ) . ConfigureAwait ( false ) ;
149152
150153 return JsonSerializer . Deserialize < SessionsRemoteFileMetadata > ( stringContent ) ! ;
151154 }
@@ -155,22 +158,23 @@ public async Task<SessionsRemoteFileMetadata> UploadFileAsync(
155158 /// </summary>
156159 /// <param name="remoteFileName">The name of the remote file to download, relative to `/mnt/data`.</param>
157160 /// <param name="localFilePath">The path to save the downloaded file to. If not provided won't save it in the disk.</param>
161+ /// <param name="cancellationToken">The cancellation token.</param>
158162 /// <returns>The data of the downloaded file as byte array.</returns>
159163 [ KernelFunction , Description ( "Downloads a file from the `/mnt/data` directory of the current session." ) ]
160164 public async Task < byte [ ] > DownloadFileAsync (
161165 [ Description ( "The name of the remote file to download, relative to `/mnt/data`." ) ] string remoteFileName ,
162- [ Description ( "The path to save the downloaded file to. If not provided won't save it in the disk." ) ] string ? localFilePath = null )
166+ [ Description ( "The path to save the downloaded file to. If not provided won't save it in the disk." ) ] string ? localFilePath = null ,
167+ CancellationToken cancellationToken = default )
163168 {
164169 Verify . NotNullOrWhiteSpace ( remoteFileName , nameof ( remoteFileName ) ) ;
165170
166171 this . _logger . LogTrace ( "Downloading file: {RemoteFileName} to {LocalFileName}" , remoteFileName , localFilePath ) ;
167172
168173 using var httpClient = this . _httpClientFactory . CreateClient ( ) ;
169- await this . AddHeadersAsync ( httpClient ) . ConfigureAwait ( false ) ;
170174
171- using var response = await this . SendAsync ( httpClient , HttpMethod . Get , $ "files/{ Uri . EscapeDataString ( remoteFileName ) } /content") . ConfigureAwait ( false ) ;
175+ using var response = await this . SendAsync ( httpClient , HttpMethod . Get , $ "files/{ Uri . EscapeDataString ( remoteFileName ) } /content", cancellationToken ) . ConfigureAwait ( false ) ;
172176
173- var fileContent = await response . Content . ReadAsByteArrayAsync ( ) . ConfigureAwait ( false ) ;
177+ var fileContent = await response . Content . ReadAsByteArrayAndTranslateExceptionAsync ( cancellationToken ) . ConfigureAwait ( false ) ;
174178
175179 if ( ! string . IsNullOrWhiteSpace ( localFilePath ) )
176180 {
@@ -190,18 +194,18 @@ public async Task<byte[]> DownloadFileAsync(
190194 /// <summary>
191195 /// Lists all entities: files or directories in the `/mnt/data` directory of the current session.
192196 /// </summary>
197+ /// <param name="cancellationToken">The cancellation token.</param>
193198 /// <returns>The list of files in the session.</returns>
194199 [ KernelFunction , Description ( "Lists all entities: files or directories in the `/mnt/data` directory of the current session." ) ]
195- public async Task < IReadOnlyList < SessionsRemoteFileMetadata > > ListFilesAsync ( )
200+ public async Task < IReadOnlyList < SessionsRemoteFileMetadata > > ListFilesAsync ( CancellationToken cancellationToken = default )
196201 {
197202 this . _logger . LogTrace ( "Listing files for Session ID: {SessionId}" , this . _settings . SessionId ) ;
198203
199204 using var httpClient = this . _httpClientFactory . CreateClient ( ) ;
200- await this . AddHeadersAsync ( httpClient ) . ConfigureAwait ( false ) ;
201205
202- using var response = await this . SendAsync ( httpClient , HttpMethod . Get , "files" ) . ConfigureAwait ( false ) ;
206+ using var response = await this . SendAsync ( httpClient , HttpMethod . Get , "files" , cancellationToken ) . ConfigureAwait ( false ) ;
203207
204- var jsonElementResult = JsonSerializer . Deserialize < JsonElement > ( await response . Content . ReadAsStringAsync ( ) . ConfigureAwait ( false ) ) ;
208+ var jsonElementResult = JsonSerializer . Deserialize < JsonElement > ( await response . Content . ReadAsStringWithExceptionMappingAsync ( cancellationToken ) . ConfigureAwait ( false ) ) ;
205209
206210 var files = jsonElementResult . GetProperty ( "value" ) ;
207211
@@ -241,16 +245,17 @@ private static string SanitizeCodeInput(string code)
241245 }
242246
243247 /// <summary>
244- /// Add headers to the HTTP client .
248+ /// Add headers to the HTTP request .
245249 /// </summary>
246- /// <param name="httpClient">The HTTP client to add headers to.</param>
247- private async Task AddHeadersAsync ( HttpClient httpClient )
250+ /// <param name="request">The HTTP request to add headers to.</param>
251+ /// <param name="cancellationToken">The cancellation token.</param>
252+ private async Task AddHeadersAsync ( HttpRequestMessage request , CancellationToken cancellationToken )
248253 {
249- httpClient . DefaultRequestHeaders . Add ( "User-Agent" , $ "{ HttpHeaderConstant . Values . UserAgent } /{ s_assemblyVersion } (Language=dotnet)") ;
254+ request . Headers . Add ( "User-Agent" , $ "{ HttpHeaderConstant . Values . UserAgent } /{ s_assemblyVersion } (Language=dotnet)") ;
250255
251256 if ( this . _authTokenProvider is not null )
252257 {
253- httpClient . DefaultRequestHeaders . Add ( "Authorization" , $ "Bearer { ( await this . _authTokenProvider ( ) . ConfigureAwait ( false ) ) } ") ;
258+ request . Headers . Add ( "Authorization" , $ "Bearer { ( await this . _authTokenProvider ( cancellationToken ) . ConfigureAwait ( false ) ) } ") ;
254259 }
255260 }
256261
@@ -260,9 +265,10 @@ private async Task AddHeadersAsync(HttpClient httpClient)
260265 /// <param name="httpClient">The HTTP client to use.</param>
261266 /// <param name="method">The HTTP method to use.</param>
262267 /// <param name="path">The path to send the request to.</param>
268+ /// <param name="cancellationToken">The cancellation token.</param>
263269 /// <param name="httpContent">The content to send with the request.</param>
264270 /// <returns>The HTTP response message.</returns>
265- private async Task < HttpResponseMessage > SendAsync ( HttpClient httpClient , HttpMethod method , string path , HttpContent ? httpContent = null )
271+ private async Task < HttpResponseMessage > SendAsync ( HttpClient httpClient , HttpMethod method , string path , CancellationToken cancellationToken , HttpContent ? httpContent = null )
266272 {
267273 // The query string is the same for all operations
268274 var pathWithQueryString = $ "{ path } ?identifier={ this . _settings . SessionId } &api-version={ ApiVersion } ";
@@ -281,7 +287,9 @@ private async Task<HttpResponseMessage> SendAsync(HttpClient httpClient, HttpMet
281287 Content = httpContent ,
282288 } ;
283289
284- return await httpClient . SendWithSuccessCheckAsync ( request , CancellationToken . None ) . ConfigureAwait ( false ) ;
290+ await this . AddHeadersAsync ( request , cancellationToken ) . ConfigureAwait ( false ) ;
291+
292+ return await httpClient . SendWithSuccessCheckAsync ( request , cancellationToken ) . ConfigureAwait ( false ) ;
285293 }
286294
287295#if NET
0 commit comments