From 8d9b04c713687f6151a9c03bb60e11c252764719 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:13:09 +0000 Subject: [PATCH] refactor(data): pin server output settings and guard busy connections Pin bytea_output=hex and standard_conforming_strings=on in the startup packet instead of tracking ParameterStatus values nobody read, so the legacy bytea escape decoder goes away. A PostgreSQL connection now refuses a new command while a row stream is still open, and the pool discards such a connection. Drop unused SQLite declarations. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Data/Postgres/PgConnector.cs | 21 ++++---- src/Titano.Data/Postgres/PgPool.cs | 4 +- src/Titano.Data/Postgres/PgTypes.cs | 51 +++++++------------ src/Titano.Data/Sqlite/SqliteNative.cs | 2 - src/Titano.Data/Sqlite/SqliteSession.cs | 4 +- .../Postgres/PgProtocolUnitTests.cs | 9 ++-- .../Titano.Data.Tests/Postgres/PgWireTests.cs | 11 ++++ 7 files changed, 51 insertions(+), 51 deletions(-) diff --git a/src/Titano.Data/Postgres/PgConnector.cs b/src/Titano.Data/Postgres/PgConnector.cs index 21c2bf52..a06d5292 100644 --- a/src/Titano.Data/Postgres/PgConnector.cs +++ b/src/Titano.Data/Postgres/PgConnector.cs @@ -36,7 +36,6 @@ internal sealed class PgConnector : IAsyncDisposable private readonly Dictionary> _statements = new(StringComparer.Ordinal); private readonly LinkedList _statementLru = new(); private readonly List _statementsToClose = []; - private readonly Dictionary _serverParameters = new(StringComparer.Ordinal); private byte[] _read = new byte[16 * 1024]; private int _readPos; private int _readEnd; @@ -48,6 +47,7 @@ internal sealed class PgConnector : IAsyncDisposable private int _disposed; private CancellationTokenSource _ioAbort = new(); private Task _pendingCancel = Task.CompletedTask; + private Operation? _active; private PgConnector(PostgresSettings settings, Socket socket, Stream stream) { @@ -64,9 +64,10 @@ internal sealed class PgConnector : IAsyncDisposable /// Last ReadyForQuery status: 'I' idle, 'T' in transaction, 'E' failed transaction. public char TransactionStatus { get; private set; } = 'I'; - public TimeSpan IdleTime => TimeSpan.FromMilliseconds(Environment.TickCount64 - _idleSince); + /// A command's response is still being read (an enumeration that was neither finished nor disposed). + public bool IsBusy => _active is not null; - public IReadOnlyDictionary ServerParameters => _serverParameters; + public TimeSpan IdleTime => TimeSpan.FromMilliseconds(Environment.TickCount64 - _idleSince); /// Receives NotificationResponse messages (listener connections). public Action? NotificationReceived { get; set; } @@ -379,6 +380,9 @@ internal sealed class PgConnector : IAsyncDisposable Parameter("TimeZone", "UTC"); Parameter("DateStyle", "ISO, MDY"); Parameter("extra_float_digits", "3"); + Parameter("bytea_output", "hex"); + // LIKE … ESCAPE '\' in the repositories needs backslashes to be literal in string constants. + Parameter("standard_conforming_strings", "on"); if (_settings.SearchPath is { } searchPath) Parameter("search_path", searchPath); _write.WriteByte(0); _write.EndMessage(); @@ -469,8 +473,10 @@ internal sealed class PgConnector : IAsyncDisposable private Operation StartOperation(string sql, DbParam[] parameters, bool decodeRows, CancellationToken cancellationToken) { if (IsBroken) throw new DatabaseConnectionException("The connection is broken."); + if (IsBusy) throw new InvalidOperationException("A command is still running on this session; finish or dispose its enumeration first."); cancellationToken.ThrowIfCancellationRequested(); var op = new Operation(this, sql, parameters, decodeRows, cancellationToken); + _active = op; if (cancellationToken.CanBeCanceled) op.Registration = cancellationToken.UnsafeRegister(static state => ((Operation)state!).Owner.RequestCancel((Operation)state!), op); return op; @@ -545,6 +551,7 @@ internal sealed class PgConnector : IAsyncDisposable _ioAbort.Dispose(); _ioAbort = new CancellationTokenSource(); } + _active = null; MarkIdle(); } } @@ -846,12 +853,8 @@ internal sealed class PgConnector : IAsyncDisposable LogNotice(); continue; case (byte)'S': - { - var pos = 0; - var name = ReadCString(Payload, ref pos); - _serverParameters[name] = ReadCString(Payload, ref pos); - continue; - } + // ParameterStatus: the settings the decoder relies on are pinned in the startup packet. + continue; case (byte)'A': { var pos = 4; diff --git a/src/Titano.Data/Postgres/PgPool.cs b/src/Titano.Data/Postgres/PgPool.cs index 2e2002b6..8f2beb39 100644 --- a/src/Titano.Data/Postgres/PgPool.cs +++ b/src/Titano.Data/Postgres/PgPool.cs @@ -52,11 +52,11 @@ internal sealed class PgPool : IAsyncDisposable } } - /// Takes a connection back; a broken one, or one not idle at transaction level, is closed instead. + /// 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.TransactionStatus == 'I') + if (!connector.IsBroken && !connector.IsBusy && connector.TransactionStatus == 'I') { connector.MarkIdle(); lock (_gate) diff --git a/src/Titano.Data/Postgres/PgTypes.cs b/src/Titano.Data/Postgres/PgTypes.cs index 1f06cd9b..443a0ad5 100644 --- a/src/Titano.Data/Postgres/PgTypes.cs +++ b/src/Titano.Data/Postgres/PgTypes.cs @@ -10,22 +10,16 @@ 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; @@ -151,7 +145,10 @@ internal static class PgTypes } } - /// Decodes a text-format result value by its type OID; unknown types stay strings. + /// + /// 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. + /// public static object Decode(uint oid, ReadOnlySpan utf8) { var inv = CultureInfo.InvariantCulture; @@ -185,35 +182,23 @@ internal static class PgTypes } } - /// bytea output: hex (\x0a0b, the default since 9.0) or the legacy escape format. + /// bytea in hex output format (\x0a0b), which the startup packet pins with bytea_output=hex. private static byte[] DecodeBytea(ReadOnlySpan text) { - if (text.Length >= 2 && text[0] == '\\' && text[1] == 'x') - return Convert.FromHexString(Encoding.ASCII.GetString(text[2..])); - var result = new List(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]; + 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 HexDigits => "0123456789abcdef"u8; } diff --git a/src/Titano.Data/Sqlite/SqliteNative.cs b/src/Titano.Data/Sqlite/SqliteNative.cs index 95fe8590..97938b91 100644 --- a/src/Titano.Data/Sqlite/SqliteNative.cs +++ b/src/Titano.Data/Sqlite/SqliteNative.cs @@ -14,7 +14,6 @@ internal static unsafe class SqliteNative private static int _resolverInstalled; public const int SQLITE_OK = 0; - public const int SQLITE_ERROR = 1; public const int SQLITE_INTERRUPT = 9; public const int SQLITE_BUSY = 5; public const int SQLITE_LOCKED = 6; @@ -70,7 +69,6 @@ internal static unsafe class SqliteNative [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_exec(nint db, byte* sql, nint callback, nint arg, out byte* errmsg); [DllImport(Library, ExactSpelling = true)] public static extern void sqlite3_free(void* p); [DllImport(Library, ExactSpelling = true)] public static extern byte* sqlite3_errmsg(nint db); - [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_extended_errcode(nint db); [DllImport(Library, ExactSpelling = true)] public static extern void sqlite3_interrupt(nint db); [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_changes(nint db); [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_total_changes(nint db); diff --git a/src/Titano.Data/Sqlite/SqliteSession.cs b/src/Titano.Data/Sqlite/SqliteSession.cs index 472a3155..4954f572 100644 --- a/src/Titano.Data/Sqlite/SqliteSession.cs +++ b/src/Titano.Data/Sqlite/SqliteSession.cs @@ -6,8 +6,8 @@ namespace Titano.Data.Sqlite; /// /// A pooled SQLite connection. Statements that write take the database write lock for their duration when no -/// transaction holds it already; SQLITE_BUSY/LOCKED from other processes is retried a few times outside -/// transactions. Cancellation interrupts the running statement with sqlite3_interrupt. +/// transaction holds it already; lock conflicts are retried (see ). Cancellation +/// interrupts the running statement with sqlite3_interrupt. /// internal sealed class SqliteSession(SqliteDatabase database, SqliteConnection connection) : IDbSession { diff --git a/tests/Titano.Data.Tests/Postgres/PgProtocolUnitTests.cs b/tests/Titano.Data.Tests/Postgres/PgProtocolUnitTests.cs index 5e1ac58d..51e76d87 100644 --- a/tests/Titano.Data.Tests/Postgres/PgProtocolUnitTests.cs +++ b/tests/Titano.Data.Tests/Postgres/PgProtocolUnitTests.cs @@ -61,10 +61,13 @@ public sealed class PgProtocolUnitTests } [Test] - public void DecodesByteaInHexAndEscapeFormats() + public void DecodesHexByteaAndRejectsOtherForms() { - Assert.BytesEqual(new byte[] { 0xDE, 0xAD }, (byte[])PgTypes.Decode(PgTypes.Bytea, "\\xdead"u8)); - Assert.BytesEqual(new byte[] { (byte)'a', 0, (byte)'\\', 0xFF }, (byte[])PgTypes.Decode(PgTypes.Bytea, "a\\000\\\\\\377"u8)); + Assert.BytesEqual(new byte[] { 0xDE, 0xAD, 0x01 }, (byte[])PgTypes.Decode(PgTypes.Bytea, "\\xdeAD01"u8)); + Assert.Equal(0, ((byte[])PgTypes.Decode(PgTypes.Bytea, "\\x"u8)).Length); + Assert.Throws(() => PgTypes.Decode(PgTypes.Bytea, "a\\000"u8)); + Assert.Throws(() => PgTypes.Decode(PgTypes.Bytea, "\\xabc"u8)); + Assert.Throws(() => PgTypes.Decode(PgTypes.Bytea, "\\xzz"u8)); } [Theory] diff --git a/tests/Titano.Data.Tests/Postgres/PgWireTests.cs b/tests/Titano.Data.Tests/Postgres/PgWireTests.cs index 4e7ebfba..b9f15d97 100644 --- a/tests/Titano.Data.Tests/Postgres/PgWireTests.cs +++ b/tests/Titano.Data.Tests/Postgres/PgWireTests.cs @@ -260,6 +260,17 @@ public sealed class PgWireTests(TestContext context) : DatabaseTest(context) Assert.Equal("x", second.GetString("b")); } + [Test] + public async Task ACommandCannotStartWhileARowStreamIsOpen() + { + await using var session = await (await OpenAsync()).OpenAsync(Ct); + var rows = session.QueryAsync("SELECT generate_series(1, 1000)", [], Ct).GetAsyncEnumerator(Ct); + Assert.True(await rows.MoveNextAsync()); + await Assert.ThrowsAsync(() => session.ExecuteAsync("SELECT 1", [], Ct)); + await rows.DisposeAsync(); + Assert.Equal(1, await session.ScalarAsync("SELECT 1", [], Ct)); + } + [Test] public async Task NoticesAndScriptsDoNotDisturbTheSession() {