refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s

The owner renamed the product and moved the repository to the self-hosted
Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control,
and asked for Actions and a first automatic release with the server package
and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md).

- Chronos everywhere: a byte-exact rename of contents and paths, then a
  per-language review of the forms the old name's ending had dictated.
- Gitea instead of GitHub: the update check, licence, issue and support
  links read ChronosReleasesUrl; the update check takes the highest stable
  version, offers a pre-release build its final release and reports a
  repository it cannot see as a failed check. EULA, security policy and
  Gitea issue forms live at the repository root.
- Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release,
  nightly image and performance gates in the .NET SDK container with git
  checkout and the system SQLite. The release cross-compiles the Windows
  programs, checks their icon, version and DPI manifest, packs installers
  and zips, publishes the Gitea release and pushes the server image
  (REGISTRY_TOKEN). Windows-only tests run in an opt-in job on a Windows
  runner (WINDOWS_RUNNER).
- New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the
  docker-exec script, which Gitea's service containers do not allow; the
  throw-away server runs without durability) and pe-check.
- Timed tests take their budget from TestTiming (CHRONOS_TEST_TIME_FACTOR,
  3 on the shared runner; the weekly performance gates keep theirs).

BREAKING CHANGE: programs, settings, data folders, file types, environment
variables and the Docker image use the new name; nothing is migrated from
Titano, which never had a release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #6.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-10-23 12:45:18 +02:00
1 parent c99842cc86
commit f2b58522b9
1801 files changed
+11804 -10676

No files matched your search

@@ -0,0 +1,141 @@
using System.Globalization;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Text;
namespace Chronos.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";
/// <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}";
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.");
IsServerVerified = true;
}
/// <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
+118
View File
@@ -0,0 +1,118 @@
using Chronos.Core.Diagnostics;
namespace Chronos.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 readonly Lock _gate = new();
private TaskCompletionSource<PostgresException?>? _pending;
private bool _closed;
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();
}
/// <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
{
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);
}
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(OnCommandCompleted, _stop.Token).ConfigureAwait(false);
}
catch (Exception) when (_stop.IsCancellationRequested)
{
}
finally
{
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
{
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);
}
}
}
+138
View File
@@ -0,0 +1,138 @@
using System.Net.Sockets;
using Chronos.Core.Diagnostics;
namespace Chronos.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)
{
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;
}
}
/// <summary>Takes a connection back; a broken or busy one, or one inside a transaction, is closed instead.</summary>
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<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();
}
}
+204
View File
@@ -0,0 +1,204 @@
using System.Buffers;
using System.Buffers.Text;
using System.Globalization;
using System.Text;
namespace Chronos.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 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 Float4 = 700;
public const uint Float8 = 701;
public const uint Date = 1082;
public const uint Timestamp = 1114;
public const uint TimestampTz = 1184;
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. Every other type (text, varchar, bpchar, name, json,
/// jsonb, numeric, …) stays a string, which is also how numeric is meant to be read.
/// </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 in hex output format (<c>\x0a0b</c>), which the startup packet pins with <c>bytea_output=hex</c>.</summary>
private static byte[] DecodeBytea(ReadOnlySpan<byte> text)
{
if (text.Length < 2 || text[0] != '\\' || text[1] != 'x' || text.Length % 2 != 0)
throw new FormatException("A bytea value is not in hex output format.");
var result = new byte[(text.Length - 2) / 2];
for (var i = 0; i < result.Length; i++) result[i] = (byte)((HexValue(text[2 + 2 * i]) << 4) | HexValue(text[3 + 2 * i]));
return result;
}
private static int HexValue(byte c) => c switch
{
>= (byte)'0' and <= (byte)'9' => c - '0',
>= (byte)'a' and <= (byte)'f' => c - 'a' + 10,
>= (byte)'A' and <= (byte)'F' => c - 'A' + 10,
_ => throw new FormatException("Invalid hex digit in a bytea value."),
};
private static ReadOnlySpan<byte> HexDigits => "0123456789abcdef"u8;
}
@@ -0,0 +1,98 @@
using System.Buffers;
using System.Buffers.Binary;
using System.Text;
namespace Chronos.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,233 @@
using System.Runtime.CompilerServices;
using Chronos.Core.Diagnostics;
namespace Chronos.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;
try
{
if (_transaction is not null) await RollBackQuietlyAsync(connection).ConfigureAwait(false);
}
finally
{
_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. 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 (disposing)
{
if (_connector is { } connection) await RollBackQuietlyAsync(connection).ConfigureAwait(false);
}
else 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 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 };
/// <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);
await session.EndTransactionAsync(this, commit: true, disposing: false, cancellationToken).ConfigureAwait(false);
_completed = true;
}
public async Task RollbackAsync(CancellationToken cancellationToken = default)
{
ObjectDisposedException.ThrowIf(_completed, this);
await session.EndTransactionAsync(this, commit: false, disposing: false, cancellationToken).ConfigureAwait(false);
_completed = true;
}
public async ValueTask DisposeAsync()
{
if (_completed) return;
_completed = true;
await session.EndTransactionAsync(this, commit: false, disposing: true, CancellationToken.None).ConfigureAwait(false);
}
}
@@ -0,0 +1,47 @@
namespace Chronos.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 Chronos.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> (chronos-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; } = "chronos-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") ?? "chronos-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 || settings.IdleLifetime <= TimeSpan.Zero)
throw new FormatException("'Statement Cache Size' must be ≥ 0; 'Timeout' and 'Connection Idle Lifetime' must be > 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)."),
};
}