Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
Expand All @@ -15,7 +19,7 @@ namespace Postgrest.Tests.Requests;
/// The HTTP transport a <see cref="Client" /> sends through: a caller-supplied <see cref="ClientOptions.HttpClient" />
/// is used verbatim instead of the client building its own — both for <see cref="Table{TModel}" /> requests and
/// for <see cref="Client.Rpc(string, object)" />, which routes through the client's own resolved transport
/// rather than a table.
/// rather than a table. The client built for a <see cref="ClientOptions.Proxy" /> is reused across tables.
/// </summary>
[TestClass]
[TestCategory("Contract")]
Expand Down Expand Up @@ -69,4 +73,47 @@ public async Task Rpc_ShouldSendThroughTheInjectedHttpClient_GivenClientOptions(
.Which.RequestMessage!.Headers!["X-Injected"][0].Should().Be("true",
"Rpc must route through the client's own resolved transport, not a separate default");
}

[TestMethod]
public async Task Get_ShouldReuseTheProxyConnection_GivenASecondTable()
{
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
var connections = 0;
_ = Task.Run(async () =>
{
while (true)
{
var connection = await listener.AcceptTcpClientAsync();
connections++;
_ = AnswerGetRequests(connection);
}
});
var proxy = new WebProxy($"http://127.0.0.1:{((IPEndPoint) listener.LocalEndpoint).Port}");
var client = new Client("http://postgrest.test", new ClientOptions { Proxy = proxy });

try
{
await client.Table<Todo>().Get();
await client.Table<Todo>().Get();

connections.Should().Be(1, "a new HttpClient per table opens a new connection each time (issue #450)");
}
finally
{
listener.Stop();
}
}

private static async Task AnswerGetRequests(TcpClient connection)
{
var stream = connection.GetStream();
using var reader = new StreamReader(stream);
while (await reader.ReadLineAsync() is { } line)
{
// A GET has no body, so the blank line ends the request.
if (line.Length == 0)
await stream.WriteAsync(Encoding.ASCII.GetBytes("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 2\r\n\r\n[]"));
}
}
}
12 changes: 9 additions & 3 deletions packages/Postgrest/Postgrest/Helpers.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Text;
Expand All @@ -26,15 +27,20 @@ internal static class Helpers
{
private static readonly HttpClient Client = new HttpClient();

// One client per proxy object. It is freed when the proxy is.
private static readonly ConditionalWeakTable<IWebProxy, HttpClient> ProxyClients = new();

private static readonly Guid AppSession = Guid.NewGuid();

/// <summary>
/// Resolves the client a request should be sent through, once per <see cref="Postgrest.Client"/>/<see cref="Table{TModel}"/>
/// construction: the caller-injected <see cref="ClientOptions.HttpClient"/>, else a proxy-configured client when
/// <see cref="ClientOptions.Proxy"/> is set, else null (callers fall back to the shared default <see cref="Client"/>).
/// construction: the caller-injected <see cref="ClientOptions.HttpClient"/>, else the client for
/// <see cref="ClientOptions.Proxy"/> when it is set, else null (callers fall back to the shared default <see cref="Client"/>).
/// </summary>
internal static HttpClient? ResolveHttpClient(ClientOptions options) =>
options.HttpClient ?? (options.Proxy != null ? DefaultHttpClientFactory.Create(proxy: options.Proxy) : null);
options.HttpClient ?? (options.Proxy != null
? ProxyClients.GetValue(options.Proxy, proxy => DefaultHttpClientFactory.Create(proxy: proxy))
: null);

/// <summary>
/// Mirrors Newtonsoft's <c>JToken.HasValues</c>: true only when the serialized payload is a non-empty
Expand Down
Loading