feat(data): add in-house PostgreSQL wire protocol v3 client
TCP with optional TLS (disable/prefer/require/verify-full), SCRAM-SHA-256, MD5, cleartext and trust authentication, simple and extended query with a per-connection LRU of prepared statements, text-format parameters with binary bytea, OID-based result decoding, COPY FROM STDIN, LISTEN/NOTIFY, CancelRequest cancellation, typed PostgresException, and a connection pool with health checks, idle eviction and one retry for reads that hit a lost connection. DatabaseFactory opens either engine from options. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
10 files changed
+2104
No files matched your search
@@ -0,0 +1,54 @@
|
||||
using Titano.Data.Postgres;
|
||||
using Titano.Data.Sqlite;
|
||||
|
||||
namespace Titano.Data;
|
||||
|
||||
/// <summary>Which engine to open and how to reach it.</summary>
|
||||
/// <remarks>
|
||||
/// SQLite: <c>Data Source=<path>|:memory:;Pool Size=4</c>.
|
||||
/// PostgreSQL: <c>Host=…;Port=5432;Database=…;Username=…;Password=…;SslMode=disable|prefer|require|verify-full</c>
|
||||
/// plus the optional keys listed on <see cref="PostgresSettings"/>.
|
||||
/// </remarks>
|
||||
public sealed record DatabaseOptions
|
||||
{
|
||||
public required Dialect Dialect { get; init; }
|
||||
|
||||
public required string ConnectionString { get; init; }
|
||||
|
||||
public static DatabaseOptions Sqlite(string path) => new()
|
||||
{
|
||||
Dialect = Dialect.Sqlite,
|
||||
ConnectionString = "Data Source='" + path.Replace("'", "''", StringComparison.Ordinal) + "'",
|
||||
};
|
||||
|
||||
/// <summary>A private in-memory SQLite database that lives until the <see cref="IDatabase"/> is disposed.</summary>
|
||||
public static DatabaseOptions SqliteInMemory() => new() { Dialect = Dialect.Sqlite, ConnectionString = "Data Source=:memory:" };
|
||||
|
||||
public static DatabaseOptions Postgres(string connectionString) => new() { Dialect = Dialect.Postgres, ConnectionString = connectionString };
|
||||
|
||||
/// <summary>
|
||||
/// Infers the dialect: a string with <c>Host</c>/<c>Server</c> is PostgreSQL; <c>Data Source</c> or a bare
|
||||
/// path (no <c>=</c>) is SQLite.
|
||||
/// </summary>
|
||||
public static DatabaseOptions Parse(string connectionString)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(connectionString);
|
||||
if (!connectionString.Contains('=', StringComparison.Ordinal)) return Sqlite(connectionString.Trim());
|
||||
var cs = new ConnectionString(connectionString);
|
||||
if (cs.Contains("Host") || cs.Contains("Server")) return Postgres(connectionString);
|
||||
if (cs.Contains("Data Source") || cs.Contains("Filename")) return new() { Dialect = Dialect.Sqlite, ConnectionString = connectionString };
|
||||
throw new FormatException("The connection string names neither a PostgreSQL host nor a SQLite data source.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Builds the <see cref="IDatabase"/> implementation for a set of options.</summary>
|
||||
public static class DatabaseFactory
|
||||
{
|
||||
/// <summary>Creates the database object; SQLite opens the file now, PostgreSQL connects on the first session.</summary>
|
||||
public static IDatabase Open(DatabaseOptions options) => options.Dialect switch
|
||||
{
|
||||
Dialect.Sqlite => SqliteDatabase.Open(SqliteSettings.Parse(options.ConnectionString)),
|
||||
Dialect.Postgres => new PostgresDatabase(PostgresSettings.Parse(options.ConnectionString)),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(options), options.Dialect, "Unknown dialect."),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
using System.Globalization;
|
||||
using System.Security.Authentication;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace Titano.Data.Postgres;
|
||||
|
||||
/// <summary>
|
||||
/// Client side of SCRAM-SHA-256 (RFC 5802 / RFC 7677) as PostgreSQL uses it: no channel binding
|
||||
/// (<c>n,,</c> GS2 header) and an empty user name, since the server takes the user from the startup packet.
|
||||
/// </summary>
|
||||
internal sealed class ScramSha256
|
||||
{
|
||||
private readonly string _password;
|
||||
private readonly string _username;
|
||||
private readonly string _clientNonce;
|
||||
private string? _clientFirstBare;
|
||||
private byte[]? _expectedServerSignature;
|
||||
|
||||
public ScramSha256(string password, string username = "", string? clientNonce = null)
|
||||
{
|
||||
_password = password;
|
||||
_username = username.Replace("=", "=3D", StringComparison.Ordinal).Replace(",", "=2C", StringComparison.Ordinal);
|
||||
_clientNonce = clientNonce ?? Convert.ToBase64String(RandomNumberGenerator.GetBytes(18));
|
||||
}
|
||||
|
||||
public const string Mechanism = "SCRAM-SHA-256";
|
||||
|
||||
public byte[] ClientFirstMessage()
|
||||
{
|
||||
_clientFirstBare = $"n={_username},r={_clientNonce}";
|
||||
return Encoding.UTF8.GetBytes("n,," + _clientFirstBare);
|
||||
}
|
||||
|
||||
/// <summary>Checks the server-first message and returns client-final with the proof.</summary>
|
||||
public byte[] ClientFinalMessage(ReadOnlySpan<byte> serverFirst)
|
||||
{
|
||||
if (_clientFirstBare is null) throw new InvalidOperationException("ClientFirstMessage must be sent first.");
|
||||
var serverFirstText = Encoding.UTF8.GetString(serverFirst);
|
||||
string? nonce = null, salt = null, iterations = null;
|
||||
foreach (var part in serverFirstText.Split(','))
|
||||
{
|
||||
if (part.StartsWith("r=", StringComparison.Ordinal)) nonce = part[2..];
|
||||
else if (part.StartsWith("s=", StringComparison.Ordinal)) salt = part[2..];
|
||||
else if (part.StartsWith("i=", StringComparison.Ordinal)) iterations = part[2..];
|
||||
}
|
||||
if (nonce is null || salt is null || iterations is null
|
||||
|| !nonce.StartsWith(_clientNonce, StringComparison.Ordinal) || nonce.Length == _clientNonce.Length
|
||||
|| !int.TryParse(iterations, NumberStyles.None, CultureInfo.InvariantCulture, out var count) || count < 1)
|
||||
throw new AuthenticationException("Invalid SCRAM server-first message.");
|
||||
|
||||
var saltedPassword = Rfc2898DeriveBytes.Pbkdf2(
|
||||
Encoding.UTF8.GetBytes(SaslPrep(_password)), Convert.FromBase64String(salt), count, HashAlgorithmName.SHA256, 32);
|
||||
var clientKey = HMACSHA256.HashData(saltedPassword, "Client Key"u8);
|
||||
var storedKey = SHA256.HashData(clientKey);
|
||||
var withoutProof = "c=biws,r=" + nonce;
|
||||
var authMessage = Encoding.UTF8.GetBytes(_clientFirstBare + "," + serverFirstText + "," + withoutProof);
|
||||
var proof = HMACSHA256.HashData(storedKey, authMessage);
|
||||
for (var i = 0; i < proof.Length; i++) proof[i] ^= clientKey[i];
|
||||
_expectedServerSignature = HMACSHA256.HashData(HMACSHA256.HashData(saltedPassword, "Server Key"u8), authMessage);
|
||||
return Encoding.UTF8.GetBytes(withoutProof + ",p=" + Convert.ToBase64String(proof));
|
||||
}
|
||||
|
||||
/// <summary>Verifies the server signature, proving the server knows the password too.</summary>
|
||||
public void VerifyServerFinal(ReadOnlySpan<byte> serverFinal)
|
||||
{
|
||||
var text = Encoding.UTF8.GetString(serverFinal);
|
||||
if (text.StartsWith("e=", StringComparison.Ordinal)) throw new AuthenticationException("SCRAM authentication failed: " + text[2..]);
|
||||
var end = text.IndexOf(',', StringComparison.Ordinal);
|
||||
var value = text.StartsWith("v=", StringComparison.Ordinal) ? text[2..(end < 0 ? text.Length : end)] : null;
|
||||
if (_expectedServerSignature is null || value is null
|
||||
|| !CryptographicOperations.FixedTimeEquals(Convert.FromBase64String(value), _expectedServerSignature))
|
||||
throw new AuthenticationException("The server's SCRAM signature is invalid.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SASLprep (RFC 4013) as PostgreSQL applies it: non-ASCII spaces become U+0020, "mapped to nothing"
|
||||
/// characters are dropped, then NFKC; a result with prohibited code points falls back to the raw password.
|
||||
/// The unassigned-code-point and bidi checks are omitted.
|
||||
/// </summary>
|
||||
internal static string SaslPrep(string password)
|
||||
{
|
||||
var ascii = true;
|
||||
foreach (var c in password)
|
||||
{
|
||||
if (c > 0x7F)
|
||||
{
|
||||
ascii = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Printable ASCII is unchanged by SASLprep; ASCII controls are prohibited, which also means "use raw".
|
||||
if (ascii) return password;
|
||||
|
||||
var mapped = new StringBuilder(password.Length);
|
||||
foreach (var rune in password.EnumerateRunes())
|
||||
{
|
||||
var v = rune.Value;
|
||||
if (v is 0x00A0 or 0x1680 or (>= 0x2000 and <= 0x200B) or 0x202F or 0x205F or 0x3000) mapped.Append(' ');
|
||||
else if (v is 0x00AD or 0x034F or 0x1806 or (>= 0x180B and <= 0x180D) or (>= 0x200C and <= 0x200D) or 0x2060
|
||||
or (>= 0xFE00 and <= 0xFE0F) or 0xFEFF) continue;
|
||||
else mapped.Append(rune.ToString());
|
||||
}
|
||||
var normalized = mapped.ToString().Normalize(NormalizationForm.FormKC);
|
||||
foreach (var rune in normalized.EnumerateRunes())
|
||||
{
|
||||
if (IsProhibited(rune.Value)) return password;
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
private static bool IsProhibited(int v) =>
|
||||
v < 0x20 || v is >= 0x7F and <= 0x9F // C.2.1, C.2.2 controls
|
||||
|| v is 0x06DD or 0x070F or 0x180E or 0x2028 or 0x2029 or (>= 0x2060 and <= 0x2063) // C.2.2
|
||||
|| v is >= 0x1D173 and <= 0x1D17A
|
||||
|| v is >= 0xE000 and <= 0xF8FF || v >= 0xF0000 // C.3 private use
|
||||
|| v is >= 0xFDD0 and <= 0xFDEF || (v & 0xFFFE) == 0xFFFE // C.4 non-characters
|
||||
|| v is >= 0xFFF9 and <= 0xFFFD // C.6
|
||||
|| v is >= 0x2FF0 and <= 0x2FFB // C.7
|
||||
|| v is 0x0340 or 0x0341 or 0x200E or 0x200F or (>= 0x202A and <= 0x202E) or (>= 0x206A and <= 0x206F) // C.8
|
||||
|| v is 0xE0001 or (>= 0xE0020 and <= 0xE007F); // C.9
|
||||
}
|
||||
|
||||
/// <summary>PostgreSQL's MD5 password response: <c>"md5" + md5hex(md5hex(password + user) + salt)</c>.</summary>
|
||||
internal static class PgMd5
|
||||
{
|
||||
public static string Response(string username, string password, ReadOnlySpan<byte> salt)
|
||||
{
|
||||
var inner = Hex(MD5.HashData(Encoding.UTF8.GetBytes(password + username)));
|
||||
var buffer = new byte[inner.Length + salt.Length];
|
||||
Encoding.ASCII.GetBytes(inner, buffer);
|
||||
salt.CopyTo(buffer.AsSpan(inner.Length));
|
||||
return "md5" + Hex(MD5.HashData(buffer));
|
||||
}
|
||||
|
||||
private static string Hex(byte[] bytes) => Convert.ToHexStringLower(bytes);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,96 @@
|
||||
using Titano.Core.Diagnostics;
|
||||
|
||||
namespace Titano.Data.Postgres;
|
||||
|
||||
/// <summary>
|
||||
/// LISTEN/NOTIFY on a dedicated connection (multi-instance job wake-ups). <see cref="Notification"/> is raised on
|
||||
/// a background thread; <see cref="Completion"/> ends when the listener is disposed or faults if the connection
|
||||
/// is lost, after which a new listener must be created.
|
||||
/// </summary>
|
||||
public sealed class PgListener : IAsyncDisposable
|
||||
{
|
||||
private const string LogCategory = "Data.Postgres";
|
||||
private readonly PgConnector _connector;
|
||||
private readonly SemaphoreSlim _commandLock = new(1, 1);
|
||||
private readonly CancellationTokenSource _stop = new();
|
||||
private TaskCompletionSource<PostgresException?>? _pending;
|
||||
|
||||
internal PgListener(PgConnector connector)
|
||||
{
|
||||
_connector = connector;
|
||||
connector.NotificationReceived = Raise;
|
||||
Completion = Task.Run(RunAsync);
|
||||
}
|
||||
|
||||
public event EventHandler<PgNotification>? Notification;
|
||||
|
||||
public Task Completion { get; }
|
||||
|
||||
public Task ListenAsync(string channel, CancellationToken cancellationToken = default) =>
|
||||
CommandAsync("LISTEN " + SqlDialect.QuoteIdentifier(channel), cancellationToken);
|
||||
|
||||
public Task UnlistenAsync(string channel, CancellationToken cancellationToken = default) =>
|
||||
CommandAsync("UNLISTEN " + SqlDialect.QuoteIdentifier(channel), cancellationToken);
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (_stop.IsCancellationRequested) return;
|
||||
await _stop.CancelAsync().ConfigureAwait(false);
|
||||
await _connector.DisposeAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await Completion.ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is DatabaseException or OperationCanceledException)
|
||||
{
|
||||
// The loop ends with whatever the closed socket raised.
|
||||
}
|
||||
_stop.Dispose();
|
||||
}
|
||||
|
||||
private async Task CommandAsync(string sql, CancellationToken cancellationToken)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_stop.IsCancellationRequested, this);
|
||||
await _commandLock.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
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;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_commandLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RunAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await _connector.RunListenerAsync(error => Volatile.Read(ref _pending)?.TrySetResult(error), _stop.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception) when (_stop.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
finally
|
||||
{
|
||||
Volatile.Read(ref _pending)?.TrySetException(new DatabaseConnectionException("The listener connection is closed."));
|
||||
}
|
||||
}
|
||||
|
||||
private void Raise(PgNotification notification)
|
||||
{
|
||||
try
|
||||
{
|
||||
Notification?.Invoke(this, notification);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// A faulty handler must not stop delivery to the others.
|
||||
Log.Error(LogCategory, $"Notification handler failed for channel '{notification.Channel}'.", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
using System.Net.Sockets;
|
||||
using Titano.Core.Diagnostics;
|
||||
|
||||
namespace Titano.Data.Postgres;
|
||||
|
||||
/// <summary>
|
||||
/// Connection pool: at most <c>Maximum Pool Size</c> connections, reused most-recent-first; a connection idle
|
||||
/// longer than <c>Health Check Interval</c> is pinged with <c>SELECT 1</c> before reuse; broken connections and
|
||||
/// those left inside a transaction are discarded; idle ones beyond <c>Minimum Pool Size</c> are closed after
|
||||
/// <c>Connection Idle Lifetime</c>.
|
||||
/// </summary>
|
||||
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<PgConnector> _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<PgConnector> 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)
|
||||
{
|
||||
if (!connector.IsBroken
|
||||
&& (connector.IdleTime < _settings.HealthCheckInterval || await connector.PingAsync(cancellationToken).ConfigureAwait(false)))
|
||||
return connector;
|
||||
await connector.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
return await OpenAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
_slots.Release();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Takes a connection back; a broken one, or one not idle at transaction level, is closed instead.</summary>
|
||||
public void Return(PgConnector connector)
|
||||
{
|
||||
PgConnector? discard = connector;
|
||||
if (!connector.IsBroken && 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<PgConnector> 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);
|
||||
}
|
||||
|
||||
/// <summary>Opens a connection, retrying once after a second when the server is starting up or refused it.</summary>
|
||||
private async Task<PgConnector> 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<PgConnector>? 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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
using System.Buffers;
|
||||
using System.Buffers.Text;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
|
||||
namespace Titano.Data.Postgres;
|
||||
|
||||
/// <summary>Type OIDs, text-format value encoding and result decoding (BRIEF §6.3 type mapping).</summary>
|
||||
internal static class PgTypes
|
||||
{
|
||||
public const uint Bool = 16;
|
||||
public const uint Bytea = 17;
|
||||
public const uint Char = 18;
|
||||
public const uint Name = 19;
|
||||
public const uint Int8 = 20;
|
||||
public const uint Int2 = 21;
|
||||
public const uint Int4 = 23;
|
||||
public const uint Text = 25;
|
||||
public const uint Oid = 26;
|
||||
public const uint Json = 114;
|
||||
public const uint Float4 = 700;
|
||||
public const uint Float8 = 701;
|
||||
public const uint Bpchar = 1042;
|
||||
public const uint Varchar = 1043;
|
||||
public const uint Date = 1082;
|
||||
public const uint Timestamp = 1114;
|
||||
public const uint TimestampTz = 1184;
|
||||
public const uint Numeric = 1700;
|
||||
public const uint Uuid = 2950;
|
||||
public const uint Jsonb = 3802;
|
||||
|
||||
private static readonly SearchValues<char> CopySpecials = SearchValues.Create("\\\t\n\r");
|
||||
|
||||
/// <summary>Parameter type sent in Parse; 0 lets the server infer an untyped NULL.</summary>
|
||||
public static uint OidOf(DbValueType type) => type switch
|
||||
{
|
||||
DbValueType.Text => Text,
|
||||
DbValueType.Int32 => Int4,
|
||||
DbValueType.Int64 => Int8,
|
||||
DbValueType.Double => Float8,
|
||||
DbValueType.Bool => Bool,
|
||||
DbValueType.Uuid => Uuid,
|
||||
DbValueType.Timestamp => TimestampTz,
|
||||
DbValueType.LocalDateTime => Timestamp,
|
||||
DbValueType.Bytes => Bytea,
|
||||
DbValueType.Json => Jsonb,
|
||||
_ => 0,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Writes the text form of a canonical <see cref="DbParam"/> value (anything but byte[]) as UTF-8 and returns
|
||||
/// the byte count. <paramref name="destination"/> must hold <see cref="MaxTextLength"/> bytes.
|
||||
/// </summary>
|
||||
public static int FormatText(object value, Span<byte> destination)
|
||||
{
|
||||
var inv = CultureInfo.InvariantCulture;
|
||||
int written;
|
||||
bool ok;
|
||||
switch (value)
|
||||
{
|
||||
case string s:
|
||||
return Encoding.UTF8.GetBytes(s, destination);
|
||||
case bool b:
|
||||
destination[0] = b ? (byte)'t' : (byte)'f';
|
||||
return 1;
|
||||
case int i:
|
||||
ok = i.TryFormat(destination, out written, default, inv);
|
||||
break;
|
||||
case long l:
|
||||
ok = l.TryFormat(destination, out written, default, inv);
|
||||
break;
|
||||
case double d:
|
||||
ok = d.TryFormat(destination, out written, "R", inv);
|
||||
break;
|
||||
case Guid g:
|
||||
ok = g.TryFormat(destination, out written, "D");
|
||||
break;
|
||||
case DateTimeOffset o:
|
||||
ok = o.UtcDateTime.TryFormat(destination, out written, "yyyy-MM-dd'T'HH:mm:ss.ffffff'Z'", inv);
|
||||
break;
|
||||
case DateTime d:
|
||||
ok = d.TryFormat(destination, out written, "yyyy-MM-dd'T'HH:mm:ss.ffffff", inv);
|
||||
break;
|
||||
default:
|
||||
throw new NotSupportedException($"Cannot send {value.GetType().Name} as text.");
|
||||
}
|
||||
return ok ? written : throw new FormatException($"Cannot format {value}.");
|
||||
}
|
||||
|
||||
/// <summary>Upper bound of <see cref="FormatText"/> output for <paramref name="value"/>.</summary>
|
||||
public static int MaxTextLength(object value) => value is string s ? Encoding.UTF8.GetMaxByteCount(s.Length) : 64;
|
||||
|
||||
/// <summary>
|
||||
/// Writes a value in COPY text format: <c>\N</c> for NULL, specials in strings backslash-escaped, bytea in
|
||||
/// hex form (<c>\\x…</c>). Values of other CLR types go through <see cref="DbParam"/> normalisation.
|
||||
/// </summary>
|
||||
public static void WriteCopyValue(object? value, IBufferWriter<byte> writer)
|
||||
{
|
||||
switch (value)
|
||||
{
|
||||
case null:
|
||||
writer.Write("\\N"u8);
|
||||
return;
|
||||
case string s:
|
||||
WriteCopyEscaped(s, writer);
|
||||
return;
|
||||
case byte[] bytes:
|
||||
{
|
||||
var span = writer.GetSpan(3 + bytes.Length * 2);
|
||||
"\\\\x"u8.CopyTo(span);
|
||||
for (var i = 0; i < bytes.Length; i++)
|
||||
{
|
||||
span[3 + 2 * i] = HexDigits[bytes[i] >> 4];
|
||||
span[4 + 2 * i] = HexDigits[bytes[i] & 0xF];
|
||||
}
|
||||
writer.Advance(3 + bytes.Length * 2);
|
||||
return;
|
||||
}
|
||||
case int or long or double or bool or Guid or DateTimeOffset:
|
||||
case DateTime { Kind: DateTimeKind.Unspecified }:
|
||||
writer.Advance(FormatText(value, writer.GetSpan(64)));
|
||||
return;
|
||||
default:
|
||||
var normalized = new DbParam(value);
|
||||
WriteCopyValue(normalized.Value, writer);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private static void WriteCopyEscaped(string s, IBufferWriter<byte> writer)
|
||||
{
|
||||
var rest = s.AsSpan();
|
||||
while (!rest.IsEmpty)
|
||||
{
|
||||
var special = rest.IndexOfAny(CopySpecials);
|
||||
var plain = special < 0 ? rest : rest[..special];
|
||||
if (!plain.IsEmpty)
|
||||
{
|
||||
var n = Encoding.UTF8.GetBytes(plain, writer.GetSpan(Encoding.UTF8.GetMaxByteCount(plain.Length)));
|
||||
writer.Advance(n);
|
||||
}
|
||||
if (special < 0) return;
|
||||
writer.Write(rest[special] switch
|
||||
{
|
||||
'\\' => "\\\\"u8,
|
||||
'\t' => "\\t"u8,
|
||||
'\n' => "\\n"u8,
|
||||
_ => "\\r"u8,
|
||||
});
|
||||
rest = rest[(special + 1)..];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Decodes a text-format result value by its type OID; unknown types stay strings.</summary>
|
||||
public static object Decode(uint oid, ReadOnlySpan<byte> utf8)
|
||||
{
|
||||
var inv = CultureInfo.InvariantCulture;
|
||||
switch (oid)
|
||||
{
|
||||
case Bool:
|
||||
return utf8.Length > 0 && utf8[0] == (byte)'t';
|
||||
case Int2 or Int4:
|
||||
return int.Parse(utf8, NumberStyles.AllowLeadingSign, inv);
|
||||
case Int8 or Oid:
|
||||
return long.Parse(utf8, NumberStyles.AllowLeadingSign, inv);
|
||||
case Float4 or Float8:
|
||||
return double.Parse(utf8, NumberStyles.Float, inv);
|
||||
case Uuid:
|
||||
return Utf8Parser.TryParse(utf8, out Guid guid, out var consumed) && consumed == utf8.Length
|
||||
? guid
|
||||
: throw new FormatException("Malformed uuid.");
|
||||
case Bytea:
|
||||
return DecodeBytea(utf8);
|
||||
case TimestampTz or Timestamp or Date when utf8.Length <= 64:
|
||||
Span<char> chars = stackalloc char[utf8.Length];
|
||||
Encoding.ASCII.GetChars(utf8, chars);
|
||||
return oid switch
|
||||
{
|
||||
TimestampTz => TextValues.ParseTimestamp(chars),
|
||||
Timestamp => TextValues.ParseLocal(chars),
|
||||
_ => DateOnly.ParseExact(chars, "yyyy-MM-dd", inv),
|
||||
};
|
||||
default:
|
||||
return Encoding.UTF8.GetString(utf8);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>bytea output: hex (<c>\x0a0b</c>, the default since 9.0) or the legacy escape format.</summary>
|
||||
private static byte[] DecodeBytea(ReadOnlySpan<byte> text)
|
||||
{
|
||||
if (text.Length >= 2 && text[0] == '\\' && text[1] == 'x')
|
||||
return Convert.FromHexString(Encoding.ASCII.GetString(text[2..]));
|
||||
var result = new List<byte>(text.Length);
|
||||
for (var i = 0; i < text.Length; i++)
|
||||
{
|
||||
if (text[i] != '\\')
|
||||
{
|
||||
result.Add(text[i]);
|
||||
}
|
||||
else if (i + 1 < text.Length && text[i + 1] == '\\')
|
||||
{
|
||||
result.Add((byte)'\\');
|
||||
i++;
|
||||
}
|
||||
else if (i + 3 < text.Length)
|
||||
{
|
||||
result.Add((byte)(((text[i + 1] - '0') << 6) | ((text[i + 2] - '0') << 3) | (text[i + 3] - '0')));
|
||||
i += 3;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new FormatException("Malformed bytea escape sequence.");
|
||||
}
|
||||
}
|
||||
return [.. result];
|
||||
}
|
||||
|
||||
private static ReadOnlySpan<byte> HexDigits => "0123456789abcdef"u8;
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
using System.Buffers;
|
||||
using System.Buffers.Binary;
|
||||
using System.Text;
|
||||
|
||||
namespace Titano.Data.Postgres;
|
||||
|
||||
/// <summary>Growable outgoing buffer that frames protocol messages (type byte + big-endian length).</summary>
|
||||
internal sealed class PgWriteBuffer : IBufferWriter<byte>
|
||||
{
|
||||
private byte[] _buffer = new byte[8192];
|
||||
private int _messageStart = -1;
|
||||
|
||||
public int Length { get; private set; }
|
||||
|
||||
public ReadOnlyMemory<byte> Written => _buffer.AsMemory(0, Length);
|
||||
|
||||
/// <summary>Starts a message; its length is patched by <see cref="EndMessage"/>.</summary>
|
||||
public void StartMessage(char type)
|
||||
{
|
||||
GetSpan(1)[0] = (byte)type;
|
||||
Advance(1);
|
||||
StartUntypedMessage();
|
||||
}
|
||||
|
||||
/// <summary>Starts a message without a type byte (startup, SSL and cancel requests).</summary>
|
||||
public void StartUntypedMessage()
|
||||
{
|
||||
_messageStart = Length;
|
||||
Advance(4);
|
||||
}
|
||||
|
||||
public void EndMessage()
|
||||
{
|
||||
BinaryPrimitives.WriteInt32BigEndian(_buffer.AsSpan(_messageStart), Length - _messageStart);
|
||||
_messageStart = -1;
|
||||
}
|
||||
|
||||
public void WriteByte(byte value)
|
||||
{
|
||||
GetSpan(1)[0] = value;
|
||||
Advance(1);
|
||||
}
|
||||
|
||||
public void WriteInt16(int value)
|
||||
{
|
||||
BinaryPrimitives.WriteInt16BigEndian(GetSpan(2), checked((short)value));
|
||||
Advance(2);
|
||||
}
|
||||
|
||||
public void WriteInt32(int value)
|
||||
{
|
||||
BinaryPrimitives.WriteInt32BigEndian(GetSpan(4), value);
|
||||
Advance(4);
|
||||
}
|
||||
|
||||
public void Write(ReadOnlySpan<byte> bytes)
|
||||
{
|
||||
bytes.CopyTo(GetSpan(bytes.Length));
|
||||
Advance(bytes.Length);
|
||||
}
|
||||
|
||||
/// <summary>UTF-8 text followed by a NUL terminator.</summary>
|
||||
public void WriteCString(string text)
|
||||
{
|
||||
var n = Encoding.UTF8.GetBytes(text, GetSpan(Encoding.UTF8.GetMaxByteCount(text.Length) + 1));
|
||||
_buffer[Length + n] = 0;
|
||||
Advance(n + 1);
|
||||
}
|
||||
|
||||
/// <summary>Empties the buffer; an oversized one (a big bytea parameter) is released so pooled connections stay small.</summary>
|
||||
public void Clear()
|
||||
{
|
||||
Length = 0;
|
||||
_messageStart = -1;
|
||||
if (_buffer.Length > 1 << 20) _buffer = new byte[8192];
|
||||
}
|
||||
|
||||
public void Advance(int count) => Length += count;
|
||||
|
||||
public Memory<byte> GetMemory(int sizeHint = 0)
|
||||
{
|
||||
Ensure(sizeHint);
|
||||
return _buffer.AsMemory(Length);
|
||||
}
|
||||
|
||||
public Span<byte> GetSpan(int sizeHint = 0)
|
||||
{
|
||||
Ensure(sizeHint);
|
||||
return _buffer.AsSpan(Length);
|
||||
}
|
||||
|
||||
private void Ensure(int sizeHint)
|
||||
{
|
||||
var needed = Length + Math.Max(sizeHint, 1);
|
||||
if (needed <= _buffer.Length) return;
|
||||
Array.Resize(ref _buffer, Math.Max(needed, _buffer.Length * 2));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using Titano.Core.Diagnostics;
|
||||
|
||||
namespace Titano.Data.Postgres;
|
||||
|
||||
/// <summary>A PostgreSQL server reached through the in-house protocol v3 client and its connection pool.</summary>
|
||||
public sealed class PostgresDatabase(PostgresSettings settings) : IDatabase
|
||||
{
|
||||
private readonly PgPool _pool = new(settings);
|
||||
|
||||
public PostgresSettings Settings { get; } = settings;
|
||||
|
||||
public Dialect Dialect => Dialect.Postgres;
|
||||
|
||||
public async Task<IDbSession> OpenAsync(CancellationToken cancellationToken) =>
|
||||
new PostgresSession(_pool, await _pool.RentAsync(cancellationToken).ConfigureAwait(false));
|
||||
|
||||
/// <summary>Opens a dedicated (unpooled) connection that raises an event for every NOTIFY on its channels.</summary>
|
||||
public async Task<PgListener> CreateListenerAsync(CancellationToken cancellationToken = default) =>
|
||||
new(await PgConnector.OpenAsync(Settings, cancellationToken).ConfigureAwait(false));
|
||||
|
||||
public ValueTask DisposeAsync() => _pool.DisposeAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A pooled PostgreSQL connection. Reads (SELECT/VALUES/SHOW/TABLE) outside a transaction are retried once on a
|
||||
/// fresh connection when the first attempt fails with a connection error before returning any row.
|
||||
/// </summary>
|
||||
internal sealed class PostgresSession(PgPool pool, PgConnector connector) : IDbSession
|
||||
{
|
||||
private const string LogCategory = "Data.Postgres";
|
||||
private PgConnector? _connector = connector;
|
||||
private PostgresTransaction? _transaction;
|
||||
private bool _disposed;
|
||||
|
||||
public Dialect Dialect => Dialect.Postgres;
|
||||
|
||||
public bool InTransaction => _transaction is not null;
|
||||
|
||||
private PgConnector Connector
|
||||
{
|
||||
get
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
return _connector ?? throw new DatabaseConnectionException("The session lost its connection.");
|
||||
}
|
||||
}
|
||||
|
||||
public Task<int> ExecuteAsync(string sql, DbParam[] parameters, CancellationToken cancellationToken) =>
|
||||
Connector.ExecuteAsync(sql, parameters, cancellationToken);
|
||||
|
||||
public async IAsyncEnumerable<DbRow> QueryAsync(string sql, DbParam[] parameters, [EnumeratorCancellation] CancellationToken cancellationToken)
|
||||
{
|
||||
var retry = _transaction is null && IsReadOnlyQuery(sql);
|
||||
while (true)
|
||||
{
|
||||
var rows = Connector.QueryAsync(sql, parameters, cancellationToken).GetAsyncEnumerator(CancellationToken.None);
|
||||
var yielded = false;
|
||||
Exception? failure = null;
|
||||
try
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
bool more;
|
||||
try
|
||||
{
|
||||
more = await rows.MoveNextAsync().ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (retry && !yielded && IsConnectionFailure(ex))
|
||||
{
|
||||
failure = ex;
|
||||
break;
|
||||
}
|
||||
if (!more) yield break;
|
||||
yielded = true;
|
||||
yield return rows.Current;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
await rows.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
Log.Warning(LogCategory, $"Retrying a read on a new connection after: {failure!.Message}");
|
||||
retry = false;
|
||||
var broken = _connector!;
|
||||
_connector = null;
|
||||
pool.Return(broken);
|
||||
_connector = await pool.RentAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
public Task ExecuteScriptAsync(string script, CancellationToken cancellationToken) =>
|
||||
Connector.SimpleQueryAsync(script, cancellationToken);
|
||||
|
||||
public async Task<IDbTransaction> BeginAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (_transaction is not null) throw new InvalidOperationException("A transaction is already active on this session.");
|
||||
await Connector.SimpleQueryAsync("BEGIN", cancellationToken).ConfigureAwait(false);
|
||||
return _transaction = new PostgresTransaction(this);
|
||||
}
|
||||
|
||||
public Task<long> BulkInsertAsync(string table, IReadOnlyList<string> columns, IAsyncEnumerable<object?[]> rows, CancellationToken cancellationToken)
|
||||
{
|
||||
if (columns.Count == 0) throw new ArgumentException("At least one column is required.", nameof(columns));
|
||||
var sql = $"COPY {SqlDialect.QuoteIdentifier(table)} ({string.Join(", ", columns.Select(SqlDialect.QuoteIdentifier))}) FROM STDIN";
|
||||
return Connector.CopyInAsync(sql, columns.Count, rows, cancellationToken);
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
if (_connector is not { } connection) return;
|
||||
_connector = null;
|
||||
if (_transaction is not null && !connection.IsBroken)
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
_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)
|
||||
{
|
||||
if (_transaction != transaction) return;
|
||||
try
|
||||
{
|
||||
if (!commit)
|
||||
{
|
||||
await Connector.SimpleQueryAsync("ROLLBACK", cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else if (Connector.TransactionStatus == 'E')
|
||||
{
|
||||
await Connector.SimpleQueryAsync("ROLLBACK", cancellationToken).ConfigureAwait(false);
|
||||
throw new InvalidOperationException("The transaction was aborted by an earlier error and has been rolled back.");
|
||||
}
|
||||
else if (await Connector.SimpleQueryAsync("COMMIT", cancellationToken).ConfigureAwait(false) == "ROLLBACK")
|
||||
{
|
||||
throw new InvalidOperationException("The server rolled the transaction back instead of committing it.");
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (_connector is not { IsBroken: false, TransactionStatus: not 'I' }) _transaction = null;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsConnectionFailure(Exception ex) =>
|
||||
ex is DatabaseConnectionException or PostgresException { IsConnectionFailure: true };
|
||||
|
||||
/// <summary>True for statements that only read, so running them twice is harmless.</summary>
|
||||
internal static bool IsReadOnlyQuery(string sql)
|
||||
{
|
||||
var s = sql.AsSpan();
|
||||
while (true)
|
||||
{
|
||||
s = s.TrimStart();
|
||||
if (s.StartsWith("--", StringComparison.Ordinal))
|
||||
{
|
||||
var newline = s.IndexOf('\n');
|
||||
s = newline < 0 ? default : s[(newline + 1)..];
|
||||
}
|
||||
else if (s.StartsWith("/*", StringComparison.Ordinal))
|
||||
{
|
||||
var end = s.IndexOf("*/", StringComparison.Ordinal);
|
||||
s = end < 0 ? default : s[(end + 2)..];
|
||||
}
|
||||
else
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
foreach (var keyword in (ReadOnlySpan<string>)["SELECT", "VALUES", "SHOW", "TABLE"])
|
||||
{
|
||||
if (s.StartsWith(keyword, StringComparison.OrdinalIgnoreCase)
|
||||
&& (s.Length == keyword.Length || !(char.IsLetterOrDigit(s[keyword.Length]) || s[keyword.Length] == '_')))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A BEGIN … COMMIT block on one session.</summary>
|
||||
internal sealed class PostgresTransaction(PostgresSession session) : IDbTransaction
|
||||
{
|
||||
private bool _completed;
|
||||
|
||||
public async Task CommitAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_completed, this);
|
||||
_completed = true;
|
||||
await session.EndTransactionAsync(this, commit: true, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async Task RollbackAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_completed, this);
|
||||
_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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
namespace Titano.Data.Postgres;
|
||||
|
||||
/// <summary>An ErrorResponse from the server, with the standard fields of the PostgreSQL protocol.</summary>
|
||||
public sealed class PostgresException : DatabaseException
|
||||
{
|
||||
internal PostgresException(string severity, string sqlState, string messageText)
|
||||
: base($"{severity} {sqlState}: {messageText}")
|
||||
{
|
||||
Severity = severity;
|
||||
SqlState = sqlState;
|
||||
MessageText = messageText;
|
||||
}
|
||||
|
||||
/// <summary>ERROR, FATAL or PANIC (non-localised when the server sends it).</summary>
|
||||
public string Severity { get; }
|
||||
|
||||
/// <summary>Five-character SQLSTATE, e.g. 23505 (unique_violation).</summary>
|
||||
public override string SqlState { get; }
|
||||
|
||||
/// <summary>The primary human-readable message.</summary>
|
||||
public string MessageText { get; }
|
||||
|
||||
public string? Detail { get; internal init; }
|
||||
public string? Hint { get; internal init; }
|
||||
|
||||
/// <summary>1-based character position of the error in the statement text.</summary>
|
||||
public int? Position { get; internal init; }
|
||||
|
||||
public string? Where { get; internal init; }
|
||||
public string? SchemaName { get; internal init; }
|
||||
public string? TableName { get; internal init; }
|
||||
public string? ColumnName { get; internal init; }
|
||||
public string? ConstraintName { get; internal init; }
|
||||
|
||||
/// <summary>The server ends the session after FATAL/PANIC errors.</summary>
|
||||
public bool IsFatal => Severity is "FATAL" or "PANIC";
|
||||
|
||||
/// <summary>Server shutdown/startup or connection failures (57P01, 57P02, 57P03, class 08): a new connection may succeed.</summary>
|
||||
public bool IsConnectionFailure => SqlState is "57P01" or "57P02" or "57P03" || SqlState.StartsWith("08", StringComparison.Ordinal);
|
||||
|
||||
/// <summary>Connection failures plus serialization failures and deadlocks.</summary>
|
||||
public override bool IsTransient => IsConnectionFailure || SqlState is "40001" or "40P01";
|
||||
|
||||
public override bool IsUniqueViolation => SqlState == "23505";
|
||||
|
||||
public override bool IsForeignKeyViolation => SqlState == "23503";
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
namespace Titano.Data.Postgres;
|
||||
|
||||
/// <summary>TLS policy, with libpq's meaning.</summary>
|
||||
public enum SslMode
|
||||
{
|
||||
/// <summary>Plain TCP.</summary>
|
||||
Disable,
|
||||
|
||||
/// <summary>TLS when the server offers it, without certificate verification; plain TCP otherwise.</summary>
|
||||
Prefer,
|
||||
|
||||
/// <summary>TLS or fail; the certificate is not verified.</summary>
|
||||
Require,
|
||||
|
||||
/// <summary>TLS with a trusted chain whose certificate matches the host name.</summary>
|
||||
VerifyFull,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// PostgreSQL connection settings. Keys (case/space-insensitive): <c>Host</c>, <c>Port</c> (5432), <c>Database</c>
|
||||
/// (defaults to the user), <c>Username</c>, <c>Password</c>, <c>SslMode</c> (prefer), <c>Root Certificate</c>
|
||||
/// (PEM trusted by verify-full), <c>Application Name</c> (titano-server), <c>Search Path</c>, <c>Timeout</c>
|
||||
/// (connect, 15 s), <c>Minimum Pool Size</c> (0), <c>Maximum Pool Size</c> (20), <c>Connection Idle Lifetime</c>
|
||||
/// (300 s), <c>Health Check Interval</c> (30 s idle before a pooled connection is pinged),
|
||||
/// <c>Statement Cache Size</c> (128 prepared statements per connection; 0 disables).
|
||||
/// </summary>
|
||||
public sealed record PostgresSettings
|
||||
{
|
||||
public required string Host { get; init; }
|
||||
public int Port { get; init; } = 5432;
|
||||
public required string Database { get; init; }
|
||||
public required string Username { get; init; }
|
||||
public string? Password { get; init; }
|
||||
public SslMode SslMode { get; init; } = SslMode.Prefer;
|
||||
public string? RootCertificate { get; init; }
|
||||
public string ApplicationName { get; init; } = "titano-server";
|
||||
public string? SearchPath { get; init; }
|
||||
public TimeSpan ConnectTimeout { get; init; } = TimeSpan.FromSeconds(15);
|
||||
public int MinPoolSize { get; init; }
|
||||
public int MaxPoolSize { get; init; } = 20;
|
||||
public TimeSpan IdleLifetime { get; init; } = TimeSpan.FromSeconds(300);
|
||||
public TimeSpan HealthCheckInterval { get; init; } = TimeSpan.FromSeconds(30);
|
||||
public int StatementCacheSize { get; init; } = 128;
|
||||
|
||||
public static PostgresSettings Parse(string connectionString)
|
||||
{
|
||||
var cs = new ConnectionString(connectionString);
|
||||
var host = cs.Get("Host", "Server") ?? throw new FormatException("A PostgreSQL connection string needs 'Host'.");
|
||||
var user = cs.Get("Username", "User Id", "User", "UserName") ?? throw new FormatException("A PostgreSQL connection string needs 'Username'.");
|
||||
var settings = new PostgresSettings
|
||||
{
|
||||
Host = host,
|
||||
Port = cs.GetInt(5432, "Port"),
|
||||
Username = user,
|
||||
Database = cs.Get("Database", "DB") ?? user,
|
||||
Password = cs.Get("Password", "Pwd"),
|
||||
SslMode = ParseSslMode(cs.Get("SslMode", "Ssl Mode")),
|
||||
RootCertificate = cs.Get("Root Certificate", "SslRootCert"),
|
||||
ApplicationName = cs.Get("Application Name") ?? "titano-server",
|
||||
SearchPath = cs.Get("Search Path"),
|
||||
ConnectTimeout = TimeSpan.FromSeconds(cs.GetInt(15, "Timeout", "Connect Timeout")),
|
||||
MinPoolSize = cs.GetInt(0, "Minimum Pool Size", "Min Pool Size"),
|
||||
MaxPoolSize = cs.GetInt(20, "Maximum Pool Size", "Max Pool Size"),
|
||||
IdleLifetime = TimeSpan.FromSeconds(cs.GetInt(300, "Connection Idle Lifetime")),
|
||||
HealthCheckInterval = TimeSpan.FromSeconds(cs.GetInt(30, "Health Check Interval")),
|
||||
StatementCacheSize = cs.GetInt(128, "Statement Cache Size", "Max Auto Prepare"),
|
||||
};
|
||||
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.");
|
||||
return settings;
|
||||
}
|
||||
|
||||
private static SslMode ParseSslMode(string? value) => value?.Trim().ToLowerInvariant() switch
|
||||
{
|
||||
null or "" or "prefer" => SslMode.Prefer,
|
||||
"disable" => SslMode.Disable,
|
||||
"require" => SslMode.Require,
|
||||
"verify-full" or "verifyfull" => SslMode.VerifyFull,
|
||||
_ => throw new FormatException($"Unsupported SslMode '{value}' (use disable, prefer, require or verify-full)."),
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user