Skip to content

Commit

Permalink
Don't dispose stream too early. (#5097) (#5100)
Browse files Browse the repository at this point in the history
In my previous pr #5035 I tried to optimize disposing of UDS. That fix was incorrect, since we rely on the fact that Stream is still open when we return `HttpResponseMessage` from `SendAsync`. Later, the consumer of `SendAsync` will dispose the `HttpResponseMessage` and it will in turn dispose the `Stream` and `Socket`.
  • Loading branch information
vadim-kovalyov authored Jun 10, 2021
1 parent c6b46f3 commit f9cdb59
Showing 1 changed file with 20 additions and 20 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,30 +21,30 @@ public HttpUdsMessageHandler(Uri providerUri)
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var endpoint = new UnixDomainSocketEndPoint(this.providerUri.LocalPath);
using (Socket socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
{
Events.Connecting(this.providerUri.LocalPath);
await socket.ConnectAsync(endpoint);
Events.Connected(this.providerUri.LocalPath);

using (var stream = new HttpBufferedStream(new NetworkStream(socket, true)))
{
var serializer = new HttpRequestResponseSerializer();
byte[] requestBytes = serializer.SerializeRequest(request);

Events.SendRequest(request.RequestUri);
await stream.WriteAsync(requestBytes, 0, requestBytes.Length, cancellationToken);
if (request.Content != null)
{
await request.Content.CopyToAsync(stream);
}
Events.Connecting(this.providerUri.LocalPath);
// do not dispose `Socket` or `HttpBufferedStream` here, b/c it will be used later
// by the consumer of HttpResponseMessage (HttpResponseMessage.Content.ReadAsStringAsync()).
// When HttpResponseMessage is disposed - the stream and socket is disposed as well.
Socket socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
await socket.ConnectAsync(endpoint);
Events.Connected(this.providerUri.LocalPath);

HttpResponseMessage response = await serializer.DeserializeResponse(stream, cancellationToken);
Events.ResponseReceived(response.StatusCode);
var stream = new HttpBufferedStream(new NetworkStream(socket, true));
var serializer = new HttpRequestResponseSerializer();
byte[] requestBytes = serializer.SerializeRequest(request);

return response;
}
Events.SendRequest(request.RequestUri);
await stream.WriteAsync(requestBytes, 0, requestBytes.Length, cancellationToken);
if (request.Content != null)
{
await request.Content.CopyToAsync(stream);
}

HttpResponseMessage response = await serializer.DeserializeResponse(stream, cancellationToken);
Events.ResponseReceived(response.StatusCode);

return response;
}

static class Events
Expand Down

0 comments on commit f9cdb59

Please sign in to comment.