Copilot commented on code in PR #3930:
URL: https://github.com/apache/thrift/pull/3930#discussion_r4099211363


##########
lib/netstd/Thrift/Transport/Client/THttpPerCallTransport.cs:
##########
@@ -0,0 +1,221 @@
+// Licensed to the Apache Software Foundation(ASF) under one
+// or more contributor license agreements.See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+// 
+//     http://www.apache.org/licenses/LICENSE-2.0
+// 
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+using System;
+using System.IO;
+using System.Net.Http;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace Thrift.Transport.Client
+{
+    /// <summary>
+    /// Implementation of a per-call transport for THttpTransport.
+    /// Each call to the server will create a new HTTP request and response.
+    /// </summary>
+    internal class THttpPerCallTransport : TEndpointTransport
+    {
+        private readonly THttpTransport _parent;
+        private readonly MemoryStream _request = new MemoryStream();
+
+        private HttpResponseMessage _response;
+        private Stream _responseStream;
+        private CancellationTokenSource _responseReadTimeout;
+        private bool _sent;
+        private bool _disposed;
+
+        public THttpPerCallTransport(THttpTransport parent) : 
base(parent.Configuration)
+        {
+            this._parent = parent;
+        }
+
+        public override bool IsOpen => !_disposed;
+
+        public override Task WriteAsync(
+            byte[] buffer,
+            int offset,
+            int length,
+            CancellationToken cancellationToken)
+        {
+            if (_sent)
+            {
+                throw new InvalidOperationException("The request has already 
been sent.");
+            }
+
+            return _request.WriteAsync(
+                buffer,
+                offset,
+                length,
+                cancellationToken);
+        }
+
+        public override async Task FlushAsync(
+            CancellationToken cancellationToken)
+        {
+            if (_sent)
+            {
+                throw new InvalidOperationException("The request has already 
been sent.");
+            }
+
+            _request.Position = 0;
+            var response = await _parent.SendAsync(_request, 
cancellationToken);
+
+            var responseReadTimeout = 
CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
+            if (_parent.ConnectTimeout > 0)
+            {
+                responseReadTimeout.CancelAfter(_parent.ConnectTimeout);
+            }
+
+            Stream responseStream = null;
+            try
+            {
+responseStream = await THttpTransport.ReadAsStreamAsync(response.Content, 
responseReadTimeout.Token);
+                if (responseStream.CanSeek)
+                {
+                    responseStream.Seek(0, SeekOrigin.Begin);
+                }
+
+                // Only take ownership of the new response/timeout/stream once 
stream acquisition
+                // and normalization have succeeded, so a failed FlushAsync 
leaves no dangling
+                // resources behind and a subsequent retry does not leak the 
previous response.
+                lock (_parent.LifecycleLock)
+                {
+                    if (_disposed || !_parent.IsLifecycleOpen)
+                    {
+                        throw new 
TTransportException(TTransportException.ExceptionType.NotOpen,
+                            "The transport has been closed.");
+                    }
+
+                    _response?.Dispose();
+                    _response = response;
+                    response = null;
+                    _responseReadTimeout?.Dispose();
+                    _responseReadTimeout = responseReadTimeout;
+                    responseReadTimeout = null;
+                    _responseStream = responseStream;
+                    responseStream = null;
+                    _sent = true;
+                }
+            }
+            catch (TTransportException)
+            {
+                throw;
+            }
+            catch (IOException iox)
+            {
+                throw new 
TTransportException(TTransportException.ExceptionType.Unknown, iox.ToString(), 
iox);
+            }
+            catch (HttpRequestException wx)
+            {
+                throw new 
TTransportException(TTransportException.ExceptionType.Unknown,
+                    "Couldn't connect to server: " + wx, wx);
+            }
+            catch (OperationCanceledException ocx)
+            {
+                throw new 
TTransportException(TTransportException.ExceptionType.Interrupted, ocx.Message, 
ocx);
+            }
+            catch (Exception ex)
+            {
+                throw new 
TTransportException(TTransportException.ExceptionType.Unknown, ex.Message, ex);
+            }
+            finally
+            {
+                responseStream?.Dispose();
+                response?.Dispose();
+                responseReadTimeout?.Dispose();
+            }
+        }
+
+        public override async ValueTask<int> ReadAsync(
+            byte[] buffer,
+            int offset,
+            int length,
+            CancellationToken cancellationToken)
+        {
+            if (!_sent)
+            {
+                throw new TTransportException( 
TTransportException.ExceptionType.NotOpen, "The request has not been sent.");
+            }
+
+            CheckReadBytesAvailable(length);
+
+            CancellationTokenSource readCts = null;
+            if (_responseReadTimeout != null)
+            {
+                readCts = 
CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, 
_responseReadTimeout.Token);
+            }

Review Comment:
   The per-call read races with `Dispose()`: the disposer disposes and nulls 
`_responseReadTimeout` under `_parent.LifecycleLock`, while this code reads the 
field and then accesses `.Token` without the lock. Closing a parent during an 
active response read can consequently surface an unwrapped 
`ObjectDisposedException` instead of a `TTransportException`. Capture the 
token/lifecycle state under the lock and handle the concurrently disposed 
response stream consistently.



##########
lib/netstd/Thrift/Transport/Client/THttpTransport.cs:
##########
@@ -151,12 +160,20 @@ public override async ValueTask<int> ReadAsync(byte[] 
buffer, int offset, int le
 
             CheckReadBytesAvailable(length);
 
+            CancellationTokenSource readCts = null;
             try
             {
+                if (_responseReadTimeout != null)
+                {
+                    readCts = 
CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, 
_responseReadTimeout.Token);
+                }

Review Comment:
   `Close()` disposes and clears `_responseReadTimeout` while holding 
`_lifecycleLock`, but this read obtains the field and its `Token` without that 
lock. A concurrent close can therefore make this access throw 
`ObjectDisposedException` (or leave the read using a disposed input stream), 
escaping the transport-exception handling. Snapshot the cancellation 
token/lifecycle state under the lock and translate a concurrent close into the 
documented `NotOpen`/`Interrupted` transport error.



##########
lib/netstd/Thrift/Transport/Client/THttpTransport.cs:
##########
@@ -237,28 +262,76 @@ private void ConfigureClient(HttpClient httpClient)
 
         public override async Task FlushAsync(CancellationToken 
cancellationToken)
         {
+            HttpClient httpClient;
+            lock (_lifecycleLock)
+            {
+                if (!_lifecycleOpen || _httpClient == null)
+                {
+                    throw new 
TTransportException(TTransportException.ExceptionType.NotOpen,
+                        "The transport has been closed.");
+                }
+                httpClient = _httpClient;
+            }
+
+            StreamContent contentStream = null;
+            HttpRequestMessage request = null;
+            HttpResponseMessage response = null;
+            CancellationTokenSource responseReadTimeout = null;
             try
             {
                 _outputStream.Seek(0, SeekOrigin.Begin);
 
-                using (var contentStream = new StreamContent(_outputStream))
+                contentStream = new StreamContent(_outputStream);
+                contentStream.Headers.ContentType = ContentType ?? new 
MediaTypeHeaderValue(@"application/x-thrift");
+
+                request = new HttpRequestMessage(HttpMethod.Post, _uri)
                 {
-                    contentStream.Headers.ContentType = ContentType ?? new 
MediaTypeHeaderValue(@"application/x-thrift");
+                    Content = contentStream
+                };
 
-                    var response = (await _httpClient.PostAsync(_uri, 
contentStream, cancellationToken)).EnsureSuccessStatusCode();
+                response = await httpClient.SendAsync(
+                    request,
+                    HttpCompletionOption.ResponseHeadersRead,
+                    cancellationToken);
+                response.EnsureSuccessStatusCode();
 
-                    _inputStream?.Dispose();
-#if NET5_0_OR_GREATER
-                    _inputStream = await 
response.Content.ReadAsStreamAsync(cancellationToken);
-#else
-                    _inputStream = await response.Content.ReadAsStreamAsync();
-#endif
-                    if (_inputStream.CanSeek)
+                responseReadTimeout = 
CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
+                if (_connectTimeout > 0)
+                {
+                    responseReadTimeout.CancelAfter(_connectTimeout);
+                }
+
+                Stream inputStream;
+inputStream = await ReadAsStreamAsync(response.Content, 
responseReadTimeout.Token);
+                if (inputStream.CanSeek)
+                {
+                    inputStream.Seek(0, SeekOrigin.Begin);
+                }
+
+                // Only take ownership of the new response/timeout/stream once 
stream acquisition
+                // has succeeded, so a failed FlushAsync leaves no dangling 
resources behind.
+                lock (_lifecycleLock)
+                {
+                    if (!_lifecycleOpen || !ReferenceEquals(_httpClient, 
httpClient))
                     {
-                        _inputStream.Seek(0, SeekOrigin.Begin);
+                        throw new 
TTransportException(TTransportException.ExceptionType.NotOpen,
+                            "The transport has been closed.");
                     }

Review Comment:
   The lifecycle check here does not protect the output stream used earlier in 
`FlushAsync`: `Close()` can run after the client snapshot, dispose and set 
`_outputStream` to null, and then this call reaches `Seek`/`SendAsync` with a 
null or disposed stream. The `finally` block subsequently replaces 
`_outputStream` with a fresh stream even though the transport is closed, so a 
close racing an in-flight flush can surface 
`NullReferenceException`/`ObjectDisposedException` and resurrect state. 
Coordinate the output-stream ownership with the lifecycle lock and avoid 
publishing a new stream after closure.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to