|
| 1 | +using System.Runtime.CompilerServices; |
| 2 | +using System.Threading.Channels; |
| 3 | +using CosmoSQLClient.Core; |
| 4 | + |
| 5 | +namespace CosmoSQLClient.CosmoKvPipes; |
| 6 | + |
| 7 | +/// <summary> |
| 8 | +/// Connection pool for <see cref="CosmoKvPipesConnection"/>. Each pooled |
| 9 | +/// socket is independent — N concurrent SQL calls run over N sockets |
| 10 | +/// rather than queueing behind one in-process lock. This is the same |
| 11 | +/// shape <c>MsSqlConnectionPool</c> uses for its underlying connections. |
| 12 | +/// <para> |
| 13 | +/// Why: a single <c>CosmoKvPipesConnection</c> serialises every Query / |
| 14 | +/// Execute behind its <c>SemaphoreSlim(1, 1)</c> because the underlying |
| 15 | +/// socket is one bidirectional stream — interleaved frames from |
| 16 | +/// concurrent callers would corrupt the protocol. Without a pool, ALL |
| 17 | +/// SQL traffic on a mail-server process queues behind one connection, |
| 18 | +/// which marivil's binary-protocol stress run on 2026-05-21 surfaced |
| 19 | +/// as 493 <c>sp_Users_GetByEmail</c> 30 s-timeouts and IMAP throughput |
| 20 | +/// collapsing 87% vs the HTTP-over-UDS baseline. |
| 21 | +/// </para> |
| 22 | +/// <para> |
| 23 | +/// Implementation: <see cref="Channel{T}"/>-based idle queue + a count |
| 24 | +/// of "opened so far," same lazy-grow strategy <c>MsSqlConnectionPool</c> |
| 25 | +/// uses. Connections are created only when needed up to |
| 26 | +/// <see cref="MaxConnections"/>, then any caller arriving when the pool |
| 27 | +/// is saturated waits on the idle channel for a release. |
| 28 | +/// </para> |
| 29 | +/// </summary> |
| 30 | +public sealed class CosmoKvPipesConnectionPool : ISqlDatabase |
| 31 | +{ |
| 32 | + private readonly CosmoKvPipesConfiguration _config; |
| 33 | + private readonly Channel<CosmoKvPipesConnection> _idle; |
| 34 | + private int _opened; |
| 35 | + private bool _disposed; |
| 36 | + |
| 37 | + public int MaxConnections { get; } |
| 38 | + |
| 39 | + public bool IsOpen => !_disposed; |
| 40 | + |
| 41 | + public CosmoKvPipesConnectionPool(CosmoKvPipesConfiguration config, int maxConnections = 16) |
| 42 | + { |
| 43 | + _config = config; |
| 44 | + MaxConnections = Math.Max(1, maxConnections); |
| 45 | + _idle = Channel.CreateUnbounded<CosmoKvPipesConnection>( |
| 46 | + new UnboundedChannelOptions { SingleReader = false, SingleWriter = false }); |
| 47 | + } |
| 48 | + |
| 49 | + public CosmoKvPipesConnectionPool(string connectionString, int maxConnections = 16) |
| 50 | + : this(CosmoKvPipesConfiguration.Parse(connectionString), maxConnections) { } |
| 51 | + |
| 52 | + // ── ISqlDatabase delegation ───────────────────────────────────────────── |
| 53 | + |
| 54 | + public Task<IReadOnlyList<SqlRow>> QueryAsync( |
| 55 | + string sql, IReadOnlyList<SqlParameter>? parameters = null, CancellationToken ct = default) |
| 56 | + => WithConnAsync(c => c.QueryAsync(sql, parameters, ct), ct); |
| 57 | + |
| 58 | + public Task<IReadOnlyList<T>> QueryAsync<T>( |
| 59 | + string sql, IReadOnlyList<SqlParameter>? parameters = null, CancellationToken ct = default) |
| 60 | + where T : new() |
| 61 | + => WithConnAsync(c => c.QueryAsync<T>(sql, parameters, ct), ct); |
| 62 | + |
| 63 | + public Task<int> ExecuteAsync( |
| 64 | + string sql, IReadOnlyList<SqlParameter>? parameters = null, CancellationToken ct = default) |
| 65 | + => WithConnAsync(c => c.ExecuteAsync(sql, parameters, ct), ct); |
| 66 | + |
| 67 | + public Task<SqlDataTable> QueryTableAsync( |
| 68 | + string sql, IReadOnlyList<SqlParameter>? parameters = null, CancellationToken ct = default) |
| 69 | + => WithConnAsync(c => c.QueryTableAsync(sql, parameters, ct), ct); |
| 70 | + |
| 71 | + /// <summary> |
| 72 | + /// Streams query results. The lease is held for the FULL enumeration |
| 73 | + /// duration — closing the enumerator returns the connection. Don't |
| 74 | + /// hold the enumerator past your immediate consumption loop or you'll |
| 75 | + /// starve other callers of a slot. |
| 76 | + /// </summary> |
| 77 | + public async IAsyncEnumerable<SqlRow> QueryStreamAsync( |
| 78 | + string sql, IReadOnlyList<SqlParameter>? parameters = null, |
| 79 | + [EnumeratorCancellation] CancellationToken ct = default) |
| 80 | + { |
| 81 | + var conn = await AcquireAsync(ct).ConfigureAwait(false); |
| 82 | + try |
| 83 | + { |
| 84 | + await foreach (var row in conn.QueryStreamAsync(sql, parameters, ct).ConfigureAwait(false)) |
| 85 | + yield return row; |
| 86 | + } |
| 87 | + finally |
| 88 | + { |
| 89 | + await ReleaseAsync(conn).ConfigureAwait(false); |
| 90 | + } |
| 91 | + } |
| 92 | + |
| 93 | + public async IAsyncEnumerable<System.Text.Json.JsonElement> QueryJsonStreamAsync( |
| 94 | + string sql, IReadOnlyList<SqlParameter>? parameters = null, int jsonColumnIndex = 0, |
| 95 | + [EnumeratorCancellation] CancellationToken ct = default) |
| 96 | + { |
| 97 | + var conn = await AcquireAsync(ct).ConfigureAwait(false); |
| 98 | + try |
| 99 | + { |
| 100 | + await foreach (var elem in conn.QueryJsonStreamAsync(sql, parameters, jsonColumnIndex, ct).ConfigureAwait(false)) |
| 101 | + yield return elem; |
| 102 | + } |
| 103 | + finally |
| 104 | + { |
| 105 | + await ReleaseAsync(conn).ConfigureAwait(false); |
| 106 | + } |
| 107 | + } |
| 108 | + |
| 109 | + public Task BeginTransactionAsync(CancellationToken ct = default) |
| 110 | + => throw new NotSupportedException( |
| 111 | + "Explicit transactions are not supported on the CosmoKvPipes binary protocol. " + |
| 112 | + "Use CosmoSQLClient.CosmoKvHttp for BEGIN/COMMIT/ROLLBACK semantics."); |
| 113 | + |
| 114 | + public Task CommitAsync(CancellationToken ct = default) => BeginTransactionAsync(ct); |
| 115 | + public Task RollbackAsync(CancellationToken ct = default) => BeginTransactionAsync(ct); |
| 116 | + |
| 117 | + public async Task CloseAsync() |
| 118 | + { |
| 119 | + if (_disposed) return; |
| 120 | + _idle.Writer.TryComplete(); |
| 121 | + await foreach (var c in _idle.Reader.ReadAllAsync().ConfigureAwait(false)) |
| 122 | + { |
| 123 | + try { await c.DisposeAsync().ConfigureAwait(false); } catch { /* best-effort */ } |
| 124 | + } |
| 125 | + } |
| 126 | + |
| 127 | + public async ValueTask DisposeAsync() |
| 128 | + { |
| 129 | + if (_disposed) return; |
| 130 | + _disposed = true; |
| 131 | + await CloseAsync().ConfigureAwait(false); |
| 132 | + } |
| 133 | + |
| 134 | + // ── Pool internals ────────────────────────────────────────────────────── |
| 135 | + |
| 136 | + private async Task<T> WithConnAsync<T>(Func<CosmoKvPipesConnection, Task<T>> op, CancellationToken ct) |
| 137 | + { |
| 138 | + var conn = await AcquireAsync(ct).ConfigureAwait(false); |
| 139 | + try { return await op(conn).ConfigureAwait(false); } |
| 140 | + finally { await ReleaseAsync(conn).ConfigureAwait(false); } |
| 141 | + } |
| 142 | + |
| 143 | + private async Task<CosmoKvPipesConnection> AcquireAsync(CancellationToken ct) |
| 144 | + { |
| 145 | + if (_disposed) throw new ObjectDisposedException(nameof(CosmoKvPipesConnectionPool)); |
| 146 | + |
| 147 | + // Fast path: pick up an idle connection if there is one. |
| 148 | + if (_idle.Reader.TryRead(out var idle) && idle.IsOpen) |
| 149 | + return idle; |
| 150 | + |
| 151 | + // No idle. If we haven't grown to MaxConnections yet, lazily open |
| 152 | + // a new one. Increment-and-check-then-decrement-on-fail is the |
| 153 | + // racing-safe form (multiple acquirers may briefly observe the |
| 154 | + // count past max; the decrement on failure keeps the bookkeeping |
| 155 | + // consistent). |
| 156 | + int n = Interlocked.Increment(ref _opened); |
| 157 | + if (n <= MaxConnections) |
| 158 | + { |
| 159 | + try { return await CosmoKvPipesConnection.OpenAsync(_config, ct).ConfigureAwait(false); } |
| 160 | + catch { Interlocked.Decrement(ref _opened); throw; } |
| 161 | + } |
| 162 | + Interlocked.Decrement(ref _opened); |
| 163 | + |
| 164 | + // Pool is saturated — wait for a release on the idle channel. |
| 165 | + // Loop because a released-but-dead connection should be discarded |
| 166 | + // and the wait resumed. |
| 167 | + while (true) |
| 168 | + { |
| 169 | + var pooled = await _idle.Reader.ReadAsync(ct).ConfigureAwait(false); |
| 170 | + if (pooled.IsOpen) return pooled; |
| 171 | + await DiscardAsync(pooled).ConfigureAwait(false); |
| 172 | + } |
| 173 | + } |
| 174 | + |
| 175 | + private async ValueTask ReleaseAsync(CosmoKvPipesConnection conn) |
| 176 | + { |
| 177 | + if (!conn.IsOpen || _disposed) |
| 178 | + { |
| 179 | + await DiscardAsync(conn).ConfigureAwait(false); |
| 180 | + return; |
| 181 | + } |
| 182 | + if (!_idle.Writer.TryWrite(conn)) |
| 183 | + { |
| 184 | + // Channel was completed mid-release (Dispose racing with the |
| 185 | + // last call). Discard the connection to avoid leaking it. |
| 186 | + await DiscardAsync(conn).ConfigureAwait(false); |
| 187 | + } |
| 188 | + } |
| 189 | + |
| 190 | + private async ValueTask DiscardAsync(CosmoKvPipesConnection conn) |
| 191 | + { |
| 192 | + Interlocked.Decrement(ref _opened); |
| 193 | + try { await conn.DisposeAsync().ConfigureAwait(false); } catch { /* best-effort */ } |
| 194 | + } |
| 195 | +} |
0 commit comments