fix(data): close concurrency and cleanup gaps found in review
- SQLite restore holds every pool slot instead of the write lock first, removing a lock-order deadlock with sessions that begin to write. - PostgreSQL sessions always return their connection on dispose, a rollback while disposing never masks the original exception, and a busy session keeps its transaction until it is discarded. - The pool disposes a connection whose health check the caller cancels. - Listener commands keep their lock until the server answers and never tear a write with the caller's token; closing and pending no longer race. - Tag replacement locks the sequence and the tag row; unused-tag cleanup locks candidates and re-checks them with a fresh snapshot; render counts and stats refreshes lock the sequence row on PostgreSQL. - Sequence upserts keep rendered_count, which renders maintain. - AuthenticationOk after an unfinished SCRAM exchange is rejected. - Oversized read buffers are released; failed backups leave no .tmp; a zero idle lifetime is rejected. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
17 files changed
+240
-61
No files matched your search
@@ -26,6 +26,9 @@ internal sealed class ScramSha256
|
||||
|
||||
public const string Mechanism = "SCRAM-SHA-256";
|
||||
|
||||
/// <summary>The server proved knowledge of the password with a valid final signature.</summary>
|
||||
public bool IsServerVerified { get; private set; }
|
||||
|
||||
public byte[] ClientFirstMessage()
|
||||
{
|
||||
_clientFirstBare = $"n={_username},r={_clientNonce}";
|
||||
@@ -71,6 +74,7 @@ internal sealed class ScramSha256
|
||||
if (_expectedServerSignature is null || value is null
|
||||
|| !CryptographicOperations.FixedTimeEquals(Convert.FromBase64String(value), _expectedServerSignature))
|
||||
throw new AuthenticationException("The server's SCRAM signature is invalid.");
|
||||
IsServerVerified = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -4,6 +4,7 @@ using System.Net.Security;
|
||||
using System.Net.Sockets;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.ExceptionServices;
|
||||
using System.Security.Authentication;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using System.Text;
|
||||
using Titano.Core.Diagnostics;
|
||||
@@ -423,6 +424,9 @@ internal sealed class PgConnector : IAsyncDisposable
|
||||
switch (code)
|
||||
{
|
||||
case 0:
|
||||
// A server that started SCRAM must finish it: only its final signature proves it knows the password.
|
||||
if (scram is { IsServerVerified: false })
|
||||
throw new AuthenticationException("The server skipped the final SCRAM message.");
|
||||
return scram;
|
||||
case 3:
|
||||
WritePassword(RequirePassword());
|
||||
@@ -551,6 +555,12 @@ internal sealed class PgConnector : IAsyncDisposable
|
||||
_ioAbort.Dispose();
|
||||
_ioAbort = new CancellationTokenSource();
|
||||
}
|
||||
// A huge row (a large bytea) grew the buffer; do not keep it for the life of a pooled connection.
|
||||
if (_read.Length > 1 << 20 && _readPos == _readEnd)
|
||||
{
|
||||
_read = new byte[16 * 1024];
|
||||
_readPos = _readEnd = 0;
|
||||
}
|
||||
_active = null;
|
||||
MarkIdle();
|
||||
}
|
||||
|
||||
@@ -13,7 +13,9 @@ public sealed class PgListener : IAsyncDisposable
|
||||
private readonly PgConnector _connector;
|
||||
private readonly SemaphoreSlim _commandLock = new(1, 1);
|
||||
private readonly CancellationTokenSource _stop = new();
|
||||
private readonly Lock _gate = new();
|
||||
private TaskCompletionSource<PostgresException?>? _pending;
|
||||
private bool _closed;
|
||||
|
||||
internal PgListener(PgConnector connector)
|
||||
{
|
||||
@@ -48,39 +50,59 @@ public sealed class PgListener : IAsyncDisposable
|
||||
_stop.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends one command and waits for its ReadyForQuery. The command lock is held until the server has answered,
|
||||
/// even when the caller stops waiting, so a late answer can never be taken for the next command's.
|
||||
/// </summary>
|
||||
private async Task CommandAsync(string sql, CancellationToken cancellationToken)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_stop.IsCancellationRequested, this);
|
||||
await _commandLock.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
var pending = new TaskCompletionSource<PostgresException?>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
try
|
||||
{
|
||||
if (Completion.IsCompleted) throw new DatabaseConnectionException("The listener connection is closed.", Completion.Exception?.InnerException);
|
||||
var pending = new TaskCompletionSource<PostgresException?>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
Volatile.Write(ref _pending, pending);
|
||||
await _connector.SendQueryAsync(sql, cancellationToken).ConfigureAwait(false);
|
||||
if (await pending.Task.WaitAsync(cancellationToken).ConfigureAwait(false) is { } error) throw error;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_closed) throw new DatabaseConnectionException("The listener connection is closed.", Completion.Exception?.InnerException);
|
||||
_pending = pending;
|
||||
}
|
||||
// The listener's own token: a write torn by the caller's token would corrupt the protocol stream.
|
||||
await _connector.SendQueryAsync(sql, _stop.Token).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
catch
|
||||
{
|
||||
_commandLock.Release();
|
||||
throw;
|
||||
}
|
||||
_ = pending.Task.ContinueWith(static (_, state) => ((SemaphoreSlim)state!).Release(), _commandLock,
|
||||
CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
|
||||
if (await pending.Task.WaitAsync(cancellationToken).ConfigureAwait(false) is { } error) throw error;
|
||||
}
|
||||
|
||||
private async Task RunAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await _connector.RunListenerAsync(error => Volatile.Read(ref _pending)?.TrySetResult(error), _stop.Token).ConfigureAwait(false);
|
||||
await _connector.RunListenerAsync(OnCommandCompleted, _stop.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception) when (_stop.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
finally
|
||||
{
|
||||
Volatile.Read(ref _pending)?.TrySetException(new DatabaseConnectionException("The listener connection is closed."));
|
||||
lock (_gate)
|
||||
{
|
||||
_closed = true;
|
||||
_pending?.TrySetException(new DatabaseConnectionException("The listener connection is closed."));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void OnCommandCompleted(PostgresException? error)
|
||||
{
|
||||
lock (_gate) _pending?.TrySetResult(error);
|
||||
}
|
||||
|
||||
private void Raise(PgNotification notification)
|
||||
{
|
||||
try
|
||||
|
||||
@@ -38,9 +38,19 @@ internal sealed class PgPool : IAsyncDisposable
|
||||
{
|
||||
while (TakeIdle() is { } connector)
|
||||
{
|
||||
if (!connector.IsBroken
|
||||
&& (connector.IdleTime < _settings.HealthCheckInterval || await connector.PingAsync(cancellationToken).ConfigureAwait(false)))
|
||||
return connector;
|
||||
bool healthy;
|
||||
try
|
||||
{
|
||||
healthy = !connector.IsBroken
|
||||
&& (connector.IdleTime < _settings.HealthCheckInterval || await connector.PingAsync(cancellationToken).ConfigureAwait(false));
|
||||
}
|
||||
catch
|
||||
{
|
||||
// The caller gave up during the health check; the connection's state is unknown.
|
||||
await connector.DisposeAsync().ConfigureAwait(false);
|
||||
throw;
|
||||
}
|
||||
if (healthy) return connector;
|
||||
await connector.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
return await OpenAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
@@ -112,28 +112,32 @@ internal sealed class PostgresSession(PgPool pool, PgConnector connector) : IDbS
|
||||
_disposed = true;
|
||||
if (_connector is not { } connection) return;
|
||||
_connector = null;
|
||||
if (_transaction is not null && !connection.IsBroken)
|
||||
try
|
||||
{
|
||||
try
|
||||
{
|
||||
await connection.SimpleQueryAsync("ROLLBACK", CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
catch (DatabaseException ex)
|
||||
{
|
||||
Log.Warning(LogCategory, "Rollback on session close failed; the connection is discarded.", ex);
|
||||
}
|
||||
if (_transaction is not null) await RollBackQuietlyAsync(connection).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_transaction = null;
|
||||
pool.Return(connection);
|
||||
}
|
||||
_transaction = null;
|
||||
pool.Return(connection);
|
||||
}
|
||||
|
||||
/// <summary>Ends <paramref name="transaction"/> if it is still active. COMMIT of an aborted transaction is reported, not silently rolled back.</summary>
|
||||
internal async Task EndTransactionAsync(PostgresTransaction transaction, bool commit, CancellationToken cancellationToken)
|
||||
/// <summary>
|
||||
/// Ends <paramref name="transaction"/> if it is still active. COMMIT of an aborted transaction is reported, not
|
||||
/// silently rolled back. A rollback while disposing never throws: a broken connection's transaction dies with
|
||||
/// it, and on a busy one the session stays in the transaction until it is disposed (the pool then discards it).
|
||||
/// </summary>
|
||||
internal async Task EndTransactionAsync(PostgresTransaction transaction, bool commit, bool disposing, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_transaction != transaction) return;
|
||||
try
|
||||
{
|
||||
if (!commit)
|
||||
if (disposing)
|
||||
{
|
||||
if (_connector is { } connection) await RollBackQuietlyAsync(connection).ConfigureAwait(false);
|
||||
}
|
||||
else if (!commit)
|
||||
{
|
||||
await Connector.SimpleQueryAsync("ROLLBACK", cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
@@ -153,6 +157,19 @@ internal sealed class PostgresSession(PgPool pool, PgConnector connector) : IDbS
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task RollBackQuietlyAsync(PgConnector connection)
|
||||
{
|
||||
if (connection.IsBroken || connection.IsBusy) return;
|
||||
try
|
||||
{
|
||||
await connection.SimpleQueryAsync("ROLLBACK", CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
catch (DatabaseException ex)
|
||||
{
|
||||
Log.Warning(LogCategory, "Rollback on dispose failed; the connection is discarded.", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsConnectionFailure(Exception ex) =>
|
||||
ex is DatabaseConnectionException or PostgresException { IsConnectionFailure: true };
|
||||
|
||||
@@ -196,21 +213,21 @@ internal sealed class PostgresTransaction(PostgresSession session) : IDbTransact
|
||||
public async Task CommitAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_completed, this);
|
||||
await session.EndTransactionAsync(this, commit: true, disposing: false, cancellationToken).ConfigureAwait(false);
|
||||
_completed = true;
|
||||
await session.EndTransactionAsync(this, commit: true, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async Task RollbackAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_completed, this);
|
||||
await session.EndTransactionAsync(this, commit: false, disposing: false, cancellationToken).ConfigureAwait(false);
|
||||
_completed = true;
|
||||
await session.EndTransactionAsync(this, commit: false, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (_completed) return;
|
||||
_completed = true;
|
||||
await session.EndTransactionAsync(this, commit: false, CancellationToken.None).ConfigureAwait(false);
|
||||
await session.EndTransactionAsync(this, commit: false, disposing: true, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -68,8 +68,8 @@ public sealed record PostgresSettings
|
||||
cs.ThrowOnUnknownKeys();
|
||||
if (settings.MaxPoolSize < 1 || settings.MinPoolSize < 0 || settings.MinPoolSize > settings.MaxPoolSize)
|
||||
throw new FormatException("Pool sizes must satisfy 0 ≤ Minimum Pool Size ≤ Maximum Pool Size, Maximum ≥ 1.");
|
||||
if (settings.StatementCacheSize < 0 || settings.ConnectTimeout <= TimeSpan.Zero)
|
||||
throw new FormatException("'Statement Cache Size' must be ≥ 0 and 'Timeout' > 0.");
|
||||
if (settings.StatementCacheSize < 0 || settings.ConnectTimeout <= TimeSpan.Zero || settings.IdleLifetime <= TimeSpan.Zero)
|
||||
throw new FormatException("'Statement Cache Size' must be ≥ 0; 'Timeout' and 'Connection Idle Lifetime' must be > 0.");
|
||||
return settings;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user