using System.Net.Sockets;
using Chronos.Core.Diagnostics;
namespace Chronos.Data.Postgres;
///
/// Connection pool: at most Maximum Pool Size connections, reused most-recent-first; a connection idle
/// longer than Health Check Interval is pinged with SELECT 1 before reuse; broken connections and
/// those left inside a transaction are discarded; idle ones beyond Minimum Pool Size are closed after
/// Connection Idle Lifetime.
///
internal sealed class PgPool : IAsyncDisposable
{
private const string LogCategory = "Data.Postgres";
private static readonly TimeSpan PruneInterval = TimeSpan.FromSeconds(10);
private readonly PostgresSettings _settings;
private readonly SemaphoreSlim _slots;
private readonly LinkedList _idle = new();
private readonly Lock _gate = new();
private readonly Timer _pruner;
private bool _disposed;
public PgPool(PostgresSettings settings)
{
_settings = settings;
_slots = new SemaphoreSlim(settings.MaxPoolSize, settings.MaxPoolSize);
var interval = settings.IdleLifetime < PruneInterval ? settings.IdleLifetime : PruneInterval;
_pruner = new Timer(static state => ((PgPool)state!).Prune(), this, interval, interval);
}
public async Task RentAsync(CancellationToken cancellationToken)
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (!await _slots.WaitAsync(_settings.ConnectTimeout, cancellationToken).ConfigureAwait(false))
throw new DatabaseConnectionException($"No pooled connection became free within {_settings.ConnectTimeout.TotalSeconds} s (Maximum Pool Size={_settings.MaxPoolSize}).");
try
{
while (TakeIdle() is { } 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);
}
catch
{
_slots.Release();
throw;
}
}
/// Takes a connection back; a broken or busy one, or one inside a transaction, is closed instead.
public void Return(PgConnector connector)
{
PgConnector? discard = connector;
if (!connector.IsBroken && !connector.IsBusy && connector.TransactionStatus == 'I')
{
connector.MarkIdle();
lock (_gate)
{
if (!_disposed)
{
_idle.AddFirst(connector);
discard = null;
}
}
}
if (discard is not null) _ = discard.DisposeAsync().AsTask();
_slots.Release();
}
public async ValueTask DisposeAsync()
{
List idle;
lock (_gate)
{
if (_disposed) return;
_disposed = true;
idle = [.. _idle];
_idle.Clear();
}
await _pruner.DisposeAsync().ConfigureAwait(false);
foreach (var connector in idle) await connector.DisposeAsync().ConfigureAwait(false);
}
/// Opens a connection, retrying once after a second when the server is starting up or refused it.
private async Task OpenAsync(CancellationToken cancellationToken)
{
try
{
return await PgConnector.OpenAsync(_settings, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is PostgresException { IsConnectionFailure: true } or DatabaseConnectionException { InnerException: SocketException })
{
Log.Warning(LogCategory, $"Connecting to {_settings.Host}:{_settings.Port} failed ({ex.Message}); retrying once.");
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ConfigureAwait(false);
return await PgConnector.OpenAsync(_settings, cancellationToken).ConfigureAwait(false);
}
}
private PgConnector? TakeIdle()
{
lock (_gate)
{
if (_idle.First is not { } first) return null;
_idle.RemoveFirst();
return first.Value;
}
}
private void Prune()
{
List? expired = null;
lock (_gate)
{
while (_idle.Count > _settings.MinPoolSize && _idle.Last is { } last && last.Value.IdleTime >= _settings.IdleLifetime)
{
_idle.RemoveLast();
(expired ??= []).Add(last.Value);
}
}
if (expired is null) return;
foreach (var connector in expired) _ = connector.DisposeAsync().AsTask();
}
}