diff --git a/src/Titano.Data/ConnectionString.cs b/src/Titano.Data/ConnectionString.cs new file mode 100644 index 00000000..849656e4 --- /dev/null +++ b/src/Titano.Data/ConnectionString.cs @@ -0,0 +1,111 @@ +using System.Globalization; +using System.Text; + +namespace Titano.Data; + +/// +/// key=value;… connection strings. Keys are case- and space-insensitive (SslMode = Ssl Mode); +/// values may be single- or double-quoted, with the quote doubled inside. +/// +internal sealed class ConnectionString +{ + private readonly Dictionary _values = new(StringComparer.Ordinal); + private readonly HashSet _used = new(StringComparer.Ordinal); + + public ConnectionString(string text) + { + var i = 0; + while (i < text.Length) + { + var eq = text.IndexOf('=', i); + if (eq < 0) + { + if (text.AsSpan(i).Trim().Trim(';').IsEmpty) break; + throw new FormatException($"Connection string segment '{text[i..].Trim()}' has no '='."); + } + var key = Normalize(text.AsSpan(i, eq - i).Trim().TrimStart(';')); + i = eq + 1; + while (i < text.Length && char.IsWhiteSpace(text[i])) i++; + string value; + if (i < text.Length && text[i] is '"' or '\'') + { + var quote = text[i++]; + var sb = new StringBuilder(); + while (true) + { + if (i >= text.Length) throw new FormatException("Unterminated quoted value in connection string."); + if (text[i] == quote) + { + if (i + 1 < text.Length && text[i + 1] == quote) + { + sb.Append(quote); + i += 2; + continue; + } + i++; + break; + } + sb.Append(text[i++]); + } + value = sb.ToString(); + while (i < text.Length && char.IsWhiteSpace(text[i])) i++; + if (i < text.Length && text[i] != ';') throw new FormatException("Unexpected text after a quoted connection string value."); + } + else + { + var end = text.IndexOf(';', i); + if (end < 0) end = text.Length; + value = text[i..end].Trim(); + i = end; + } + if (key.Length == 0) throw new FormatException("Empty key in connection string."); + _values[key] = value; + if (i < text.Length && text[i] == ';') i++; + } + } + + /// First present key among (synonyms), or null. + public string? Get(params string[] keys) + { + foreach (var key in keys) + { + var normalized = Normalize(key); + if (_values.TryGetValue(normalized, out var value)) + { + _used.Add(normalized); + return value; + } + } + return null; + } + + public int GetInt(int defaultValue, params string[] keys) + { + var text = Get(keys); + if (text is null) return defaultValue; + return int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value) + ? value + : throw new FormatException($"Connection string value '{keys[0]}' must be an integer."); + } + + public bool Contains(string key) => _values.ContainsKey(Normalize(key)); + + /// Rejects keys that no call consumed, so typos do not pass silently. + public void ThrowOnUnknownKeys() + { + foreach (var key in _values.Keys) + { + if (!_used.Contains(key)) throw new FormatException($"Unknown connection string key '{key}'."); + } + } + + private static string Normalize(ReadOnlySpan key) + { + var sb = new StringBuilder(key.Length); + foreach (var c in key) + { + if (!char.IsWhiteSpace(c)) sb.Append(char.ToLowerInvariant(c)); + } + return sb.ToString(); + } +} diff --git a/src/Titano.Data/DatabaseException.cs b/src/Titano.Data/DatabaseException.cs new file mode 100644 index 00000000..413c271b --- /dev/null +++ b/src/Titano.Data/DatabaseException.cs @@ -0,0 +1,34 @@ +using System.Data.Common; + +namespace Titano.Data; + +/// Base of errors reported by a database engine; repositories test the kind without knowing the dialect. +public abstract class DatabaseException : DbException +{ + protected DatabaseException(string message, Exception? innerException = null) + : base(message, innerException) + { + } + + /// A UNIQUE or PRIMARY KEY constraint rejected the statement. + public virtual bool IsUniqueViolation => false; + + /// A FOREIGN KEY constraint rejected the statement. + public virtual bool IsForeignKeyViolation => false; +} + +/// The connection to the database server could not be established or was lost. +public sealed class DatabaseConnectionException(string message, Exception? innerException = null) + : DatabaseException(message, innerException) +{ + public override bool IsTransient => true; +} + +/// The database was migrated by a newer build; opening it would risk corrupting data this build does not know. +public sealed class SchemaTooNewException(int databaseVersion, int supportedVersion) + : InvalidOperationException($"The database schema version {databaseVersion} is newer than the version {supportedVersion} this build supports.") +{ + public int DatabaseVersion { get; } = databaseVersion; + + public int SupportedVersion { get; } = supportedVersion; +} diff --git a/src/Titano.Data/DatabaseOptions.cs b/src/Titano.Data/DatabaseOptions.cs new file mode 100644 index 00000000..6d857a27 --- /dev/null +++ b/src/Titano.Data/DatabaseOptions.cs @@ -0,0 +1,54 @@ +using Titano.Data.Postgres; +using Titano.Data.Sqlite; + +namespace Titano.Data; + +/// Which engine to open and how to reach it. +/// +/// SQLite: Data Source=<path>|:memory:;Pool Size=4. +/// PostgreSQL: Host=…;Port=5432;Database=…;Username=…;Password=…;SslMode=disable|prefer|require|verify-full +/// plus the optional keys listed on . +/// +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) + "'", + }; + + /// A private in-memory SQLite database that lives until the is disposed. + public static DatabaseOptions SqliteInMemory() => new() { Dialect = Dialect.Sqlite, ConnectionString = "Data Source=:memory:" }; + + public static DatabaseOptions Postgres(string connectionString) => new() { Dialect = Dialect.Postgres, ConnectionString = connectionString }; + + /// + /// Infers the dialect: a string with Host/Server is PostgreSQL; Data Source or a bare + /// path (no =) is SQLite. + /// + 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."); + } +} + +/// Builds the implementation for a set of options. +public static class DatabaseFactory +{ + /// Creates the database object; SQLite opens the file now, PostgreSQL connects on the first session. + 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."), + }; +} diff --git a/src/Titano.Data/DbParam.cs b/src/Titano.Data/DbParam.cs new file mode 100644 index 00000000..f6790b84 --- /dev/null +++ b/src/Titano.Data/DbParam.cs @@ -0,0 +1,125 @@ +namespace Titano.Data; + +/// Logical type of a : decides the SQLite binding and the PostgreSQL parameter type. +public enum DbValueType +{ + /// Inferred from the CLR type of the value; a null stays untyped. + Auto, + Text, + Int32, + Int64, + Double, + Bool, + Uuid, + + /// An instant, stored in UTC (timestamptz / ISO-8601 text ending in Z). + Timestamp, + + /// A wall-clock date and time without offset (timestamp / ISO-8601 text without zone). + LocalDateTime, + + Bytes, + + /// JSON text (jsonb on PostgreSQL, TEXT on SQLite). + Json, +} + +/// +/// A positional statement parameter: the n-th parameter binds to $n in the SQL text on both dialects. +/// Implicit conversions keep the CLR type even for nulls, so (Guid?)null is still a typed uuid. +/// +public readonly struct DbParam +{ + public DbParam(object? value, DbValueType type = DbValueType.Auto, string? name = null) + { + Name = name; + Type = type == DbValueType.Auto && value is not null ? Infer(value) : type; + Value = value is null ? null : Normalize(value, Type); + } + + /// Optional label used in diagnostics only; binding is by position. + public string? Name { get; } + + /// + /// The value in the canonical CLR form of : string (Text, Json), int, long, double, bool, + /// Guid, DateTimeOffset (Timestamp), DateTime (LocalDateTime) or byte[]. + /// + public object? Value { get; } + + /// Effective type; only for an untyped null. + public DbValueType Type { get; } + + /// An untyped SQL NULL. + public static DbParam Null => default; + + public static DbParam Text(string? value) => new(value, DbValueType.Text); + public static DbParam Json(string? value) => new(value, DbValueType.Json); + public static DbParam Bytes(byte[]? value) => new(value, DbValueType.Bytes); + + /// Maps a CLR value to the type it binds as; throws for unsupported types. + public static DbValueType Infer(object value) => value switch + { + string => DbValueType.Text, + int or short or byte or sbyte or ushort => DbValueType.Int32, + long or uint or ulong => DbValueType.Int64, + double or float => DbValueType.Double, + bool => DbValueType.Bool, + Guid => DbValueType.Uuid, + DateTimeOffset => DbValueType.Timestamp, + DateTime d => d.Kind == DateTimeKind.Unspecified ? DbValueType.LocalDateTime : DbValueType.Timestamp, + byte[] => DbValueType.Bytes, + Enum => DbValueType.Int64, + _ => throw new NotSupportedException($"Parameter values of type {value.GetType().Name} are not supported."), + }; + + private static object Normalize(object value, DbValueType type) + { + var inv = System.Globalization.CultureInfo.InvariantCulture; + return type switch + { + DbValueType.Text or DbValueType.Json => value as string ?? Convert.ToString(value, inv) ?? string.Empty, + DbValueType.Int32 => value is int ? value : Convert.ToInt32(value, inv), + DbValueType.Int64 => value is long ? value : Convert.ToInt64(value, inv), + DbValueType.Double => value is double ? value : Convert.ToDouble(value, inv), + DbValueType.Bool => value is bool ? value : Convert.ToBoolean(value, inv), + DbValueType.Uuid => value is Guid ? value : Guid.Parse(Convert.ToString(value, inv)!), + DbValueType.Timestamp => value switch + { + DateTimeOffset o => o, + DateTime { Kind: DateTimeKind.Unspecified } d => new DateTimeOffset(d, TimeSpan.Zero), + DateTime d => new DateTimeOffset(d.ToUniversalTime()), + _ => throw new NotSupportedException($"Cannot bind {value.GetType().Name} as a timestamp."), + }, + DbValueType.LocalDateTime => value switch + { + DateTime d => d, + DateTimeOffset o => o.DateTime, + _ => throw new NotSupportedException($"Cannot bind {value.GetType().Name} as a date-time."), + }, + DbValueType.Bytes => value as byte[] ?? throw new NotSupportedException($"Cannot bind {value.GetType().Name} as bytes."), + _ => value, + }; + } + + public static implicit operator DbParam(string? value) => new(value, DbValueType.Text); + public static implicit operator DbParam(byte[]? value) => new(value, DbValueType.Bytes); + public static implicit operator DbParam(int value) => new(value, DbValueType.Int32); + public static implicit operator DbParam(int? value) => new(value, DbValueType.Int32); + public static implicit operator DbParam(long value) => new(value, DbValueType.Int64); + public static implicit operator DbParam(long? value) => new(value, DbValueType.Int64); + public static implicit operator DbParam(double value) => new(value, DbValueType.Double); + public static implicit operator DbParam(double? value) => new(value, DbValueType.Double); + public static implicit operator DbParam(bool value) => new(value, DbValueType.Bool); + public static implicit operator DbParam(bool? value) => new(value, DbValueType.Bool); + public static implicit operator DbParam(Guid value) => new(value, DbValueType.Uuid); + public static implicit operator DbParam(Guid? value) => new(value, DbValueType.Uuid); + public static implicit operator DbParam(DateTimeOffset value) => new(value, DbValueType.Timestamp); + public static implicit operator DbParam(DateTimeOffset? value) => new(value, DbValueType.Timestamp); + + /// Unspecified-kind values are wall-clock times; UTC/local kinds are instants. + public static implicit operator DbParam(DateTime value) => new(value); + + public static implicit operator DbParam(DateTime? value) => value is { } v ? new(v) : new(null, DbValueType.LocalDateTime); + + public override string ToString() => $"{Name ?? "?"}:{Type}={Value ?? "NULL"}"; +} diff --git a/src/Titano.Data/DbRow.cs b/src/Titano.Data/DbRow.cs new file mode 100644 index 00000000..7af799c7 --- /dev/null +++ b/src/Titano.Data/DbRow.cs @@ -0,0 +1,200 @@ +using System.Globalization; + +namespace Titano.Data; + +/// Column names of a result set, shared by all of its rows. +internal sealed class DbColumns(string[] names) +{ + private Dictionary? _ordinals; + + public string[] Names { get; } = names; + + public int GetOrdinal(string name) + { + if (_ordinals is null) + { + var map = new Dictionary(Names.Length, StringComparer.OrdinalIgnoreCase); + for (var i = 0; i < Names.Length; i++) map.TryAdd(Names[i], i); + _ordinals = map; + } + return _ordinals.TryGetValue(name, out var ordinal) + ? ordinal + : throw new IndexOutOfRangeException($"No column named '{name}' in the result."); + } +} + +/// +/// One materialised result row. Values keep the provider's natural CLR type (SQLite: long, double, string, +/// byte[]; PostgreSQL: decoded by type OID) and the typed getters convert between compatible forms, so the +/// same mapping code reads both dialects (e.g. a SQLite TEXT uuid through ). +/// Rows stay valid after the enumeration that produced them ends. +/// +public sealed class DbRow +{ + private readonly DbColumns _columns; + private readonly object?[] _values; + + internal DbRow(DbColumns columns, object?[] values) + { + _columns = columns; + _values = values; + } + + public int FieldCount => _values.Length; + + public string GetName(int ordinal) => _columns.Names[ordinal]; + + /// Case-insensitive column lookup; the first column with that name wins. + public int GetOrdinal(string name) => _columns.GetOrdinal(name); + + public bool IsNull(int ordinal) => _values[ordinal] is null; + + public object? GetValue(int ordinal) => _values[ordinal]; + + public string GetString(int ordinal) => GetStringOrNull(ordinal) ?? throw NullValue(ordinal); + public int GetInt32(int ordinal) => GetInt32OrNull(ordinal) ?? throw NullValue(ordinal); + public long GetInt64(int ordinal) => GetInt64OrNull(ordinal) ?? throw NullValue(ordinal); + public double GetDouble(int ordinal) => GetDoubleOrNull(ordinal) ?? throw NullValue(ordinal); + public bool GetBool(int ordinal) => GetBoolOrNull(ordinal) ?? throw NullValue(ordinal); + public Guid GetGuid(int ordinal) => GetGuidOrNull(ordinal) ?? throw NullValue(ordinal); + public DateTimeOffset GetDateTimeOffset(int ordinal) => GetDateTimeOffsetOrNull(ordinal) ?? throw NullValue(ordinal); + public DateTime GetDateTime(int ordinal) => GetDateTimeOrNull(ordinal) ?? throw NullValue(ordinal); + public byte[] GetBytes(int ordinal) => GetBytesOrNull(ordinal) ?? throw NullValue(ordinal); + + public string? GetStringOrNull(int ordinal) => _values[ordinal] switch + { + null => null, + string s => s, + Guid g => TextValues.FormatGuid(g), + DateTimeOffset o => TextValues.FormatTimestamp(o), + DateTime d => TextValues.FormatLocal(d), + byte[] => throw Mismatch(ordinal, "string"), + var v => Convert.ToString(v, CultureInfo.InvariantCulture), + }; + + public int? GetInt32OrNull(int ordinal) => _values[ordinal] switch + { + null => null, + int i => i, + var v => checked((int)ToInt64(ordinal, v)), + }; + + public long? GetInt64OrNull(int ordinal) => _values[ordinal] is { } v ? ToInt64(ordinal, v) : null; + + public double? GetDoubleOrNull(int ordinal) => _values[ordinal] switch + { + null => null, + double d => d, + long l => l, + int i => i, + float f => f, + string s => double.Parse(s, NumberStyles.Float, CultureInfo.InvariantCulture), + _ => throw Mismatch(ordinal, "double"), + }; + + public bool? GetBoolOrNull(int ordinal) => _values[ordinal] switch + { + null => null, + bool b => b, + long l => l != 0, + int i => i != 0, + _ => throw Mismatch(ordinal, "bool"), + }; + + public Guid? GetGuidOrNull(int ordinal) => _values[ordinal] switch + { + null => null, + Guid g => g, + string s => Guid.Parse(s), + _ => throw Mismatch(ordinal, "Guid"), + }; + + /// Instants: timestamptz values, ISO-8601 text, or timestamp values taken as UTC. + public DateTimeOffset? GetDateTimeOffsetOrNull(int ordinal) => _values[ordinal] switch + { + null => null, + DateTimeOffset o => o, + string s => TextValues.ParseTimestamp(s), + DateTime d => new DateTimeOffset(DateTime.SpecifyKind(d, DateTimeKind.Utc)), + _ => throw Mismatch(ordinal, "DateTimeOffset"), + }; + + /// Wall-clock date-times (unspecified kind); instants are returned as UTC. + public DateTime? GetDateTimeOrNull(int ordinal) => _values[ordinal] switch + { + null => null, + DateTime d => d, + string s => TextValues.ParseLocal(s), + DateTimeOffset o => o.UtcDateTime, + DateOnly d => d.ToDateTime(TimeOnly.MinValue), + _ => throw Mismatch(ordinal, "DateTime"), + }; + + public byte[]? GetBytesOrNull(int ordinal) => _values[ordinal] switch + { + null => null, + byte[] b => b, + _ => throw Mismatch(ordinal, "byte[]"), + }; + + public string GetString(string name) => GetString(GetOrdinal(name)); + public string? GetStringOrNull(string name) => GetStringOrNull(GetOrdinal(name)); + public int GetInt32(string name) => GetInt32(GetOrdinal(name)); + public int? GetInt32OrNull(string name) => GetInt32OrNull(GetOrdinal(name)); + public long GetInt64(string name) => GetInt64(GetOrdinal(name)); + public long? GetInt64OrNull(string name) => GetInt64OrNull(GetOrdinal(name)); + public double GetDouble(string name) => GetDouble(GetOrdinal(name)); + public double? GetDoubleOrNull(string name) => GetDoubleOrNull(GetOrdinal(name)); + public bool GetBool(string name) => GetBool(GetOrdinal(name)); + public bool? GetBoolOrNull(string name) => GetBoolOrNull(GetOrdinal(name)); + public Guid GetGuid(string name) => GetGuid(GetOrdinal(name)); + public Guid? GetGuidOrNull(string name) => GetGuidOrNull(GetOrdinal(name)); + public DateTimeOffset GetDateTimeOffset(string name) => GetDateTimeOffset(GetOrdinal(name)); + public DateTimeOffset? GetDateTimeOffsetOrNull(string name) => GetDateTimeOffsetOrNull(GetOrdinal(name)); + public DateTime GetDateTime(string name) => GetDateTime(GetOrdinal(name)); + public DateTime? GetDateTimeOrNull(string name) => GetDateTimeOrNull(GetOrdinal(name)); + public byte[] GetBytes(string name) => GetBytes(GetOrdinal(name)); + public byte[]? GetBytesOrNull(string name) => GetBytesOrNull(GetOrdinal(name)); + + /// + /// Generic read used by scalar helpers: string, int, long, double, bool, Guid, DateTimeOffset, DateTime, + /// byte[], their nullable forms and enums (from integers). A null reads as default. + /// + public T? Get(int ordinal) + { + if (_values[ordinal] is null) return default; + var target = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T); + object value = target switch + { + _ when target == typeof(string) => GetString(ordinal), + _ when target == typeof(int) => GetInt32(ordinal), + _ when target == typeof(long) => GetInt64(ordinal), + _ when target == typeof(double) => GetDouble(ordinal), + _ when target == typeof(bool) => GetBool(ordinal), + _ when target == typeof(Guid) => GetGuid(ordinal), + _ when target == typeof(DateTimeOffset) => GetDateTimeOffset(ordinal), + _ when target == typeof(DateTime) => GetDateTime(ordinal), + _ when target == typeof(byte[]) => GetBytes(ordinal), + { IsEnum: true } => Enum.ToObject(target, GetInt64(ordinal)), + _ => _values[ordinal] is T ? _values[ordinal]! : throw Mismatch(ordinal, target.Name), + }; + return (T)value; + } + + private long ToInt64(int ordinal, object value) => value switch + { + long l => l, + int i => i, + short s => s, + bool b => b ? 1 : 0, + double d when d == Math.Floor(d) && d is >= long.MinValue and < long.MaxValue => (long)d, + string s => long.Parse(s, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture), + _ => throw Mismatch(ordinal, "integer"), + }; + + private InvalidCastException NullValue(int ordinal) => + new($"Column '{_columns.Names[ordinal]}' is NULL."); + + private InvalidCastException Mismatch(int ordinal, string target) => + new($"Column '{_columns.Names[ordinal]}' holds {_values[ordinal]!.GetType().Name}, which cannot be read as {target}."); +} diff --git a/src/Titano.Data/DbSessionExtensions.cs b/src/Titano.Data/DbSessionExtensions.cs new file mode 100644 index 00000000..af6fb729 --- /dev/null +++ b/src/Titano.Data/DbSessionExtensions.cs @@ -0,0 +1,55 @@ +namespace Titano.Data; + +/// Single-row, list and scalar helpers over . +public static class DbSessionExtensions +{ + /// The only row, or null when there is none; more than one row is an error. + public static async Task QuerySingleOrDefaultAsync(this IDbSession session, string sql, DbParam[] parameters, CancellationToken cancellationToken) + { + DbRow? found = null; + await foreach (var row in session.QueryAsync(sql, parameters, cancellationToken).ConfigureAwait(false)) + { + if (found is not null) throw new InvalidOperationException("The query returned more than one row."); + found = row; + } + return found; + } + + public static Task QuerySingleOrDefaultAsync(this IDbSession session, string sql, params DbParam[] parameters) => + session.QuerySingleOrDefaultAsync(sql, parameters, CancellationToken.None); + + /// The only row; none or more than one is an error. + public static async Task QuerySingleAsync(this IDbSession session, string sql, DbParam[] parameters, CancellationToken cancellationToken) => + await session.QuerySingleOrDefaultAsync(sql, parameters, cancellationToken).ConfigureAwait(false) + ?? throw new InvalidOperationException("The query returned no rows."); + + public static Task QuerySingleAsync(this IDbSession session, string sql, params DbParam[] parameters) => + session.QuerySingleAsync(sql, parameters, CancellationToken.None); + + /// Maps the only row, or returns default when there is none. + public static async Task QuerySingleOrDefaultAsync(this IDbSession session, string sql, DbParam[] parameters, Func map, CancellationToken cancellationToken) + { + var row = await session.QuerySingleOrDefaultAsync(sql, parameters, cancellationToken).ConfigureAwait(false); + return row is null ? default : map(row); + } + + /// Maps every row into a list. + public static async Task> QueryListAsync(this IDbSession session, string sql, DbParam[] parameters, Func map, CancellationToken cancellationToken) + { + var list = new List(); + await foreach (var row in session.QueryAsync(sql, parameters, cancellationToken).ConfigureAwait(false)) + list.Add(map(row)); + return list; + } + + /// First column of the first row converted with ; default when there is no row or it is NULL. + public static async Task ScalarAsync(this IDbSession session, string sql, DbParam[] parameters, CancellationToken cancellationToken) + { + await foreach (var row in session.QueryAsync(sql, parameters, cancellationToken).ConfigureAwait(false)) + return row.Get(0); + return default; + } + + public static Task ScalarAsync(this IDbSession session, string sql, params DbParam[] parameters) => + session.ScalarAsync(sql, parameters, CancellationToken.None); +} diff --git a/src/Titano.Data/IDatabase.cs b/src/Titano.Data/IDatabase.cs new file mode 100644 index 00000000..9c58d185 --- /dev/null +++ b/src/Titano.Data/IDatabase.cs @@ -0,0 +1,60 @@ +namespace Titano.Data; + +/// A database (SQLite file or PostgreSQL server) that hands out pooled sessions (BRIEF §6.1). +public interface IDatabase : IAsyncDisposable +{ + Dialect Dialect { get; } + + /// Rents a connection from the pool; dispose the session to return it. + Task OpenAsync(CancellationToken cancellationToken); +} + +/// +/// One pooled connection. SQL uses positional $1…$n placeholders on both dialects. A session is not +/// thread-safe: run one command at a time and finish (or dispose) a query enumeration before the next command. +/// +public interface IDbSession : IAsyncDisposable +{ + Dialect Dialect { get; } + + /// True between and commit/rollback. + bool InTransaction { get; } + + /// Runs one statement and returns the number of rows it inserted, updated or deleted. + Task ExecuteAsync(string sql, DbParam[] parameters, CancellationToken cancellationToken); + + /// Streams the rows of one statement. + IAsyncEnumerable QueryAsync(string sql, DbParam[] parameters, CancellationToken cancellationToken); + + /// Runs a parameterless multi-statement script (migrations, maintenance). + Task ExecuteScriptAsync(string script, CancellationToken cancellationToken); + + /// + /// Starts a transaction (BEGIN IMMEDIATE on SQLite, so writers queue up front instead of failing later). + /// Nested transactions are not supported. + /// + Task BeginAsync(CancellationToken cancellationToken); + + /// + /// Inserts many rows: COPY … FROM STDIN on PostgreSQL, multi-row INSERTs in one transaction on SQLite. + /// Each row array is consumed before the next one is requested, so producers may reuse it. + /// + Task BulkInsertAsync(string table, IReadOnlyList columns, IAsyncEnumerable rows, CancellationToken cancellationToken); + + Task ExecuteAsync(string sql, params DbParam[] parameters) => ExecuteAsync(sql, parameters, CancellationToken.None); + + IAsyncEnumerable QueryAsync(string sql, params DbParam[] parameters) => QueryAsync(sql, parameters, CancellationToken.None); + + Task BeginAsync() => BeginAsync(CancellationToken.None); + + Task BulkInsertAsync(string table, IReadOnlyList columns, IAsyncEnumerable rows) => + BulkInsertAsync(table, columns, rows, CancellationToken.None); +} + +/// An open transaction; disposing it without rolls it back. +public interface IDbTransaction : IAsyncDisposable +{ + Task CommitAsync(CancellationToken cancellationToken = default); + + Task RollbackAsync(CancellationToken cancellationToken = default); +} diff --git a/src/Titano.Data/Migrations/MigrationRunner.cs b/src/Titano.Data/Migrations/MigrationRunner.cs new file mode 100644 index 00000000..b100ce03 --- /dev/null +++ b/src/Titano.Data/Migrations/MigrationRunner.cs @@ -0,0 +1,90 @@ +using System.Globalization; +using Titano.Core.Diagnostics; + +namespace Titano.Data.Migrations; + +/// A numbered schema change shipped as Migrations/<dialect>/NNNN_name.sql. +public sealed record Migration(int Version, string Name, string Sql); + +/// +/// Applies the embedded migrations of a dialect at startup (BRIEF §6.1): all pending ones in a single +/// transaction, each recorded in schema_migrations(version, name, applied_at). A database that already +/// holds a version this build does not know is refused with . +/// +public static class MigrationRunner +{ + private const string ResourcePrefix = "Titano.Data.Migrations."; + + /// Serialises concurrent migrators on one PostgreSQL database (several server instances starting). + private const long AdvisoryLockKey = 0x5469_7461_6E6F; + + /// The embedded migrations of , by ascending version. + public static IReadOnlyList Load(Dialect dialect) + { + var folder = ResourcePrefix + (dialect == Dialect.Postgres ? "postgres" : "sqlite"); + var assembly = typeof(MigrationRunner).Assembly; + var migrations = new List(); + foreach (var resource in assembly.GetManifestResourceNames()) + { + // The logical name keeps the folder separator of the build host ('/' or '\'). + if (resource.Length <= folder.Length + 1 || !resource.StartsWith(folder, StringComparison.Ordinal) + || resource[folder.Length] is not ('/' or '\\')) + continue; + var file = resource[(folder.Length + 1)..]; + var underscore = file.IndexOf('_', StringComparison.Ordinal); + if (underscore <= 0 || !file.EndsWith(".sql", StringComparison.Ordinal) + || !int.TryParse(file.AsSpan(0, underscore), NumberStyles.None, CultureInfo.InvariantCulture, out var version)) + throw new InvalidOperationException($"Migration resource '{resource}' is not named NNNN_name.sql."); + using var reader = new StreamReader(assembly.GetManifestResourceStream(resource)!); + migrations.Add(new Migration(version, file[(underscore + 1)..^4], reader.ReadToEnd())); + } + migrations.Sort((a, b) => a.Version.CompareTo(b.Version)); + for (var i = 1; i < migrations.Count; i++) + { + if (migrations[i].Version == migrations[i - 1].Version) + throw new InvalidOperationException($"Two migrations share version {migrations[i].Version}."); + } + return migrations; + } + + /// Migrates to the newest embedded version and returns that version. + public static Task MigrateAsync(IDatabase database, CancellationToken cancellationToken = default) => + MigrateAsync(database, Load(database.Dialect), cancellationToken); + + /// Applies every migration of not yet recorded; returns the resulting version. + public static async Task MigrateAsync(IDatabase database, IReadOnlyList migrations, CancellationToken cancellationToken = default) + { + var postgres = database.Dialect == Dialect.Postgres; + var session = await database.OpenAsync(cancellationToken).ConfigureAwait(false); + await using (session.ConfigureAwait(false)) + { + var transaction = await session.BeginAsync(cancellationToken).ConfigureAwait(false); + await using (transaction.ConfigureAwait(false)) + { + if (postgres) await session.ExecuteAsync("SELECT pg_advisory_xact_lock($1)", [AdvisoryLockKey], cancellationToken).ConfigureAwait(false); + await session.ExecuteScriptAsync(postgres + ? "CREATE TABLE IF NOT EXISTS schema_migrations (version integer PRIMARY KEY, name text NOT NULL, applied_at timestamptz NOT NULL)" + : "CREATE TABLE IF NOT EXISTS schema_migrations (version INTEGER PRIMARY KEY, name TEXT NOT NULL, applied_at TEXT NOT NULL)", + cancellationToken).ConfigureAwait(false); + + var applied = new HashSet(await session.QueryListAsync( + "SELECT version FROM schema_migrations", [], r => r.GetInt32(0), cancellationToken).ConfigureAwait(false)); + var supported = migrations.Count == 0 ? 0 : migrations[^1].Version; + var current = applied.Count == 0 ? 0 : applied.Max(); + if (current > supported) throw new SchemaTooNewException(current, supported); + + foreach (var migration in migrations) + { + if (applied.Contains(migration.Version)) continue; + await session.ExecuteScriptAsync(migration.Sql, cancellationToken).ConfigureAwait(false); + await session.ExecuteAsync( + "INSERT INTO schema_migrations (version, name, applied_at) VALUES ($1, $2, $3)", + [migration.Version, migration.Name, DateTimeOffset.UtcNow], cancellationToken).ConfigureAwait(false); + Log.Info("Data", $"Applied {database.Dialect} migration {migration.Version:0000} {migration.Name}"); + } + await transaction.CommitAsync(cancellationToken).ConfigureAwait(false); + return supported; + } + } + } +} diff --git a/src/Titano.Data/Migrations/postgres/0001_initial.sql b/src/Titano.Data/Migrations/postgres/0001_initial.sql new file mode 100644 index 00000000..f62a74fd --- /dev/null +++ b/src/Titano.Data/Migrations/postgres/0001_initial.sql @@ -0,0 +1,250 @@ +-- Titano schema v1 (PostgreSQL). Instants are timestamptz, camera wall-clock times timestamp, JSON jsonb. +-- Sort keys use the "C" collation so ordering equals SQLite's binary UTF-8 order. Mirrors sqlite/0001_initial.sql. + +CREATE TABLE archives ( + id uuid NOT NULL PRIMARY KEY, + name text NOT NULL, + root_path text NOT NULL, + folder_template text NOT NULL, + file_template text NOT NULL, + schema_version integer NOT NULL DEFAULT 1, + created timestamptz NOT NULL, + proxy_long_edge integer NOT NULL DEFAULT 1920 +); + +CREATE TABLE users ( + id uuid NOT NULL PRIMARY KEY, + username text NOT NULL, + username_key text NOT NULL UNIQUE, + display_name text, + password_hash text NOT NULL, + role integer NOT NULL, + permissions bigint NOT NULL, + quota_bytes bigint NOT NULL DEFAULT 0, + used_bytes bigint NOT NULL DEFAULT 0, + disabled boolean NOT NULL DEFAULT FALSE, + must_change_password boolean NOT NULL DEFAULT FALSE, + created timestamptz NOT NULL, + last_login timestamptz +); + +CREATE TABLE sequences ( + id uuid NOT NULL PRIMARY KEY, + archive_id uuid NOT NULL REFERENCES archives (id) ON DELETE CASCADE, + title text, + title_key text COLLATE "C" NOT NULL, + search_text text NOT NULL, + folder text NOT NULL, + camera_make text, + camera_model text, + camera_serial text, + lens text, + first_capture timestamp, + last_capture timestamp, + frame_count integer NOT NULL DEFAULT 0, + median_interval double precision, + total_bytes bigint NOT NULL DEFAULT 0, + status integer NOT NULL DEFAULT 0, + rendered_count integer NOT NULL DEFAULT 0, + verified_at timestamptz, + hero_frame_id uuid, + rating integer NOT NULL DEFAULT 0, + notes text, + settings_json jsonb, + analysis_json jsonb, + origin integer NOT NULL DEFAULT 0, + sync_state integer NOT NULL DEFAULT 0, + settings_version integer NOT NULL DEFAULT 0, + frames_version integer NOT NULL DEFAULT 0, + owner_user_id uuid, + warning_count integer NOT NULL DEFAULT 0, + updated_at timestamptz NOT NULL +); +CREATE INDEX ix_sequences_archive_capture ON sequences (archive_id, first_capture, id); +CREATE INDEX ix_sequences_capture ON sequences (first_capture, id); +CREATE INDEX ix_sequences_camera ON sequences (camera_model); + +CREATE TABLE frames ( + id uuid NOT NULL PRIMARY KEY, + sequence_id uuid NOT NULL REFERENCES sequences (id) ON DELETE CASCADE, + idx integer NOT NULL, + relative_path text NOT NULL, + file_name text NOT NULL, + original_file_name text, + size bigint NOT NULL DEFAULT 0, + sha256 text, + captured_at timestamp, + utc_offset_minutes integer, + timestamp_source integer NOT NULL DEFAULT 0, + exposure_time double precision, + f_number double precision, + iso integer, + focal_length double precision, + exposure_bias double precision, + white_balance integer, + orientation integer NOT NULL DEFAULT 1, + width integer NOT NULL DEFAULT 0, + height integer NOT NULL DEFAULT 0, + format integer NOT NULL DEFAULT 0, + preview_offset bigint, + preview_length bigint, + mean_log_luminance double precision, + clip_low double precision, + clip_high double precision, + flags integer NOT NULL DEFAULT 0 +); +CREATE UNIQUE INDEX ux_frames_sequence_idx ON frames (sequence_id, idx); +CREATE INDEX ix_frames_sha256 ON frames (sha256); +CREATE INDEX ix_frames_captured_at ON frames (captured_at); + +CREATE TABLE renders ( + id uuid NOT NULL PRIMARY KEY, + sequence_id uuid NOT NULL REFERENCES sequences (id) ON DELETE CASCADE, + preset_name text NOT NULL, + settings_json jsonb, + output_path text NOT NULL, + codec text, + width integer NOT NULL DEFAULT 0, + height integer NOT NULL DEFAULT 0, + fps double precision NOT NULL DEFAULT 0, + duration_seconds double precision NOT NULL DEFAULT 0, + bytes bigint NOT NULL DEFAULT 0, + created timestamptz NOT NULL, + produced_by text +); +CREATE INDEX ix_renders_sequence ON renders (sequence_id, created); + +CREATE TABLE jobs ( + id uuid NOT NULL PRIMARY KEY, + kind integer NOT NULL, + target_ids text NOT NULL DEFAULT '', + target_label text, + parameters_json jsonb, + state integer NOT NULL, + priority integer NOT NULL, + progress_done bigint NOT NULL DEFAULT 0, + progress_total bigint NOT NULL DEFAULT 0, + items_per_second double precision, + eta_seconds double precision, + checkpoint text, + log_tail text, + created_by uuid, + node_id text, + attempts integer NOT NULL DEFAULT 0, + error text, + created timestamptz NOT NULL, + started timestamptz, + finished timestamptz +); +CREATE INDEX ix_jobs_queue ON jobs (state, priority DESC, created, id); +CREATE INDEX ix_jobs_state_created ON jobs (state, created, id); +CREATE INDEX ix_jobs_finished ON jobs (finished); + +CREATE TABLE media_cards ( + id uuid NOT NULL PRIMARY KEY, + identity text NOT NULL UNIQUE, + volume_serial bigint NOT NULL, + label text, + capacity bigint NOT NULL DEFAULT 0, + nickname text, + camera_make text, + camera_model text, + camera_serial text, + profile_json jsonb, + auto_import boolean NOT NULL DEFAULT FALSE, + first_seen timestamptz NOT NULL, + last_seen timestamptz NOT NULL +); + +CREATE TABLE import_history ( + card_id uuid NOT NULL REFERENCES media_cards (id) ON DELETE CASCADE, + path text NOT NULL, + size bigint NOT NULL, + mtime timestamptz NOT NULL, + sha256 text, + frame_id uuid REFERENCES frames (id) ON DELETE SET NULL, + job_id uuid, + imported_at timestamptz NOT NULL, + PRIMARY KEY (card_id, path, size, mtime) +); +CREATE INDEX ix_import_history_frame ON import_history (frame_id); + +CREATE TABLE tokens ( + token_hash text NOT NULL PRIMARY KEY, + user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE, + client_name text, + created timestamptz NOT NULL, + expires timestamptz NOT NULL, + last_used timestamptz NOT NULL, + revoked boolean NOT NULL DEFAULT FALSE +); +CREATE INDEX ix_tokens_user ON tokens (user_id); +CREATE INDEX ix_tokens_expires ON tokens (expires); + +CREATE TABLE render_nodes ( + id uuid NOT NULL PRIMARY KEY, + user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE, + client_name text NOT NULL, + capabilities_json jsonb, + last_heartbeat timestamptz NOT NULL, + state text NOT NULL +); +CREATE INDEX ix_render_nodes_user ON render_nodes (user_id); +CREATE INDEX ix_render_nodes_heartbeat ON render_nodes (last_heartbeat); + +CREATE TABLE settings ( + scope text NOT NULL, + scope_id text NOT NULL DEFAULT '', + key text NOT NULL, + value_json jsonb NOT NULL, + updated_at timestamptz NOT NULL, + PRIMARY KEY (scope, scope_id, key) +); + +CREATE TABLE tags ( + id uuid NOT NULL PRIMARY KEY, + name text NOT NULL, + name_key text COLLATE "C" NOT NULL UNIQUE +); + +CREATE TABLE sequence_tags ( + sequence_id uuid NOT NULL REFERENCES sequences (id) ON DELETE CASCADE, + tag_id uuid NOT NULL REFERENCES tags (id) ON DELETE CASCADE, + PRIMARY KEY (sequence_id, tag_id) +); +CREATE INDEX ix_sequence_tags_tag ON sequence_tags (tag_id); + +CREATE TABLE audit_log ( + id uuid NOT NULL PRIMARY KEY, + at timestamptz NOT NULL, + user_id uuid, + username text, + action text NOT NULL, + target_kind text, + target_id text, + details text, + remote_address text +); +CREATE INDEX ix_audit_log_at ON audit_log (at, id); +CREATE INDEX ix_audit_log_user ON audit_log (user_id, at); + +CREATE TABLE uploads ( + id uuid NOT NULL PRIMARY KEY, + user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE, + sequence_id uuid REFERENCES sequences (id) ON DELETE SET NULL, + file_name text NOT NULL, + size bigint NOT NULL, + sha256 text NOT NULL, + captured_at timestamp, + chunk_size integer NOT NULL, + received bytea NOT NULL, + received_count integer NOT NULL DEFAULT 0, + state integer NOT NULL, + frame_id uuid, + created timestamptz NOT NULL, + updated_at timestamptz NOT NULL +); +CREATE INDEX ix_uploads_user ON uploads (user_id, created); +CREATE INDEX ix_uploads_state ON uploads (state, updated_at); +CREATE INDEX ix_uploads_sha256 ON uploads (sha256); +CREATE INDEX ix_uploads_sequence ON uploads (sequence_id); diff --git a/src/Titano.Data/Migrations/sqlite/0001_initial.sql b/src/Titano.Data/Migrations/sqlite/0001_initial.sql new file mode 100644 index 00000000..6d2c442b --- /dev/null +++ b/src/Titano.Data/Migrations/sqlite/0001_initial.sql @@ -0,0 +1,250 @@ +-- Titano schema v1 (SQLite). Ids are UUID text, instants ISO-8601 UTC text ('…Z'), camera wall-clock times +-- ISO-8601 text without zone, JSON as text, booleans as 0/1. Mirrors postgres/0001_initial.sql. + +CREATE TABLE archives ( + id TEXT NOT NULL PRIMARY KEY, + name TEXT NOT NULL, + root_path TEXT NOT NULL, + folder_template TEXT NOT NULL, + file_template TEXT NOT NULL, + schema_version INTEGER NOT NULL DEFAULT 1, + created TEXT NOT NULL, + proxy_long_edge INTEGER NOT NULL DEFAULT 1920 +); + +CREATE TABLE users ( + id TEXT NOT NULL PRIMARY KEY, + username TEXT NOT NULL, + username_key TEXT NOT NULL UNIQUE, + display_name TEXT, + password_hash TEXT NOT NULL, + role INTEGER NOT NULL, + permissions INTEGER NOT NULL, + quota_bytes INTEGER NOT NULL DEFAULT 0, + used_bytes INTEGER NOT NULL DEFAULT 0, + disabled INTEGER NOT NULL DEFAULT 0, + must_change_password INTEGER NOT NULL DEFAULT 0, + created TEXT NOT NULL, + last_login TEXT +); + +CREATE TABLE sequences ( + id TEXT NOT NULL PRIMARY KEY, + archive_id TEXT NOT NULL REFERENCES archives (id) ON DELETE CASCADE, + title TEXT, + title_key TEXT NOT NULL, + search_text TEXT NOT NULL, + folder TEXT NOT NULL, + camera_make TEXT, + camera_model TEXT, + camera_serial TEXT, + lens TEXT, + first_capture TEXT, + last_capture TEXT, + frame_count INTEGER NOT NULL DEFAULT 0, + median_interval REAL, + total_bytes INTEGER NOT NULL DEFAULT 0, + status INTEGER NOT NULL DEFAULT 0, + rendered_count INTEGER NOT NULL DEFAULT 0, + verified_at TEXT, + hero_frame_id TEXT, + rating INTEGER NOT NULL DEFAULT 0, + notes TEXT, + settings_json TEXT, + analysis_json TEXT, + origin INTEGER NOT NULL DEFAULT 0, + sync_state INTEGER NOT NULL DEFAULT 0, + settings_version INTEGER NOT NULL DEFAULT 0, + frames_version INTEGER NOT NULL DEFAULT 0, + owner_user_id TEXT, + warning_count INTEGER NOT NULL DEFAULT 0, + updated_at TEXT NOT NULL +); +CREATE INDEX ix_sequences_archive_capture ON sequences (archive_id, first_capture, id); +CREATE INDEX ix_sequences_capture ON sequences (first_capture, id); +CREATE INDEX ix_sequences_camera ON sequences (camera_model); + +CREATE TABLE frames ( + id TEXT NOT NULL PRIMARY KEY, + sequence_id TEXT NOT NULL REFERENCES sequences (id) ON DELETE CASCADE, + idx INTEGER NOT NULL, + relative_path TEXT NOT NULL, + file_name TEXT NOT NULL, + original_file_name TEXT, + size INTEGER NOT NULL DEFAULT 0, + sha256 TEXT, + captured_at TEXT, + utc_offset_minutes INTEGER, + timestamp_source INTEGER NOT NULL DEFAULT 0, + exposure_time REAL, + f_number REAL, + iso INTEGER, + focal_length REAL, + exposure_bias REAL, + white_balance INTEGER, + orientation INTEGER NOT NULL DEFAULT 1, + width INTEGER NOT NULL DEFAULT 0, + height INTEGER NOT NULL DEFAULT 0, + format INTEGER NOT NULL DEFAULT 0, + preview_offset INTEGER, + preview_length INTEGER, + mean_log_luminance REAL, + clip_low REAL, + clip_high REAL, + flags INTEGER NOT NULL DEFAULT 0 +); +CREATE UNIQUE INDEX ux_frames_sequence_idx ON frames (sequence_id, idx); +CREATE INDEX ix_frames_sha256 ON frames (sha256); +CREATE INDEX ix_frames_captured_at ON frames (captured_at); + +CREATE TABLE renders ( + id TEXT NOT NULL PRIMARY KEY, + sequence_id TEXT NOT NULL REFERENCES sequences (id) ON DELETE CASCADE, + preset_name TEXT NOT NULL, + settings_json TEXT, + output_path TEXT NOT NULL, + codec TEXT, + width INTEGER NOT NULL DEFAULT 0, + height INTEGER NOT NULL DEFAULT 0, + fps REAL NOT NULL DEFAULT 0, + duration_seconds REAL NOT NULL DEFAULT 0, + bytes INTEGER NOT NULL DEFAULT 0, + created TEXT NOT NULL, + produced_by TEXT +); +CREATE INDEX ix_renders_sequence ON renders (sequence_id, created); + +CREATE TABLE jobs ( + id TEXT NOT NULL PRIMARY KEY, + kind INTEGER NOT NULL, + target_ids TEXT NOT NULL DEFAULT '', + target_label TEXT, + parameters_json TEXT, + state INTEGER NOT NULL, + priority INTEGER NOT NULL, + progress_done INTEGER NOT NULL DEFAULT 0, + progress_total INTEGER NOT NULL DEFAULT 0, + items_per_second REAL, + eta_seconds REAL, + checkpoint TEXT, + log_tail TEXT, + created_by TEXT, + node_id TEXT, + attempts INTEGER NOT NULL DEFAULT 0, + error TEXT, + created TEXT NOT NULL, + started TEXT, + finished TEXT +); +CREATE INDEX ix_jobs_queue ON jobs (state, priority DESC, created, id); +CREATE INDEX ix_jobs_state_created ON jobs (state, created, id); +CREATE INDEX ix_jobs_finished ON jobs (finished); + +CREATE TABLE media_cards ( + id TEXT NOT NULL PRIMARY KEY, + identity TEXT NOT NULL UNIQUE, + volume_serial INTEGER NOT NULL, + label TEXT, + capacity INTEGER NOT NULL DEFAULT 0, + nickname TEXT, + camera_make TEXT, + camera_model TEXT, + camera_serial TEXT, + profile_json TEXT, + auto_import INTEGER NOT NULL DEFAULT 0, + first_seen TEXT NOT NULL, + last_seen TEXT NOT NULL +); + +CREATE TABLE import_history ( + card_id TEXT NOT NULL REFERENCES media_cards (id) ON DELETE CASCADE, + path TEXT NOT NULL, + size INTEGER NOT NULL, + mtime TEXT NOT NULL, + sha256 TEXT, + frame_id TEXT REFERENCES frames (id) ON DELETE SET NULL, + job_id TEXT, + imported_at TEXT NOT NULL, + PRIMARY KEY (card_id, path, size, mtime) +); +CREATE INDEX ix_import_history_frame ON import_history (frame_id); + +CREATE TABLE tokens ( + token_hash TEXT NOT NULL PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE, + client_name TEXT, + created TEXT NOT NULL, + expires TEXT NOT NULL, + last_used TEXT NOT NULL, + revoked INTEGER NOT NULL DEFAULT 0 +); +CREATE INDEX ix_tokens_user ON tokens (user_id); +CREATE INDEX ix_tokens_expires ON tokens (expires); + +CREATE TABLE render_nodes ( + id TEXT NOT NULL PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE, + client_name TEXT NOT NULL, + capabilities_json TEXT, + last_heartbeat TEXT NOT NULL, + state TEXT NOT NULL +); +CREATE INDEX ix_render_nodes_user ON render_nodes (user_id); +CREATE INDEX ix_render_nodes_heartbeat ON render_nodes (last_heartbeat); + +CREATE TABLE settings ( + scope TEXT NOT NULL, + scope_id TEXT NOT NULL DEFAULT '', + key TEXT NOT NULL, + value_json TEXT NOT NULL, + updated_at TEXT NOT NULL, + PRIMARY KEY (scope, scope_id, key) +); + +CREATE TABLE tags ( + id TEXT NOT NULL PRIMARY KEY, + name TEXT NOT NULL, + name_key TEXT NOT NULL UNIQUE +); + +CREATE TABLE sequence_tags ( + sequence_id TEXT NOT NULL REFERENCES sequences (id) ON DELETE CASCADE, + tag_id TEXT NOT NULL REFERENCES tags (id) ON DELETE CASCADE, + PRIMARY KEY (sequence_id, tag_id) +); +CREATE INDEX ix_sequence_tags_tag ON sequence_tags (tag_id); + +CREATE TABLE audit_log ( + id TEXT NOT NULL PRIMARY KEY, + at TEXT NOT NULL, + user_id TEXT, + username TEXT, + action TEXT NOT NULL, + target_kind TEXT, + target_id TEXT, + details TEXT, + remote_address TEXT +); +CREATE INDEX ix_audit_log_at ON audit_log (at, id); +CREATE INDEX ix_audit_log_user ON audit_log (user_id, at); + +CREATE TABLE uploads ( + id TEXT NOT NULL PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE, + sequence_id TEXT REFERENCES sequences (id) ON DELETE SET NULL, + file_name TEXT NOT NULL, + size INTEGER NOT NULL, + sha256 TEXT NOT NULL, + captured_at TEXT, + chunk_size INTEGER NOT NULL, + received BLOB NOT NULL, + received_count INTEGER NOT NULL DEFAULT 0, + state INTEGER NOT NULL, + frame_id TEXT, + created TEXT NOT NULL, + updated_at TEXT NOT NULL +); +CREATE INDEX ix_uploads_user ON uploads (user_id, created); +CREATE INDEX ix_uploads_state ON uploads (state, updated_at); +CREATE INDEX ix_uploads_sha256 ON uploads (sha256); +CREATE INDEX ix_uploads_sequence ON uploads (sequence_id); diff --git a/src/Titano.Data/Postgres/PgAuthentication.cs b/src/Titano.Data/Postgres/PgAuthentication.cs new file mode 100644 index 00000000..96f3299f --- /dev/null +++ b/src/Titano.Data/Postgres/PgAuthentication.cs @@ -0,0 +1,141 @@ +using System.Globalization; +using System.Security.Authentication; +using System.Security.Cryptography; +using System.Text; + +namespace Titano.Data.Postgres; + +/// +/// Client side of SCRAM-SHA-256 (RFC 5802 / RFC 7677) as PostgreSQL uses it: no channel binding +/// (n,, GS2 header) and an empty user name, since the server takes the user from the startup packet. +/// +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"; + + /// The server proved knowledge of the password with a valid final signature. + public bool IsServerVerified { get; private set; } + + public byte[] ClientFirstMessage() + { + _clientFirstBare = $"n={_username},r={_clientNonce}"; + return Encoding.UTF8.GetBytes("n,," + _clientFirstBare); + } + + /// Checks the server-first message and returns client-final with the proof. + public byte[] ClientFinalMessage(ReadOnlySpan 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)); + } + + /// Verifies the server signature, proving the server knows the password too. + public void VerifyServerFinal(ReadOnlySpan 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; + } + + /// + /// 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. + /// + 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 +} + +/// PostgreSQL's MD5 password response: "md5" + md5hex(md5hex(password + user) + salt). +internal static class PgMd5 +{ + public static string Response(string username, string password, ReadOnlySpan 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); +} diff --git a/src/Titano.Data/Postgres/PgConnector.cs b/src/Titano.Data/Postgres/PgConnector.cs new file mode 100644 index 00000000..74edffc4 --- /dev/null +++ b/src/Titano.Data/Postgres/PgConnector.cs @@ -0,0 +1,1038 @@ +using System.Buffers.Binary; +using System.Globalization; +using System.Net.Security; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Runtime.ExceptionServices; +using System.Security.Authentication; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using Titano.Core.Diagnostics; + +namespace Titano.Data.Postgres; + +/// A NOTIFY delivered to a listening connection. +public sealed record PgNotification(int ProcessId, string Channel, string Payload); + +/// +/// One physical connection speaking protocol v3 (BRIEF §6.3): startup and authentication, simple and extended +/// query with a per-connection LRU of named prepared statements, COPY FROM STDIN, notices and notifications, +/// and cancellation through a CancelRequest on a second socket. Not thread-safe; the pool lends it to one +/// session at a time. +/// +internal sealed class PgConnector : IAsyncDisposable +{ + private const int ProtocolVersion3 = 196608; + private const int SslRequestCode = 80877103; + private const int CancelRequestCode = 80877102; + private const int CopyChunkBytes = 64 * 1024; + private const string LogCategory = "Data.Postgres"; + private static readonly TimeSpan CancelGracePeriod = TimeSpan.FromSeconds(5); + private static readonly DbColumns NoColumns = new([]); + + private readonly PostgresSettings _settings; + private readonly Socket _socket; + private readonly Stream _stream; + private readonly PgWriteBuffer _write = new(); + private readonly Dictionary> _statements = new(StringComparer.Ordinal); + private readonly LinkedList _statementLru = new(); + private readonly List _statementsToClose = []; + private byte[] _read = new byte[16 * 1024]; + private int _readPos; + private int _readEnd; + private int _messageStart; + private int _messageLength; + private int _statementCounter; + private int _secretKey; + private long _idleSince; + private int _disposed; + private CancellationTokenSource _ioAbort = new(); + private Task _pendingCancel = Task.CompletedTask; + private Operation? _active; + + private PgConnector(PostgresSettings settings, Socket socket, Stream stream) + { + _settings = settings; + _socket = socket; + _stream = stream; + } + + public int ProcessId { get; private set; } + + /// The connection failed or the server ended the session; it must be discarded. + public bool IsBroken { get; private set; } + + /// Last ReadyForQuery status: 'I' idle, 'T' in transaction, 'E' failed transaction. + public char TransactionStatus { get; private set; } = 'I'; + + /// A command's response is still being read (an enumeration that was neither finished nor disposed). + public bool IsBusy => _active is not null; + + public TimeSpan IdleTime => TimeSpan.FromMilliseconds(Environment.TickCount64 - _idleSince); + + /// Receives NotificationResponse messages (listener connections). + public Action? NotificationReceived { get; set; } + + private ReadOnlySpan Payload => _read.AsSpan(_messageStart, _messageLength); + + public static async Task OpenAsync(PostgresSettings settings, CancellationToken cancellationToken) + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(settings.ConnectTimeout); + var socket = new Socket(SocketType.Stream, ProtocolType.Tcp) { NoDelay = true }; + Stream? stream = null; + try + { + await socket.ConnectAsync(settings.Host, settings.Port, timeout.Token).ConfigureAwait(false); + stream = new NetworkStream(socket, ownsSocket: false); + if (settings.SslMode != SslMode.Disable) + stream = await NegotiateTlsAsync(stream, settings, timeout.Token).ConfigureAwait(false); + var connector = new PgConnector(settings, socket, stream); + await connector.StartupAsync(timeout.Token).ConfigureAwait(false); + connector.MarkIdle(); + return connector; + } + catch (Exception ex) + { + if (stream is not null) await stream.DisposeAsync().ConfigureAwait(false); + socket.Dispose(); + if (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested) + throw new DatabaseConnectionException($"Timed out connecting to {settings.Host}:{settings.Port}.", ex); + if (ex is SocketException or IOException) + throw new DatabaseConnectionException($"Cannot connect to {settings.Host}:{settings.Port}: {ex.Message}", ex); + throw; + } + } + + public void MarkIdle() => _idleSince = Environment.TickCount64; + + /// Runs one statement with the extended protocol and returns the rows it changed. + public async Task ExecuteAsync(string sql, DbParam[] parameters, CancellationToken cancellationToken) + { + var op = StartOperation(sql, parameters, decodeRows: false, cancellationToken); + try + { + await SendExtendedAsync(op).ConfigureAwait(false); + while (await ReadRowAsync(op).ConfigureAwait(false) is not null) + { + } + return op.Affected; + } + finally + { + await EndOperationAsync(op).ConfigureAwait(false); + } + } + + /// Streams the rows of one statement; abandoning the enumeration drains the rest of the response. + public async IAsyncEnumerable QueryAsync(string sql, DbParam[] parameters, [EnumeratorCancellation] CancellationToken cancellationToken) + { + var op = StartOperation(sql, parameters, decodeRows: true, cancellationToken); + try + { + await SendExtendedAsync(op).ConfigureAwait(false); + while (await ReadRowAsync(op).ConfigureAwait(false) is { } row) yield return row; + } + finally + { + await EndOperationAsync(op).ConfigureAwait(false); + } + } + + /// Runs a simple-protocol query (scripts, transaction control) and returns the last command tag. + public async Task SimpleQueryAsync(string sql, CancellationToken cancellationToken) + { + var op = StartOperation(sql, [], decodeRows: false, cancellationToken); + try + { + WriteQuery(sql); + await FlushAsync(op).ConfigureAwait(false); + await DrainAsync(op).ConfigureAwait(false); + return op.Tag; + } + finally + { + await EndOperationAsync(op).ConfigureAwait(false); + } + } + + /// True when SELECT 1 succeeds within the connect timeout; marks the connection broken otherwise. + public async Task PingAsync(CancellationToken cancellationToken) + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(_settings.ConnectTimeout); + try + { + await SimpleQueryAsync("SELECT 1", timeout.Token).ConfigureAwait(false); + return true; + } + catch (Exception ex) when (ex is DatabaseException or OperationCanceledException && !cancellationToken.IsCancellationRequested) + { + IsBroken = true; + return false; + } + } + + /// + /// Streams rows through COPY … FROM STDIN in text format. A failing producer aborts the copy with + /// CopyFail, so the table is left untouched, and its exception is rethrown. + /// + public async Task CopyInAsync(string copySql, int columnCount, IAsyncEnumerable rows, CancellationToken cancellationToken) + { + var op = StartOperation(copySql, [], decodeRows: false, cancellationToken); + try + { + WriteQuery(copySql); + await FlushAsync(op).ConfigureAwait(false); + while (true) + { + var type = await NextMessageAsync(op).ConfigureAwait(false); + if (type == 'G') break; + if (type == 'E') OnError(op); + else if (type == 'Z') throw Complete(op) ?? ProtocolViolation(type); + } + + ExceptionDispatchInfo? failure = null; + try + { + _write.StartMessage('d'); + await foreach (var row in rows.WithCancellation(cancellationToken).ConfigureAwait(false)) + { + if (row.Length != columnCount) + throw new ArgumentException($"A row has {row.Length} values for {columnCount} columns.", nameof(rows)); + for (var i = 0; i < row.Length; i++) + { + if (i > 0) _write.WriteByte((byte)'\t'); + PgTypes.WriteCopyValue(row[i], _write); + } + _write.WriteByte((byte)'\n'); + if (_write.Length >= CopyChunkBytes) + { + _write.EndMessage(); + await FlushAsync(op).ConfigureAwait(false); + _write.StartMessage('d'); + } + } + _write.EndMessage(); + _write.StartMessage('c'); + _write.EndMessage(); + await FlushAsync(op).ConfigureAwait(false); + } + catch (Exception ex) when (!IsBroken) + { + failure = ExceptionDispatchInfo.Capture(ex); + _write.Clear(); + _write.StartMessage('f'); + _write.WriteCString(ex.Message); + _write.EndMessage(); + await FlushAsync(op).ConfigureAwait(false); + } + + try + { + await DrainAsync(op).ConfigureAwait(false); + } + catch (PostgresException) when (failure is not null) + { + // The server reports our CopyFail; the producer's exception is the real cause. + } + catch (OperationCanceledException) when (failure is not null) + { + } + failure?.Throw(); + return op.Affected; + } + finally + { + await EndOperationAsync(op).ConfigureAwait(false); + } + } + + /// Sends a simple query without reading the response (listener commands; the read loop completes them). + public async Task SendQueryAsync(string sql, CancellationToken cancellationToken) + { + WriteQuery(sql); + try + { + await _stream.WriteAsync(_write.Written, cancellationToken).ConfigureAwait(false); + await _stream.FlushAsync(cancellationToken).ConfigureAwait(false); + } + finally + { + _write.Clear(); + } + } + + /// + /// Listener read loop: notifications go to ; each ReadyForQuery reports the + /// error (or null) of the command it ends. Runs until or the connection fails. + /// + public async Task RunListenerAsync(Action commandCompleted, CancellationToken stop) + { + PostgresException? error = null; + while (true) + { + var type = await ReadMessageAsync(stop).ConfigureAwait(false); + if (type == 'E') + { + error = ParseError(); + if (error.IsFatal) + { + IsBroken = true; + throw error; + } + } + else if (type == 'Z') + { + TransactionStatus = (char)Payload[0]; + commandCompleted(error); + error = null; + } + } + } + + public async ValueTask DisposeAsync() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) return; + if (!IsBroken) + { + try + { + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(1)); + _write.Clear(); + _write.StartMessage('X'); + _write.EndMessage(); + await _stream.WriteAsync(_write.Written, timeout.Token).ConfigureAwait(false); + } + catch (Exception ex) when (ex is IOException or SocketException or OperationCanceledException or ObjectDisposedException) + { + // Terminate is a courtesy; the socket closes either way. + } + } + IsBroken = true; + try + { + await _stream.DisposeAsync().ConfigureAwait(false); + } + catch (IOException) + { + } + _socket.Dispose(); + _ioAbort.Dispose(); + } + + private static async Task NegotiateTlsAsync(Stream stream, PostgresSettings settings, CancellationToken cancellationToken) + { + var request = new byte[8]; + BinaryPrimitives.WriteInt32BigEndian(request, 8); + BinaryPrimitives.WriteInt32BigEndian(request.AsSpan(4), SslRequestCode); + await stream.WriteAsync(request, cancellationToken).ConfigureAwait(false); + var answer = new byte[1]; + await stream.ReadExactlyAsync(answer, cancellationToken).ConfigureAwait(false); + if (answer[0] == 'N') + { + if (settings.SslMode == SslMode.Prefer) return stream; + throw new DatabaseConnectionException($"The server at {settings.Host}:{settings.Port} does not support TLS, which SslMode={settings.SslMode} requires."); + } + if (answer[0] != 'S') throw new DatabaseConnectionException("Unexpected answer to the TLS request."); + + var tls = new SslStream(stream, leaveInnerStreamOpen: false); + var options = new SslClientAuthenticationOptions + { + TargetHost = settings.Host, + RemoteCertificateValidationCallback = (_, certificate, chain, errors) => + settings.SslMode != SslMode.VerifyFull || IsTrusted(settings, certificate, chain, errors), + }; + await tls.AuthenticateAsClientAsync(options, cancellationToken).ConfigureAwait(false); + return tls; + } + + /// verify-full: the system trust store, or the configured root certificate, plus a host name match. + private static bool IsTrusted(PostgresSettings settings, X509Certificate? certificate, X509Chain? chain, SslPolicyErrors errors) + { + if (settings.RootCertificate is null) return errors == SslPolicyErrors.None; + if (certificate is null || (errors & (SslPolicyErrors.RemoteCertificateNotAvailable | SslPolicyErrors.RemoteCertificateNameMismatch)) != 0) + return false; + using var custom = new X509Chain(); + custom.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust; + custom.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; + custom.ChainPolicy.CustomTrustStore.ImportFromPemFile(settings.RootCertificate); + if (chain is not null) + { + foreach (var element in chain.ChainElements) custom.ChainPolicy.ExtraStore.Add(element.Certificate); + } + using var leaf = X509CertificateLoader.LoadCertificate(certificate.GetRawCertData()); + return custom.Build(leaf); + } + + private async Task StartupAsync(CancellationToken cancellationToken) + { + _write.StartUntypedMessage(); + _write.WriteInt32(ProtocolVersion3); + void Parameter(string name, string value) + { + _write.WriteCString(name); + _write.WriteCString(value); + } + Parameter("user", _settings.Username); + Parameter("database", _settings.Database); + Parameter("application_name", _settings.ApplicationName); + Parameter("client_encoding", "UTF8"); + 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(); + await WriteAndClearAsync(cancellationToken).ConfigureAwait(false); + + ScramSha256? scram = null; + while (true) + { + var type = await ReadMessageAsync(cancellationToken).ConfigureAwait(false); + switch (type) + { + case (byte)'R': + scram = Authenticate(scram); + if (_write.Length > 0) await WriteAndClearAsync(cancellationToken).ConfigureAwait(false); + break; + case (byte)'K': + ProcessId = BinaryPrimitives.ReadInt32BigEndian(Payload); + _secretKey = BinaryPrimitives.ReadInt32BigEndian(Payload[4..]); + break; + case (byte)'Z': + TransactionStatus = (char)Payload[0]; + return; + case (byte)'E': + throw ParseError(); + case (byte)'v': + break; // NegotiateProtocolVersion: we request no protocol extensions. + default: + throw ProtocolViolation(type); + } + } + } + + /// Answers one Authentication* message, queuing the response in the write buffer. + private ScramSha256? Authenticate(ScramSha256? scram) + { + var payload = Payload; + var code = BinaryPrimitives.ReadInt32BigEndian(payload); + switch (code) + { + case 0: + // A server that started SCRAM must finish it: only its final signature proves it knows the password. + if (scram is { IsServerVerified: false }) + throw new AuthenticationException("The server skipped the final SCRAM message."); + return scram; + case 3: + WritePassword(RequirePassword()); + return scram; + case 5: + WritePassword(PgMd5.Response(_settings.Username, RequirePassword(), payload.Slice(4, 4))); + return scram; + case 10: + { + var mechanisms = new List(); + var pos = 4; + while (pos < payload.Length && payload[pos] != 0) mechanisms.Add(ReadCString(payload, ref pos)); + if (!mechanisms.Contains(ScramSha256.Mechanism)) + throw new NotSupportedException($"The server offers SASL mechanisms {string.Join(", ", mechanisms)}; only {ScramSha256.Mechanism} is supported."); + scram = new ScramSha256(RequirePassword()); + var first = scram.ClientFirstMessage(); + _write.StartMessage('p'); + _write.WriteCString(ScramSha256.Mechanism); + _write.WriteInt32(first.Length); + _write.Write(first); + _write.EndMessage(); + return scram; + } + case 11: + var final = (scram ?? throw ProtocolViolation((byte)'R')).ClientFinalMessage(payload[4..]); + _write.StartMessage('p'); + _write.Write(final); + _write.EndMessage(); + return scram; + case 12: + (scram ?? throw ProtocolViolation((byte)'R')).VerifyServerFinal(payload[4..]); + return scram; + default: + throw new NotSupportedException($"PostgreSQL authentication method {code} is not supported (use scram-sha-256, md5, password or trust)."); + } + } + + private string RequirePassword() => + _settings.Password ?? throw new InvalidOperationException($"The server requires a password for user '{_settings.Username}'."); + + private void WritePassword(string password) + { + _write.StartMessage('p'); + _write.WriteCString(password); + _write.EndMessage(); + } + + 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; + } + + private void RequestCancel(Operation op) + { + if (op.Completed) return; + op.CancelSent = true; + Volatile.Write(ref _pendingCancel, SendCancelRequestAsync()); + // If the server does not react, the socket is aborted so the caller is never stuck. + _ioAbort.CancelAfter(CancelGracePeriod); + } + + private async Task SendCancelRequestAsync() + { + try + { + using var timeout = new CancellationTokenSource(CancelGracePeriod); + using var socket = new Socket(SocketType.Stream, ProtocolType.Tcp) { NoDelay = true }; + await socket.ConnectAsync(_settings.Host, _settings.Port, timeout.Token).ConfigureAwait(false); + var packet = new byte[16]; + BinaryPrimitives.WriteInt32BigEndian(packet, 16); + BinaryPrimitives.WriteInt32BigEndian(packet.AsSpan(4), CancelRequestCode); + BinaryPrimitives.WriteInt32BigEndian(packet.AsSpan(8), ProcessId); + BinaryPrimitives.WriteInt32BigEndian(packet.AsSpan(12), _secretKey); + await socket.SendAsync(packet, SocketFlags.None, timeout.Token).ConfigureAwait(false); + // The postmaster closes the socket once it has signalled the backend. + await socket.ReceiveAsync(new byte[1], SocketFlags.None, timeout.Token).ConfigureAwait(false); + } + catch (Exception ex) when (ex is SocketException or OperationCanceledException or IOException) + { + Log.Warning(LogCategory, $"Cancel request to backend {ProcessId} failed: {ex.Message}"); + } + } + + /// Drains an abandoned response, then makes sure a late cancel request cannot hit the next command. + private async ValueTask EndOperationAsync(Operation op) + { + try + { + if (!op.Completed && !IsBroken) + { + try + { + await DrainAsync(op).ConfigureAwait(false); + } + catch (Exception ex) when (ex is PostgresException or OperationCanceledException) + { + // Errors after the consumer stopped reading are not its concern. + } + } + } + finally + { + op.Completed = true; + await op.Registration.DisposeAsync().ConfigureAwait(false); + if (op.CancelSent) + { + try + { + await Volatile.Read(ref _pendingCancel).WaitAsync(CancelGracePeriod).ConfigureAwait(false); + } + catch (TimeoutException) + { + IsBroken = true; + } + } + if (!_ioAbort.TryReset()) + { + IsBroken = true; + _ioAbort.Dispose(); + _ioAbort = new CancellationTokenSource(); + } + // A huge row (a large bytea) grew the buffer; do not keep it for the life of a pooled connection. + if (_read.Length > 1 << 20 && _readPos == _readEnd) + { + _read = new byte[16 * 1024]; + _readPos = _readEnd = 0; + } + _active = null; + MarkIdle(); + } + } + + private async ValueTask SendExtendedAsync(Operation op) + { + var statement = Lookup(op.Sql, op.ParameterOids, out var hit); + op.Statement = statement; + op.CacheHit = hit; + try + { + foreach (var name in _statementsToClose) + { + _write.StartMessage('C'); + _write.WriteByte((byte)'S'); + _write.WriteCString(name); + _write.EndMessage(); + } + if (!hit) + { + _write.StartMessage('P'); + _write.WriteCString(statement.Name); + _write.WriteCString(op.Sql); + _write.WriteInt16(op.ParameterOids.Length); + foreach (var oid in op.ParameterOids) _write.WriteInt32((int)oid); + _write.EndMessage(); + _write.StartMessage('D'); + _write.WriteByte((byte)'S'); + _write.WriteCString(statement.Name); + _write.EndMessage(); + } + WriteBind(statement.Name, op.Parameters); + _write.StartMessage('E'); + _write.WriteCString(string.Empty); + _write.WriteInt32(0); + _write.EndMessage(); + _write.StartMessage('S'); + _write.EndMessage(); + } + catch + { + // Nothing was sent: forget the half-built batch so the connection stays usable. + _write.Clear(); + op.Completed = true; + throw; + } + _statementsToClose.Clear(); + await FlushAsync(op).ConfigureAwait(false); + } + + private void WriteBind(string statement, DbParam[] parameters) + { + _write.StartMessage('B'); + _write.WriteCString(string.Empty); + _write.WriteCString(statement); + _write.WriteInt16(parameters.Length); + foreach (var p in parameters) _write.WriteInt16(p.Type == DbValueType.Bytes ? 1 : 0); + _write.WriteInt16(parameters.Length); + foreach (var p in parameters) + { + switch (p.Value) + { + case null: + _write.WriteInt32(-1); + break; + case byte[] bytes: + _write.WriteInt32(bytes.Length); + _write.Write(bytes); + break; + case var value: + var span = _write.GetSpan(4 + PgTypes.MaxTextLength(value)); + var n = PgTypes.FormatText(value, span[4..]); + BinaryPrimitives.WriteInt32BigEndian(span, n); + _write.Advance(4 + n); + break; + } + } + _write.WriteInt16(1); + _write.WriteInt16(0); // every result column in text format + _write.EndMessage(); + } + + private void WriteQuery(string sql) + { + _write.StartMessage('Q'); + _write.WriteCString(sql); + _write.EndMessage(); + } + + /// Reads until the next DataRow (returned) or the end of the response (null), then throws any server error. + private async ValueTask ReadRowAsync(Operation op) + { + while (true) + { + var type = await NextMessageAsync(op).ConfigureAwait(false); + switch (type) + { + case (byte)'1': + Remember(op.Statement!); + break; + case (byte)'T': + op.Statement!.SetColumns(ParseRowDescription(out var oids), oids); + break; + case (byte)'n': + op.Statement!.SetColumns(NoColumns, []); + break; + case (byte)'D': + if (op.DecodeRows) return DecodeRow(op.Statement!); + break; + case (byte)'C': + op.Tag = ReadTag(); + op.Affected = AffectedRows(op.Tag); + break; + case (byte)'E': + OnError(op); + break; + case (byte)'Z': + // A cached statement invalidated by DDL is re-prepared once, if no transaction was aborted by it. + if (op.Error is { } stale && op.CacheHit && op.CanRetryStale && IsStale(stale) && Payload[0] == 'I') + { + TransactionStatus = 'I'; + op.Error = null; + op.CanRetryStale = false; + await SendExtendedAsync(op).ConfigureAwait(false); + break; + } + if (Complete(op) is { } error) throw error; + return null; + case (byte)'2' or (byte)'3' or (byte)'t' or (byte)'I' or (byte)'s': + break; + default: + throw ProtocolViolation(type); + } + } + } + + /// Reads to ReadyForQuery, keeping the command tag and the first error; answers stray COPY requests. + private async ValueTask DrainAsync(Operation op) + { + while (true) + { + var type = await NextMessageAsync(op).ConfigureAwait(false); + switch (type) + { + case (byte)'C': + op.Tag = ReadTag(); + op.Affected = AffectedRows(op.Tag); + break; + case (byte)'E': + OnError(op); + break; + case (byte)'G': + _write.StartMessage('f'); + _write.WriteCString("COPY FROM STDIN is only supported through BulkInsertAsync."); + _write.EndMessage(); + await FlushAsync(op).ConfigureAwait(false); + break; + case (byte)'Z': + if (Complete(op) is { } error) throw error; + return; + } + } + } + + /// Handles an ErrorResponse: keeps the first error, evicts a stale cached statement, and ends the operation on FATAL. + private void OnError(Operation op) + { + var error = ParseError(); + op.Error ??= error; + if (op.CacheHit && IsStale(error)) Evict(op.Statement!, close: error.SqlState != "26000"); + if (error.IsFatal) + { + // The server closes the session after FATAL; no ReadyForQuery follows. + IsBroken = true; + op.Completed = true; + throw error; + } + } + + /// Marks the operation finished at ReadyForQuery and returns the exception to raise, if any. + private Exception? Complete(Operation op) + { + TransactionStatus = (char)Payload[0]; + op.Completed = true; + return op.Error switch + { + null => null, + { SqlState: "57014" } e when op.Cancellation.IsCancellationRequested => new OperationCanceledException("The query was cancelled.", e, op.Cancellation), + var e => e, + }; + } + + private static bool IsStale(PostgresException e) => e.SqlState is "26000" or "0A000"; + + private PgStatement Lookup(string sql, uint[] oids, out bool hit) + { + if (_statements.TryGetValue(sql, out var node)) + { + if (node.Value.ParameterOids.AsSpan().SequenceEqual(oids)) + { + _statementLru.Remove(node); + _statementLru.AddFirst(node); + hit = true; + return node.Value; + } + Evict(node.Value, close: true); + } + hit = false; + var name = _settings.StatementCacheSize > 0 ? "titano_" + (++_statementCounter).ToString(CultureInfo.InvariantCulture) : string.Empty; + return new PgStatement(name, sql, oids); + } + + /// Caches a statement once the server confirmed its Parse; the least recently used one is closed when full. + private void Remember(PgStatement statement) + { + if (statement.Name.Length == 0 || _statements.ContainsKey(statement.Sql)) return; + _statements[statement.Sql] = _statementLru.AddFirst(statement); + while (_statementLru.Count > _settings.StatementCacheSize) Evict(_statementLru.Last!.Value, close: true); + } + + private void Evict(PgStatement statement, bool close) + { + if (_statements.Remove(statement.Sql, out var node)) _statementLru.Remove(node); + if (close && statement.Name.Length > 0) _statementsToClose.Add(statement.Name); + } + + private async ValueTask NextMessageAsync(Operation op) + { + try + { + return await ReadMessageAsync(_ioAbort.Token).ConfigureAwait(false); + } + catch (Exception ex) when (IsIoFailure(ex)) + { + throw ConnectionLost(ex, op); + } + } + + private async ValueTask FlushAsync(Operation op) + { + try + { + await WriteAndClearAsync(_ioAbort.Token).ConfigureAwait(false); + } + catch (Exception ex) when (IsIoFailure(ex)) + { + throw ConnectionLost(ex, op); + } + } + + private async ValueTask WriteAndClearAsync(CancellationToken cancellationToken) + { + try + { + await _stream.WriteAsync(_write.Written, cancellationToken).ConfigureAwait(false); + await _stream.FlushAsync(cancellationToken).ConfigureAwait(false); + } + finally + { + _write.Clear(); + } + } + + private static bool IsIoFailure(Exception ex) => + ex is IOException or SocketException or ObjectDisposedException or OperationCanceledException; + + private Exception ConnectionLost(Exception ex, Operation op) + { + IsBroken = true; + op.Completed = true; + return op.Cancellation.IsCancellationRequested + ? new OperationCanceledException("The query was cancelled and the connection closed.", ex, op.Cancellation) + : new DatabaseConnectionException($"The connection to {_settings.Host}:{_settings.Port} was lost: {ex.Message}", ex); + } + + private DatabaseConnectionException ProtocolViolation(byte type) + { + IsBroken = true; + return new DatabaseConnectionException($"Protocol violation: unexpected message '{(char)type}'."); + } + + /// Reads one message into the buffer, handling notices, parameter changes and notifications inline. + private async ValueTask ReadMessageAsync(CancellationToken cancellationToken) + { + while (true) + { + await EnsureAsync(5, cancellationToken).ConfigureAwait(false); + var type = _read[_readPos]; + var length = BinaryPrimitives.ReadInt32BigEndian(_read.AsSpan(_readPos + 1)); + if (length < 4) throw ProtocolViolation(type); + _readPos += 5; + await EnsureAsync(length - 4, cancellationToken).ConfigureAwait(false); + _messageStart = _readPos; + _messageLength = length - 4; + _readPos += _messageLength; + switch (type) + { + case (byte)'N': + LogNotice(); + continue; + case (byte)'S': + // ParameterStatus: the settings the decoder relies on are pinned in the startup packet. + continue; + case (byte)'A': + { + var pos = 4; + var channel = ReadCString(Payload, ref pos); + var payload = ReadCString(Payload, ref pos); + NotificationReceived?.Invoke(new PgNotification(BinaryPrimitives.ReadInt32BigEndian(Payload), channel, payload)); + continue; + } + default: + return type; + } + } + } + + private async ValueTask EnsureAsync(int count, CancellationToken cancellationToken) + { + if (_readEnd - _readPos >= count) return; + if (_readPos + count > _read.Length) + { + var target = count > _read.Length ? new byte[Math.Max(count, _read.Length * 2)] : _read; + Buffer.BlockCopy(_read, _readPos, target, 0, _readEnd - _readPos); + _read = target; + _readEnd -= _readPos; + _readPos = 0; + } + while (_readEnd - _readPos < count) + { + var n = await _stream.ReadAsync(_read.AsMemory(_readEnd), cancellationToken).ConfigureAwait(false); + if (n == 0) throw new EndOfStreamException("The server closed the connection."); + _readEnd += n; + } + } + + private DbColumns ParseRowDescription(out uint[] oids) + { + var payload = Payload; + var count = BinaryPrimitives.ReadInt16BigEndian(payload); + var names = new string[count]; + oids = new uint[count]; + var pos = 2; + for (var i = 0; i < count; i++) + { + names[i] = ReadCString(payload, ref pos); + oids[i] = BinaryPrimitives.ReadUInt32BigEndian(payload[(pos + 6)..]); + pos += 18; // table oid, column number, type oid, type size, type modifier, format + } + return new DbColumns(names); + } + + private DbRow DecodeRow(PgStatement statement) + { + var payload = Payload; + var oids = statement.ColumnOids ?? throw ProtocolViolation((byte)'D'); + var values = new object?[BinaryPrimitives.ReadInt16BigEndian(payload)]; + var pos = 2; + for (var i = 0; i < values.Length; i++) + { + var length = BinaryPrimitives.ReadInt32BigEndian(payload[pos..]); + pos += 4; + if (length < 0) continue; + values[i] = PgTypes.Decode(oids[i], payload.Slice(pos, length)); + pos += length; + } + return new DbRow(statement.Columns!, values); + } + + private string ReadTag() + { + var pos = 0; + return ReadCString(Payload, ref pos); + } + + /// Row count of an INSERT/UPDATE/DELETE/MERGE/COPY tag ("INSERT 0 5" → 5); 0 for other commands. + private static int AffectedRows(string tag) + { + var space = tag.LastIndexOf(' '); + if (space < 0) return 0; + var command = tag[..tag.IndexOf(' ', StringComparison.Ordinal)]; + if (command is not ("INSERT" or "UPDATE" or "DELETE" or "MERGE" or "COPY")) return 0; + return long.TryParse(tag.AsSpan(space + 1), NumberStyles.None, CultureInfo.InvariantCulture, out var n) ? (int)Math.Min(n, int.MaxValue) : 0; + } + + private PostgresException ParseError() + { + var fields = ParseFields(); + fields.TryGetValue('V', out var severity); + fields.TryGetValue('S', out var localized); + fields.TryGetValue('C', out var code); + fields.TryGetValue('M', out var message); + fields.TryGetValue('P', out var position); + return new PostgresException(severity ?? localized ?? "ERROR", code ?? "XX000", message ?? string.Empty) + { + Detail = fields.GetValueOrDefault('D'), + Hint = fields.GetValueOrDefault('H'), + Position = int.TryParse(position, NumberStyles.None, CultureInfo.InvariantCulture, out var p) ? p : null, + Where = fields.GetValueOrDefault('W'), + SchemaName = fields.GetValueOrDefault('s'), + TableName = fields.GetValueOrDefault('t'), + ColumnName = fields.GetValueOrDefault('c'), + ConstraintName = fields.GetValueOrDefault('n'), + }; + } + + private void LogNotice() + { + var fields = ParseFields(); + var severity = fields.GetValueOrDefault('V') ?? fields.GetValueOrDefault('S') ?? "NOTICE"; + var text = $"{severity} {fields.GetValueOrDefault('C')}: {fields.GetValueOrDefault('M')}"; + if (severity == "WARNING") Log.Warning(LogCategory, text); + else if (severity is "DEBUG" or "LOG") Log.Debug(LogCategory, text); + else Log.Info(LogCategory, text); + } + + private Dictionary ParseFields() + { + var payload = Payload; + var fields = new Dictionary(); + var pos = 0; + while (pos < payload.Length && payload[pos] != 0) + { + var field = (char)payload[pos++]; + fields[field] = ReadCString(payload, ref pos); + } + return fields; + } + + private static string ReadCString(ReadOnlySpan payload, ref int pos) + { + var end = payload[pos..].IndexOf((byte)0); + if (end < 0) throw new DatabaseConnectionException("Protocol violation: unterminated string."); + var value = Encoding.UTF8.GetString(payload.Slice(pos, end)); + pos += end + 1; + return value; + } + + /// State of one command: its statement, the first server error, and cancellation bookkeeping. + private sealed class Operation(PgConnector owner, string sql, DbParam[] parameters, bool decodeRows, CancellationToken cancellation) + { + public PgConnector Owner { get; } = owner; + public string Sql { get; } = sql; + public DbParam[] Parameters { get; } = parameters; + public uint[] ParameterOids { get; } = Array.ConvertAll(parameters, p => PgTypes.OidOf(p.Type)); + public bool DecodeRows { get; } = decodeRows; + public CancellationToken Cancellation { get; } = cancellation; + public CancellationTokenRegistration Registration { get; set; } + public PgStatement? Statement { get; set; } + public bool CacheHit { get; set; } + public bool CanRetryStale { get; set; } = true; + public PostgresException? Error { get; set; } + public string? Tag { get; set; } + public int Affected { get; set; } + public bool Completed { get; set; } + public bool CancelSent { get; set; } + } + + /// A server-side prepared statement and its result shape. + private sealed class PgStatement(string name, string sql, uint[] parameterOids) + { + public string Name { get; } = name; + public string Sql { get; } = sql; + public uint[] ParameterOids { get; } = parameterOids; + public DbColumns? Columns { get; private set; } + public uint[]? ColumnOids { get; private set; } + + public void SetColumns(DbColumns columns, uint[] oids) + { + Columns = columns; + ColumnOids = oids; + } + } +} diff --git a/src/Titano.Data/Postgres/PgListener.cs b/src/Titano.Data/Postgres/PgListener.cs new file mode 100644 index 00000000..b6bcedf8 --- /dev/null +++ b/src/Titano.Data/Postgres/PgListener.cs @@ -0,0 +1,118 @@ +using Titano.Core.Diagnostics; + +namespace Titano.Data.Postgres; + +/// +/// LISTEN/NOTIFY on a dedicated connection (multi-instance job wake-ups). is raised on +/// a background thread; ends when the listener is disposed or faults if the connection +/// is lost, after which a new listener must be created. +/// +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? _pending; + private bool _closed; + + internal PgListener(PgConnector connector) + { + _connector = connector; + connector.NotificationReceived = Raise; + Completion = Task.Run(RunAsync); + } + + public event EventHandler? 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(); + } + + /// + /// 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. + /// + private async Task CommandAsync(string sql, CancellationToken cancellationToken) + { + ObjectDisposedException.ThrowIf(_stop.IsCancellationRequested, this); + await _commandLock.WaitAsync(cancellationToken).ConfigureAwait(false); + var pending = new TaskCompletionSource(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); + } + } +} diff --git a/src/Titano.Data/Postgres/PgPool.cs b/src/Titano.Data/Postgres/PgPool.cs new file mode 100644 index 00000000..c9f8e9f4 --- /dev/null +++ b/src/Titano.Data/Postgres/PgPool.cs @@ -0,0 +1,138 @@ +using System.Net.Sockets; +using Titano.Core.Diagnostics; + +namespace Titano.Data.Postgres; + +/// +/// Connection pool: at most Maximum Pool Size connections, reused most-recent-first; a connection idle +/// longer than Health Check Interval is pinged with SELECT 1 before reuse; broken connections and +/// those left inside a transaction are discarded; idle ones beyond Minimum Pool Size are closed after +/// Connection Idle Lifetime. +/// +internal sealed class PgPool : IAsyncDisposable +{ + private const string LogCategory = "Data.Postgres"; + private static readonly TimeSpan PruneInterval = TimeSpan.FromSeconds(10); + + private readonly PostgresSettings _settings; + private readonly SemaphoreSlim _slots; + private readonly LinkedList _idle = new(); + private readonly Lock _gate = new(); + private readonly Timer _pruner; + private bool _disposed; + + public PgPool(PostgresSettings settings) + { + _settings = settings; + _slots = new SemaphoreSlim(settings.MaxPoolSize, settings.MaxPoolSize); + var interval = settings.IdleLifetime < PruneInterval ? settings.IdleLifetime : PruneInterval; + _pruner = new Timer(static state => ((PgPool)state!).Prune(), this, interval, interval); + } + + public async Task RentAsync(CancellationToken cancellationToken) + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (!await _slots.WaitAsync(_settings.ConnectTimeout, cancellationToken).ConfigureAwait(false)) + throw new DatabaseConnectionException($"No pooled connection became free within {_settings.ConnectTimeout.TotalSeconds} s (Maximum Pool Size={_settings.MaxPoolSize})."); + try + { + while (TakeIdle() is { } connector) + { + bool healthy; + try + { + healthy = !connector.IsBroken + && (connector.IdleTime < _settings.HealthCheckInterval || await connector.PingAsync(cancellationToken).ConfigureAwait(false)); + } + catch + { + // The caller gave up during the health check; the connection's state is unknown. + await connector.DisposeAsync().ConfigureAwait(false); + throw; + } + if (healthy) return connector; + await connector.DisposeAsync().ConfigureAwait(false); + } + return await OpenAsync(cancellationToken).ConfigureAwait(false); + } + catch + { + _slots.Release(); + throw; + } + } + + /// Takes a connection back; a broken or busy one, or one inside a transaction, is closed instead. + public void Return(PgConnector connector) + { + PgConnector? discard = connector; + if (!connector.IsBroken && !connector.IsBusy && connector.TransactionStatus == 'I') + { + connector.MarkIdle(); + lock (_gate) + { + if (!_disposed) + { + _idle.AddFirst(connector); + discard = null; + } + } + } + if (discard is not null) _ = discard.DisposeAsync().AsTask(); + _slots.Release(); + } + + public async ValueTask DisposeAsync() + { + List idle; + lock (_gate) + { + if (_disposed) return; + _disposed = true; + idle = [.. _idle]; + _idle.Clear(); + } + await _pruner.DisposeAsync().ConfigureAwait(false); + foreach (var connector in idle) await connector.DisposeAsync().ConfigureAwait(false); + } + + /// Opens a connection, retrying once after a second when the server is starting up or refused it. + private async Task OpenAsync(CancellationToken cancellationToken) + { + try + { + return await PgConnector.OpenAsync(_settings, cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (ex is PostgresException { IsConnectionFailure: true } or DatabaseConnectionException { InnerException: SocketException }) + { + Log.Warning(LogCategory, $"Connecting to {_settings.Host}:{_settings.Port} failed ({ex.Message}); retrying once."); + await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ConfigureAwait(false); + return await PgConnector.OpenAsync(_settings, cancellationToken).ConfigureAwait(false); + } + } + + private PgConnector? TakeIdle() + { + lock (_gate) + { + if (_idle.First is not { } first) return null; + _idle.RemoveFirst(); + return first.Value; + } + } + + private void Prune() + { + List? expired = null; + lock (_gate) + { + while (_idle.Count > _settings.MinPoolSize && _idle.Last is { } last && last.Value.IdleTime >= _settings.IdleLifetime) + { + _idle.RemoveLast(); + (expired ??= []).Add(last.Value); + } + } + if (expired is null) return; + foreach (var connector in expired) _ = connector.DisposeAsync().AsTask(); + } +} diff --git a/src/Titano.Data/Postgres/PgTypes.cs b/src/Titano.Data/Postgres/PgTypes.cs new file mode 100644 index 00000000..443a0ad5 --- /dev/null +++ b/src/Titano.Data/Postgres/PgTypes.cs @@ -0,0 +1,204 @@ +using System.Buffers; +using System.Buffers.Text; +using System.Globalization; +using System.Text; + +namespace Titano.Data.Postgres; + +/// Type OIDs, text-format value encoding and result decoding (BRIEF §6.3 type mapping). +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 CopySpecials = SearchValues.Create("\\\t\n\r"); + + /// Parameter type sent in Parse; 0 lets the server infer an untyped NULL. + 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, + }; + + /// + /// Writes the text form of a canonical value (anything but byte[]) as UTF-8 and returns + /// the byte count. must hold bytes. + /// + public static int FormatText(object value, Span 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}."); + } + + /// Upper bound of output for . + public static int MaxTextLength(object value) => value is string s ? Encoding.UTF8.GetMaxByteCount(s.Length) : 64; + + /// + /// Writes a value in COPY text format: \N for NULL, specials in strings backslash-escaped, bytea in + /// hex form (\\x…). Values of other CLR types go through normalisation. + /// + public static void WriteCopyValue(object? value, IBufferWriter 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 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)..]; + } + } + + /// + /// 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; + 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 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); + } + } + + /// 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' || 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/Postgres/PgWriteBuffer.cs b/src/Titano.Data/Postgres/PgWriteBuffer.cs new file mode 100644 index 00000000..6c761553 --- /dev/null +++ b/src/Titano.Data/Postgres/PgWriteBuffer.cs @@ -0,0 +1,98 @@ +using System.Buffers; +using System.Buffers.Binary; +using System.Text; + +namespace Titano.Data.Postgres; + +/// Growable outgoing buffer that frames protocol messages (type byte + big-endian length). +internal sealed class PgWriteBuffer : IBufferWriter +{ + private byte[] _buffer = new byte[8192]; + private int _messageStart = -1; + + public int Length { get; private set; } + + public ReadOnlyMemory Written => _buffer.AsMemory(0, Length); + + /// Starts a message; its length is patched by . + public void StartMessage(char type) + { + GetSpan(1)[0] = (byte)type; + Advance(1); + StartUntypedMessage(); + } + + /// Starts a message without a type byte (startup, SSL and cancel requests). + 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 bytes) + { + bytes.CopyTo(GetSpan(bytes.Length)); + Advance(bytes.Length); + } + + /// UTF-8 text followed by a NUL terminator. + 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); + } + + /// Empties the buffer; an oversized one (a big bytea parameter) is released so pooled connections stay small. + 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 GetMemory(int sizeHint = 0) + { + Ensure(sizeHint); + return _buffer.AsMemory(Length); + } + + public Span 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)); + } +} diff --git a/src/Titano.Data/Postgres/PostgresDatabase.cs b/src/Titano.Data/Postgres/PostgresDatabase.cs new file mode 100644 index 00000000..84bf644d --- /dev/null +++ b/src/Titano.Data/Postgres/PostgresDatabase.cs @@ -0,0 +1,233 @@ +using System.Runtime.CompilerServices; +using Titano.Core.Diagnostics; + +namespace Titano.Data.Postgres; + +/// A PostgreSQL server reached through the in-house protocol v3 client and its connection pool. +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 OpenAsync(CancellationToken cancellationToken) => + new PostgresSession(_pool, await _pool.RentAsync(cancellationToken).ConfigureAwait(false)); + + /// Opens a dedicated (unpooled) connection that raises an event for every NOTIFY on its channels. + public async Task CreateListenerAsync(CancellationToken cancellationToken = default) => + new(await PgConnector.OpenAsync(Settings, cancellationToken).ConfigureAwait(false)); + + public ValueTask DisposeAsync() => _pool.DisposeAsync(); +} + +/// +/// 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. +/// +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 ExecuteAsync(string sql, DbParam[] parameters, CancellationToken cancellationToken) => + Connector.ExecuteAsync(sql, parameters, cancellationToken); + + public async IAsyncEnumerable 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 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 BulkInsertAsync(string table, IReadOnlyList columns, IAsyncEnumerable 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); + } + } + + /// + /// Ends 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). + /// + 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 }; + + /// True for statements that only read, so running them twice is harmless. + 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)["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; + } +} + +/// A BEGIN … COMMIT block on one session. +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); + } +} diff --git a/src/Titano.Data/Postgres/PostgresException.cs b/src/Titano.Data/Postgres/PostgresException.cs new file mode 100644 index 00000000..92a1159c --- /dev/null +++ b/src/Titano.Data/Postgres/PostgresException.cs @@ -0,0 +1,47 @@ +namespace Titano.Data.Postgres; + +/// An ErrorResponse from the server, with the standard fields of the PostgreSQL protocol. +public sealed class PostgresException : DatabaseException +{ + internal PostgresException(string severity, string sqlState, string messageText) + : base($"{severity} {sqlState}: {messageText}") + { + Severity = severity; + SqlState = sqlState; + MessageText = messageText; + } + + /// ERROR, FATAL or PANIC (non-localised when the server sends it). + public string Severity { get; } + + /// Five-character SQLSTATE, e.g. 23505 (unique_violation). + public override string SqlState { get; } + + /// The primary human-readable message. + public string MessageText { get; } + + public string? Detail { get; internal init; } + public string? Hint { get; internal init; } + + /// 1-based character position of the error in the statement text. + 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; } + + /// The server ends the session after FATAL/PANIC errors. + public bool IsFatal => Severity is "FATAL" or "PANIC"; + + /// Server shutdown/startup or connection failures (57P01, 57P02, 57P03, class 08): a new connection may succeed. + public bool IsConnectionFailure => SqlState is "57P01" or "57P02" or "57P03" || SqlState.StartsWith("08", StringComparison.Ordinal); + + /// Connection failures plus serialization failures and deadlocks. + public override bool IsTransient => IsConnectionFailure || SqlState is "40001" or "40P01"; + + public override bool IsUniqueViolation => SqlState == "23505"; + + public override bool IsForeignKeyViolation => SqlState == "23503"; +} diff --git a/src/Titano.Data/Postgres/PostgresSettings.cs b/src/Titano.Data/Postgres/PostgresSettings.cs new file mode 100644 index 00000000..00f1601c --- /dev/null +++ b/src/Titano.Data/Postgres/PostgresSettings.cs @@ -0,0 +1,84 @@ +namespace Titano.Data.Postgres; + +/// TLS policy, with libpq's meaning. +public enum SslMode +{ + /// Plain TCP. + Disable, + + /// TLS when the server offers it, without certificate verification; plain TCP otherwise. + Prefer, + + /// TLS or fail; the certificate is not verified. + Require, + + /// TLS with a trusted chain whose certificate matches the host name. + VerifyFull, +} + +/// +/// PostgreSQL connection settings. Keys (case/space-insensitive): Host, Port (5432), Database +/// (defaults to the user), Username, Password, SslMode (prefer), Root Certificate +/// (PEM trusted by verify-full), Application Name (titano-server), Search Path, Timeout +/// (connect, 15 s), Minimum Pool Size (0), Maximum Pool Size (20), Connection Idle Lifetime +/// (300 s), Health Check Interval (30 s idle before a pooled connection is pinged), +/// Statement Cache Size (128 prepared statements per connection; 0 disables). +/// +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 || 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)."), + }; +} diff --git a/src/Titano.Data/Repositories/ArchiveRepository.cs b/src/Titano.Data/Repositories/ArchiveRepository.cs new file mode 100644 index 00000000..717eb4f9 --- /dev/null +++ b/src/Titano.Data/Repositories/ArchiveRepository.cs @@ -0,0 +1,43 @@ +using Titano.Core.Model; + +namespace Titano.Data.Repositories; + +/// Archive roots (BRIEF §5, §7). +public sealed class ArchiveRepository +{ + private const string Columns = "id, name, root_path, folder_template, file_template, schema_version, created, proxy_long_edge"; + + private static readonly string UpsertSql = SqlDialect.Upsert("archives", + ["id", "name", "root_path", "folder_template", "file_template", "schema_version", "created", "proxy_long_edge"], 1); + + private readonly DbAccess _db; + + internal ArchiveRepository(DbAccess db) => _db = db; + + public async Task UpsertAsync(Archive archive, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync(UpsertSql, + [archive.Id, archive.Name, archive.RootPath, archive.FolderTemplate, archive.FileTemplate, archive.SchemaVersion, archive.Created, archive.ProxyLongEdge], + cancellationToken).ConfigureAwait(false); + + public Task GetAsync(Guid id, CancellationToken cancellationToken = default) => + _db.SingleAsync($"SELECT {Columns} FROM archives WHERE id = $1", [id], Map, cancellationToken); + + public Task> ListAsync(CancellationToken cancellationToken = default) => + _db.ListAsync($"SELECT {Columns} FROM archives ORDER BY name, id", [], Map, cancellationToken); + + /// Deletes the archive and everything indexed under it (the files on disk are untouched). + public async Task DeleteAsync(Guid id, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync("DELETE FROM archives WHERE id = $1", [id], cancellationToken).ConfigureAwait(false) > 0; + + private static Archive Map(DbRow r) => new() + { + Id = r.GetGuid(0), + Name = r.GetString(1), + RootPath = r.GetString(2), + FolderTemplate = r.GetString(3), + FileTemplate = r.GetString(4), + SchemaVersion = r.GetInt32(5), + Created = r.GetDateTimeOffset(6), + ProxyLongEdge = r.GetInt32(7), + }; +} diff --git a/src/Titano.Data/Repositories/AuditRepository.cs b/src/Titano.Data/Repositories/AuditRepository.cs new file mode 100644 index 00000000..46e13c31 --- /dev/null +++ b/src/Titano.Data/Repositories/AuditRepository.cs @@ -0,0 +1,58 @@ +using Titano.Core.Model; + +namespace Titano.Data.Repositories; + +/// Append-only record of who did what (BRIEF §5 AuditLog, §14.2). +public sealed class AuditRepository +{ + private const string Columns = "id, at, user_id, username, action, target_kind, target_id, details, remote_address"; + + private readonly DbAccess _db; + + internal AuditRepository(DbAccess db) => _db = db; + + public async Task AppendAsync(AuditEntry entry, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync($"INSERT INTO audit_log ({Columns}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)", + [entry.Id, entry.At, entry.UserId, entry.Username, entry.Action, entry.TargetKind, entry.TargetId, entry.Details, entry.RemoteAddress], + cancellationToken).ConfigureAwait(false); + + /// Entries newest first, optionally of one user. + public Task> ListAsync(Guid? userId = null, int limit = 100, string? cursor = null, CancellationToken cancellationToken = default) + { + var p = new SqlParameters(); + var where = new List(); + if (userId is { } user) where.Add($"user_id = {p.Add(user)}"); + if (cursor is not null) + { + var (value, id) = Cursor.Decode("audit", cursor); + where.Add(Cursor.After("at", "id", descending: true, value, id, p.Add)); + } + var take = Cursor.ClampLimit(limit); + var sql = $"SELECT {Columns} FROM audit_log{(where.Count > 0 ? " WHERE " + string.Join(" AND ", where) : string.Empty)} " + + $"ORDER BY at DESC, id DESC LIMIT {p.Add(take + 1)}"; + return _db.RunAsync(async session => + { + var entries = await session.QueryListAsync(sql, p.ToArray(), Map, cancellationToken).ConfigureAwait(false); + string? next = null; + if (entries.Count > take) + { + entries.RemoveAt(take); + next = Cursor.Encode("audit", entries[^1].At, entries[^1].Id); + } + return new Page(entries, next); + }, cancellationToken); + } + + private static AuditEntry Map(DbRow r) => new() + { + Id = r.GetGuid(0), + At = r.GetDateTimeOffset(1), + UserId = r.GetGuidOrNull(2), + Username = r.GetStringOrNull(3), + Action = r.GetString(4), + TargetKind = r.GetStringOrNull(5), + TargetId = r.GetStringOrNull(6), + Details = r.GetStringOrNull(7), + RemoteAddress = r.GetStringOrNull(8), + }; +} diff --git a/src/Titano.Data/Repositories/DbAccess.cs b/src/Titano.Data/Repositories/DbAccess.cs new file mode 100644 index 00000000..77a419cf --- /dev/null +++ b/src/Titano.Data/Repositories/DbAccess.cs @@ -0,0 +1,145 @@ +using System.Buffers.Text; +using System.Globalization; +using System.Text; + +namespace Titano.Data.Repositories; + +/// One page of a keyset-paginated listing; pass back to get the following page. +public sealed record Page(IReadOnlyList Items, string? NextCursor); + +/// +/// Where repository commands run: on a caller's session (so they join its transaction) or on a session +/// borrowed from the pool for the duration of one call. +/// +internal sealed class DbAccess +{ + private readonly IDatabase? _database; + private readonly IDbSession? _session; + + public DbAccess(IDatabase database) + { + _database = database; + Sql = SqlDialect.For(database.Dialect); + } + + public DbAccess(IDbSession session) + { + _session = session; + Sql = SqlDialect.For(session.Dialect); + } + + public SqlDialect Sql { get; } + + public async Task RunAsync(Func> work, CancellationToken cancellationToken) + { + if (_session is not null) return await work(_session).ConfigureAwait(false); + var session = await _database!.OpenAsync(cancellationToken).ConfigureAwait(false); + await using (session.ConfigureAwait(false)) return await work(session).ConfigureAwait(false); + } + + /// Runs atomically: inside the caller's transaction, or in a new one. + public Task InTransactionAsync(Func> work, CancellationToken cancellationToken) => + RunAsync(async session => + { + if (session.InTransaction) return await work(session).ConfigureAwait(false); + var transaction = await session.BeginAsync(cancellationToken).ConfigureAwait(false); + await using (transaction.ConfigureAwait(false)) + { + var result = await work(session).ConfigureAwait(false); + await transaction.CommitAsync(cancellationToken).ConfigureAwait(false); + return result; + } + }, cancellationToken); + + public Task ExecuteAsync(string sql, DbParam[] parameters, CancellationToken cancellationToken) => + RunAsync(s => s.ExecuteAsync(sql, parameters, cancellationToken), cancellationToken); + + public async Task> ListAsync(string sql, DbParam[] parameters, Func map, CancellationToken cancellationToken) => + await RunAsync(s => s.QueryListAsync(sql, parameters, map, cancellationToken), cancellationToken).ConfigureAwait(false); + + public Task SingleAsync(string sql, DbParam[] parameters, Func map, CancellationToken cancellationToken) => + RunAsync(s => s.QuerySingleOrDefaultAsync(sql, parameters, map, cancellationToken), cancellationToken); + + public Task ScalarAsync(string sql, DbParam[] parameters, CancellationToken cancellationToken) => + RunAsync(s => s.ScalarAsync(sql, parameters, cancellationToken), cancellationToken); +} + +/// +/// Opaque keyset cursors: the sort value and id of the last row of a page, tagged with the listing they belong +/// to so a cursor cannot be replayed against a different ordering. +/// +internal static class Cursor +{ + public static string Encode(string scope, object? value, Guid id) + { + var payload = value switch + { + null => "n", + DateTime d => "t" + d.Ticks.ToString(CultureInfo.InvariantCulture), + DateTimeOffset o => "o" + o.UtcTicks.ToString(CultureInfo.InvariantCulture), + long l => "i" + l.ToString(CultureInfo.InvariantCulture), + int i => "i" + i.ToString(CultureInfo.InvariantCulture), + string s => "s" + s, + _ => throw new NotSupportedException($"Cursor values of type {value.GetType().Name} are not supported."), + }; + return Base64Url.EncodeToString(Encoding.UTF8.GetBytes($"{scope}|{id:N}|{payload}")); + } + + /// Decodes a cursor of ; anything else is a . + public static (object? Value, Guid Id) Decode(string scope, string cursor) + { + string text; + try + { + text = Encoding.UTF8.GetString(Base64Url.DecodeFromChars(cursor)); + } + catch (FormatException ex) + { + throw new FormatException("Invalid paging cursor.", ex); + } + var parts = text.Split('|', 3); + if (parts.Length != 3 || parts[0] != scope || !Guid.TryParseExact(parts[1], "N", out var id) || parts[2].Length == 0) + throw new FormatException("The paging cursor does not belong to this listing."); + var payload = parts[2][1..]; + object? value = parts[2][0] switch + { + 'n' => null, + 't' => new DateTime(long.Parse(payload, CultureInfo.InvariantCulture), DateTimeKind.Unspecified), + 'o' => new DateTimeOffset(long.Parse(payload, CultureInfo.InvariantCulture), TimeSpan.Zero), + 'i' => long.Parse(payload, CultureInfo.InvariantCulture), + 's' => payload, + _ => throw new FormatException("Invalid paging cursor."), + }; + return (value, id); + } + + /// + /// Keyset condition "after (value, id)" for ORDER BY column dir NULLS LAST, id dir; adds its parameters + /// through , which returns the placeholder text. + /// + public static string After(string column, string idColumn, bool descending, object? value, Guid id, Func parameter) + { + var op = descending ? "<" : ">"; + var idParam = parameter(id); + if (value is null) return $"({column} IS NULL AND {idColumn} {op} {idParam})"; + var v = parameter(new DbParam(value)); + return $"({column} {op} {v} OR ({column} = {v} AND {idColumn} {op} {idParam}) OR {column} IS NULL)"; + } + + public static int ClampLimit(int limit) => Math.Clamp(limit, 1, 1000); +} + +/// Builds positional parameter lists alongside SQL text. +internal sealed class SqlParameters +{ + private readonly List _values = []; + + /// Adds a value and returns its placeholder ($n). + public string Add(DbParam value) + { + _values.Add(value); + return "$" + _values.Count.ToString(CultureInfo.InvariantCulture); + } + + public DbParam[] ToArray() => [.. _values]; +} diff --git a/src/Titano.Data/Repositories/FrameRepository.cs b/src/Titano.Data/Repositories/FrameRepository.cs new file mode 100644 index 00000000..30350e5e --- /dev/null +++ b/src/Titano.Data/Repositories/FrameRepository.cs @@ -0,0 +1,157 @@ +using System.Text; +using Titano.Core.Imaging; +using Titano.Core.Model; + +namespace Titano.Data.Repositories; + +/// Light statistics of one frame, written by the analysis job. +public readonly record struct FrameLightStats(Guid FrameId, double? MeanLogLuminance, double? ClipLow, double? ClipHigh); + +/// Frames of sequences: bulk import, paged listing, duplicate lookup and bulk updates. +public sealed class FrameRepository +{ + private static readonly string[] ColumnNames = + [ + "id", "sequence_id", "idx", "relative_path", "file_name", "original_file_name", "size", "sha256", "captured_at", + "utc_offset_minutes", "timestamp_source", "exposure_time", "f_number", "iso", "focal_length", "exposure_bias", + "white_balance", "orientation", "width", "height", "format", "preview_offset", "preview_length", + "mean_log_luminance", "clip_low", "clip_high", "flags", + ]; + + private static readonly string Columns = string.Join(", ", ColumnNames); + private static readonly string InsertSql = + $"INSERT INTO frames ({Columns}) VALUES ({string.Join(", ", ColumnNames.Select((_, i) => "$" + (i + 1)))})"; + + /// Rows per statement of the batched PostgreSQL updates (4 or fewer parameters per row). + private const int Batch = 1000; + + private readonly DbAccess _db; + + internal FrameRepository(DbAccess db) => _db = db; + + public async Task InsertAsync(Frame frame, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync(InsertSql, Array.ConvertAll(Values(frame), v => new DbParam(v)), cancellationToken).ConfigureAwait(false); + + /// Inserts many frames at once (COPY on PostgreSQL, batched INSERTs in one transaction on SQLite). + public Task BulkInsertAsync(IEnumerable frames, CancellationToken cancellationToken = default) => + _db.RunAsync(session => session.BulkInsertAsync("frames", ColumnNames, frames.Select(Values).ToAsyncEnumerable(), cancellationToken), cancellationToken); + + public Task GetAsync(Guid id, CancellationToken cancellationToken = default) => + _db.SingleAsync($"SELECT {Columns} FROM frames WHERE id = $1", [id], Map, cancellationToken); + + /// Frames of a sequence by index, starting after (keyset paging). + public Task> ListBySequenceAsync(Guid sequenceId, int afterIndex = -1, int limit = 1000, CancellationToken cancellationToken = default) => + _db.ListAsync($"SELECT {Columns} FROM frames WHERE sequence_id = $1 AND idx > $2 ORDER BY idx LIMIT $3", + [sequenceId, afterIndex, Cursor.ClampLimit(limit)], Map, cancellationToken); + + /// Every frame with this content hash (duplicate detection, upload short-circuit). + public Task> FindBySha256Async(string sha256, CancellationToken cancellationToken = default) => + _db.ListAsync($"SELECT {Columns} FROM frames WHERE sha256 = $1 ORDER BY sequence_id, idx", [sha256.ToLowerInvariant()], Map, cancellationToken); + + /// Writes analysis results for many frames in one transaction; returns the number of frames updated. + public Task UpdateLightStatsAsync(IReadOnlyList stats, CancellationToken cancellationToken = default) => + _db.InTransactionAsync(async session => + { + var updated = 0; + if (_db.Sql.IsPostgres) + { + // One UPDATE … FROM (VALUES …) per batch instead of a round trip per frame. + for (var start = 0; start < stats.Count; start += Batch) + { + var count = Math.Min(Batch, stats.Count - start); + var sql = new StringBuilder("UPDATE frames AS f SET mean_log_luminance = v.m, clip_low = v.lo, clip_high = v.hi FROM (VALUES "); + var args = new DbParam[count * 4]; + for (var i = 0; i < count; i++) + { + var s = stats[start + i]; + sql.Append(i > 0 ? ", (" : "(").Append('$').Append(4 * i + 1).Append(", $").Append(4 * i + 2) + .Append(", $").Append(4 * i + 3).Append(", $").Append(4 * i + 4).Append(')'); + args[4 * i] = s.FrameId; + args[4 * i + 1] = s.MeanLogLuminance; + args[4 * i + 2] = s.ClipLow; + args[4 * i + 3] = s.ClipHigh; + } + sql.Append(") AS v(id, m, lo, hi) WHERE f.id = v.id"); + updated += await session.ExecuteAsync(sql.ToString(), args, cancellationToken).ConfigureAwait(false); + } + } + else + { + foreach (var s in stats) + { + updated += await session.ExecuteAsync( + "UPDATE frames SET mean_log_luminance = $2, clip_low = $3, clip_high = $4 WHERE id = $1", + [s.FrameId, s.MeanLogLuminance, s.ClipLow, s.ClipHigh], cancellationToken).ConfigureAwait(false); + } + } + return updated; + }, cancellationToken); + + /// Sets and clears flags on many frames in one transaction; returns the number of frames updated. + public Task UpdateFlagsAsync(IReadOnlyList frameIds, FrameFlags set, FrameFlags clear, CancellationToken cancellationToken = default) => + _db.InTransactionAsync(async session => + { + // 500 ids per statement stays below SQLite's historical 999-variable limit. + const int idsPerStatement = 500; + var updated = 0; + for (var start = 0; start < frameIds.Count; start += idsPerStatement) + { + var count = Math.Min(idsPerStatement, frameIds.Count - start); + var args = new DbParam[count + 2]; + args[0] = (int)set; + args[1] = (int)clear; + var placeholders = new StringBuilder(); + for (var i = 0; i < count; i++) + { + args[i + 2] = frameIds[start + i]; + placeholders.Append(i > 0 ? ", $" : "$").Append(i + 3); + } + updated += await session.ExecuteAsync($"UPDATE frames SET flags = (flags | $1) & ~$2 WHERE id IN ({placeholders})", + args, cancellationToken).ConfigureAwait(false); + } + return updated; + }, cancellationToken); + + /// Removes every frame of a sequence; returns how many. + public Task DeleteBySequenceAsync(Guid sequenceId, CancellationToken cancellationToken = default) => + _db.ExecuteAsync("DELETE FROM frames WHERE sequence_id = $1", [sequenceId], cancellationToken); + + private static object?[] Values(Frame f) => + [ + f.Id, f.SequenceId, f.Index, f.RelativePath, f.FileName, f.OriginalFileName, f.Size, f.Sha256?.ToLowerInvariant(), + SequenceRepository.Wall(f.CapturedAt), f.UtcOffsetMinutes, (int)f.TimestampSource, f.ExposureTime, f.FNumber, f.Iso, + f.FocalLength, f.ExposureBias, f.WhiteBalance, f.Orientation, f.Width, f.Height, (int)f.Format, f.PreviewOffset, + f.PreviewLength, f.MeanLogLuminance, f.ClipLow, f.ClipHigh, (int)f.Flags, + ]; + + private static Frame Map(DbRow r) => new() + { + Id = r.GetGuid(0), + SequenceId = r.GetGuid(1), + Index = r.GetInt32(2), + RelativePath = r.GetString(3), + FileName = r.GetString(4), + OriginalFileName = r.GetStringOrNull(5), + Size = r.GetInt64(6), + Sha256 = r.GetStringOrNull(7), + CapturedAt = r.GetDateTimeOrNull(8), + UtcOffsetMinutes = r.GetInt32OrNull(9), + TimestampSource = (TimestampSource)r.GetInt32(10), + ExposureTime = r.GetDoubleOrNull(11), + FNumber = r.GetDoubleOrNull(12), + Iso = r.GetInt32OrNull(13), + FocalLength = r.GetDoubleOrNull(14), + ExposureBias = r.GetDoubleOrNull(15), + WhiteBalance = r.GetInt32OrNull(16), + Orientation = r.GetInt32(17), + Width = r.GetInt32(18), + Height = r.GetInt32(19), + Format = (ImageFileFormat)r.GetInt32(20), + PreviewOffset = r.GetInt64OrNull(21), + PreviewLength = r.GetInt64OrNull(22), + MeanLogLuminance = r.GetDoubleOrNull(23), + ClipLow = r.GetDoubleOrNull(24), + ClipHigh = r.GetDoubleOrNull(25), + Flags = (FrameFlags)r.GetInt32(26), + }; +} diff --git a/src/Titano.Data/Repositories/JobRepository.cs b/src/Titano.Data/Repositories/JobRepository.cs new file mode 100644 index 00000000..b3bd9857 --- /dev/null +++ b/src/Titano.Data/Repositories/JobRepository.cs @@ -0,0 +1,142 @@ +using System.Globalization; +using Titano.Core.Model; + +namespace Titano.Data.Repositories; + +/// +/// The persistent job queue (BRIEF §14.6): workers claim the oldest job of the highest priority atomically, +/// write checkpoints while running, and on startup requeue what a crash left running. +/// +public sealed class JobRepository +{ + private const string Columns = + "id, kind, target_ids, target_label, parameters_json, state, priority, progress_done, progress_total, items_per_second, " + + "eta_seconds, checkpoint, log_tail, created_by, node_id, attempts, error, created, started, finished"; + + private readonly DbAccess _db; + + internal JobRepository(DbAccess db) => _db = db; + + public async Task EnqueueAsync(Job job, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync( + $"INSERT INTO jobs ({Columns}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20)", + [ + job.Id, (int)job.Kind, string.Join(',', job.TargetIds), job.TargetLabel, DbParam.Json(job.ParametersJson), (int)job.State, + (int)job.Priority, job.ProgressDone, job.ProgressTotal, job.ItemsPerSecond, job.Eta?.TotalSeconds, job.Checkpoint, job.LogTail, + job.CreatedBy, job.NodeId, job.Attempts, job.Error, job.Created, job.Started, job.Finished, + ], cancellationToken).ConfigureAwait(false); + + public Task GetAsync(Guid id, CancellationToken cancellationToken = default) => + _db.SingleAsync($"SELECT {Columns} FROM jobs WHERE id = $1", [id], Map, cancellationToken); + + /// + /// Marks the next queued job (highest priority, then oldest) of the given kinds as running for + /// and returns it, or null when none waits. Concurrent claimers never get the same + /// job: PostgreSQL skips rows locked by other claimers, SQLite holds its write lock across select and update. + /// + public Task ClaimNextAsync(string workerId, IReadOnlyCollection? kinds = null, CancellationToken cancellationToken = default) + { + var kindFilter = kinds is { Count: > 0 } + ? " AND kind IN (" + string.Join(", ", kinds.Select(k => ((int)k).ToString(CultureInfo.InvariantCulture))) + ")" + : string.Empty; + var pick = $"SELECT id FROM jobs WHERE state = {(int)JobState.Queued}{kindFilter} ORDER BY priority DESC, created, id LIMIT 1"; + var claim = $"UPDATE jobs SET state = {(int)JobState.Running}, node_id = $1, started = $2, finished = NULL, error = NULL, attempts = attempts + 1"; + DbParam[] args = [workerId, DateTimeOffset.UtcNow]; + if (_db.Sql.IsPostgres) + return _db.SingleAsync($"{claim} WHERE id = ({pick}{_db.Sql.ForUpdateSkipLocked}) RETURNING {Columns}", args, Map, cancellationToken); + + return _db.InTransactionAsync(async session => + { + var id = await session.ScalarAsync(pick, [], cancellationToken).ConfigureAwait(false); + if (id is null) return null; + await session.ExecuteAsync($"{claim} WHERE id = $3", [.. args, id], cancellationToken).ConfigureAwait(false); + return await session.QuerySingleOrDefaultAsync($"SELECT {Columns} FROM jobs WHERE id = $1", [id], Map, cancellationToken).ConfigureAwait(false); + }, cancellationToken); + } + + /// + /// Checkpoint of a running job. Returns false when the job is no longer running (cancelled or paused meanwhile), + /// which tells the worker to stop. + /// + public async Task UpdateProgressAsync(Guid id, long done, long total, double? itemsPerSecond, TimeSpan? eta, + string? checkpoint, string? logTail, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync( + "UPDATE jobs SET progress_done = $2, progress_total = $3, items_per_second = $4, eta_seconds = $5, checkpoint = $6, log_tail = $7 " + + $"WHERE id = $1 AND state = {(int)JobState.Running}", + [id, done, total, itemsPerSecond, eta?.TotalSeconds, checkpoint, logTail], cancellationToken).ConfigureAwait(false) > 0; + + /// Moves a job to ; done/failed/cancelled stamp the finish time, queued clears it for a retry. + public async Task SetStateAsync(Guid id, JobState state, string? error = null, CancellationToken cancellationToken = default) + { + var terminal = state is JobState.Done or JobState.Failed or JobState.Cancelled; + return await _db.ExecuteAsync("UPDATE jobs SET state = $2, error = $3, finished = $4 WHERE id = $1", + [id, (int)state, error, terminal ? DateTimeOffset.UtcNow : (DateTimeOffset?)null], cancellationToken).ConfigureAwait(false) > 0; + } + + /// Jobs, newest first, optionally of one state. + public Task> ListAsync(JobState? state = null, int limit = 50, string? cursor = null, CancellationToken cancellationToken = default) + { + var p = new SqlParameters(); + var where = new List(); + if (state is { } s) where.Add($"state = {p.Add((int)s)}"); + if (cursor is not null) + { + var (value, id) = Cursor.Decode("jobs", cursor); + where.Add(Cursor.After("created", "id", descending: true, value, id, p.Add)); + } + var take = Cursor.ClampLimit(limit); + var sql = $"SELECT {Columns} FROM jobs{(where.Count > 0 ? " WHERE " + string.Join(" AND ", where) : string.Empty)} " + + $"ORDER BY created DESC, id DESC LIMIT {p.Add(take + 1)}"; + return _db.RunAsync(async session => + { + var jobs = await session.QueryListAsync(sql, p.ToArray(), Map, cancellationToken).ConfigureAwait(false); + string? next = null; + if (jobs.Count > take) + { + jobs.RemoveAt(take); + next = Cursor.Encode("jobs", jobs[^1].Created, jobs[^1].Id); + } + return new Page(jobs, next); + }, cancellationToken); + } + + /// Deletes finished jobs (done, failed, cancelled) that finished before . + public Task PurgeHistoryAsync(DateTimeOffset finishedBefore, CancellationToken cancellationToken = default) => + _db.ExecuteAsync( + $"DELETE FROM jobs WHERE state IN ({(int)JobState.Done}, {(int)JobState.Failed}, {(int)JobState.Cancelled}) AND finished < $1", + [finishedBefore], cancellationToken); + + /// + /// Crash recovery: puts running jobs back in the queue, keeping their checkpoints. With + /// only that worker's jobs are requeued (other server instances keep theirs). + /// + public Task RequeueRunningAsync(string? nodeId = null, CancellationToken cancellationToken = default) => + _db.ExecuteAsync( + $"UPDATE jobs SET state = {(int)JobState.Queued}, node_id = NULL, started = NULL WHERE state = {(int)JobState.Running}" + + (nodeId is null ? string.Empty : " AND node_id = $1"), + nodeId is null ? [] : [nodeId], cancellationToken); + + private static Job Map(DbRow r) => new() + { + Id = r.GetGuid(0), + Kind = (JobKind)r.GetInt32(1), + TargetIds = r.GetString(2) is { Length: > 0 } ids ? Array.ConvertAll(ids.Split(','), Guid.Parse) : [], + TargetLabel = r.GetStringOrNull(3), + ParametersJson = r.GetStringOrNull(4), + State = (JobState)r.GetInt32(5), + Priority = (JobPriority)r.GetInt32(6), + ProgressDone = r.GetInt64(7), + ProgressTotal = r.GetInt64(8), + ItemsPerSecond = r.GetDoubleOrNull(9), + Eta = r.GetDoubleOrNull(10) is { } seconds ? TimeSpan.FromSeconds(seconds) : null, + Checkpoint = r.GetStringOrNull(11), + LogTail = r.GetStringOrNull(12), + CreatedBy = r.GetGuidOrNull(13), + NodeId = r.GetStringOrNull(14), + Attempts = r.GetInt32(15), + Error = r.GetStringOrNull(16), + Created = r.GetDateTimeOffset(17), + Started = r.GetDateTimeOffsetOrNull(18), + Finished = r.GetDateTimeOffsetOrNull(19), + }; +} diff --git a/src/Titano.Data/Repositories/MediaCardRepository.cs b/src/Titano.Data/Repositories/MediaCardRepository.cs new file mode 100644 index 00000000..ab95cc5f --- /dev/null +++ b/src/Titano.Data/Repositories/MediaCardRepository.cs @@ -0,0 +1,125 @@ +using Titano.Core.Model; + +namespace Titano.Data.Repositories; + +/// +/// Identity of a file on a card as seen at import: path on the card, size and modification time. Times are +/// truncated to whole microseconds, the precision the database keeps, so keys built from the file system match +/// stored ones. +/// +public readonly record struct ImportKey +{ + public ImportKey(string path, long size, DateTimeOffset modified) + { + Path = path; + Size = size; + Modified = new DateTimeOffset(modified.UtcTicks - modified.UtcTicks % 10, TimeSpan.Zero); + } + + public string Path { get; } + + public long Size { get; } + + public DateTimeOffset Modified { get; } +} + +/// One file imported from a card and where it went. +public sealed record ImportRecord(Guid CardId, ImportKey Key, string? Sha256, Guid? FrameId, Guid? JobId, DateTimeOffset ImportedAt); + +/// Known memory cards and their import history (BRIEF §13), used to skip files already imported. +public sealed class MediaCardRepository +{ + private const string Columns = + "id, identity, volume_serial, label, capacity, nickname, camera_make, camera_model, camera_serial, profile_json, auto_import, first_seen, last_seen"; + + private static readonly string UpsertSql = SqlDialect.Upsert("media_cards", + [ + "id", "identity", "volume_serial", "label", "capacity", "nickname", "camera_make", "camera_model", "camera_serial", + "profile_json", "auto_import", "first_seen", "last_seen", + ], 1); + + private static readonly string RecordSql = SqlDialect.Upsert("import_history", + ["card_id", "path", "size", "mtime", "sha256", "frame_id", "job_id", "imported_at"], 4); + + private readonly DbAccess _db; + + internal MediaCardRepository(DbAccess db) => _db = db; + + public async Task UpsertAsync(MediaCard card, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync(UpsertSql, + [ + card.Id, card.Identity, (long)card.VolumeSerial, card.Label, card.Capacity, card.Nickname, card.CameraMake, card.CameraModel, + card.CameraSerial, DbParam.Json(card.ProfileJson), card.AutoImport, card.FirstSeen, card.LastSeen, + ], cancellationToken).ConfigureAwait(false); + + public Task GetAsync(Guid id, CancellationToken cancellationToken = default) => + _db.SingleAsync($"SELECT {Columns} FROM media_cards WHERE id = $1", [id], Map, cancellationToken); + + /// The card with this {volumeSerial}-{label}-{capacity} identity, if seen before. + public Task FindByIdentityAsync(string identity, CancellationToken cancellationToken = default) => + _db.SingleAsync($"SELECT {Columns} FROM media_cards WHERE identity = $1", [identity], Map, cancellationToken); + + /// Cards, most recently seen first. + public Task> ListAsync(CancellationToken cancellationToken = default) => + _db.ListAsync($"SELECT {Columns} FROM media_cards ORDER BY last_seen DESC, id", [], Map, cancellationToken); + + public async Task TouchAsync(Guid id, DateTimeOffset seen, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync("UPDATE media_cards SET last_seen = $2 WHERE id = $1", [id, seen], cancellationToken).ConfigureAwait(false) > 0; + + /// Forgets a card and its import history. + public async Task DeleteAsync(Guid id, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync("DELETE FROM media_cards WHERE id = $1", [id], cancellationToken).ConfigureAwait(false) > 0; + + /// Records imported files in one transaction; re-recording a key updates its hash, frame and job. + public Task RecordImportsAsync(IEnumerable records, CancellationToken cancellationToken = default) => + _db.InTransactionAsync(async session => + { + var count = 0; + foreach (var r in records) + { + count += await session.ExecuteAsync(RecordSql, + [r.CardId, r.Key.Path, r.Key.Size, r.Key.Modified, r.Sha256?.ToLowerInvariant(), r.FrameId, r.JobId, r.ImportedAt], + cancellationToken).ConfigureAwait(false); + } + return count; + }, cancellationToken); + + /// Keys of every file already imported from the card, for skipping them on re-insert. + public async Task> GetImportedKeysAsync(Guid cardId, CancellationToken cancellationToken = default) + { + var keys = await _db.ListAsync("SELECT path, size, mtime FROM import_history WHERE card_id = $1", [cardId], + r => new ImportKey(r.GetString(0), r.GetInt64(1), r.GetDateTimeOffset(2)), cancellationToken).ConfigureAwait(false); + return keys.ToHashSet(); + } + + public async Task IsImportedAsync(Guid cardId, ImportKey key, CancellationToken cancellationToken = default) => + await _db.ScalarAsync("SELECT 1 FROM import_history WHERE card_id = $1 AND path = $2 AND size = $3 AND mtime = $4", + [cardId, key.Path, key.Size, key.Modified], cancellationToken).ConfigureAwait(false) is not null; + + /// Most recent imports from a card. + public Task> ListImportsAsync(Guid cardId, int limit = 1000, CancellationToken cancellationToken = default) => + _db.ListAsync( + "SELECT card_id, path, size, mtime, sha256, frame_id, job_id, imported_at FROM import_history WHERE card_id = $1 " + + "ORDER BY imported_at DESC, path LIMIT $2", + [cardId, Cursor.ClampLimit(limit)], + r => new ImportRecord(r.GetGuid(0), new ImportKey(r.GetString(1), r.GetInt64(2), r.GetDateTimeOffset(3)), + r.GetStringOrNull(4), r.GetGuidOrNull(5), r.GetGuidOrNull(6), r.GetDateTimeOffset(7)), + cancellationToken); + + private static MediaCard Map(DbRow r) => new() + { + Id = r.GetGuid(0), + Identity = r.GetString(1), + VolumeSerial = checked((uint)r.GetInt64(2)), + Label = r.GetStringOrNull(3), + Capacity = r.GetInt64(4), + Nickname = r.GetStringOrNull(5), + CameraMake = r.GetStringOrNull(6), + CameraModel = r.GetStringOrNull(7), + CameraSerial = r.GetStringOrNull(8), + ProfileJson = r.GetStringOrNull(9), + AutoImport = r.GetBool(10), + FirstSeen = r.GetDateTimeOffset(11), + LastSeen = r.GetDateTimeOffset(12), + }; +} diff --git a/src/Titano.Data/Repositories/RenderNodeRepository.cs b/src/Titano.Data/Repositories/RenderNodeRepository.cs new file mode 100644 index 00000000..898f1500 --- /dev/null +++ b/src/Titano.Data/Repositories/RenderNodeRepository.cs @@ -0,0 +1,49 @@ +using Titano.Core.Model; + +namespace Titano.Data.Repositories; + +/// Clients offering their PC as render node (BRIEF §14.7). +public sealed class RenderNodeRepository +{ + private const string Columns = "id, user_id, client_name, capabilities_json, last_heartbeat, state"; + + private static readonly string UpsertSql = SqlDialect.Upsert("render_nodes", + ["id", "user_id", "client_name", "capabilities_json", "last_heartbeat", "state"], 1); + + private readonly DbAccess _db; + + internal RenderNodeRepository(DbAccess db) => _db = db; + + /// Registers a node or refreshes its client name, capabilities and state. + public async Task RegisterAsync(RenderNode node, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync(UpsertSql, + [node.Id, node.UserId, node.ClientName, DbParam.Json(node.CapabilitiesJson), node.LastHeartbeat, node.State], + cancellationToken).ConfigureAwait(false); + + public async Task HeartbeatAsync(Guid id, string state, DateTimeOffset at, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync("UPDATE render_nodes SET last_heartbeat = $2, state = $3 WHERE id = $1", [id, at, state], cancellationToken) + .ConfigureAwait(false) > 0; + + public Task GetAsync(Guid id, CancellationToken cancellationToken = default) => + _db.SingleAsync($"SELECT {Columns} FROM render_nodes WHERE id = $1", [id], Map, cancellationToken); + + public Task> ListAsync(CancellationToken cancellationToken = default) => + _db.ListAsync($"SELECT {Columns} FROM render_nodes ORDER BY client_name, id", [], Map, cancellationToken); + + /// Nodes whose last heartbeat is at or after , most recent first. + public Task> ListOnlineAsync(DateTimeOffset since, CancellationToken cancellationToken = default) => + _db.ListAsync($"SELECT {Columns} FROM render_nodes WHERE last_heartbeat >= $1 ORDER BY last_heartbeat DESC, id", [since], Map, cancellationToken); + + public async Task DeleteAsync(Guid id, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync("DELETE FROM render_nodes WHERE id = $1", [id], cancellationToken).ConfigureAwait(false) > 0; + + private static RenderNode Map(DbRow r) => new() + { + Id = r.GetGuid(0), + UserId = r.GetGuid(1), + ClientName = r.GetString(2), + CapabilitiesJson = r.GetStringOrNull(3), + LastHeartbeat = r.GetDateTimeOffset(4), + State = r.GetString(5), + }; +} diff --git a/src/Titano.Data/Repositories/RenderRepository.cs b/src/Titano.Data/Repositories/RenderRepository.cs new file mode 100644 index 00000000..f7d52f45 --- /dev/null +++ b/src/Titano.Data/Repositories/RenderRepository.cs @@ -0,0 +1,73 @@ +using Titano.Core.Model; + +namespace Titano.Data.Repositories; + +/// Exports of sequences; keeps sequences.rendered_count in step. +public sealed class RenderRepository +{ + private const string Columns = + "id, sequence_id, preset_name, settings_json, output_path, codec, width, height, fps, duration_seconds, bytes, created, produced_by"; + + private const string RecountSql = + "UPDATE sequences SET rendered_count = (SELECT count(*) FROM renders WHERE sequence_id = $1) WHERE id = $1"; + + private readonly DbAccess _db; + + internal RenderRepository(DbAccess db) => _db = db; + + public Task InsertAsync(Render render, CancellationToken cancellationToken = default) => + _db.InTransactionAsync(async session => + { + await LockSequenceAsync(session, render.SequenceId, cancellationToken).ConfigureAwait(false); + await session.ExecuteAsync($"INSERT INTO renders ({Columns}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)", + [ + render.Id, render.SequenceId, render.PresetName, DbParam.Json(render.SettingsJson), render.OutputPath, render.Codec, + render.Width, render.Height, render.Fps, render.DurationSeconds, render.Bytes, render.Created, render.ProducedBy, + ], cancellationToken).ConfigureAwait(false); + return await session.ExecuteAsync(RecountSql, [render.SequenceId], cancellationToken).ConfigureAwait(false); + }, cancellationToken); + + public Task GetAsync(Guid id, CancellationToken cancellationToken = default) => + _db.SingleAsync($"SELECT {Columns} FROM renders WHERE id = $1", [id], Map, cancellationToken); + + /// Renders of a sequence, newest first. + public Task> ListBySequenceAsync(Guid sequenceId, CancellationToken cancellationToken = default) => + _db.ListAsync($"SELECT {Columns} FROM renders WHERE sequence_id = $1 ORDER BY created DESC, id DESC", [sequenceId], Map, cancellationToken); + + public Task DeleteAsync(Guid id, CancellationToken cancellationToken = default) => + _db.InTransactionAsync(async session => + { + var sequenceId = await session.ScalarAsync("SELECT sequence_id FROM renders WHERE id = $1", [id], cancellationToken).ConfigureAwait(false); + if (sequenceId is null) return false; + await LockSequenceAsync(session, sequenceId.Value, cancellationToken).ConfigureAwait(false); + if (await session.ExecuteAsync("DELETE FROM renders WHERE id = $1", [id], cancellationToken).ConfigureAwait(false) == 0) return false; + await session.ExecuteAsync(RecountSql, [sequenceId], cancellationToken).ConfigureAwait(false); + return true; + }, cancellationToken); + + /// + /// Serialises render changes per sequence on PostgreSQL, so the recount (a new statement, hence a new snapshot) + /// sees every committed render; SQLite's write lock already does this. + /// + private async Task LockSequenceAsync(IDbSession session, Guid sequenceId, CancellationToken cancellationToken) + { + if (_db.Sql.IsPostgres) await SequenceRepository.LockAsync(session, sequenceId, cancellationToken).ConfigureAwait(false); + } + + private static Render Map(DbRow r) => new() + { + Id = r.GetGuid(0), + SequenceId = r.GetGuid(1), + PresetName = r.GetString(2), + SettingsJson = r.GetStringOrNull(3), + OutputPath = r.GetString(4), + Codec = r.GetStringOrNull(5), + Width = r.GetInt32(6), + Height = r.GetInt32(7), + Fps = r.GetDouble(8), + DurationSeconds = r.GetDouble(9), + Bytes = r.GetInt64(10), + Created = r.GetDateTimeOffset(11), + ProducedBy = r.GetStringOrNull(12), + }; +} diff --git a/src/Titano.Data/Repositories/SequenceRepository.cs b/src/Titano.Data/Repositories/SequenceRepository.cs new file mode 100644 index 00000000..4912cec5 --- /dev/null +++ b/src/Titano.Data/Repositories/SequenceRepository.cs @@ -0,0 +1,395 @@ +using Titano.Core.Imaging; +using Titano.Core.Model; + +namespace Titano.Data.Repositories; + +/// Orderings of the Library; every one is keyset-paginated with the sequence id as tie-breaker. +public enum SequenceSort +{ + /// Latest first capture first; sequences without captures last. + Newest, + Oldest, + + /// Display title, case-insensitive. + Title, + FrameCount, + Size, +} + +/// Library filters (all optional, combined with AND) plus sort and page. +public sealed record SequenceQuery +{ + public Guid? ArchiveId { get; init; } + + /// Calendar year of the first capture. + public int? Year { get; init; } + + /// Exact camera model. + public string? Camera { get; init; } + + /// Status flags that must all be set. + public SequenceStatus WithStatus { get; init; } + + /// Status flags that must all be clear. + public SequenceStatus WithoutStatus { get; init; } + + public string? Tag { get; init; } + + /// Case-insensitive substring of the title, camera make/model or a tag. + public string? Text { get; init; } + + public Guid? OwnerUserId { get; init; } + + public SequenceSort Sort { get; init; } = SequenceSort.Newest; + + /// Page size, 1–1000. + public int Limit { get; init; } = 100; + + /// of the previous page, or null for the first page. + public string? Cursor { get; init; } +} + +/// Figures of the Archive screen (BRIEF §12.5). +public sealed record ArchiveStats( + int Sequences, + long Photos, + long Bytes, + IReadOnlyList ByYear, + IReadOnlyList ByMonth, + IReadOnlyList ByCamera, + IReadOnlyList ByFormat, + ArchiveHealth Health); + +public sealed record YearBucket(int Year, int Sequences, long Photos, long Bytes); + +/// One heatmap cell: sequences and photos whose first capture falls in the month. +public sealed record MonthBucket(int Year, int Month, int Sequences, long Photos); + +public sealed record CameraBucket(string? Make, string? Model, int Sequences, long Photos, long Bytes); + +public sealed record FormatBucket(ImageFileFormat Format, long Photos, long Bytes); + +/// Health counters: sequences needing attention and flagged frames. +public sealed record ArchiveHealth( + int Unverified, + int WithWarnings, + int WithErrors, + int NotAnalyzed, + long MissingFrames, + long CorruptFrames, + long DuplicateFrames); + +/// Sequences (projects) with their tags; Library listing and Archive statistics. +public sealed class SequenceRepository +{ + private const string Columns = + "s.id, s.archive_id, s.title, s.folder, s.camera_make, s.camera_model, s.camera_serial, s.lens, s.first_capture, s.last_capture, " + + "s.frame_count, s.median_interval, s.total_bytes, s.status, s.rendered_count, s.verified_at, s.hero_frame_id, s.rating, s.notes, " + + "s.settings_json, s.analysis_json, s.origin, s.sync_state, s.settings_version, s.frames_version, s.owner_user_id, s.warning_count, s.updated_at"; + + /// rendered_count is owned by once the row exists. + private static readonly string UpsertSql = SqlDialect.Upsert("sequences", + [ + "id", "archive_id", "title", "title_key", "search_text", "folder", "camera_make", "camera_model", "camera_serial", "lens", + "first_capture", "last_capture", "frame_count", "median_interval", "total_bytes", "status", "rendered_count", "verified_at", + "hero_frame_id", "rating", "notes", "settings_json", "analysis_json", "origin", "sync_state", "settings_version", + "frames_version", "owner_user_id", "warning_count", "updated_at", + ], 1, ["rendered_count"]); + + /// Ordinal of the tag list after , and of the sort key a listing appends after it. + private const int TagsOrdinal = 28; + private const int SortKeyOrdinal = 29; + + private readonly DbAccess _db; + private readonly string _select; + + internal SequenceRepository(DbAccess db) + { + _db = db; + _select = SelectSql(string.Empty); + } + + private string SelectSql(string extraColumns) => + $"SELECT {Columns}, (SELECT {_db.Sql.StringAgg("t.name")} FROM sequence_tags st JOIN tags t ON t.id = st.tag_id " + + $"WHERE st.sequence_id = s.id) AS tags{extraColumns} FROM sequences s"; + + /// + /// Inserts the sequence, or replaces every stored field and the tag set with the record's (last writer wins); + /// only of an existing row is kept, as renders maintain it. For concurrent + /// partial changes use , or . + /// + public Task UpsertAsync(Sequence sequence, CancellationToken cancellationToken = default) => + _db.InTransactionAsync(async session => + { + await UpsertRowAsync(session, sequence, cancellationToken).ConfigureAwait(false); + await ReplaceTagsAsync(session, sequence.Id, sequence.Tags, cancellationToken).ConfigureAwait(false); + return true; + }, cancellationToken); + + public Task GetAsync(Guid id, CancellationToken cancellationToken = default) => + _db.SingleAsync($"{_select} WHERE s.id = $1", [id], Map, cancellationToken); + + /// Deletes the sequence with its frames, renders and tag links. + public async Task DeleteAsync(Guid id, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync("DELETE FROM sequences WHERE id = $1", [id], cancellationToken).ConfigureAwait(false) > 0; + + /// Replaces the tags of a sequence (trimmed, de-duplicated case-insensitively). + public async Task SetTagsAsync(Guid id, IEnumerable tags, CancellationToken cancellationToken = default) => + await _db.InTransactionAsync(async session => + { + if (!await LockAsync(session, id, cancellationToken).ConfigureAwait(false)) return false; + await ReplaceTagsAsync(session, id, tags, cancellationToken).ConfigureAwait(false); + await session.ExecuteAsync("UPDATE sequences SET settings_version = settings_version + 1, updated_at = $2 WHERE id = $1", + [id, DateTimeOffset.UtcNow], cancellationToken).ConfigureAwait(false); + return true; + }, cancellationToken).ConfigureAwait(false); + + /// Sets and clears status flags in one statement. + public async Task UpdateStatusAsync(Guid id, SequenceStatus set, SequenceStatus clear, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync("UPDATE sequences SET status = (status | $2) & ~$3, updated_at = $4 WHERE id = $1", + [id, (int)set, (int)clear, DateTimeOffset.UtcNow], cancellationToken).ConfigureAwait(false) > 0; + + /// Recomputes frame count, total bytes and first/last capture from the frames table. + public Task RefreshStatsAsync(Guid id, CancellationToken cancellationToken = default) => + _db.InTransactionAsync(async session => + { + var current = await session.QuerySingleOrDefaultAsync($"{_select} WHERE s.id = $1{_db.Sql.ForUpdate}", [id], Map, cancellationToken) + .ConfigureAwait(false); + if (current is null) return null; + var stats = await session.QuerySingleAsync( + "SELECT count(*), COALESCE(SUM(size), 0), MIN(captured_at), MAX(captured_at) FROM frames WHERE sequence_id = $1", + [id], cancellationToken).ConfigureAwait(false); + var updated = current with + { + FrameCount = (int)stats.GetInt64(0), + TotalBytes = stats.GetInt64(1), + FirstCapture = stats.GetDateTimeOrNull(2), + LastCapture = stats.GetDateTimeOrNull(3), + FramesVersion = current.FramesVersion + 1, + UpdatedAt = DateTimeOffset.UtcNow, + }; + await UpsertRowAsync(session, updated, cancellationToken).ConfigureAwait(false); + return updated; + }, cancellationToken); + + /// One page of sequences matching . + public Task> ListAsync(SequenceQuery query, CancellationToken cancellationToken = default) + { + var p = new SqlParameters(); + var where = Filter(query, p); + var (column, descending) = SortKey(query.Sort); + var scope = "seq:" + query.Sort; + if (query.Cursor is not null) + { + var (value, id) = Cursor.Decode(scope, query.Cursor); + where.Add(Cursor.After(column, "s.id", descending, value, id, p.Add)); + } + var limit = Cursor.ClampLimit(query.Limit); + var direction = descending ? "DESC" : "ASC"; + var sql = $"{SelectSql($", {column} AS sort_key")}{Where(where)} " + + $"ORDER BY {column} {direction} NULLS LAST, s.id {direction} LIMIT {p.Add(limit + 1)}"; + return _db.RunAsync(async session => + { + var rows = await session.QueryListAsync(sql, p.ToArray(), r => (Item: Map(r), Key: SortValue(query.Sort, r)), cancellationToken).ConfigureAwait(false); + string? next = null; + if (rows.Count > limit) + { + rows.RemoveAt(limit); + next = Cursor.Encode(scope, rows[^1].Key, rows[^1].Item.Id); + } + return new Page(rows.ConvertAll(r => r.Item), next); + }, cancellationToken); + } + + /// Number of sequences matching the filters of (sort and page ignored). + public async Task CountAsync(SequenceQuery query, CancellationToken cancellationToken = default) + { + var p = new SqlParameters(); + var where = Filter(query, p); + return (int)await _db.ScalarAsync($"SELECT count(*) FROM sequences s{Where(where)}", p.ToArray(), cancellationToken).ConfigureAwait(false); + } + + /// Totals, distributions and health counters of one archive, or of all archives. + public Task GetStatsAsync(Guid? archiveId = null, CancellationToken cancellationToken = default) + { + var sql = _db.Sql; + DbParam[] args = archiveId is { } a ? [a] : []; + var seqWhere = archiveId is null ? string.Empty : " WHERE s.archive_id = $1"; + var seqAnd = archiveId is null ? " WHERE" : " WHERE s.archive_id = $1 AND"; + var frameFrom = archiveId is null ? "frames f" : "frames f JOIN sequences s ON s.id = f.sequence_id WHERE s.archive_id = $1"; + var year = sql.Year("s.first_capture"); + return _db.RunAsync(async session => + { + var totals = await session.QuerySingleAsync( + $"SELECT count(*), COALESCE(SUM(s.frame_count), 0), COALESCE(SUM(s.total_bytes), 0) FROM sequences s{seqWhere}", + args, cancellationToken).ConfigureAwait(false); + var byYear = await session.QueryListAsync( + $"SELECT {year}, count(*), COALESCE(SUM(s.frame_count), 0), COALESCE(SUM(s.total_bytes), 0) FROM sequences s" + + $"{seqAnd} s.first_capture IS NOT NULL GROUP BY 1 ORDER BY 1", args, + r => new YearBucket(r.GetInt32(0), r.GetInt32(1), r.GetInt64(2), r.GetInt64(3)), cancellationToken).ConfigureAwait(false); + var byMonth = await session.QueryListAsync( + $"SELECT {year}, {sql.Month("s.first_capture")}, count(*), COALESCE(SUM(s.frame_count), 0) FROM sequences s" + + $"{seqAnd} s.first_capture IS NOT NULL GROUP BY 1, 2 ORDER BY 1, 2", args, + r => new MonthBucket(r.GetInt32(0), r.GetInt32(1), r.GetInt32(2), r.GetInt64(3)), cancellationToken).ConfigureAwait(false); + var byCamera = await session.QueryListAsync( + $"SELECT s.camera_make, s.camera_model, count(*), COALESCE(SUM(s.frame_count), 0), COALESCE(SUM(s.total_bytes), 0) " + + $"FROM sequences s{seqWhere} GROUP BY s.camera_make, s.camera_model ORDER BY 4 DESC, 2 NULLS LAST, 1 NULLS LAST", args, + r => new CameraBucket(r.GetStringOrNull(0), r.GetStringOrNull(1), r.GetInt32(2), r.GetInt64(3), r.GetInt64(4)), cancellationToken).ConfigureAwait(false); + var byFormat = await session.QueryListAsync( + $"SELECT f.format, count(*), COALESCE(SUM(f.size), 0) FROM {frameFrom} GROUP BY f.format ORDER BY 2 DESC, 1", args, + r => new FormatBucket((ImageFileFormat)r.GetInt32(0), r.GetInt64(1), r.GetInt64(2)), cancellationToken).ConfigureAwait(false); + var sequenceHealth = await session.QuerySingleAsync( + "SELECT " + + "COALESCE(SUM(CASE WHEN s.verified_at IS NULL THEN 1 ELSE 0 END), 0), " + + $"COALESCE(SUM(CASE WHEN (s.status & {(int)SequenceStatus.HasWarnings}) <> 0 OR s.warning_count > 0 THEN 1 ELSE 0 END), 0), " + + $"COALESCE(SUM(CASE WHEN (s.status & {(int)SequenceStatus.HasErrors}) <> 0 THEN 1 ELSE 0 END), 0), " + + $"COALESCE(SUM(CASE WHEN (s.status & {(int)SequenceStatus.AnalyzedLight}) = 0 THEN 1 ELSE 0 END), 0) " + + $"FROM sequences s{seqWhere}", args, cancellationToken).ConfigureAwait(false); + var frameHealth = await session.QuerySingleAsync( + "SELECT " + + $"COALESCE(SUM(CASE WHEN (f.flags & {(int)FrameFlags.Missing}) <> 0 THEN 1 ELSE 0 END), 0), " + + $"COALESCE(SUM(CASE WHEN (f.flags & {(int)FrameFlags.Corrupt}) <> 0 THEN 1 ELSE 0 END), 0), " + + $"COALESCE(SUM(CASE WHEN (f.flags & {(int)FrameFlags.Duplicate}) <> 0 THEN 1 ELSE 0 END), 0) " + + $"FROM {frameFrom}", args, cancellationToken).ConfigureAwait(false); + return new ArchiveStats( + totals.GetInt32(0), totals.GetInt64(1), totals.GetInt64(2), byYear, byMonth, byCamera, byFormat, + new ArchiveHealth( + sequenceHealth.GetInt32(0), sequenceHealth.GetInt32(1), sequenceHealth.GetInt32(2), sequenceHealth.GetInt32(3), + frameHealth.GetInt64(0), frameHealth.GetInt64(1), frameHealth.GetInt64(2))); + }, cancellationToken); + } + + private static List Filter(SequenceQuery query, SqlParameters p) + { + var where = new List(); + if (query.ArchiveId is { } archive) where.Add($"s.archive_id = {p.Add(archive)}"); + if (query.Year is { } year) + where.Add($"s.first_capture >= {p.Add(new DateTime(year, 1, 1))} AND s.first_capture < {p.Add(new DateTime(year + 1, 1, 1))}"); + if (query.Camera is { } camera) where.Add($"s.camera_model = {p.Add(camera)}"); + if (query.WithStatus != SequenceStatus.None) + { + var mask = p.Add((int)query.WithStatus); + where.Add($"(s.status & {mask}) = {mask}"); + } + if (query.WithoutStatus != SequenceStatus.None) where.Add($"(s.status & {p.Add((int)query.WithoutStatus)}) = 0"); + if (query.Tag is { } tag) + where.Add("EXISTS (SELECT 1 FROM sequence_tags st JOIN tags t ON t.id = st.tag_id " + + $"WHERE st.sequence_id = s.id AND t.name_key = {p.Add(TagRepository.Key(tag))})"); + if (!string.IsNullOrWhiteSpace(query.Text)) + { + var pattern = p.Add(SqlDialect.ContainsPattern(query.Text.Trim().ToLowerInvariant())); + where.Add($"(s.search_text LIKE {pattern} ESCAPE '\\' OR EXISTS (SELECT 1 FROM sequence_tags st JOIN tags t ON t.id = st.tag_id " + + $"WHERE st.sequence_id = s.id AND t.name_key LIKE {pattern} ESCAPE '\\'))"); + } + if (query.OwnerUserId is { } owner) where.Add($"s.owner_user_id = {p.Add(owner)}"); + return where; + } + + private static string Where(List conditions) => + conditions.Count == 0 ? string.Empty : " WHERE " + string.Join(" AND ", conditions); + + private static (string Column, bool Descending) SortKey(SequenceSort sort) => sort switch + { + SequenceSort.Newest => ("s.first_capture", true), + SequenceSort.Oldest => ("s.first_capture", false), + SequenceSort.Title => ("s.title_key", false), + SequenceSort.FrameCount => ("s.frame_count", true), + SequenceSort.Size => ("s.total_bytes", true), + _ => throw new ArgumentOutOfRangeException(nameof(sort), sort, null), + }; + + private static object? SortValue(SequenceSort sort, DbRow row) => sort switch + { + SequenceSort.Newest or SequenceSort.Oldest => row.GetDateTimeOrNull(SortKeyOrdinal), + SequenceSort.Title => row.GetString(SortKeyOrdinal), + _ => row.GetInt64(SortKeyOrdinal), + }; + + private static Task UpsertRowAsync(IDbSession session, Sequence s, CancellationToken cancellationToken) + { + var search = string.Join(' ', new[] { s.Title, s.CameraMake, s.CameraModel }.Where(v => !string.IsNullOrWhiteSpace(v))).ToLowerInvariant(); + return session.ExecuteAsync(UpsertSql, + [ + s.Id, s.ArchiveId, s.Title, s.DisplayTitle.ToLowerInvariant(), search, s.Folder, s.CameraMake, s.CameraModel, s.CameraSerial, s.Lens, + Wall(s.FirstCapture), Wall(s.LastCapture), s.FrameCount, s.MedianInterval, s.TotalBytes, (int)s.Status, s.RenderedCount, s.VerifiedAt, + s.HeroFrameId, s.Rating, s.Notes, DbParam.Json(s.SettingsJson), DbParam.Json(s.AnalysisJson), (int)s.Origin, (int)s.SyncState, + s.SettingsVersion, s.FramesVersion, s.OwnerUserId, s.WarningCount, s.UpdatedAt, + ], cancellationToken); + } + + /// + /// Row-locks a sequence for a read-modify-write (PostgreSQL; SQLite's write lock already serialises writers). + /// False when it does not exist. + /// + internal static async Task LockAsync(IDbSession session, Guid id, CancellationToken cancellationToken) => + await session.ScalarAsync($"SELECT id FROM sequences WHERE id = $1{SqlDialect.For(session.Dialect).ForUpdate}", [id], cancellationToken) + .ConfigureAwait(false) is not null; + + /// Replaces the tag links of a sequence whose row the caller has locked (or just upserted). + private async Task ReplaceTagsAsync(IDbSession session, Guid sequenceId, IEnumerable tags, CancellationToken cancellationToken) + { + await session.ExecuteAsync("DELETE FROM sequence_tags WHERE sequence_id = $1", [sequenceId], cancellationToken).ConfigureAwait(false); + foreach (var tag in TagRepository.NormalizeSet(tags)) + { + DbParam[] args = [Guid.CreateVersion7(), tag, TagRepository.Key(tag)]; + Guid tagId; + if (_db.Sql.IsPostgres) + { + // The no-op update locks an existing tag, so a concurrent DeleteUnusedAsync cannot remove it before the link exists. + tagId = (await session.ScalarAsync( + "INSERT INTO tags (id, name, name_key) VALUES ($1, $2, $3) ON CONFLICT (name_key) DO UPDATE SET name_key = excluded.name_key RETURNING id", + args, cancellationToken).ConfigureAwait(false))!.Value; + } + else + { + await session.ExecuteAsync("INSERT INTO tags (id, name, name_key) VALUES ($1, $2, $3) ON CONFLICT (name_key) DO NOTHING", + args, cancellationToken).ConfigureAwait(false); + tagId = (await session.ScalarAsync("SELECT id FROM tags WHERE name_key = $1", [args[2]], cancellationToken).ConfigureAwait(false))!.Value; + } + await session.ExecuteAsync("INSERT INTO sequence_tags (sequence_id, tag_id) VALUES ($1, $2)", [sequenceId, tagId], cancellationToken) + .ConfigureAwait(false); + } + } + + /// Camera wall-clock times are stored without zone, whatever kind the caller's value has. + internal static DateTime? Wall(DateTime? value) => + value is { } v ? DateTime.SpecifyKind(v, DateTimeKind.Unspecified) : null; + + private static Sequence Map(DbRow r) + { + var tags = r.GetStringOrNull(TagsOrdinal) is { Length: > 0 } list ? list.Split(SqlDialect.ListSeparator) : []; + Array.Sort(tags, StringComparer.OrdinalIgnoreCase); + return new Sequence + { + Id = r.GetGuid(0), + ArchiveId = r.GetGuid(1), + Title = r.GetStringOrNull(2), + Folder = r.GetString(3), + CameraMake = r.GetStringOrNull(4), + CameraModel = r.GetStringOrNull(5), + CameraSerial = r.GetStringOrNull(6), + Lens = r.GetStringOrNull(7), + FirstCapture = r.GetDateTimeOrNull(8), + LastCapture = r.GetDateTimeOrNull(9), + FrameCount = r.GetInt32(10), + MedianInterval = r.GetDoubleOrNull(11), + TotalBytes = r.GetInt64(12), + Status = (SequenceStatus)r.GetInt32(13), + RenderedCount = r.GetInt32(14), + VerifiedAt = r.GetDateTimeOffsetOrNull(15), + HeroFrameId = r.GetGuidOrNull(16), + Rating = r.GetInt32(17), + Notes = r.GetStringOrNull(18), + SettingsJson = r.GetStringOrNull(19), + AnalysisJson = r.GetStringOrNull(20), + Origin = (SequenceOrigin)r.GetInt32(21), + SyncState = (SyncState)r.GetInt32(22), + SettingsVersion = r.GetInt32(23), + FramesVersion = r.GetInt32(24), + OwnerUserId = r.GetGuidOrNull(25), + WarningCount = r.GetInt32(26), + UpdatedAt = r.GetDateTimeOffset(27), + Tags = tags, + }; + } +} diff --git a/src/Titano.Data/Repositories/SettingsRepository.cs b/src/Titano.Data/Repositories/SettingsRepository.cs new file mode 100644 index 00000000..73c56ca3 --- /dev/null +++ b/src/Titano.Data/Repositories/SettingsRepository.cs @@ -0,0 +1,93 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Text.Json.Serialization.Metadata; + +namespace Titano.Data.Repositories; + +/// Who a setting belongs to. +public enum SettingScope +{ + /// The installation (client app or server); no scope id. + App, + + /// One archive; the scope id is the archive id. + Archive, + + /// One user; the scope id is the user id. + User, +} + +/// Typed key/value settings stored as JSON (BRIEF §5 Setting). +public sealed class SettingsRepository +{ + private static readonly string UpsertSql = SqlDialect.Upsert("settings", ["scope", "scope_id", "key", "value_json", "updated_at"], 3); + + private readonly DbAccess _db; + + internal SettingsRepository(DbAccess db) => _db = db; + + /// The raw JSON of a setting, or null when unset. + public Task GetJsonAsync(SettingScope scope, Guid? scopeId, string key, CancellationToken cancellationToken = default) => + _db.ScalarAsync("SELECT value_json FROM settings WHERE scope = $1 AND scope_id = $2 AND key = $3", + [ScopeName(scope), ScopeId(scope, scopeId), key], cancellationToken); + + /// Stores a JSON value; malformed JSON is rejected on both dialects. + public async Task SetJsonAsync(SettingScope scope, Guid? scopeId, string key, string json, CancellationToken cancellationToken = default) + { + using (JsonDocument.Parse(json)) + { + } + await _db.ExecuteAsync(UpsertSql, [ScopeName(scope), ScopeId(scope, scopeId), key, DbParam.Json(json), DateTimeOffset.UtcNow], cancellationToken) + .ConfigureAwait(false); + } + + /// Reads a setting with source-generated metadata (trim/AOT safe); default when unset. + public async Task GetAsync(SettingScope scope, Guid? scopeId, string key, JsonTypeInfo typeInfo, CancellationToken cancellationToken = default) => + await GetJsonAsync(scope, scopeId, key, cancellationToken).ConfigureAwait(false) is { } json + ? JsonSerializer.Deserialize(json, typeInfo) + : default; + + public Task SetAsync(SettingScope scope, Guid? scopeId, string key, T value, JsonTypeInfo typeInfo, CancellationToken cancellationToken = default) => + SetJsonAsync(scope, scopeId, key, JsonSerializer.Serialize(value, typeInfo), cancellationToken); + + /// Reads a setting through reflection-based serialization; default when unset. + [RequiresUnreferencedCode("Reflection-based JSON; use the JsonTypeInfo overload in trimmed builds.")] + [RequiresDynamicCode("Reflection-based JSON; use the JsonTypeInfo overload in AOT builds.")] + public async Task GetAsync(SettingScope scope, Guid? scopeId, string key, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) => + await GetJsonAsync(scope, scopeId, key, cancellationToken).ConfigureAwait(false) is { } json + ? JsonSerializer.Deserialize(json, options) + : default; + + [RequiresUnreferencedCode("Reflection-based JSON; use the JsonTypeInfo overload in trimmed builds.")] + [RequiresDynamicCode("Reflection-based JSON; use the JsonTypeInfo overload in AOT builds.")] + public Task SetAsync(SettingScope scope, Guid? scopeId, string key, T value, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) => + SetJsonAsync(scope, scopeId, key, JsonSerializer.Serialize(value, options), cancellationToken); + + public async Task DeleteAsync(SettingScope scope, Guid? scopeId, string key, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync("DELETE FROM settings WHERE scope = $1 AND scope_id = $2 AND key = $3", + [ScopeName(scope), ScopeId(scope, scopeId), key], cancellationToken).ConfigureAwait(false) > 0; + + /// Every setting of a scope as key → JSON. + public async Task> ListAsync(SettingScope scope, Guid? scopeId, CancellationToken cancellationToken = default) + { + var rows = await _db.ListAsync("SELECT key, value_json FROM settings WHERE scope = $1 AND scope_id = $2 ORDER BY key", + [ScopeName(scope), ScopeId(scope, scopeId)], r => KeyValuePair.Create(r.GetString(0), r.GetString(1)), cancellationToken).ConfigureAwait(false); + return new Dictionary(rows, StringComparer.Ordinal); + } + + private static string ScopeName(SettingScope scope) => scope switch + { + SettingScope.App => "app", + SettingScope.Archive => "archive", + SettingScope.User => "user", + _ => throw new ArgumentOutOfRangeException(nameof(scope), scope, null), + }; + + private static string ScopeId(SettingScope scope, Guid? scopeId) => (scope, scopeId) switch + { + (SettingScope.App, null) => string.Empty, + (SettingScope.App, _) => throw new ArgumentException("App settings have no scope id.", nameof(scopeId)), + (_, { } id) => TextValues.FormatGuid(id), + _ => throw new ArgumentException($"{scope} settings need a scope id.", nameof(scopeId)), + }; +} diff --git a/src/Titano.Data/Repositories/TagRepository.cs b/src/Titano.Data/Repositories/TagRepository.cs new file mode 100644 index 00000000..bb8a616a --- /dev/null +++ b/src/Titano.Data/Repositories/TagRepository.cs @@ -0,0 +1,97 @@ +using System.Text; + +namespace Titano.Data.Repositories; + +/// A tag and how many sequences carry it. +public sealed record TagInfo(Guid Id, string Name, int SequenceCount); + +/// +/// Normalised tags (BRIEF §5 Tag/SequenceTag): one row per case-insensitive name, linked to sequences through +/// sequence_tags. The first spelling of a name is kept. +/// +public sealed class TagRepository +{ + /// Longest tag name accepted, in characters. + public const int MaxLength = 64; + + private readonly DbAccess _db; + + internal TagRepository(DbAccess db) => _db = db; + + /// All tags by name with their usage counts. + public Task> ListAsync(CancellationToken cancellationToken = default) => + _db.ListAsync( + "SELECT t.id, t.name, (SELECT count(*) FROM sequence_tags st WHERE st.tag_id = t.id) FROM tags t ORDER BY t.name_key", + [], r => new TagInfo(r.GetGuid(0), r.GetString(1), r.GetInt32(2)), cancellationToken); + + /// Renames a tag; a name already used by another tag violates the unique key (). + public async Task RenameAsync(Guid id, string name, CancellationToken cancellationToken = default) + { + var normalized = Normalize(name); + return await _db.ExecuteAsync("UPDATE tags SET name = $2, name_key = $3 WHERE id = $1", + [id, normalized, Key(normalized)], cancellationToken).ConfigureAwait(false) > 0; + } + + /// Deletes a tag and removes it from every sequence. + public async Task DeleteAsync(Guid id, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync("DELETE FROM tags WHERE id = $1", [id], cancellationToken).ConfigureAwait(false) > 0; + + /// + /// Deletes tags no sequence uses any more; returns how many. Candidates are locked first (skipping tags a + /// concurrent tagger holds) and re-checked by a later statement, whose fresh snapshot sees every link committed + /// before the lock, so a tag being attached at the same moment survives. + /// + public Task DeleteUnusedAsync(CancellationToken cancellationToken = default) => + _db.InTransactionAsync(async session => + { + const string unused = "NOT EXISTS (SELECT 1 FROM sequence_tags st WHERE st.tag_id = tags.id)"; + var candidates = await session.QueryListAsync($"SELECT id FROM tags WHERE {unused}{_db.Sql.ForUpdateSkipLocked}", [], + r => r.GetGuid(0), cancellationToken).ConfigureAwait(false); + var deleted = 0; + foreach (var chunk in candidates.Chunk(500)) + { + var p = new SqlParameters(); + var ids = string.Join(", ", chunk.Select(id => p.Add(id))); + deleted += await session.ExecuteAsync($"DELETE FROM tags WHERE id IN ({ids}) AND {unused}", p.ToArray(), cancellationToken) + .ConfigureAwait(false); + } + return deleted; + }, cancellationToken); + + /// Trims, collapses inner whitespace and validates a tag name. + public static string Normalize(string name) + { + var sb = new StringBuilder(name.Length); + foreach (var c in name.Trim()) + { + if (char.IsControl(c)) throw new ArgumentException("Tags cannot contain control characters.", nameof(name)); + if (char.IsWhiteSpace(c)) + { + if (sb.Length > 0 && sb[^1] != ' ') sb.Append(' '); + } + else + { + sb.Append(c); + } + } + if (sb.Length == 0) throw new ArgumentException("A tag cannot be empty.", nameof(name)); + if (sb.Length > MaxLength) throw new ArgumentException($"A tag is at most {MaxLength} characters.", nameof(name)); + return sb.ToString(); + } + + /// The case-insensitive identity of a tag name. + public static string Key(string name) => Normalize(name).ToLowerInvariant(); + + /// Normalised tags without case-insensitive duplicates, first spelling kept. + internal static List NormalizeSet(IEnumerable tags) + { + var seen = new HashSet(StringComparer.Ordinal); + var result = new List(); + foreach (var tag in tags) + { + var normalized = Normalize(tag); + if (seen.Add(normalized.ToLowerInvariant())) result.Add(normalized); + } + return result; + } +} diff --git a/src/Titano.Data/Repositories/TokenRepository.cs b/src/Titano.Data/Repositories/TokenRepository.cs new file mode 100644 index 00000000..8b88c0fc --- /dev/null +++ b/src/Titano.Data/Repositories/TokenRepository.cs @@ -0,0 +1,57 @@ +using Titano.Core.Model; + +namespace Titano.Data.Repositories; + +/// API session tokens, stored by SHA-256 hash, with sliding expiry and revocation (BRIEF §14.2). +public sealed class TokenRepository +{ + private const string Columns = "token_hash, user_id, client_name, created, expires, last_used, revoked"; + + private readonly DbAccess _db; + + internal TokenRepository(DbAccess db) => _db = db; + + public async Task InsertAsync(SessionToken token, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync($"INSERT INTO tokens ({Columns}) VALUES ($1, $2, $3, $4, $5, $6, $7)", + [token.TokenHash, token.UserId, token.ClientName, token.Created, token.Expires, token.LastUsed, token.Revoked], + cancellationToken).ConfigureAwait(false); + + /// The token with this hash, revoked or expired ones included (the caller decides). + public Task GetAsync(string tokenHash, CancellationToken cancellationToken = default) => + _db.SingleAsync($"SELECT {Columns} FROM tokens WHERE token_hash = $1", [tokenHash], Map, cancellationToken); + + /// + /// Sliding expiry: records use at and moves the expiry to . + /// Returns false for unknown, revoked or already expired tokens. + /// + public async Task TouchAsync(string tokenHash, DateTimeOffset now, DateTimeOffset expires, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync( + "UPDATE tokens SET last_used = $2, expires = $3 WHERE token_hash = $1 AND revoked = FALSE AND expires > $2", + [tokenHash, now, expires], cancellationToken).ConfigureAwait(false) > 0; + + public async Task RevokeAsync(string tokenHash, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync("UPDATE tokens SET revoked = TRUE WHERE token_hash = $1 AND revoked = FALSE", [tokenHash], cancellationToken) + .ConfigureAwait(false) > 0; + + /// Revokes every live token of a user (password change, account disabled). + public Task RevokeAllAsync(Guid userId, CancellationToken cancellationToken = default) => + _db.ExecuteAsync("UPDATE tokens SET revoked = TRUE WHERE user_id = $1 AND revoked = FALSE", [userId], cancellationToken); + + public Task> ListByUserAsync(Guid userId, CancellationToken cancellationToken = default) => + _db.ListAsync($"SELECT {Columns} FROM tokens WHERE user_id = $1 ORDER BY last_used DESC", [userId], Map, cancellationToken); + + /// Deletes tokens that expired by or were revoked. + public Task PurgeAsync(DateTimeOffset now, CancellationToken cancellationToken = default) => + _db.ExecuteAsync("DELETE FROM tokens WHERE expires <= $1 OR revoked = TRUE", [now], cancellationToken); + + private static SessionToken Map(DbRow r) => new() + { + TokenHash = r.GetString(0), + UserId = r.GetGuid(1), + ClientName = r.GetStringOrNull(2), + Created = r.GetDateTimeOffset(3), + Expires = r.GetDateTimeOffset(4), + LastUsed = r.GetDateTimeOffset(5), + Revoked = r.GetBool(6), + }; +} diff --git a/src/Titano.Data/Repositories/UploadRepository.cs b/src/Titano.Data/Repositories/UploadRepository.cs new file mode 100644 index 00000000..355511ec --- /dev/null +++ b/src/Titano.Data/Repositories/UploadRepository.cs @@ -0,0 +1,135 @@ +namespace Titano.Data.Repositories; + +/// Life cycle of a resumable upload (BRIEF §14.4). +public enum UploadState +{ + /// Chunks are arriving. + Receiving, + + /// All chunks are in; the server is verifying the hash and moving the file into the archive. + Committing, + + /// The file is a frame of the archive (). + Committed, + Failed, + Cancelled, +} + +/// A chunked upload and its received-chunk bitmap (bit n of byte n/8, least significant first). +public sealed record Upload +{ + public required Guid Id { get; init; } + public required Guid UserId { get; init; } + public Guid? SequenceId { get; init; } + public required string FileName { get; init; } + public long Size { get; init; } + + /// Lower-case hex SHA-256 announced by the client. + public required string Sha256 { get; init; } + + public DateTime? CapturedAt { get; init; } + public required int ChunkSize { get; init; } + public byte[] Received { get; init; } = []; + public int ReceivedCount { get; init; } + public UploadState State { get; init; } + public Guid? FrameId { get; init; } + public DateTimeOffset Created { get; init; } + public DateTimeOffset UpdatedAt { get; init; } + + public int ChunkCount => (int)((Size + ChunkSize - 1) / ChunkSize); + + public bool IsComplete => ReceivedCount >= ChunkCount; + + public bool HasChunk(int index) => + index >= 0 && index / 8 < Received.Length && (Received[index / 8] & (1 << (index % 8))) != 0; +} + +/// Resumable uploads: creation, per-chunk bookkeeping, state changes and cleanup. +public sealed class UploadRepository +{ + private const string Columns = + "id, user_id, sequence_id, file_name, size, sha256, captured_at, chunk_size, received, received_count, state, frame_id, created, updated_at"; + + private readonly DbAccess _db; + + internal UploadRepository(DbAccess db) => _db = db; + + /// Stores a new upload with an empty bitmap sized for its chunk count. + public async Task CreateAsync(Upload upload, CancellationToken cancellationToken = default) + { + ArgumentOutOfRangeException.ThrowIfLessThan(upload.ChunkSize, 1); + ArgumentOutOfRangeException.ThrowIfNegative(upload.Size); + var stored = upload with { Received = new byte[(upload.ChunkCount + 7) / 8], ReceivedCount = 0, Sha256 = upload.Sha256.ToLowerInvariant() }; + await _db.ExecuteAsync( + $"INSERT INTO uploads ({Columns}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)", + [ + stored.Id, stored.UserId, stored.SequenceId, stored.FileName, stored.Size, stored.Sha256, SequenceRepository.Wall(stored.CapturedAt), + stored.ChunkSize, stored.Received, 0, (int)stored.State, stored.FrameId, stored.Created, stored.UpdatedAt, + ], cancellationToken).ConfigureAwait(false); + return stored; + } + + public Task GetAsync(Guid id, CancellationToken cancellationToken = default) => + _db.SingleAsync($"SELECT {Columns} FROM uploads WHERE id = $1", [id], Map, cancellationToken); + + /// An upload of the same content by the same user that is still receiving, so a client can resume it. + public Task FindReceivingAsync(Guid userId, string sha256, CancellationToken cancellationToken = default) => + _db.SingleAsync( + $"SELECT {Columns} FROM uploads WHERE user_id = $1 AND sha256 = $2 AND state = {(int)UploadState.Receiving} ORDER BY created DESC LIMIT 1", + [userId, sha256.ToLowerInvariant()], Map, cancellationToken); + + /// + /// Marks chunk as received (idempotent; concurrent chunks of one upload serialise on + /// its row) and returns the updated upload, or null when it does not exist. + /// + public Task MarkChunkReceivedAsync(Guid id, int index, CancellationToken cancellationToken = default) => + _db.InTransactionAsync(async session => + { + var upload = await session.QuerySingleOrDefaultAsync($"SELECT {Columns} FROM uploads WHERE id = $1{_db.Sql.ForUpdate}", [id], Map, cancellationToken) + .ConfigureAwait(false); + if (upload is null) return null; + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(index, upload.ChunkCount); + if (upload.HasChunk(index)) return upload; + var bitmap = (byte[])upload.Received.Clone(); + bitmap[index / 8] |= (byte)(1 << (index % 8)); + var updated = upload with { Received = bitmap, ReceivedCount = upload.ReceivedCount + 1, UpdatedAt = DateTimeOffset.UtcNow }; + await session.ExecuteAsync("UPDATE uploads SET received = $2, received_count = $3, updated_at = $4 WHERE id = $1", + [id, bitmap, updated.ReceivedCount, updated.UpdatedAt], cancellationToken).ConfigureAwait(false); + return updated; + }, cancellationToken); + + /// Moves an upload to , recording the frame it became when committed. + public async Task SetStateAsync(Guid id, UploadState state, Guid? frameId = null, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync("UPDATE uploads SET state = $2, frame_id = COALESCE($3, frame_id), updated_at = $4 WHERE id = $1", + [id, (int)state, frameId, DateTimeOffset.UtcNow], cancellationToken).ConfigureAwait(false) > 0; + + public Task> ListByUserAsync(Guid userId, CancellationToken cancellationToken = default) => + _db.ListAsync($"SELECT {Columns} FROM uploads WHERE user_id = $1 ORDER BY created DESC", [userId], Map, cancellationToken); + + /// Uploads still receiving but untouched since (abandoned; their part files can go). + public Task> ListStaleAsync(DateTimeOffset updatedBefore, CancellationToken cancellationToken = default) => + _db.ListAsync($"SELECT {Columns} FROM uploads WHERE state = {(int)UploadState.Receiving} AND updated_at < $1 ORDER BY updated_at", + [updatedBefore], Map, cancellationToken); + + public async Task DeleteAsync(Guid id, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync("DELETE FROM uploads WHERE id = $1", [id], cancellationToken).ConfigureAwait(false) > 0; + + private static Upload Map(DbRow r) => new() + { + Id = r.GetGuid(0), + UserId = r.GetGuid(1), + SequenceId = r.GetGuidOrNull(2), + FileName = r.GetString(3), + Size = r.GetInt64(4), + Sha256 = r.GetString(5), + CapturedAt = r.GetDateTimeOrNull(6), + ChunkSize = r.GetInt32(7), + Received = r.GetBytes(8), + ReceivedCount = r.GetInt32(9), + State = (UploadState)r.GetInt32(10), + FrameId = r.GetGuidOrNull(11), + Created = r.GetDateTimeOffset(12), + UpdatedAt = r.GetDateTimeOffset(13), + }; +} diff --git a/src/Titano.Data/Repositories/UserRepository.cs b/src/Titano.Data/Repositories/UserRepository.cs new file mode 100644 index 00000000..4fe75107 --- /dev/null +++ b/src/Titano.Data/Repositories/UserRepository.cs @@ -0,0 +1,75 @@ +using Titano.Core.Model; + +namespace Titano.Data.Repositories; + +/// Server accounts. User names are unique case-insensitively. +public sealed class UserRepository +{ + private const string Columns = + "id, username, display_name, password_hash, role, permissions, quota_bytes, used_bytes, disabled, must_change_password, created, last_login"; + + private readonly DbAccess _db; + + internal UserRepository(DbAccess db) => _db = db; + + /// Adds a user; a taken name raises a with . + public async Task CreateAsync(User user, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync( + "INSERT INTO users (id, username, username_key, display_name, password_hash, role, permissions, quota_bytes, used_bytes, " + + "disabled, must_change_password, created, last_login) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)", + [ + user.Id, user.Username, Key(user.Username), user.DisplayName, user.PasswordHash, (int)user.Role, (long)user.Permissions, + user.QuotaBytes, user.UsedBytes, user.Disabled, user.MustChangePassword, user.Created, user.LastLogin, + ], cancellationToken).ConfigureAwait(false); + + /// Saves every field except id and creation time. + public async Task UpdateAsync(User user, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync( + "UPDATE users SET username = $2, username_key = $3, display_name = $4, password_hash = $5, role = $6, permissions = $7, " + + "quota_bytes = $8, used_bytes = $9, disabled = $10, must_change_password = $11, last_login = $12 WHERE id = $1", + [ + user.Id, user.Username, Key(user.Username), user.DisplayName, user.PasswordHash, (int)user.Role, (long)user.Permissions, + user.QuotaBytes, user.UsedBytes, user.Disabled, user.MustChangePassword, user.LastLogin, + ], cancellationToken).ConfigureAwait(false) > 0; + + public Task GetAsync(Guid id, CancellationToken cancellationToken = default) => + _db.SingleAsync($"SELECT {Columns} FROM users WHERE id = $1", [id], Map, cancellationToken); + + public Task GetByUsernameAsync(string username, CancellationToken cancellationToken = default) => + _db.SingleAsync($"SELECT {Columns} FROM users WHERE username_key = $1", [Key(username)], Map, cancellationToken); + + public Task> ListAsync(CancellationToken cancellationToken = default) => + _db.ListAsync($"SELECT {Columns} FROM users ORDER BY username_key", [], Map, cancellationToken); + + public async Task CountAsync(CancellationToken cancellationToken = default) => + (int)await _db.ScalarAsync("SELECT count(*) FROM users", [], cancellationToken).ConfigureAwait(false); + + /// Deletes the user with their tokens, render nodes and uploads. + public async Task DeleteAsync(Guid id, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync("DELETE FROM users WHERE id = $1", [id], cancellationToken).ConfigureAwait(false) > 0; + + public async Task RecordLoginAsync(Guid id, DateTimeOffset at, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync("UPDATE users SET last_login = $2 WHERE id = $1", [id, at], cancellationToken).ConfigureAwait(false) > 0; + + /// Adds (negative to release) to the user's quota usage atomically. + public async Task AddUsedBytesAsync(Guid id, long delta, CancellationToken cancellationToken = default) => + await _db.ExecuteAsync("UPDATE users SET used_bytes = used_bytes + $2 WHERE id = $1", [id, delta], cancellationToken).ConfigureAwait(false) > 0; + + private static string Key(string username) => username.Trim().ToLowerInvariant(); + + private static User Map(DbRow r) => new() + { + Id = r.GetGuid(0), + Username = r.GetString(1), + DisplayName = r.GetStringOrNull(2), + PasswordHash = r.GetString(3), + Role = (UserRole)r.GetInt32(4), + Permissions = (Permissions)r.GetInt64(5), + QuotaBytes = r.GetInt64(6), + UsedBytes = r.GetInt64(7), + Disabled = r.GetBool(8), + MustChangePassword = r.GetBool(9), + Created = r.GetDateTimeOffset(10), + LastLogin = r.GetDateTimeOffsetOrNull(11), + }; +} diff --git a/src/Titano.Data/SqlDialect.cs b/src/Titano.Data/SqlDialect.cs new file mode 100644 index 00000000..a847dbec --- /dev/null +++ b/src/Titano.Data/SqlDialect.cs @@ -0,0 +1,79 @@ +using System.Text; + +namespace Titano.Data; + +/// +/// The few SQL fragments that differ between SQLite (≥ 3.31) and PostgreSQL. Everything else in the +/// repositories is plain SQL that both accept: $n placeholders, ON CONFLICT … DO UPDATE, +/// TRUE/FALSE, NULLS LAST, LIKE … ESCAPE. +/// +public sealed class SqlDialect +{ + /// Separator of lists (ASCII unit separator, never part of a tag). + public const char ListSeparator = '\u001f'; + + private SqlDialect(Dialect dialect) => Dialect = dialect; + + public static SqlDialect Sqlite { get; } = new(Dialect.Sqlite); + + public static SqlDialect Postgres { get; } = new(Dialect.Postgres); + + public Dialect Dialect { get; } + + public bool IsPostgres => Dialect == Dialect.Postgres; + + public static SqlDialect For(Dialect dialect) => dialect == Dialect.Postgres ? Postgres : Sqlite; + + /// Row lock for read-modify-write inside a transaction; empty on SQLite, whose BEGIN IMMEDIATE already holds the write lock. + public string ForUpdate => IsPostgres ? " FOR UPDATE" : string.Empty; + + /// Like , but rows another transaction has locked are skipped instead of awaited. + public string ForUpdateSkipLocked => IsPostgres ? " FOR UPDATE SKIP LOCKED" : string.Empty; + + /// Calendar year of a timestamp column (SQLite stores ISO-8601 text). + public string Year(string expression) => IsPostgres + ? $"CAST(EXTRACT(YEAR FROM {expression}) AS integer)" + : $"CAST(substr({expression}, 1, 4) AS INTEGER)"; + + /// Month (1–12) of a timestamp column. + public string Month(string expression) => IsPostgres + ? $"CAST(EXTRACT(MONTH FROM {expression}) AS integer)" + : $"CAST(substr({expression}, 6, 2) AS INTEGER)"; + + /// Aggregate that joins the group's values with (order unspecified). + public string StringAgg(string expression) => IsPostgres + ? $"string_agg({expression}, chr(31))" + : $"group_concat({expression}, char(31))"; + + /// + /// INSERT … VALUES ($1…$n) ON CONFLICT (keys) DO UPDATE SET …; the first + /// columns form the conflict target and columns keep their stored value on + /// conflict. The syntax is shared by SQLite ≥ 3.24 and PostgreSQL ≥ 9.5. + /// + public static string Upsert(string table, IReadOnlyList columns, int keyCount, IReadOnlyCollection? insertOnly = null) + { + ArgumentOutOfRangeException.ThrowIfLessThan(keyCount, 1); + ArgumentOutOfRangeException.ThrowIfGreaterThan(keyCount, columns.Count); + var sb = new StringBuilder("INSERT INTO ").Append(table).Append(" (").AppendJoin(", ", columns).Append(") VALUES ("); + for (var i = 1; i <= columns.Count; i++) sb.Append(i > 1 ? ", $" : "$").Append(i); + sb.Append(") ON CONFLICT (").AppendJoin(", ", columns.Take(keyCount)).Append(')'); + var updated = columns.Skip(keyCount).Where(c => insertOnly is null || !insertOnly.Contains(c)).ToList(); + if (updated.Count == 0) return sb.Append(" DO NOTHING").ToString(); + return sb.Append(" DO UPDATE SET ").AppendJoin(", ", updated.Select(c => $"{c} = excluded.{c}")).ToString(); + } + + /// Double-quotes an identifier (both dialects). + public static string QuoteIdentifier(string name) => "\"" + name.Replace("\"", "\"\"", StringComparison.Ordinal) + "\""; + + /// A LIKE … ESCAPE '\' pattern that matches anywhere. + public static string ContainsPattern(string text) + { + var sb = new StringBuilder(text.Length + 2).Append('%'); + foreach (var c in text) + { + if (c is '%' or '_' or '\\') sb.Append('\\'); + sb.Append(c); + } + return sb.Append('%').ToString(); + } +} diff --git a/src/Titano.Data/Sqlite/SqliteConnection.cs b/src/Titano.Data/Sqlite/SqliteConnection.cs new file mode 100644 index 00000000..b81c7f10 --- /dev/null +++ b/src/Titano.Data/Sqlite/SqliteConnection.cs @@ -0,0 +1,209 @@ +using System.Text; +using static Titano.Data.Sqlite.SqliteNative; + +namespace Titano.Data.Sqlite; + +/// One native SQLite connection with its pragmas and an LRU cache of prepared statements. +internal sealed unsafe class SqliteConnection : IDisposable +{ + private const int StatementCacheCapacity = 64; + private const string Pragmas = + "PRAGMA synchronous=NORMAL; PRAGMA foreign_keys=ON; PRAGMA temp_store=MEMORY; " + + "PRAGMA cache_size=-65536; PRAGMA mmap_size=268435456;"; + + private readonly Dictionary> _cache = new(StringComparer.Ordinal); + private readonly LinkedList _lru = new(); + + private SqliteConnection(nint handle) => Handle = handle; + + public nint Handle { get; private set; } + + public bool IsAutoCommit => sqlite3_get_autocommit(Handle) != 0; + + /// Rows changed by INSERT/UPDATE/DELETE since the connection opened (DDL does not count). + public int TotalChanges => sqlite3_total_changes(Handle); + + /// Rows changed by the most recent INSERT/UPDATE/DELETE. + public int Changes => sqlite3_changes(Handle); + + /// Opens a read-write connection and applies the BRIEF §6.2 pragmas (WAL only for files). + public static SqliteConnection Open(string filename, bool isMemory, int busyTimeoutMs) + { + var connection = OpenRaw(filename, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_URI | SQLITE_OPEN_NOMUTEX); + try + { + sqlite3_busy_timeout(connection.Handle, busyTimeoutMs); + connection.Exec(isMemory ? Pragmas : "PRAGMA journal_mode=WAL; " + Pragmas); + return connection; + } + catch + { + connection.Dispose(); + throw; + } + } + + public static SqliteConnection OpenReadOnly(string path) => + OpenRaw(path, SQLITE_OPEN_READONLY | SQLITE_OPEN_NOMUTEX); + + private static SqliteConnection OpenRaw(string filename, int flags) + { + nint db; + int rc; + fixed (byte* p = NullTerminated(filename)) rc = sqlite3_open_v2(p, out db, flags, null); + if (rc != SQLITE_OK) + { + var message = db != 0 ? Utf8(sqlite3_errmsg(db)) : null; + if (db != 0) sqlite3_close_v2(db); + throw new SqliteException($"Cannot open SQLite database '{filename}': {message ?? "error " + rc}", rc); + } + sqlite3_extended_result_codes(db, 1); + return new SqliteConnection(db); + } + + /// Runs one or more parameterless statements. + public void Exec(string sql) + { + byte* error; + int rc; + fixed (byte* p = NullTerminated(sql)) rc = sqlite3_exec(Handle, p, 0, 0, out error); + if (rc == SQLITE_OK) return; + var message = Utf8(error) ?? $"SQLite error {rc}"; + sqlite3_free(error); + throw new SqliteException(message, rc); + } + + /// Takes a statement from the cache (or prepares one); give it back with . + public SqliteStatement Rent(string sql) + { + if (_cache.TryGetValue(sql, out var node)) + { + if (!node.Value.InUse) + { + _lru.Remove(node); + _lru.AddFirst(node); + node.Value.InUse = true; + return node.Value; + } + // Same SQL already running on this connection (nested enumeration): use a private copy. + var copy = Prepare(sql); + copy.InUse = true; + return copy; + } + + var statement = Prepare(sql); + statement.InUse = true; + statement.Cached = true; + _cache[sql] = _lru.AddFirst(statement); + if (_lru.Count > StatementCacheCapacity && _lru.Last is { Value.InUse: false } last) + { + _lru.RemoveLast(); + _cache.Remove(last.Value.Sql); + last.Value.Dispose(); + } + return statement; + } + + public void Return(SqliteStatement statement) + { + statement.InUse = false; + if (statement.Cached) statement.Reset(); + else statement.Dispose(); + } + + public void Interrupt() => sqlite3_interrupt(Handle); + + public SqliteException Error(int rc) => new(Utf8(sqlite3_errmsg(Handle)) ?? $"SQLite error {rc}", rc); + + public void Dispose() + { + if (Handle == 0) return; + foreach (var statement in _lru) statement.Dispose(); + _lru.Clear(); + _cache.Clear(); + sqlite3_close_v2(Handle); + Handle = 0; + } + + private SqliteStatement Prepare(string sql) + { + var bytes = Encoding.UTF8.GetBytes(SqliteSqlText.TranslatePlaceholders(sql)); + fixed (byte* p = bytes) + { + var rc = sqlite3_prepare_v2(Handle, p, bytes.Length, out var statement, out var tail); + if (rc != SQLITE_OK) throw Error(rc); + if (statement == 0) throw new ArgumentException("The SQL text contains no statement.", nameof(sql)); + var rest = bytes.Length - (int)(tail - p); + if (rest > 0 && HasStatement(tail, rest)) + { + sqlite3_finalize(statement); + throw new ArgumentException("Only one statement per command is allowed; use ExecuteScriptAsync for scripts.", nameof(sql)); + } + return new SqliteStatement(this, statement, sql); + } + } + + /// True when the remaining text holds more than whitespace and comments. + private bool HasStatement(byte* text, int length) + { + var rc = sqlite3_prepare_v2(Handle, text, length, out var statement, out _); + if (statement != 0) sqlite3_finalize(statement); + return rc != SQLITE_OK || statement != 0; + } + + private static byte[] NullTerminated(string s) + { + var bytes = new byte[Encoding.UTF8.GetByteCount(s) + 1]; + Encoding.UTF8.GetBytes(s, bytes); + return bytes; + } +} + +/// Rewrites $n placeholders for SQLite, which numbers $name parameters by first appearance. +internal static class SqliteSqlText +{ + /// Turns $n into ?n outside string literals, quoted identifiers and comments. + public static string TranslatePlaceholders(string sql) + { + if (!sql.Contains('$', StringComparison.Ordinal)) return sql; + var sb = new StringBuilder(sql.Length); + var i = 0; + while (i < sql.Length) + { + var c = sql[i]; + var next = i + 1 < sql.Length ? sql[i + 1] : '\0'; + int end; + switch (c) + { + case '\'' or '"' or '`': + end = sql.IndexOf(c, i + 1); + break; + case '[': + end = sql.IndexOf(']', i + 1); + break; + case '-' when next == '-': + end = sql.IndexOf('\n', i + 2); + break; + case '/' when next == '*': + end = sql.IndexOf("*/", i + 2, StringComparison.Ordinal); + if (end >= 0) end++; + break; + case '$' when char.IsAsciiDigit(next) && (i == 0 || !IsIdentifierChar(sql[i - 1])): + sb.Append('?'); + i++; + continue; + default: + sb.Append(c); + i++; + continue; + } + // Copy the literal, identifier or comment verbatim (to the end of the text if unterminated). + end = end < 0 ? sql.Length : end + 1; + sb.Append(sql, i, end - i); + i = end; + } + return sb.ToString(); + } + + private static bool IsIdentifierChar(char c) => char.IsLetterOrDigit(c) || c is '_' or '$'; +} diff --git a/src/Titano.Data/Sqlite/SqliteDatabase.cs b/src/Titano.Data/Sqlite/SqliteDatabase.cs new file mode 100644 index 00000000..f7dc78e9 --- /dev/null +++ b/src/Titano.Data/Sqlite/SqliteDatabase.cs @@ -0,0 +1,285 @@ +using System.Globalization; +using System.Text.RegularExpressions; +using Titano.Core.Diagnostics; +using Titano.Core.IO; +using static Titano.Data.Sqlite.SqliteNative; + +namespace Titano.Data.Sqlite; + +/// Parsed SQLite connection string: Data Source=<path>|:memory:;Pool Size=4. +internal sealed record SqliteSettings(string DataSource, int PoolSize) +{ + public bool IsMemory => DataSource == ":memory:"; + + public static SqliteSettings Parse(string connectionString) + { + var cs = new ConnectionString(connectionString); + var source = cs.Get("Data Source", "DataSource", "Filename") + ?? throw new FormatException("A SQLite connection string needs 'Data Source'."); + var pool = cs.GetInt(4, "Pool Size", "Max Pool Size"); + cs.ThrowOnUnknownKeys(); + if (pool < 1) throw new FormatException("'Pool Size' must be at least 1."); + return new SqliteSettings(source, pool); + } +} + +/// +/// SQLite through the system library (BRIEF §6.2). Up to Pool Size connections serve concurrent +/// readers (WAL); writes are serialised in-process by one async write lock, so writers wait in a queue instead +/// of spinning on SQLITE_BUSY. An in-memory database is a shared-cache URI that lives while the pool holds a +/// connection; its table locks (SQLITE_LOCKED) are retried by the sessions. +/// +public sealed class SqliteDatabase : IDatabase +{ + /// 3.31.0, the oldest library accepted: it has UPSERT, NULLS LAST and VACUUM INTO. + public const int MinimumVersionNumber = 3_031_000; + + internal const int BusyTimeoutMs = 5000; + private const string LogCategory = "Data.Sqlite"; + private static readonly TimeSpan WriteLockTimeout = TimeSpan.FromSeconds(60); + + private readonly string _filename; + private readonly bool _memory; + private readonly int _maxConnections; + private readonly SemaphoreSlim _slots; + private readonly SemaphoreSlim _writeLock = new(1, 1); + private readonly SemaphoreSlim _restoreGate = new(1, 1); + private readonly Stack _idle = new(); + private readonly Lock _gate = new(); + private bool _disposed; + + private SqliteDatabase(SqliteSettings settings) + { + _memory = settings.IsMemory; + if (_memory) + { + _filename = $"file:titano-{Guid.NewGuid():N}?mode=memory&cache=shared"; + } + else + { + Path = System.IO.Path.GetFullPath(settings.DataSource); + var directory = System.IO.Path.GetDirectoryName(Path); + if (!string.IsNullOrEmpty(directory)) Directory.CreateDirectory(directory); + _filename = Path; + } + _maxConnections = settings.PoolSize; + _slots = new SemaphoreSlim(_maxConnections, _maxConnections); + } + + public Dialect Dialect => Dialect.Sqlite; + + /// Full path of the database file; null for an in-memory database. + public string? Path { get; } + + /// Version string of the loaded SQLite library, e.g. "3.45.1". + public static string LibraryVersion + { + get + { + EnsureLibrary(); + unsafe + { + return Utf8(sqlite3_libversion()) ?? "?"; + } + } + } + + internal static SqliteDatabase Open(SqliteSettings settings) + { + EnsureLibrary(); + var database = new SqliteDatabase(settings); + // The first connection validates the path, switches the file to WAL and keeps a memory database alive. + database._idle.Push(database.CreateConnection()); + return database; + } + + public async Task OpenAsync(CancellationToken cancellationToken) + { + ObjectDisposedException.ThrowIf(_disposed, this); + await _slots.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + SqliteConnection? connection; + lock (_gate) _idle.TryPop(out connection); + return new SqliteSession(this, connection ?? CreateConnection()); + } + catch + { + _slots.Release(); + throw; + } + } + + /// + /// Writes a consistent copy with VACUUM INTO to as + /// <name>-yyyyMMdd-HHmmss-fff.db and deletes all but the newest copies. + /// Readers and writers continue meanwhile. Returns the new file. + /// + public async Task BackupAsync(string directory, int keep = 3, CancellationToken cancellationToken = default) + { + ArgumentOutOfRangeException.ThrowIfLessThan(keep, 1); + Directory.CreateDirectory(directory); + var stem = BackupStem; + string target; + while (true) + { + target = System.IO.Path.Combine(directory, string.Create(CultureInfo.InvariantCulture, $"{stem}-{DateTime.UtcNow:yyyyMMdd-HHmmss-fff}.db")); + if (!File.Exists(target)) break; + await Task.Delay(2, cancellationToken).ConfigureAwait(false); + } + var temp = target + ".tmp"; + try + { + await using (var session = (SqliteSession)await OpenAsync(cancellationToken).ConfigureAwait(false)) + await Task.Run(() => session.VacuumInto(temp, cancellationToken), cancellationToken).ConfigureAwait(false); + File.Move(temp, target); + } + catch + { + File.Delete(temp); + throw; + } + + var pattern = new Regex("^" + Regex.Escape(stem) + @"-\d{8}-\d{6}-\d{3}\.db$", RegexOptions.CultureInvariant); + var backups = Directory.EnumerateFiles(directory) + .Where(f => pattern.IsMatch(System.IO.Path.GetFileName(f))) + .OrderByDescending(f => System.IO.Path.GetFileName(f), StringComparer.Ordinal) + .ToList(); + foreach (var old in backups.Skip(keep)) File.Delete(old); + Log.Info(LogCategory, $"Backup written to {target}"); + return target; + } + + /// + /// Replaces the database file with a backup after checking it with PRAGMA quick_check. Waits until + /// every session of this instance is returned (a caller must not hold one meanwhile); no other process may + /// have the file open. + /// + public async Task RestoreAsync(string backupPath, CancellationToken cancellationToken = default) + { + if (Path is null) throw new NotSupportedException("An in-memory database cannot be restored."); + if (!File.Exists(backupPath)) throw new FileNotFoundException("Backup file not found.", backupPath); + Validate(backupPath); + + // Holding every pool slot excludes all sessions, and with them the write lock, which only sessions take. + await _restoreGate.WaitAsync(cancellationToken).ConfigureAwait(false); + var taken = 0; + try + { + for (; taken < _maxConnections; taken++) await _slots.WaitAsync(cancellationToken).ConfigureAwait(false); + lock (_gate) + { + while (_idle.TryPop(out var connection)) connection.Dispose(); + } + var temp = AtomicFile.TempPathFor(Path); + File.Copy(backupPath, temp); + // A WAL left behind belongs to the old file and would be replayed onto the restored one. + File.Delete(Path + "-wal"); + File.Delete(Path + "-shm"); + AtomicFile.Commit(temp, Path); + Log.Info(LogCategory, $"Database restored from {backupPath}"); + } + finally + { + if (taken > 0) _slots.Release(taken); + _restoreGate.Release(); + } + } + + public ValueTask DisposeAsync() + { + lock (_gate) + { + if (_disposed) return ValueTask.CompletedTask; + _disposed = true; + while (_idle.TryPop(out var connection)) connection.Dispose(); + } + return ValueTask.CompletedTask; + } + + /// + /// Queues for the write lock. The wait is bounded so a transaction left open by mistake surfaces as a transient + /// SQLITE_BUSY instead of hanging every writer; the bound is generous because bulk imports hold the lock for long. + /// + internal async Task AcquireWriteAsync(CancellationToken cancellationToken) + { + if (!await _writeLock.WaitAsync(WriteLockTimeout, cancellationToken).ConfigureAwait(false)) + throw new SqliteException($"database is locked: no write lock within {WriteLockTimeout.TotalSeconds} s", SQLITE_BUSY); + } + + internal void ReleaseWrite() => _writeLock.Release(); + + /// Takes back a session's connection; one left inside a transaction is rolled back or dropped. + internal void Return(SqliteConnection connection) + { + try + { + if (!connection.IsAutoCommit) + { + try + { + connection.Exec("ROLLBACK"); + } + catch (SqliteException ex) + { + Log.Warning(LogCategory, "Dropping a connection whose transaction could not be rolled back.", ex); + connection.Dispose(); + return; + } + } + lock (_gate) + { + if (_disposed) connection.Dispose(); + else _idle.Push(connection); + } + } + finally + { + _slots.Release(); + } + } + + private string BackupStem => Path is null ? "titano" : System.IO.Path.GetFileNameWithoutExtension(Path); + + private SqliteConnection CreateConnection() => SqliteConnection.Open(_filename, _memory, BusyTimeoutMs); + + private static void EnsureLibrary() + { + EnsureResolver(); + int version; + try + { + version = sqlite3_libversion_number(); + } + catch (DllNotFoundException ex) + { + throw new NotSupportedException("The system SQLite library was not found (winsqlite3.dll, libsqlite3.so.0 or libsqlite3.dylib).", ex); + } + if (version < MinimumVersionNumber) + throw new NotSupportedException($"SQLite {version / 1_000_000}.{version / 1000 % 1000}.{version % 1000} is too old; 3.31 or newer is required."); + } + + private static void Validate(string backupPath) + { + try + { + using var connection = SqliteConnection.OpenReadOnly(backupPath); + var statement = connection.Rent("PRAGMA quick_check"); + try + { + var rc = statement.Step(); + if (rc != SQLITE_ROW) throw connection.Error(rc); + var result = statement.ReadRow(statement.ReadColumns()).GetStringOrNull(0); + if (result != "ok") throw new InvalidDataException($"The backup failed its integrity check: {result}"); + } + finally + { + connection.Return(statement); + } + } + catch (SqliteException ex) + { + throw new InvalidDataException("The file is not a readable SQLite database.", ex); + } + } +} diff --git a/src/Titano.Data/Sqlite/SqliteException.cs b/src/Titano.Data/Sqlite/SqliteException.cs new file mode 100644 index 00000000..360c977f --- /dev/null +++ b/src/Titano.Data/Sqlite/SqliteException.cs @@ -0,0 +1,19 @@ +namespace Titano.Data.Sqlite; + +/// An error returned by SQLite, with its primary and extended result codes. +public sealed class SqliteException(string message, int extendedResultCode) : DatabaseException(message) +{ + /// Primary result code (low byte), e.g. 19 = SQLITE_CONSTRAINT. + public int ResultCode => ExtendedResultCode & 0xFF; + + /// Extended result code, e.g. 2067 = SQLITE_CONSTRAINT_UNIQUE. + public int ExtendedResultCode { get; } = extendedResultCode; + + public override int ErrorCode => ExtendedResultCode; + + public override bool IsTransient => ResultCode is SqliteNative.SQLITE_BUSY or SqliteNative.SQLITE_LOCKED; + + public override bool IsUniqueViolation => ExtendedResultCode is SqliteNative.SQLITE_CONSTRAINT_UNIQUE or SqliteNative.SQLITE_CONSTRAINT_PRIMARYKEY; + + public override bool IsForeignKeyViolation => ExtendedResultCode == SqliteNative.SQLITE_CONSTRAINT_FOREIGNKEY; +} diff --git a/src/Titano.Data/Sqlite/SqliteNative.cs b/src/Titano.Data/Sqlite/SqliteNative.cs new file mode 100644 index 00000000..97938b91 --- /dev/null +++ b/src/Titano.Data/Sqlite/SqliteNative.cs @@ -0,0 +1,102 @@ +using System.Reflection; +using System.Runtime.InteropServices; + +namespace Titano.Data.Sqlite; + +/// +/// P/Invoke surface of the system SQLite library: winsqlite3.dll (Windows 10 1709+), libsqlite3.so.0 +/// (Linux) or libsqlite3.dylib (macOS). Strings cross the boundary as UTF-8 encoded by hand; the default +/// calling convention matches winsqlite3's __stdcall exports on x86 and is cdecl elsewhere. +/// +internal static unsafe class SqliteNative +{ + private const string Library = "titano-sqlite3"; + private static int _resolverInstalled; + + public const int SQLITE_OK = 0; + public const int SQLITE_INTERRUPT = 9; + public const int SQLITE_BUSY = 5; + public const int SQLITE_LOCKED = 6; + public const int SQLITE_CONSTRAINT = 19; + public const int SQLITE_ROW = 100; + public const int SQLITE_DONE = 101; + + public const int SQLITE_CONSTRAINT_FOREIGNKEY = SQLITE_CONSTRAINT | (3 << 8); + public const int SQLITE_CONSTRAINT_PRIMARYKEY = SQLITE_CONSTRAINT | (6 << 8); + public const int SQLITE_CONSTRAINT_UNIQUE = SQLITE_CONSTRAINT | (8 << 8); + + public const int SQLITE_OPEN_READONLY = 0x00000001; + public const int SQLITE_OPEN_READWRITE = 0x00000002; + public const int SQLITE_OPEN_CREATE = 0x00000004; + public const int SQLITE_OPEN_URI = 0x00000040; + public const int SQLITE_OPEN_NOMUTEX = 0x00008000; + + public const int SQLITE_INTEGER = 1; + public const int SQLITE_FLOAT = 2; + public const int SQLITE_TEXT = 3; + public const int SQLITE_BLOB = 4; + public const int SQLITE_NULL = 5; + + /// Destructor sentinel that makes SQLite copy bound text/blobs before the call returns. + public static readonly nint SQLITE_TRANSIENT = -1; + + /// Routes the logical library name to the platform's system SQLite (once per process). + public static void EnsureResolver() + { + if (Interlocked.Exchange(ref _resolverInstalled, 1) == 0) + NativeLibrary.SetDllImportResolver(typeof(SqliteNative).Assembly, Resolve); + } + + private static nint Resolve(string name, Assembly assembly, DllImportSearchPath? searchPath) + { + if (name != Library) return 0; + string[] candidates = OperatingSystem.IsWindows() ? ["winsqlite3.dll"] + : OperatingSystem.IsMacOS() ? ["libsqlite3.dylib", "/usr/lib/libsqlite3.dylib"] + : ["libsqlite3.so.0", "libsqlite3.so"]; + foreach (var candidate in candidates) + { + if (NativeLibrary.TryLoad(candidate, assembly, searchPath, out var handle)) return handle; + } + return 0; + } + + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_libversion_number(); + [DllImport(Library, ExactSpelling = true)] public static extern byte* sqlite3_libversion(); + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_open_v2(byte* filename, out nint db, int flags, byte* vfs); + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_close_v2(nint db); + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_extended_result_codes(nint db, int onoff); + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_busy_timeout(nint db, int ms); + [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 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); + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_get_autocommit(nint db); + + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_prepare_v2(nint db, byte* sql, int nBytes, out nint stmt, out byte* tail); + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_step(nint stmt); + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_reset(nint stmt); + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_clear_bindings(nint stmt); + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_finalize(nint stmt); + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_stmt_readonly(nint stmt); + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_bind_parameter_count(nint stmt); + + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_bind_null(nint stmt, int index); + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_bind_int64(nint stmt, int index, long value); + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_bind_double(nint stmt, int index, double value); + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_bind_text(nint stmt, int index, byte* text, int nBytes, nint destructor); + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_bind_blob(nint stmt, int index, void* data, int nBytes, nint destructor); + + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_column_count(nint stmt); + [DllImport(Library, ExactSpelling = true)] public static extern byte* sqlite3_column_name(nint stmt, int index); + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_column_type(nint stmt, int index); + [DllImport(Library, ExactSpelling = true)] public static extern long sqlite3_column_int64(nint stmt, int index); + [DllImport(Library, ExactSpelling = true)] public static extern double sqlite3_column_double(nint stmt, int index); + [DllImport(Library, ExactSpelling = true)] public static extern byte* sqlite3_column_text(nint stmt, int index); + [DllImport(Library, ExactSpelling = true)] public static extern void* sqlite3_column_blob(nint stmt, int index); + [DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_column_bytes(nint stmt, int index); + + /// Decodes a NUL-terminated UTF-8 string owned by SQLite. + public static string? Utf8(byte* p) => p is null ? null : Marshal.PtrToStringUTF8((nint)p); +} diff --git a/src/Titano.Data/Sqlite/SqliteSession.cs b/src/Titano.Data/Sqlite/SqliteSession.cs new file mode 100644 index 00000000..4954f572 --- /dev/null +++ b/src/Titano.Data/Sqlite/SqliteSession.cs @@ -0,0 +1,324 @@ +using System.Runtime.CompilerServices; +using System.Text; +using static Titano.Data.Sqlite.SqliteNative; + +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; lock conflicts are retried (see ). Cancellation +/// interrupts the running statement with sqlite3_interrupt. +/// +internal sealed class SqliteSession(SqliteDatabase database, SqliteConnection connection) : IDbSession +{ + private const int MaxBusyRetries = 3; + private SqliteTransaction? _transaction; + private bool _disposed; + + public Dialect Dialect => Dialect.Sqlite; + + public bool InTransaction => _transaction is not null; + + public async Task ExecuteAsync(string sql, DbParam[] parameters, CancellationToken cancellationToken) + { + ObjectDisposedException.ThrowIf(_disposed, this); + cancellationToken.ThrowIfCancellationRequested(); + var statement = connection.Rent(sql); + var locked = false; + try + { + statement.Bind(parameters); + if (!statement.IsReadOnly && _transaction is null) + { + await database.AcquireWriteAsync(cancellationToken).ConfigureAwait(false); + locked = true; + } + using var interrupt = RegisterInterrupt(cancellationToken); + var before = connection.TotalChanges; + while (await StepAsync(statement, canRestart: true, cancellationToken).ConfigureAwait(false) == SQLITE_ROW) + { + } + // sqlite3_changes keeps the last DML count across DDL; only trust it when this statement changed rows. + return connection.TotalChanges != before ? connection.Changes : 0; + } + finally + { + connection.Return(statement); + if (locked) database.ReleaseWrite(); + } + } + + public async IAsyncEnumerable QueryAsync(string sql, DbParam[] parameters, [EnumeratorCancellation] CancellationToken cancellationToken) + { + ObjectDisposedException.ThrowIf(_disposed, this); + cancellationToken.ThrowIfCancellationRequested(); + var statement = connection.Rent(sql); + var locked = false; + try + { + statement.Bind(parameters); + if (!statement.IsReadOnly && _transaction is null) + { + await database.AcquireWriteAsync(cancellationToken).ConfigureAwait(false); + locked = true; + } + using var interrupt = RegisterInterrupt(cancellationToken); + DbColumns? columns = null; + var canRestart = true; + while (await StepAsync(statement, canRestart, cancellationToken).ConfigureAwait(false) == SQLITE_ROW) + { + canRestart = false; // restarting after rows were yielded would repeat them + columns ??= statement.ReadColumns(); + yield return statement.ReadRow(columns); + cancellationToken.ThrowIfCancellationRequested(); + } + } + finally + { + connection.Return(statement); + if (locked) database.ReleaseWrite(); + } + } + + public async Task ExecuteScriptAsync(string script, CancellationToken cancellationToken) + { + ObjectDisposedException.ThrowIf(_disposed, this); + cancellationToken.ThrowIfCancellationRequested(); + var locked = _transaction is null; + if (locked) await database.AcquireWriteAsync(cancellationToken).ConfigureAwait(false); + try + { + using var interrupt = RegisterInterrupt(cancellationToken); + connection.Exec(script); + } + catch (SqliteException ex) when (ex.ResultCode == SQLITE_INTERRUPT && cancellationToken.IsCancellationRequested) + { + throw new OperationCanceledException(ex.Message, ex, cancellationToken); + } + finally + { + if (locked) database.ReleaseWrite(); + } + } + + public async Task BeginAsync(CancellationToken cancellationToken) + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (_transaction is not null) throw new InvalidOperationException("A transaction is already active on this session."); + await database.AcquireWriteAsync(cancellationToken).ConfigureAwait(false); + try + { + await RunAsync("BEGIN IMMEDIATE", cancellationToken).ConfigureAwait(false); + } + catch + { + database.ReleaseWrite(); + throw; + } + return _transaction = new SqliteTransaction(this); + } + + public async Task BulkInsertAsync(string table, IReadOnlyList columns, IAsyncEnumerable rows, CancellationToken cancellationToken) + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (columns.Count == 0) throw new ArgumentException("At least one column is required.", nameof(columns)); + // 999 is the variable limit of SQLite builds before 3.32. + var rowsPerStatement = Math.Clamp(999 / columns.Count, 1, 100); + var buffer = new object?[rowsPerStatement * columns.Count]; + var ownTransaction = _transaction is null ? await BeginAsync(cancellationToken).ConfigureAwait(false) : null; + try + { + long total = 0; + var buffered = 0; + using (RegisterInterrupt(cancellationToken)) + { + await foreach (var row in rows.WithCancellation(cancellationToken).ConfigureAwait(false)) + { + if (row.Length != columns.Count) + throw new ArgumentException($"A row has {row.Length} values for {columns.Count} columns.", nameof(rows)); + Array.Copy(row, 0, buffer, buffered * columns.Count, row.Length); + if (++buffered == rowsPerStatement) + { + await InsertBufferedAsync(table, columns, buffer, buffered, cancellationToken).ConfigureAwait(false); + total += buffered; + buffered = 0; + } + } + if (buffered > 0) + { + await InsertBufferedAsync(table, columns, buffer, buffered, cancellationToken).ConfigureAwait(false); + total += buffered; + } + } + if (ownTransaction is not null) await ownTransaction.CommitAsync(cancellationToken).ConfigureAwait(false); + return total; + } + finally + { + if (ownTransaction is not null) await ownTransaction.DisposeAsync().ConfigureAwait(false); + } + } + + public async ValueTask DisposeAsync() + { + if (_disposed) return; + _disposed = true; + if (_transaction is { } transaction) + { + try + { + await EndTransactionAsync(transaction, commit: false, CancellationToken.None).ConfigureAwait(false); + } + catch (SqliteException) + { + // The pool rolls the connection back or drops it below. + } + if (_transaction is not null) + { + _transaction = null; + database.ReleaseWrite(); + } + } + database.Return(connection); + } + + /// Ends if it is still the active one; a failed COMMIT leaves it open for rollback. + internal async Task EndTransactionAsync(SqliteTransaction transaction, bool commit, CancellationToken cancellationToken) + { + if (_transaction != transaction) return; + try + { + await RunAsync(commit ? "COMMIT" : "ROLLBACK", cancellationToken).ConfigureAwait(false); + } + finally + { + if (connection.IsAutoCommit) + { + _transaction = null; + database.ReleaseWrite(); + } + } + } + + /// Runs VACUUM INTO (backups); it only reads, so no write lock is taken. + internal void VacuumInto(string path, CancellationToken cancellationToken) + { + var statement = connection.Rent("VACUUM INTO $1"); + try + { + statement.Bind([path]); + using var interrupt = RegisterInterrupt(cancellationToken); + var rc = statement.Step(); + if (rc == SQLITE_DONE) return; + if ((rc & 0xFF) == SQLITE_INTERRUPT && cancellationToken.IsCancellationRequested) throw new OperationCanceledException(cancellationToken); + throw connection.Error(rc); + } + finally + { + connection.Return(statement); + } + } + + private async Task InsertBufferedAsync(string table, IReadOnlyList columns, object?[] buffer, int rowCount, CancellationToken cancellationToken) + { + var statement = connection.Rent(InsertSql(table, columns, rowCount)); + try + { + for (var i = 0; i < rowCount * columns.Count; i++) statement.BindValue(i + 1, buffer[i]); + await StepAsync(statement, canRestart: true, cancellationToken).ConfigureAwait(false); + } + finally + { + connection.Return(statement); + } + } + + private static string InsertSql(string table, IReadOnlyList columns, int rowCount) + { + var sb = new StringBuilder("INSERT INTO ").Append(SqlDialect.QuoteIdentifier(table)).Append(" ("); + for (var c = 0; c < columns.Count; c++) sb.Append(c > 0 ? ", " : string.Empty).Append(SqlDialect.QuoteIdentifier(columns[c])); + sb.Append(") VALUES "); + var n = 1; + for (var r = 0; r < rowCount; r++) + { + sb.Append(r > 0 ? ", (" : "("); + for (var c = 0; c < columns.Count; c++) sb.Append(c > 0 ? ", ?" : "?").Append(n++); + sb.Append(')'); + } + return sb.ToString(); + } + + private async Task RunAsync(string sql, CancellationToken cancellationToken) + { + var statement = connection.Rent(sql); + try + { + await StepAsync(statement, canRestart: true, cancellationToken).ConfigureAwait(false); + } + finally + { + connection.Return(statement); + } + } + + /// + /// Steps once. While (no row returned yet) a statement stopped by a lock is + /// rewound and retried: SQLITE_LOCKED (shared-cache table locks, which busy_timeout does not cover) for up to + /// the busy timeout, SQLITE_BUSY (another process; busy_timeout already waited) a few times outside transactions. + /// + private async ValueTask StepAsync(SqliteStatement statement, bool canRestart, CancellationToken cancellationToken) + { + var waitedMs = 0; + var busyRetries = 0; + while (true) + { + var rc = statement.Step(); + if (rc is SQLITE_ROW or SQLITE_DONE) return rc; + var primary = rc & 0xFF; + if (primary == SQLITE_INTERRUPT && cancellationToken.IsCancellationRequested) + throw new OperationCanceledException(cancellationToken); + int delayMs; + if (canRestart && primary == SQLITE_LOCKED && waitedMs < SqliteDatabase.BusyTimeoutMs) + delayMs = Math.Min(50, 1 + waitedMs / 10); + else if (canRestart && primary == SQLITE_BUSY && _transaction is null && busyRetries++ < MaxBusyRetries) + delayMs = 50 * busyRetries + Random.Shared.Next(50); + else + throw connection.Error(rc); + statement.Rewind(); + await Task.Delay(delayMs, cancellationToken).ConfigureAwait(false); + waitedMs += delayMs; + } + } + + private CancellationTokenRegistration RegisterInterrupt(CancellationToken cancellationToken) => + cancellationToken.CanBeCanceled + ? cancellationToken.UnsafeRegister(static state => ((SqliteConnection)state!).Interrupt(), connection) + : default; +} + +/// A BEGIN IMMEDIATE transaction holding the database write lock until it ends. +internal sealed class SqliteTransaction(SqliteSession session) : IDbTransaction +{ + private bool _completed; + + public async Task CommitAsync(CancellationToken cancellationToken = default) + { + ObjectDisposedException.ThrowIf(_completed, this); + await session.EndTransactionAsync(this, commit: true, cancellationToken).ConfigureAwait(false); + _completed = true; + } + + 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); + } +} diff --git a/src/Titano.Data/Sqlite/SqliteStatement.cs b/src/Titano.Data/Sqlite/SqliteStatement.cs new file mode 100644 index 00000000..3b96b7d2 --- /dev/null +++ b/src/Titano.Data/Sqlite/SqliteStatement.cs @@ -0,0 +1,170 @@ +using System.Buffers; +using System.Globalization; +using System.Text; +using static Titano.Data.Sqlite.SqliteNative; + +namespace Titano.Data.Sqlite; + +/// A prepared statement owned by one ; reused through its statement cache. +internal sealed unsafe class SqliteStatement : IDisposable +{ + private const int StackTextBytes = 256; + private readonly SqliteConnection _connection; + + public SqliteStatement(SqliteConnection connection, nint handle, string sql) + { + _connection = connection; + Handle = handle; + Sql = sql; + IsReadOnly = sqlite3_stmt_readonly(handle) != 0; + ParameterCount = sqlite3_bind_parameter_count(handle); + } + + public nint Handle { get; private set; } + + /// The SQL text as the caller wrote it (cache key). + public string Sql { get; } + + /// The statement does not write the database (no write lock needed). + public bool IsReadOnly { get; } + + /// Highest parameter number used by the statement. + public int ParameterCount { get; } + + public bool InUse { get; set; } + + public bool Cached { get; set; } + + public void Bind(DbParam[] parameters) + { + if (parameters.Length != ParameterCount) + throw new ArgumentException($"The statement uses {ParameterCount} parameter(s) but {parameters.Length} were supplied.", nameof(parameters)); + for (var i = 0; i < parameters.Length; i++) Bind(i + 1, parameters[i].Value, parameters[i].Type); + } + + /// Binds a raw CLR value (bulk insert rows); the type is inferred like does. + public void BindValue(int index, object? value) => Bind(index, value, DbValueType.Auto); + + public int Step() => sqlite3_step(Handle); + + /// Rewinds for another execution with the same bindings. + public void Rewind() => sqlite3_reset(Handle); + + /// Rewinds after an execution; a step error was already reported, so the code is ignored. + public void Reset() + { + sqlite3_reset(Handle); + sqlite3_clear_bindings(Handle); + } + + public DbColumns ReadColumns() + { + var names = new string[sqlite3_column_count(Handle)]; + for (var i = 0; i < names.Length; i++) names[i] = Utf8(sqlite3_column_name(Handle, i)) ?? string.Empty; + return new DbColumns(names); + } + + public DbRow ReadRow(DbColumns columns) + { + var values = new object?[columns.Names.Length]; + for (var i = 0; i < values.Length; i++) + { + values[i] = sqlite3_column_type(Handle, i) switch + { + SQLITE_INTEGER => sqlite3_column_int64(Handle, i), + SQLITE_FLOAT => sqlite3_column_double(Handle, i), + SQLITE_TEXT => ReadText(i), + SQLITE_BLOB => ReadBlob(i), + _ => null, + }; + } + return new DbRow(columns, values); + } + + public void Dispose() + { + if (Handle != 0) + { + sqlite3_finalize(Handle); + Handle = 0; + } + } + + private void Bind(int index, object? value, DbValueType type) + { + var rc = value switch + { + null => sqlite3_bind_null(Handle, index), + string s => BindText(index, s), + long l => sqlite3_bind_int64(Handle, index, l), + int n => sqlite3_bind_int64(Handle, index, n), + double d => sqlite3_bind_double(Handle, index, d), + bool b => sqlite3_bind_int64(Handle, index, b ? 1 : 0), + Guid g => BindFormatted(index, g, "D"), + DateTimeOffset o => BindFormatted(index, o.UtcDateTime, "yyyy-MM-dd'T'HH:mm:ss.ffffff'Z'"), + DateTime d when type == DbValueType.LocalDateTime || (type == DbValueType.Auto && d.Kind == DateTimeKind.Unspecified) + => BindFormatted(index, d, "yyyy-MM-dd'T'HH:mm:ss.ffffff"), + DateTime d => BindFormatted(index, d.ToUniversalTime(), "yyyy-MM-dd'T'HH:mm:ss.ffffff'Z'"), + byte[] b => BindBlob(index, b), + _ => BindNormalized(index, new DbParam(value)), + }; + if (rc != SQLITE_OK) throw _connection.Error(rc); + } + + private int BindNormalized(int index, DbParam p) + { + Bind(index, p.Value, p.Type); + return SQLITE_OK; + } + + private int BindText(int index, string s) + { + if (s.Length <= StackTextBytes / 3) + { + var buffer = stackalloc byte[StackTextBytes]; + var n = Encoding.UTF8.GetBytes(s, new Span(buffer, StackTextBytes)); + return sqlite3_bind_text(Handle, index, buffer, n, SQLITE_TRANSIENT); + } + var rented = ArrayPool.Shared.Rent(Encoding.UTF8.GetByteCount(s)); + try + { + var n = Encoding.UTF8.GetBytes(s, rented); + fixed (byte* p = rented) return sqlite3_bind_text(Handle, index, p, n, SQLITE_TRANSIENT); + } + finally + { + ArrayPool.Shared.Return(rented); + } + } + + private int BindFormatted(int index, T value, string format) where T : IUtf8SpanFormattable + { + var buffer = stackalloc byte[64]; + var span = new Span(buffer, 64); + if (!value.TryFormat(span, out var n, format, CultureInfo.InvariantCulture)) + throw new FormatException($"Cannot format {value} for SQLite."); + return sqlite3_bind_text(Handle, index, buffer, n, SQLITE_TRANSIENT); + } + + private int BindBlob(int index, byte[] data) + { + byte empty = 0; + // A null pointer would bind NULL; an empty blob needs any valid address. + if (data.Length == 0) return sqlite3_bind_blob(Handle, index, &empty, 0, SQLITE_TRANSIENT); + fixed (byte* p = data) return sqlite3_bind_blob(Handle, index, p, data.Length, SQLITE_TRANSIENT); + } + + private string ReadText(int column) + { + var p = sqlite3_column_text(Handle, column); + var n = sqlite3_column_bytes(Handle, column); + return n == 0 ? string.Empty : Encoding.UTF8.GetString(p, n); + } + + private byte[] ReadBlob(int column) + { + var p = (byte*)sqlite3_column_blob(Handle, column); + var n = sqlite3_column_bytes(Handle, column); + return n == 0 ? [] : new ReadOnlySpan(p, n).ToArray(); + } +} diff --git a/src/Titano.Data/TextValues.cs b/src/Titano.Data/TextValues.cs new file mode 100644 index 00000000..cb1143fa --- /dev/null +++ b/src/Titano.Data/TextValues.cs @@ -0,0 +1,135 @@ +using System.Globalization; + +namespace Titano.Data; + +/// +/// Canonical text forms of values without a native SQLite type, also used for PostgreSQL text parameters. +/// Date-times are fixed-width ISO-8601 with microseconds, so text order equals chronological order. +/// +internal static class TextValues +{ + private const string TimestampFormat = "yyyy-MM-dd'T'HH:mm:ss.ffffff'Z'"; + private const string LocalFormat = "yyyy-MM-dd'T'HH:mm:ss.ffffff"; + + public static string FormatTimestamp(DateTimeOffset value) => value.UtcDateTime.ToString(TimestampFormat, CultureInfo.InvariantCulture); + + public static string FormatLocal(DateTime value) => value.ToString(LocalFormat, CultureInfo.InvariantCulture); + + public static string FormatGuid(Guid value) => value.ToString("D"); + + /// Parses an ISO-8601 or PostgreSQL timestamp; a missing offset means UTC. + public static DateTimeOffset ParseTimestamp(ReadOnlySpan text) + { + if (!TryParse(text, out var value, out var offset)) + throw new FormatException($"Invalid timestamp '{text}'."); + if (value == DateTime.MaxValue || value == DateTime.MinValue) + return new DateTimeOffset(value, TimeSpan.Zero); + return new DateTimeOffset(DateTime.SpecifyKind(value - (offset ?? TimeSpan.Zero), DateTimeKind.Utc)); + } + + /// Parses a wall-clock date-time (unspecified kind); a value carrying an offset is returned in UTC. + public static DateTime ParseLocal(ReadOnlySpan text) + { + if (!TryParse(text, out var value, out var offset)) + throw new FormatException($"Invalid date-time '{text}'."); + return offset is { } o ? DateTime.SpecifyKind(value - o, DateTimeKind.Utc) : value; + } + + /// Accepts yyyy-MM-dd[(T| )HH:mm[:ss[.f…]]][Z|±HH[[:]mm[[:]ss]]] and ±infinity. + private static bool TryParse(ReadOnlySpan s, out DateTime value, out TimeSpan? offset) + { + value = default; + offset = null; + s = s.Trim(); + if (s.SequenceEqual("infinity")) + { + value = DateTime.MaxValue; + return true; + } + if (s.SequenceEqual("-infinity")) + { + value = DateTime.MinValue; + return true; + } + if (s.Length < 10 || s[4] != '-' || s[7] != '-' + || !Digits(s[..4], out var year) || !Digits(s.Slice(5, 2), out var month) || !Digits(s.Slice(8, 2), out var day)) + return false; + + int hour = 0, minute = 0, second = 0; + long fraction = 0; + var i = 10; + if (i < s.Length && s[i] is 'T' or ' ') + { + if (s.Length < i + 6 || s[i + 3] != ':' || !Digits(s.Slice(i + 1, 2), out hour) || !Digits(s.Slice(i + 4, 2), out minute)) + return false; + i += 6; + if (i < s.Length && s[i] == ':') + { + if (s.Length < i + 3 || !Digits(s.Slice(i + 1, 2), out second)) + return false; + i += 3; + if (i < s.Length && s[i] == '.') + { + var start = ++i; + var digits = 0; + for (; i < s.Length && char.IsAsciiDigit(s[i]); i++) + { + if (digits++ < 7) fraction = fraction * 10 + (s[i] - '0'); + } + if (i == start) return false; + for (; digits < 7; digits++) fraction *= 10; + } + } + } + + if (i < s.Length) + { + if (s[i] == 'Z' && i == s.Length - 1) + { + offset = TimeSpan.Zero; + } + else if (s[i] is '+' or '-') + { + var negative = s[i++] == '-'; + if (!OffsetPart(s, ref i, out var oh, colon: false)) return false; + var om = 0; + var os = 0; + if (i < s.Length && !OffsetPart(s, ref i, out om, colon: true)) return false; + if (i < s.Length && !OffsetPart(s, ref i, out os, colon: true)) return false; + if (i != s.Length) return false; + var span = new TimeSpan(oh, om, os); + offset = negative ? -span : span; + } + else + { + return false; + } + } + + if (year < 1 || month is < 1 or > 12 || day < 1 || day > DateTime.DaysInMonth(year, month) + || hour > 23 || minute > 59 || second > 59) + return false; + value = new DateTime(year, month, day, hour, minute, second, DateTimeKind.Unspecified).AddTicks(fraction); + return true; + } + + private static bool OffsetPart(ReadOnlySpan s, ref int i, out int value, bool colon) + { + if (colon && s[i] == ':') i++; + value = 0; + if (s.Length < i + 2 || !Digits(s.Slice(i, 2), out value)) return false; + i += 2; + return true; + } + + private static bool Digits(ReadOnlySpan s, out int value) + { + value = 0; + foreach (var c in s) + { + if (!char.IsAsciiDigit(c)) return false; + value = value * 10 + (c - '0'); + } + return true; + } +} diff --git a/src/Titano.Data/TitanoDatabase.cs b/src/Titano.Data/TitanoDatabase.cs new file mode 100644 index 00000000..7913e13a --- /dev/null +++ b/src/Titano.Data/TitanoDatabase.cs @@ -0,0 +1,155 @@ +using Titano.Data.Migrations; +using Titano.Data.Repositories; +using Titano.Data.Sqlite; + +namespace Titano.Data; + +/// The repositories of the Titano schema, bound either to the database (one session per call) or to one transaction. +public abstract class TitanoRepositories +{ + private protected TitanoRepositories(DbAccess access) + { + Archives = new ArchiveRepository(access); + Sequences = new SequenceRepository(access); + Frames = new FrameRepository(access); + Renders = new RenderRepository(access); + Jobs = new JobRepository(access); + MediaCards = new MediaCardRepository(access); + Users = new UserRepository(access); + Tokens = new TokenRepository(access); + RenderNodes = new RenderNodeRepository(access); + Settings = new SettingsRepository(access); + Tags = new TagRepository(access); + Audit = new AuditRepository(access); + Uploads = new UploadRepository(access); + } + + public ArchiveRepository Archives { get; } + public SequenceRepository Sequences { get; } + public FrameRepository Frames { get; } + public RenderRepository Renders { get; } + public JobRepository Jobs { get; } + public MediaCardRepository MediaCards { get; } + public UserRepository Users { get; } + public TokenRepository Tokens { get; } + public RenderNodeRepository RenderNodes { get; } + public SettingsRepository Settings { get; } + public TagRepository Tags { get; } + public AuditRepository Audit { get; } + public UploadRepository Uploads { get; } +} + +/// +/// Entry point of the data layer: opens SQLite or PostgreSQL, migrates the schema and exposes the repositories. +/// Each repository call borrows a pooled session; use to group calls atomically. +/// +/// +/// +/// await using var db = await TitanoDatabase.OpenAsync(DatabaseOptions.Parse(connectionString), ct); +/// var page = await db.Sequences.ListAsync(new SequenceQuery { Year = 2026 }, ct); +/// await using var tx = await db.BeginAsync(ct); +/// await tx.Frames.InsertAsync(frame, ct); +/// await tx.Sequences.RefreshStatsAsync(frame.SequenceId, ct); +/// await tx.CommitAsync(ct); +/// +/// +public sealed class TitanoDatabase : TitanoRepositories, IAsyncDisposable +{ + private TitanoDatabase(IDatabase database, int schemaVersion) + : base(new DbAccess(database)) + { + Database = database; + SchemaVersion = schemaVersion; + } + + /// The underlying engine, for raw sessions and engine-specific features (backups, LISTEN). + public IDatabase Database { get; } + + public Dialect Dialect => Database.Dialect; + + /// Schema version after migration. + public int SchemaVersion { get; private set; } + + /// + /// Opens the database and applies pending migrations. Throws when a newer + /// build already migrated it. + /// + public static async Task OpenAsync(DatabaseOptions options, CancellationToken cancellationToken = default) + { + var database = DatabaseFactory.Open(options); + try + { + var version = await MigrationRunner.MigrateAsync(database, cancellationToken).ConfigureAwait(false); + return new TitanoDatabase(database, version); + } + catch + { + await database.DisposeAsync().ConfigureAwait(false); + throw; + } + } + + /// Starts a transaction whose repositories all run on it; dispose without committing to roll back. + public async Task BeginAsync(CancellationToken cancellationToken = default) + { + var session = await Database.OpenAsync(cancellationToken).ConfigureAwait(false); + try + { + return new TitanoTransaction(session, await session.BeginAsync(cancellationToken).ConfigureAwait(false)); + } + catch + { + await session.DisposeAsync().ConfigureAwait(false); + throw; + } + } + + /// SQLite only: writes a VACUUM INTO copy into , keeping the newest . + public Task BackupAsync(string directory, int keep = 3, CancellationToken cancellationToken = default) => + AsSqlite().BackupAsync(directory, keep, cancellationToken); + + /// SQLite only: replaces the database with a backup, then migrates it to this build's schema. + public async Task RestoreAsync(string backupPath, CancellationToken cancellationToken = default) + { + await AsSqlite().RestoreAsync(backupPath, cancellationToken).ConfigureAwait(false); + SchemaVersion = await MigrationRunner.MigrateAsync(Database, cancellationToken).ConfigureAwait(false); + } + + public ValueTask DisposeAsync() => Database.DisposeAsync(); + + private SqliteDatabase AsSqlite() => + Database as SqliteDatabase ?? throw new NotSupportedException("Backups of a PostgreSQL database are made with the server's own tools."); +} + +/// Repositories bound to one open transaction. +public sealed class TitanoTransaction : TitanoRepositories, IAsyncDisposable +{ + private readonly IDbTransaction _transaction; + + internal TitanoTransaction(IDbSession session, IDbTransaction transaction) + : base(new DbAccess(session)) + { + Session = session; + _transaction = transaction; + } + + /// The session the transaction runs on, for statements of your own inside it. + public IDbSession Session { get; } + + public Task CommitAsync(CancellationToken cancellationToken = default) => _transaction.CommitAsync(cancellationToken); + + public Task RollbackAsync(CancellationToken cancellationToken = default) => _transaction.RollbackAsync(cancellationToken); + + /// Rolls back unless committed, and returns the session to the pool. + public async ValueTask DisposeAsync() + { + try + { + await _transaction.DisposeAsync().ConfigureAwait(false); + } + finally + { + await Session.DisposeAsync().ConfigureAwait(false); + } + } +} diff --git a/tests/Titano.Data.Tests/Core/ValueConversionTests.cs b/tests/Titano.Data.Tests/Core/ValueConversionTests.cs new file mode 100644 index 00000000..94f98d15 --- /dev/null +++ b/tests/Titano.Data.Tests/Core/ValueConversionTests.cs @@ -0,0 +1,90 @@ +using Titano.Testing; + +namespace Titano.Data.Tests.Core; + +/// Dialect-independent value handling: parameter normalisation, row conversions, text forms. +public sealed class ValueConversionTests +{ + private static DbRow Row(params object?[] values) => + new(new DbColumns(values.Select((_, i) => "c" + i).ToArray()), values); + + [Test] + public void ParametersKeepTheirTypeEvenWhenNull() + { + Assert.Equal(DbValueType.Uuid, ((DbParam)(Guid?)null).Type); + Assert.Equal(DbValueType.LocalDateTime, ((DbParam)(DateTime?)null).Type); + Assert.Equal(DbValueType.Auto, DbParam.Null.Type); + Assert.Equal(DbValueType.Int64, new DbParam(DayOfWeek.Friday).Type); + Assert.Equal(5L, new DbParam(DayOfWeek.Friday).Value); + Assert.Equal(DbValueType.Timestamp, ((DbParam)new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc)).Type); + Assert.Equal(DbValueType.LocalDateTime, ((DbParam)new DateTime(2020, 1, 1)).Type); + Assert.Equal(3, new DbParam((short)3).Value); + Assert.Throws(() => new DbParam(new object())); + } + + [Test] + public void RowGettersConvertBetweenProviderForms() + { + var guid = Guid.CreateVersion7(); + var row = Row(42L, "0190a8b4-5c4e-7a1b-9c3d-0123456789ab", "2026-09-28T16:30:15.123456Z", "2024-02-29T23:59:58.500000", 1L, 3.0, guid, null); + Assert.Equal(42, row.GetInt32(0)); + Assert.Equal(Guid.Parse("0190a8b4-5c4e-7a1b-9c3d-0123456789ab"), row.GetGuid(1)); + Assert.Equal(new DateTimeOffset(2026, 9, 28, 16, 30, 15, 123, TimeSpan.Zero).AddTicks(4560), row.GetDateTimeOffset(2)); + Assert.Equal(new DateTime(2024, 2, 29, 23, 59, 58, 500), row.GetDateTime(3)); + Assert.True(row.GetBool(4)); + Assert.Equal(3L, row.GetInt64(5)); + Assert.Equal(guid.ToString(), row.GetString(6)); + Assert.Null(row.GetInt32OrNull(7)); + Assert.Equal(DayOfWeek.Wednesday, row.Get(5)); + Assert.Equal(42, row.Get(0)); + Assert.Null(row.Get(7)); + Assert.Equal(1, row.GetOrdinal("C1")); + Assert.Throws(() => row.GetGuid(0)); + Assert.Throws(() => Row(long.MaxValue).GetInt32(0)); + Assert.Throws(() => row.GetOrdinal("missing")); + } + + [Theory] + [Case("2026-09-28 18:30:15.5+02", "2026-09-28T16:30:15.5000000+00:00")] + [Case("2026-09-28 18:30:15+05:30", "2026-09-28T13:00:15.0000000+00:00")] + [Case("2026-09-28T18:30:15.1234567Z", "2026-09-28T18:30:15.1234567+00:00")] + [Case("2026-09-28T18:30:15.12345678Z", "2026-09-28T18:30:15.1234567+00:00")] + [Case("2026-09-28 18:30", "2026-09-28T18:30:00.0000000+00:00")] + [Case("2026-09-28", "2026-09-28T00:00:00.0000000+00:00")] + [Case("1999-12-31 23:00:00-01", "2000-01-01T00:00:00.0000000+00:00")] + public void ParsesTimestampTextForms(string text, string expected) => + Assert.Equal(expected, TextValues.ParseTimestamp(text).ToString("O")); + + [Theory] + [Case("2026-02-30")] + [Case("2026-09-28 25:00:00")] + [Case("26-09-28")] + [Case("2026-09-28T10:00:00.Z")] + [Case("2026-09-28T10:00:00+1")] + public void RejectsMalformedTimestamps(string text) => + Assert.Throws(() => TextValues.ParseTimestamp(text)); + + [Test] + public void StoredTextFormsSortChronologically() + { + var a = new DateTimeOffset(2026, 1, 1, 9, 0, 0, TimeSpan.Zero); + var values = new[] { a, a.AddTicks(10), a.AddSeconds(1), a.AddYears(-1), a.AddMilliseconds(999) }; + var sorted = values.Select(TextValues.FormatTimestamp).OrderBy(s => s, StringComparer.Ordinal).ToList(); + Assert.SequenceEqual(values.OrderBy(v => v).Select(TextValues.FormatTimestamp), sorted); + Assert.Equal("2026-01-01T09:00:00.000001Z", TextValues.FormatTimestamp(a.AddTicks(10))); + } + + [Test] + public void BuildsUpsertsAndPatterns() + { + Assert.Equal( + "INSERT INTO t (a, b, c) VALUES ($1, $2, $3) ON CONFLICT (a) DO UPDATE SET b = excluded.b, c = excluded.c", + SqlDialect.Upsert("t", ["a", "b", "c"], 1)); + Assert.Equal("INSERT INTO t (a, b) VALUES ($1, $2) ON CONFLICT (a, b) DO NOTHING", SqlDialect.Upsert("t", ["a", "b"], 2)); + Assert.Equal( + "INSERT INTO t (a, b, c) VALUES ($1, $2, $3) ON CONFLICT (a) DO UPDATE SET c = excluded.c", + SqlDialect.Upsert("t", ["a", "b", "c"], 1, ["b"])); + Assert.Equal("%50\\%\\_off\\\\%", SqlDialect.ContainsPattern("50%_off\\")); + Assert.Equal("\"we\"\"ird\"", SqlDialect.QuoteIdentifier("we\"ird")); + } +} diff --git a/tests/Titano.Data.Tests/Infrastructure/DatabaseTest.cs b/tests/Titano.Data.Tests/Infrastructure/DatabaseTest.cs new file mode 100644 index 00000000..cb2a015f --- /dev/null +++ b/tests/Titano.Data.Tests/Infrastructure/DatabaseTest.cs @@ -0,0 +1,104 @@ +using Titano.Data.Postgres; +using Titano.Testing; + +namespace Titano.Data.Tests.Infrastructure; + +/// Engine a dialect-parameterised test class runs against. +public enum Backend +{ + SqliteMemory, + SqliteFile, + Postgres, +} + +/// +/// The PostgreSQL server named by TITANO_TEST_PG. Every test gets its own schema (selected through +/// Search Path), so classes run in parallel without seeing each other's tables. +/// +internal static class PgTestServer +{ + public const string Variable = "TITANO_TEST_PG"; + + private static readonly Lazy Admin = new(() => + new PostgresDatabase(PostgresSettings.Parse(ConnectionString) with { MaxPoolSize = 4 })); + + public static string ConnectionString => + Environment.GetEnvironmentVariable(Variable) is { Length: > 0 } cs ? cs : throw new SkipException($"{Variable} not set"); + + /// A connection string for another role (MD5, cleartext, trust tests), or a skip when not configured. + public static string Optional(string variable) => + Environment.GetEnvironmentVariable(variable) is { Length: > 0 } cs ? cs : throw new SkipException($"{variable} not set"); + + public static async Task CreateSchemaAsync(CancellationToken cancellationToken) + { + var name = "titano_t_" + Guid.NewGuid().ToString("N")[..16]; + await using var session = await Admin.Value.OpenAsync(cancellationToken); + await session.ExecuteScriptAsync($"CREATE SCHEMA {name}", cancellationToken); + return name; + } + + public static async Task DropSchemaAsync(string name) + { + await using var session = await Admin.Value.OpenAsync(CancellationToken.None); + await session.ExecuteScriptAsync($"DROP SCHEMA IF EXISTS {name} CASCADE", CancellationToken.None); + } + + public static string With(string connectionString, string extra) => connectionString.TrimEnd(';', ' ') + ";" + extra; +} + +/// +/// Base of tests that run against a fresh database per test: an in-memory or temporary-file SQLite database, or +/// a private schema on the PostgreSQL test server. Everything opened through it is disposed after the test. +/// +public abstract class DatabaseTest(TestContext context) : IAsyncDisposable +{ + private readonly List _owned = []; + private readonly List _schemas = []; + + protected TestContext Context => context; + + protected CancellationToken Ct => context.Cancellation; + + protected abstract Backend Backend { get; } + + protected Dialect Dialect => Backend == Backend.Postgres ? Dialect.Postgres : Dialect.Sqlite; + + /// Picks the DDL/SQL variant of the current dialect. + protected string ForDialect(string sqlite, string postgres) => Dialect == Dialect.Postgres ? postgres : sqlite; + + /// Options for a new empty database; forces a SQLite file (pooled readers). + protected async Task NewOptionsAsync(bool multiConnection = false, string? extraPostgres = null) + { + switch (Backend) + { + case Backend.SqliteMemory when !multiConnection: + return DatabaseOptions.SqliteInMemory(); + case Backend.SqliteMemory or Backend.SqliteFile: + return DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory(), "titano.db")); + default: + var schema = await PgTestServer.CreateSchemaAsync(Ct); + _schemas.Add(schema); + var cs = PgTestServer.With(PgTestServer.ConnectionString, $"Search Path={schema};Maximum Pool Size=12"); + return DatabaseOptions.Postgres(extraPostgres is null ? cs : PgTestServer.With(cs, extraPostgres)); + } + } + + /// Opens a bare database (no migrations). + protected async Task OpenDatabaseAsync(bool multiConnection = false) + { + var database = DatabaseFactory.Open(await NewOptionsAsync(multiConnection)); + return Own(database); + } + + protected T Own(T disposable) where T : IAsyncDisposable + { + _owned.Add(disposable); + return disposable; + } + + public async ValueTask DisposeAsync() + { + for (var i = _owned.Count - 1; i >= 0; i--) await _owned[i].DisposeAsync(); + foreach (var schema in _schemas) await PgTestServer.DropSchemaAsync(schema); + } +} diff --git a/tests/Titano.Data.Tests/Infrastructure/TestData.cs b/tests/Titano.Data.Tests/Infrastructure/TestData.cs new file mode 100644 index 00000000..b0bc9814 --- /dev/null +++ b/tests/Titano.Data.Tests/Infrastructure/TestData.cs @@ -0,0 +1,80 @@ +using Titano.Core.Imaging; +using Titano.Core.Model; +using Titano.Testing; + +namespace Titano.Data.Tests.Infrastructure; + +/// Base of repository tests: a migrated per test. +public abstract class RepositoryTest(TestContext context) : DatabaseTest(context) +{ + /// Opens a fresh migrated database; forces a SQLite file. + protected async Task OpenTitanoAsync(bool multiConnection = false) => + Own(await TitanoDatabase.OpenAsync(await NewOptionsAsync(multiConnection), Ct)); +} + +/// Builders of valid entities with distinct ids; override fields with with. +internal static class TestData +{ + /// A fixed reference instant (microsecond precision, like the databases). + public static readonly DateTimeOffset Now = new(2026, 10, 2, 9, 0, 0, TimeSpan.Zero); + + public static Archive Archive(string name = "Main") => new() + { + Id = Guid.CreateVersion7(), + Name = name, + RootPath = "/archive/" + name, + Created = Now, + }; + + public static Sequence Sequence(Guid archiveId, DateTime? firstCapture = null, string? title = null, string camera = "EOS R5") => new() + { + Id = Guid.CreateVersion7(), + ArchiveId = archiveId, + Title = title, + Folder = $"2026/{Guid.NewGuid():N}", + CameraMake = "Canon", + CameraModel = camera, + FirstCapture = firstCapture, + LastCapture = firstCapture?.AddHours(1), + UpdatedAt = Now, + }; + + public static Frame Frame(Guid sequenceId, int index, DateTime? capturedAt = null) => new() + { + Id = Guid.CreateVersion7(), + SequenceId = sequenceId, + Index = index, + RelativePath = $"2026/seq/originals/IMG_{index:0000}.CR3", + FileName = $"IMG_{index:0000}.CR3", + Size = 25_000_000 + index, + Sha256 = Convert.ToHexStringLower(BitConverter.GetBytes((long)index)).PadLeft(64, '0'), + CapturedAt = capturedAt ?? new DateTime(2026, 9, 28, 18, 0, 0).AddSeconds(5 * index), + TimestampSource = TimestampSource.ExifOriginal, + ExposureTime = 1 / 250.0, + FNumber = 8, + Iso = 100, + FocalLength = 24, + Width = 8192, + Height = 5464, + Format = ImageFileFormat.Cr3, + }; + + public static Job Job(JobKind kind = JobKind.Scan, JobPriority priority = JobPriority.Normal, DateTimeOffset? created = null) => new() + { + Id = Guid.CreateVersion7(), + Kind = kind, + Priority = priority, + State = JobState.Queued, + Created = created ?? Now, + }; + + public static User User(string username = "alice") => new() + { + Id = Guid.CreateVersion7(), + Username = username, + PasswordHash = "pbkdf2-sha512$210000$salt$hash", + Role = UserRole.Editor, + Permissions = RolePermissions.Default(UserRole.Editor), + Created = Now, + }; +} diff --git a/tests/Titano.Data.Tests/Migrations/MigrationTests.cs b/tests/Titano.Data.Tests/Migrations/MigrationTests.cs new file mode 100644 index 00000000..755f9c20 --- /dev/null +++ b/tests/Titano.Data.Tests/Migrations/MigrationTests.cs @@ -0,0 +1,95 @@ +using Titano.Data.Migrations; +using Titano.Data.Tests.Infrastructure; +using Titano.Testing; + +namespace Titano.Data.Tests.Migrations; + +public abstract class MigrationTests(TestContext context) : RepositoryTest(context) +{ + private static readonly string[] Tables = + [ + "archives", "sequences", "frames", "renders", "jobs", "media_cards", "import_history", "users", "tokens", + "render_nodes", "settings", "tags", "sequence_tags", "audit_log", "uploads", + ]; + + [Test] + public void EmbeddedScriptsAreFoundForBothDialects() + { + foreach (var dialect in new[] { Dialect.Sqlite, Dialect.Postgres }) + { + var migrations = MigrationRunner.Load(dialect); + Assert.NotEmpty(migrations); + Assert.Equal(1, migrations[0].Version); + Assert.Equal("initial", migrations[0].Name); + Assert.Contains("CREATE TABLE frames", migrations[0].Sql); + } + } + + [Test] + public async Task CreatesEveryTableAndIsIdempotent() + { + var titano = await OpenTitanoAsync(); + var latest = MigrationRunner.Load(Dialect)[^1].Version; + Assert.Equal(latest, titano.SchemaVersion); + Assert.Equal(latest, await MigrationRunner.MigrateAsync(titano.Database, Ct)); + + await using var session = await titano.Database.OpenAsync(Ct); + foreach (var table in Tables) Assert.Equal(0L, await session.ScalarAsync($"SELECT count(*) FROM {table}", [], Ct)); + var recorded = await session.QueryListAsync("SELECT version, name, applied_at FROM schema_migrations ORDER BY version", [], r => r, Ct); + Assert.Equal(MigrationRunner.Load(Dialect).Count, recorded.Count); + Assert.Equal("initial", recorded[0].GetString(1)); + Assert.True(recorded[0].GetDateTimeOffset(2) > DateTimeOffset.UtcNow.AddMinutes(-5)); + } + + [Test] + public async Task AppliesOnlyPendingMigrations() + { + var titano = await OpenTitanoAsync(); + var next = MigrationRunner.Load(Dialect).Append(new Migration(9000, "extra", "CREATE TABLE extra (id integer PRIMARY KEY)")).ToList(); + Assert.Equal(9000, await MigrationRunner.MigrateAsync(titano.Database, next, Ct)); + Assert.Equal(9000, await MigrationRunner.MigrateAsync(titano.Database, next, Ct)); + await using var session = await titano.Database.OpenAsync(Ct); + Assert.Equal(1L, await session.ScalarAsync("SELECT count(*) FROM schema_migrations WHERE version = $1", [9000], Ct)); + Assert.Equal(0L, await session.ScalarAsync("SELECT count(*) FROM extra", [], Ct)); + } + + [Test] + public async Task RefusesADatabaseFromANewerBuild() + { + var titano = await OpenTitanoAsync(); + await using (var session = await titano.Database.OpenAsync(Ct)) + await session.ExecuteAsync("INSERT INTO schema_migrations (version, name, applied_at) VALUES ($1, $2, $3)", [9999, "future", DateTimeOffset.UtcNow], Ct); + var error = await Assert.ThrowsAsync(() => MigrationRunner.MigrateAsync(titano.Database, Ct)); + Assert.Equal(9999, error.DatabaseVersion); + Assert.Equal(MigrationRunner.Load(Dialect)[^1].Version, error.SupportedVersion); + } + + [Test] + public async Task AFailingMigrationLeavesNothingBehind() + { + var database = await OpenDatabaseAsync(); + List broken = + [ + new(1, "good", "CREATE TABLE good_one (id integer PRIMARY KEY)"), + new(2, "bad", "CREATE TABLE good_two (id integer PRIMARY KEY); THIS IS NOT SQL"), + ]; + await Assert.ThrowsAsync(() => MigrationRunner.MigrateAsync(database, broken, Ct)); + await using var session = await database.OpenAsync(Ct); + var leftovers = await session.ScalarAsync(ForDialect( + "SELECT count(*) FROM sqlite_master WHERE name IN ('good_one', 'good_two', 'schema_migrations')", + "SELECT count(*) FROM information_schema.tables WHERE table_schema = current_schema() AND table_name IN ('good_one', 'good_two', 'schema_migrations')"), + [], Ct); + Assert.Equal(0L, leftovers); + } +} + +public sealed class SqliteMigrationTests(TestContext context) : MigrationTests(context) +{ + protected override Backend Backend => Backend.SqliteMemory; +} + +[RequiresEnvironment(PgTestServer.Variable)] +public sealed class PostgresMigrationTests(TestContext context) : MigrationTests(context) +{ + protected override Backend Backend => Backend.Postgres; +} diff --git a/tests/Titano.Data.Tests/Postgres/PgProtocolUnitTests.cs b/tests/Titano.Data.Tests/Postgres/PgProtocolUnitTests.cs new file mode 100644 index 00000000..1f037797 --- /dev/null +++ b/tests/Titano.Data.Tests/Postgres/PgProtocolUnitTests.cs @@ -0,0 +1,112 @@ +using System.Buffers; +using System.Text; +using Titano.Data.Postgres; +using Titano.Testing; + +namespace Titano.Data.Tests.Postgres; + +/// Protocol pieces that need no server. +public sealed class PgProtocolUnitTests +{ + [Test] + public void ScramMatchesTheRfc7677Example() + { + var scram = new ScramSha256("pencil", "user", "rOprNGfwEbeRWgbNEkqO"); + Assert.Equal("n,,n=user,r=rOprNGfwEbeRWgbNEkqO", Encoding.UTF8.GetString(scram.ClientFirstMessage())); + var final = scram.ClientFinalMessage(Encoding.UTF8.GetBytes( + "r=rOprNGfwEbeRWgbNEkqO%hvYDpWUa2RaTCAfuxFIlj)hNlF$k0,s=W22ZaJ0SNY7soEsUEjb6gQ==,i=4096")); + Assert.Equal( + "c=biws,r=rOprNGfwEbeRWgbNEkqO%hvYDpWUa2RaTCAfuxFIlj)hNlF$k0,p=dHzbZapWIk4jUhN+Ute9ytag9zjfMHgsqmmiz7AndVQ=", + Encoding.UTF8.GetString(final)); + Assert.False(scram.IsServerVerified); + Assert.Throws(() => scram.VerifyServerFinal("v=AAAA"u8)); + Assert.False(scram.IsServerVerified); + scram.VerifyServerFinal("v=6rriTRBi23WpRR/wtup+mMhUZUn/dB5nLTJRsjl95G4="u8); + Assert.True(scram.IsServerVerified); + } + + [Test] + public void ScramRejectsANonceTheClientDidNotStart() + { + var scram = new ScramSha256("pencil", "user", "abc"); + scram.ClientFirstMessage(); + Assert.Throws( + () => scram.ClientFinalMessage("r=xyz123,s=W22ZaJ0SNY7soEsUEjb6gQ==,i=4096"u8)); + } + + [Theory] + [Case("plain-ascii", "plain-ascii")] + [Case("I\u00ADX", "IX")] + [Case("a\u00A0b", "a b")] + [Case("\u2168", "IX")] + [Case("\u00AA", "a")] + [Case("bell\u0007", "bell\u0007")] + [Case("x\u00ADy\u0007", "x\u00ADy\u0007")] + public void SaslPrepMapsNormalisesAndFallsBack(string input, string expected) => + Assert.Equal(expected, ScramSha256.SaslPrep(input)); + + [Test] + public void Md5ResponseMatchesPostgresFormula() => + Assert.Equal("md534d7feefdad153ddeacb423a9893b99e", PgMd5.Response("titano_md5", "md5-pw", [1, 2, 3, 4])); + + [Test] + public void CopyTextEscapesSpecialsAndEncodesValues() + { + var buffer = new ArrayBufferWriter(); + foreach (var value in new object?[] { "a\tb\nc\rd\\e ✓", null, new byte[] { 0, 0xAB }, true, 42L, Guid.Empty, new DateTime(2020, 1, 2, 3, 4, 5), 2.5f }) + { + PgTypes.WriteCopyValue(value, buffer); + buffer.Write("|"u8); + } + Assert.Equal( + "a\\tb\\nc\\rd\\\\e ✓|\\N|\\\\x00ab|t|42|00000000-0000-0000-0000-000000000000|2020-01-02T03:04:05.000000|2.5|", + Encoding.UTF8.GetString(buffer.WrittenSpan)); + } + + [Test] + public void DecodesHexByteaAndRejectsOtherForms() + { + 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] + [Case("SELECT 1", true)] + [Case(" -- comment\n /* block */ select * from t", true)] + [Case("VALUES (1)", true)] + [Case("SHOW TimeZone", true)] + [Case("SELECTED", false)] + [Case("UPDATE t SET a = 1", false)] + [Case("WITH x AS (DELETE FROM t RETURNING *) SELECT * FROM x", false)] + public void RecognisesRepeatableReads(string sql, bool expected) => + Assert.Equal(expected, PostgresSession.IsReadOnlyQuery(sql)); + + [Test] + public void ParsesConnectionStrings() + { + var s = PostgresSettings.Parse("Host=db.local; Port=6543; Username=me; Password='p;w''d'; SslMode=verify-full; Maximum Pool Size=7; Search Path=s1"); + Assert.Equal("db.local", s.Host); + Assert.Equal(6543, s.Port); + Assert.Equal("me", s.Database); + Assert.Equal("p;w'd", s.Password); + Assert.Equal(SslMode.VerifyFull, s.SslMode); + Assert.Equal(7, s.MaxPoolSize); + Assert.Equal("s1", s.SearchPath); + Assert.Equal("titano-server", s.ApplicationName); + Assert.Throws(() => PostgresSettings.Parse("Host=x;Username=u;SslMode=allowish")); + Assert.Throws(() => PostgresSettings.Parse("Host=x;Username=u;Pasword=typo")); + Assert.Throws(() => PostgresSettings.Parse("Host=x;Username=u;Minimum Pool Size=5;Maximum Pool Size=2")); + } + + [Test] + public void InfersTheDialectFromTheConnectionString() + { + Assert.Equal(Dialect.Postgres, DatabaseOptions.Parse("Server=x;User Id=u").Dialect); + Assert.Equal(Dialect.Sqlite, DatabaseOptions.Parse("Data Source=/tmp/a.db").Dialect); + Assert.Equal(Dialect.Sqlite, DatabaseOptions.Parse(@"C:\Users\me\titano.db").Dialect); + Assert.Throws(() => DatabaseOptions.Parse("Foo=bar")); + } +} diff --git a/tests/Titano.Data.Tests/Postgres/PgWireTests.cs b/tests/Titano.Data.Tests/Postgres/PgWireTests.cs new file mode 100644 index 00000000..132c549b --- /dev/null +++ b/tests/Titano.Data.Tests/Postgres/PgWireTests.cs @@ -0,0 +1,301 @@ +using System.Diagnostics; +using System.Security.Authentication; +using Titano.Data.Postgres; +using Titano.Data.Tests.Infrastructure; +using Titano.Testing; + +namespace Titano.Data.Tests.Postgres; + +/// Protocol-level tests against a live server (TITANO_TEST_PG; optional TITANO_TEST_PG_MD5/_CLEARTEXT/_TRUST). +[RequiresEnvironment(PgTestServer.Variable)] +public sealed class PgWireTests(TestContext context) : DatabaseTest(context) +{ + protected override Backend Backend => Backend.Postgres; + + private async Task OpenAsync(string? extra = null) => + (PostgresDatabase)Own(DatabaseFactory.Open(await NewOptionsAsync(extraPostgres: extra))); + + private async Task AuthenticateAsync(string connectionString) + { + var database = Own(new PostgresDatabase(PostgresSettings.Parse(connectionString))); + await using var session = await database.OpenAsync(Ct); + return (await session.ScalarAsync("SELECT current_user", [], Ct))!; + } + + [Test] + public async Task ScramSha256Login() + { + var settings = PostgresSettings.Parse(PgTestServer.ConnectionString); + Assert.Equal(settings.Username, await AuthenticateAsync(PgTestServer.ConnectionString)); + } + + [Test] + public async Task Md5Login() => + Assert.NotNull(await AuthenticateAsync(PgTestServer.Optional("TITANO_TEST_PG_MD5"))); + + [Test] + public async Task CleartextLogin() => + Assert.NotNull(await AuthenticateAsync(PgTestServer.Optional("TITANO_TEST_PG_CLEARTEXT"))); + + [Test] + public async Task TrustLogin() => + Assert.NotNull(await AuthenticateAsync(PgTestServer.Optional("TITANO_TEST_PG_TRUST"))); + + [Test] + public async Task WrongPasswordIsRejected() + { + var wrong = PgTestServer.With(PgTestServer.ConnectionString, "Password=definitely-wrong"); + var error = await Assert.ThrowsAsync(() => AuthenticateAsync(wrong)); + Assert.Equal("28P01", error.SqlState); + Assert.Equal("FATAL", error.Severity); + } + + [Test] + public async Task TlsIsNegotiatedWhenRequired() + { + PostgresDatabase database; + try + { + database = await OpenAsync("SslMode=Require"); + await using var probe = await database.OpenAsync(Ct); + } + catch (DatabaseConnectionException ex) when (ex.Message.Contains("does not support TLS", StringComparison.Ordinal)) + { + TestContext.Skip("server has no TLS"); + return; + } + await using var session = await database.OpenAsync(Ct); + Assert.True(await session.ScalarAsync("SELECT ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid()", [], Ct)); + + var plain = await OpenAsync("SslMode=Disable"); + await using var plainSession = await plain.OpenAsync(Ct); + Assert.False(await plainSession.ScalarAsync("SELECT ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid()", [], Ct)); + } + + [Test] + public async Task VerifyFullRejectsAnUntrustedCertificate() + { + var database = await OpenAsync("SslMode=VerifyFull"); + try + { + await using var session = await database.OpenAsync(Ct); + Assert.Fail("A self-signed server certificate must not pass verify-full."); + } + catch (DatabaseConnectionException ex) when (ex.Message.Contains("does not support TLS", StringComparison.Ordinal)) + { + TestContext.Skip("server has no TLS"); + } + catch (AuthenticationException) + { + } + } + + [Test] + public async Task DecodesEveryMappedResultType() + { + await using var session = await (await OpenAsync()).OpenAsync(Ct); + var row = await session.QuerySingleAsync( + "SELECT 'txt'::text, 'vc'::varchar(5), 'bp'::bpchar(4), 7::int2, -8::int4, 9000000000::int8, 1.5::float4, " + + "-2.25::float8, 'Infinity'::float8, true, '\\x00ff10'::bytea, '2026-09-28 18:30:15.123456+02'::timestamptz, " + + "'2024-02-29 23:59:58.5'::timestamp, '2026-01-31'::date, '0190a8b4-5c4e-7a1b-9c3d-0123456789ab'::uuid, " + + "'{\"k\": 1}'::json, '{\"k\": [true]}'::jsonb, 12345678901234567890.123::numeric, NULL::int4", [], Ct); + Assert.Equal("txt", row.GetString(0)); + Assert.Equal("vc", row.GetString(1)); + Assert.Equal("bp ", row.GetString(2)); + Assert.Equal(7, row.GetInt32(3)); + Assert.Equal(-8, row.GetInt32(4)); + Assert.Equal(9000000000L, row.GetInt64(5)); + Assert.Equal(1.5, row.GetDouble(6)); + Assert.Equal(-2.25, row.GetDouble(7)); + Assert.Equal(double.PositiveInfinity, row.GetDouble(8)); + Assert.True(row.GetBool(9)); + Assert.BytesEqual(new byte[] { 0, 0xFF, 0x10 }, row.GetBytes(10)); + Assert.Equal(new DateTimeOffset(2026, 9, 28, 16, 30, 15, 123, TimeSpan.Zero).AddTicks(4560), row.GetDateTimeOffset(11)); + Assert.Equal(new DateTime(2024, 2, 29, 23, 59, 58, 500), row.GetDateTime(12)); + Assert.Equal(new DateTime(2026, 1, 31), row.GetDateTime(13)); + Assert.Equal(Guid.Parse("0190a8b4-5c4e-7a1b-9c3d-0123456789ab"), row.GetGuid(14)); + Assert.Equal("{\"k\": 1}", row.GetString(15)); + Assert.Equal("{\"k\": [true]}", row.GetString(16)); + Assert.Equal("12345678901234567890.123", row.GetString(17)); + Assert.True(row.IsNull(18)); + } + + [Test] + public async Task ByteaTravelsInBinary() + { + await using var session = await (await OpenAsync()).OpenAsync(Ct); + await session.ExecuteScriptAsync("CREATE TABLE blobs (id integer PRIMARY KEY, data bytea)", Ct); + var all = Enumerable.Range(0, 256).Select(i => (byte)i).ToArray(); + var large = new byte[1 << 20]; + new Random(7).NextBytes(large); + await session.ExecuteAsync("INSERT INTO blobs VALUES ($1, $2), ($3, $4), ($5, $6)", [1, all, 2, large, 3, Array.Empty()], Ct); + var readAll = await session.ScalarAsync("SELECT data FROM blobs WHERE id = 1", [], Ct); + var readLarge = await session.ScalarAsync("SELECT data FROM blobs WHERE id = 2", [], Ct); + Assert.BytesEqual(all, readAll); + Assert.BytesEqual(large, readLarge); + Assert.Equal(0, (await session.ScalarAsync("SELECT data FROM blobs WHERE id = 3", [], Ct))!.Length); + Assert.Equal(1L << 20, await session.ScalarAsync("SELECT length(data) FROM blobs WHERE id = $1", [2], Ct)); + } + + [Test] + public async Task ListenReceivesNotifications() + { + var database = await OpenAsync(); + var listener = Own(await database.CreateListenerAsync(Ct)); + var received = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + listener.Notification += (_, n) => received.TrySetResult(n); + await listener.ListenAsync("titano_jobs", Ct); + + await using (var session = await database.OpenAsync(Ct)) + await session.ExecuteAsync("SELECT pg_notify($1, $2)", ["titano_jobs", "wake ✓"], Ct); + + var notification = await received.Task.WaitAsync(TimeSpan.FromSeconds(5), Ct); + Assert.Equal("titano_jobs", notification.Channel); + Assert.Equal("wake ✓", notification.Payload); + await listener.UnlistenAsync("titano_jobs", Ct); + await Assert.ThrowsAsync(() => listener.ListenAsync("", Ct)); + await listener.ListenAsync("still_usable", Ct); + } + + [Test] + public async Task ServerErrorsMapToTypedExceptions() + { + await using var session = await (await OpenAsync()).OpenAsync(Ct); + await session.ExecuteScriptAsync("CREATE TABLE u (id integer PRIMARY KEY, code text CONSTRAINT u_code_key UNIQUE)", Ct); + await session.ExecuteAsync("INSERT INTO u VALUES ($1, $2)", [1, "a"], Ct); + var unique = await Assert.ThrowsAsync(() => session.ExecuteAsync("INSERT INTO u VALUES ($1, $2)", [2, "a"], Ct)); + Assert.Equal("23505", unique.SqlState); + Assert.Equal("ERROR", unique.Severity); + Assert.Equal("u_code_key", unique.ConstraintName); + Assert.Equal("u", unique.TableName); + Assert.NotNull(unique.Detail); + Assert.True(unique.IsUniqueViolation); + + var syntax = await Assert.ThrowsAsync(() => session.ExecuteAsync("SELECT * FROM u WHER id = 1", [], Ct)); + Assert.Equal("42601", syntax.SqlState); + Assert.Equal(22, syntax.Position); + Assert.Equal(1, await session.ScalarAsync("SELECT 1", [], Ct)); + } + + [Test] + public async Task CommitOfAnAbortedTransactionThrows() + { + await using var session = await (await OpenAsync()).OpenAsync(Ct); + await session.ExecuteScriptAsync("CREATE TABLE a (id integer PRIMARY KEY)", Ct); + var tx = await session.BeginAsync(Ct); + await session.ExecuteAsync("INSERT INTO a VALUES ($1)", [1], Ct); + await Assert.ThrowsAsync(() => session.ExecuteAsync("INSERT INTO a VALUES ($1)", [1], Ct)); + await Assert.ThrowsAsync(() => tx.CommitAsync(Ct)); + Assert.False(session.InTransaction); + Assert.Equal(0L, await session.ScalarAsync("SELECT count(*) FROM a", [], Ct)); + } + + [Test] + public async Task PoolReusesConnectionsAndHandsOutDistinctOnesConcurrently() + { + var database = await OpenAsync("Maximum Pool Size=3;Timeout=2"); + int first; + await using (var s = await database.OpenAsync(Ct)) first = await s.ScalarAsync("SELECT pg_backend_pid()", [], Ct); + await using (var s = await database.OpenAsync(Ct)) Assert.Equal(first, await s.ScalarAsync("SELECT pg_backend_pid()", [], Ct)); + + var sessions = new List(); + for (var i = 0; i < 3; i++) sessions.Add(await database.OpenAsync(Ct)); + var pids = new HashSet(); + foreach (var s in sessions) pids.Add(await s.ScalarAsync("SELECT pg_backend_pid()", [], Ct)); + Assert.Equal(3, pids.Count); + var watch = Stopwatch.StartNew(); + await Assert.ThrowsAsync(() => database.OpenAsync(Ct)); + Assert.InRange(watch.Elapsed.TotalSeconds, 1.5, 5); + foreach (var s in sessions) await s.DisposeAsync(); + } + + [Test] + public async Task ReadsRecoverFromATerminatedBackend() + { + var database = await OpenAsync("Maximum Pool Size=2"); + int victim; + await using (var s = await database.OpenAsync(Ct)) victim = await s.ScalarAsync("SELECT pg_backend_pid()", [], Ct); + + var killer = Own(new PostgresDatabase(PostgresSettings.Parse(PgTestServer.ConnectionString))); + await using (var k = await killer.OpenAsync(Ct)) + Assert.True(await k.ScalarAsync("SELECT pg_terminate_backend($1)", [victim], Ct)); + await Task.Delay(200, Ct); + + await using (var s = await database.OpenAsync(Ct)) + { + var pid = await s.ScalarAsync("SELECT pg_backend_pid()", [], Ct); + Assert.NotEqual(victim, pid); + Assert.Equal(2, await s.ScalarAsync("SELECT 1 + 1", [], Ct)); + } + } + + [Test] + public async Task WritesOnABrokenConnectionFailWithoutRetry() + { + var database = await OpenAsync("Maximum Pool Size=1"); + await using var session = await database.OpenAsync(Ct); + await session.ExecuteScriptAsync("CREATE TABLE w (id integer)", Ct); + var pid = await session.ScalarAsync("SELECT pg_backend_pid()", [], Ct); + var killer = Own(new PostgresDatabase(PostgresSettings.Parse(PgTestServer.ConnectionString))); + await using (var k = await killer.OpenAsync(Ct)) await k.ExecuteAsync("SELECT pg_terminate_backend($1)", [pid], Ct); + await Task.Delay(200, Ct); + var error = await Assert.ThrowsAsync(() => session.ExecuteAsync("INSERT INTO w VALUES ($1)", [1], Ct)); + Assert.True(error.IsTransient); + } + + [Test] + public async Task StatementCacheEvictsAndSurvivesSchemaChanges() + { + await using var session = await (await OpenAsync("Statement Cache Size=2")).OpenAsync(Ct); + await session.ExecuteScriptAsync("CREATE TABLE c (a integer); INSERT INTO c VALUES (1)", Ct); + for (var i = 0; i < 5; i++) Assert.Equal(i, await session.ScalarAsync($"SELECT {i} + 0 * $1", [i], Ct)); + // Evicted statements are closed with the next command: the cache size plus the counting statement remain. + Assert.LessOrEqual(await session.ScalarAsync("SELECT count(*) FROM pg_prepared_statements", [], Ct), 3); + + var first = await session.QuerySingleAsync("SELECT * FROM c", [], Ct); + Assert.Equal(1, first.FieldCount); + await session.ExecuteScriptAsync("ALTER TABLE c ADD COLUMN b text DEFAULT 'x'", Ct); + var second = await session.QuerySingleAsync("SELECT * FROM c", [], Ct); + Assert.Equal(2, second.FieldCount); + 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 DisposingABusySessionInATransactionFreesItsPoolSlot() + { + var database = await OpenAsync("Maximum Pool Size=1;Timeout=3"); + var session = await database.OpenAsync(Ct); + await session.ExecuteScriptAsync("CREATE TABLE t (id integer)", Ct); + var tx = await session.BeginAsync(Ct); + await session.ExecuteAsync("INSERT INTO t VALUES ($1)", [1], Ct); + var rows = session.QueryAsync("SELECT generate_series(1, 1000)", [], Ct).GetAsyncEnumerator(Ct); + Assert.True(await rows.MoveNextAsync()); + await tx.DisposeAsync(); + Assert.True(session.InTransaction, "a busy session cannot roll back yet"); + await session.DisposeAsync(); + + await using var next = await database.OpenAsync(Ct); + Assert.Equal(0L, await next.ScalarAsync("SELECT count(*) FROM t", [], Ct)); + } + + [Test] + public async Task NoticesAndScriptsDoNotDisturbTheSession() + { + await using var session = await (await OpenAsync()).OpenAsync(Ct); + await session.ExecuteScriptAsync("DO $$ BEGIN RAISE NOTICE 'hello from the server'; END $$; CREATE TABLE n (id integer)", Ct); + Assert.Equal(1, await session.ExecuteAsync("INSERT INTO n VALUES ($1)", [1], Ct)); + await Assert.ThrowsAsync(() => session.ExecuteScriptAsync("SELECT 1; SELECT * FROM missing_table; SELECT 2", Ct)); + Assert.Equal(1L, await session.ScalarAsync("SELECT count(*) FROM n", [], Ct)); + } +} diff --git a/tests/Titano.Data.Tests/Program.cs b/tests/Titano.Data.Tests/Program.cs index 92339124..ffd81b63 100644 --- a/tests/Titano.Data.Tests/Program.cs +++ b/tests/Titano.Data.Tests/Program.cs @@ -1,8 +1,14 @@ +using Titano.Core.Diagnostics; using Titano.Testing; namespace Titano.Data.Tests; internal static class TestMain { - public static Task Main(string[] args) => TestRunner.RunAsync(args, typeof(TestMain).Assembly); + public static Task Main(string[] args) + { + // Migrations and schema drops log at Info for every test database; keep the console for warnings. + Log.MinimumLevel = LogLevel.Warning; + return TestRunner.RunAsync(args, typeof(TestMain).Assembly); + } } diff --git a/tests/Titano.Data.Tests/Repositories/BulkInsertTests.cs b/tests/Titano.Data.Tests/Repositories/BulkInsertTests.cs new file mode 100644 index 00000000..879f4972 --- /dev/null +++ b/tests/Titano.Data.Tests/Repositories/BulkInsertTests.cs @@ -0,0 +1,42 @@ +using System.Diagnostics; +using Titano.Data.Tests.Infrastructure; +using Titano.Testing; + +namespace Titano.Data.Tests.Repositories; + +/// The 100k-frame import of the Phase 2 gate must stay well under 15 s. +public abstract class BulkInsertTests(TestContext context) : RepositoryTest(context) +{ + [Test] + [Timeout(60_000)] + public async Task HundredThousandFramesInsertQuickly() + { + var db = await OpenTitanoAsync(multiConnection: true); + var archive = TestData.Archive(); + await db.Archives.UpsertAsync(archive, Ct); + var sequence = TestData.Sequence(archive.Id); + await db.Sequences.UpsertAsync(sequence, Ct); + var frames = Enumerable.Range(0, 100_000).Select(i => TestData.Frame(sequence.Id, i)).ToList(); + + var watch = Stopwatch.StartNew(); + Assert.Equal(100_000L, await db.Frames.BulkInsertAsync(frames, Ct)); + watch.Stop(); + Context.Log($"{Dialect}: 100k frames in {watch.Elapsed.TotalSeconds:F2} s"); + Assert.Less(watch.Elapsed.TotalSeconds, 15.0, "bulk insert time"); + + var refreshed = await db.Sequences.RefreshStatsAsync(sequence.Id, Ct); + Assert.Equal(100_000, refreshed!.FrameCount); + Assert.Equal(frames[^1], (await db.Frames.ListBySequenceAsync(sequence.Id, afterIndex: 99_998, cancellationToken: Ct)).Single()); + } +} + +public sealed class SqliteBulkInsertTests(TestContext context) : BulkInsertTests(context) +{ + protected override Backend Backend => Backend.SqliteFile; +} + +[RequiresEnvironment(PgTestServer.Variable)] +public sealed class PostgresBulkInsertTests(TestContext context) : BulkInsertTests(context) +{ + protected override Backend Backend => Backend.Postgres; +} diff --git a/tests/Titano.Data.Tests/Repositories/CatalogRepositoryTests.cs b/tests/Titano.Data.Tests/Repositories/CatalogRepositoryTests.cs new file mode 100644 index 00000000..62270019 --- /dev/null +++ b/tests/Titano.Data.Tests/Repositories/CatalogRepositoryTests.cs @@ -0,0 +1,415 @@ +using System.Text.Json.Nodes; +using Titano.Core.Imaging; +using Titano.Core.Model; +using Titano.Data.Repositories; +using Titano.Data.Tests.Infrastructure; +using Titano.Testing; + +namespace Titano.Data.Tests.Repositories; + +/// Archives, sequences, frames, renders and tags on both dialects. +public abstract class CatalogRepositoryTests(TestContext context) : RepositoryTest(context) +{ + [Test] + public async Task ArchivesRoundTripAndDelete() + { + var db = await OpenTitanoAsync(); + var archive = TestData.Archive() with { ProxyLongEdge = -1, FolderTemplate = "{year}/{title}" }; + await db.Archives.UpsertAsync(archive, Ct); + await db.Archives.UpsertAsync(archive with { Name = "Renamed" }, Ct); + Assert.Equal(archive with { Name = "Renamed" }, await db.Archives.GetAsync(archive.Id, Ct)); + Assert.Count(1, await db.Archives.ListAsync(Ct)); + Assert.True(await db.Archives.DeleteAsync(archive.Id, Ct)); + Assert.Null(await db.Archives.GetAsync(archive.Id, Ct)); + Assert.False(await db.Archives.DeleteAsync(archive.Id, Ct)); + } + + [Test] + public async Task SequencesRoundTripEveryField() + { + var db = await OpenTitanoAsync(); + var archive = TestData.Archive(); + await db.Archives.UpsertAsync(archive, Ct); + var sequence = TestData.Sequence(archive.Id, new DateTime(2026, 9, 28, 18, 30, 15, 250), "Harbour sunset") with + { + CameraSerial = "0123", + Lens = "RF 24-70", + FrameCount = 1200, + MedianInterval = 5.0, + TotalBytes = 30_000_000_000, + Status = SequenceStatus.AnalyzedLight | SequenceStatus.ThumbsBuilt, + RenderedCount = 0, + VerifiedAt = TestData.Now, + HeroFrameId = Guid.CreateVersion7(), + Rating = 4, + Notes = "windy", + SettingsJson = "{\"fps\": 25, \"deflicker\": true}", + AnalysisJson = "{\"ev\": [12.5, 13]}", + Origin = SequenceOrigin.Server, + SyncState = SyncState.LocalAhead, + SettingsVersion = 3, + FramesVersion = 7, + OwnerUserId = Guid.CreateVersion7(), + WarningCount = 2, + Tags = ["Sunset", "harbour", "SUNSET"], + }; + await db.Sequences.UpsertAsync(sequence, Ct); + + var read = Assert.NotNull(await db.Sequences.GetAsync(sequence.Id, Ct)); + Assert.True(JsonNode.DeepEquals(JsonNode.Parse(sequence.SettingsJson!), JsonNode.Parse(read.SettingsJson!))); + Assert.True(JsonNode.DeepEquals(JsonNode.Parse(sequence.AnalysisJson!), JsonNode.Parse(read.AnalysisJson!))); + Assert.SequenceEqual(["harbour", "Sunset"], read.Tags); + Assert.Equal(sequence with { Tags = read.Tags, SettingsJson = read.SettingsJson, AnalysisJson = read.AnalysisJson }, read); + + await db.Sequences.UpsertAsync(sequence with { Title = null, Tags = ["night"], Rating = 1 }, Ct); + read = Assert.NotNull(await db.Sequences.GetAsync(sequence.Id, Ct)); + Assert.Null(read.Title); + Assert.Equal("2026-09-28 EOS R5", read.DisplayTitle); + Assert.SequenceEqual(["night"], read.Tags); + Assert.Equal(1, read.Rating); + } + + [Test] + public async Task DeletingASequenceRemovesItsFramesRendersAndTagLinks() + { + var db = await OpenTitanoAsync(); + var archive = TestData.Archive(); + await db.Archives.UpsertAsync(archive, Ct); + var sequence = TestData.Sequence(archive.Id) with { Tags = ["a"] }; + await db.Sequences.UpsertAsync(sequence, Ct); + await db.Frames.BulkInsertAsync(Enumerable.Range(0, 10).Select(i => TestData.Frame(sequence.Id, i)), Ct); + await db.Renders.InsertAsync(Render(sequence.Id), Ct); + + Assert.True(await db.Sequences.DeleteAsync(sequence.Id, Ct)); + Assert.Empty(await db.Frames.ListBySequenceAsync(sequence.Id, cancellationToken: Ct)); + Assert.Empty(await db.Renders.ListBySequenceAsync(sequence.Id, Ct)); + Assert.Equal(0, (await db.Tags.ListAsync(Ct)).Single().SequenceCount); + Assert.Equal(1, await db.Tags.DeleteUnusedAsync(Ct)); + } + + [Test] + public async Task ListingFiltersCombine() + { + var db = await OpenTitanoAsync(); + var main = TestData.Archive(); + var other = TestData.Archive("Other"); + await db.Archives.UpsertAsync(main, Ct); + await db.Archives.UpsertAsync(other, Ct); + var owner = Guid.CreateVersion7(); + var harbour = TestData.Sequence(main.Id, new DateTime(2024, 6, 1), "Porto di CITTÀ vecchia") with { Status = SequenceStatus.AnalyzedLight, Tags = ["sea"] }; + var stars = TestData.Sequence(main.Id, new DateTime(2025, 1, 2), "Milky way", "Z8") with { CameraMake = "Nikon", Tags = ["Night Sky"], OwnerUserId = owner }; + var clouds = TestData.Sequence(main.Id, new DateTime(2024, 12, 31, 23, 59, 59), "50%_clouds") with { Status = SequenceStatus.AnalyzedLight | SequenceStatus.Verified }; + var elsewhere = TestData.Sequence(other.Id, new DateTime(2024, 3, 3), "Elsewhere"); + var undated = TestData.Sequence(main.Id, null, "Undated"); + foreach (var s in new[] { harbour, stars, clouds, elsewhere, undated }) await db.Sequences.UpsertAsync(s, Ct); + + async Task Titles(SequenceQuery q) => + [.. (await db.Sequences.ListAsync(q with { Sort = SequenceSort.Title }, Ct)).Items.Select(s => s.Title!)]; + + Assert.SequenceEqual(["50%_clouds", "Porto di CITTÀ vecchia"], await Titles(new() { ArchiveId = main.Id, Year = 2024 })); + Assert.SequenceEqual(["Milky way"], await Titles(new() { Camera = "Z8" })); + Assert.SequenceEqual(["50%_clouds", "Porto di CITTÀ vecchia"], await Titles(new() { WithStatus = SequenceStatus.AnalyzedLight })); + Assert.SequenceEqual(["Porto di CITTÀ vecchia"], await Titles(new() { WithStatus = SequenceStatus.AnalyzedLight, WithoutStatus = SequenceStatus.Verified })); + Assert.SequenceEqual(["Milky way"], await Titles(new() { Tag = " night SKY " })); + Assert.SequenceEqual(["Porto di CITTÀ vecchia"], await Titles(new() { Text = "città" })); + Assert.SequenceEqual(["Milky way"], await Titles(new() { Text = "NIKON" })); + Assert.SequenceEqual(["Milky way"], await Titles(new() { Text = "ght sk" })); + Assert.SequenceEqual(["50%_clouds"], await Titles(new() { Text = "50%_" })); + Assert.Empty(await Titles(new() { Text = "5_%" })); + Assert.SequenceEqual(["Milky way"], await Titles(new() { OwnerUserId = owner })); + Assert.Equal(4, await db.Sequences.CountAsync(new() { ArchiveId = main.Id }, Ct)); + Assert.Equal(2, await db.Sequences.CountAsync(new() { ArchiveId = main.Id, Year = 2024 }, Ct)); + Assert.Equal(5, await db.Sequences.CountAsync(new(), Ct)); + } + + [Theory] + [Case(SequenceSort.Newest)] + [Case(SequenceSort.Oldest)] + [Case(SequenceSort.Title)] + [Case(SequenceSort.FrameCount)] + [Case(SequenceSort.Size)] + public async Task KeysetPagesVisitEveryRowOnceInOrderDespiteTies(SequenceSort sort) + { + var db = await OpenTitanoAsync(); + var archive = TestData.Archive(); + await db.Archives.UpsertAsync(archive, Ct); + var all = Enumerable.Range(0, 23).Select(i => TestData.Sequence(archive.Id, + i % 5 == 4 ? null : new DateTime(2024 + i % 3, 1, 1, 12, 0, 0), + i % 4 == 0 ? null : "T" + (i % 6)) with + { FrameCount = i % 3, TotalBytes = i % 4 * 1000L }) + .ToList(); + foreach (var s in all) await db.Sequences.UpsertAsync(s, Ct); + + var expected = Expected(all, sort).Select(s => s.Id).ToList(); + var seen = new List(); + string? cursor = null; + var pages = 0; + do + { + var page = await db.Sequences.ListAsync(new SequenceQuery { ArchiveId = archive.Id, Sort = sort, Limit = 4, Cursor = cursor }, Ct); + Assert.True(page.Items.Count is > 0 and <= 4); + seen.AddRange(page.Items.Select(s => s.Id)); + cursor = page.NextCursor; + pages++; + } + while (cursor is not null); + + Assert.Equal(6, pages); + Assert.SequenceEqual(expected, seen); + } + + [Test] + public async Task CursorsOnlyWorkForTheirOwnSort() + { + var db = await OpenTitanoAsync(); + var archive = TestData.Archive(); + await db.Archives.UpsertAsync(archive, Ct); + for (var i = 0; i < 3; i++) await db.Sequences.UpsertAsync(TestData.Sequence(archive.Id, new DateTime(2024, 1, 1 + i)), Ct); + var page = await db.Sequences.ListAsync(new SequenceQuery { Limit = 1 }, Ct); + Assert.NotNull(page.NextCursor); + await Assert.ThrowsAsync(() => db.Sequences.ListAsync(new SequenceQuery { Sort = SequenceSort.Size, Cursor = page.NextCursor }, Ct)); + await Assert.ThrowsAsync(() => db.Sequences.ListAsync(new SequenceQuery { Cursor = "not-a-cursor" }, Ct)); + } + + [Test] + public async Task StatisticsAggregateTheArchive() + { + var db = await OpenTitanoAsync(); + var main = TestData.Archive(); + var other = TestData.Archive("Other"); + await db.Archives.UpsertAsync(main, Ct); + await db.Archives.UpsertAsync(other, Ct); + Sequence Seq(Guid archive, DateTime? first, string model, int frames, long bytes, SequenceStatus status) => + TestData.Sequence(archive, first, camera: model) with { FrameCount = frames, TotalBytes = bytes, Status = status }; + var a = Seq(main.Id, new DateTime(2024, 3, 10), "EOS R5", 10, 1000, SequenceStatus.AnalyzedLight) with { VerifiedAt = TestData.Now }; + var b = Seq(main.Id, new DateTime(2024, 3, 20), "Z8", 20, 2000, SequenceStatus.HasWarnings) with { CameraMake = "Nikon" }; + var c = Seq(main.Id, new DateTime(2025, 7, 1), "EOS R5", 30, 3000, SequenceStatus.HasErrors | SequenceStatus.AnalyzedLight); + var d = Seq(main.Id, null, "EOS R5", 0, 0, SequenceStatus.None) with { WarningCount = 1 }; + var e = Seq(other.Id, new DateTime(2023, 1, 1), "X-T5", 5, 500, SequenceStatus.None); + foreach (var s in new[] { a, b, c, d, e }) await db.Sequences.UpsertAsync(s, Ct); + await db.Frames.BulkInsertAsync( + [ + TestData.Frame(a.Id, 0) with { Flags = FrameFlags.Missing, Size = 100 }, + TestData.Frame(a.Id, 1) with { Format = ImageFileFormat.Jpeg, Size = 10, Flags = FrameFlags.Duplicate | FrameFlags.Corrupt }, + TestData.Frame(b.Id, 0) with { Size = 200 }, + TestData.Frame(e.Id, 0) with { Format = ImageFileFormat.Raf, Flags = FrameFlags.Missing }, + ], Ct); + + var stats = await db.Sequences.GetStatsAsync(main.Id, Ct); + Assert.Equal(4, stats.Sequences); + Assert.Equal(60L, stats.Photos); + Assert.Equal(6000L, stats.Bytes); + Assert.SequenceEqual([new YearBucket(2024, 2, 30, 3000), new YearBucket(2025, 1, 30, 3000)], stats.ByYear); + Assert.SequenceEqual([new MonthBucket(2024, 3, 2, 30), new MonthBucket(2025, 7, 1, 30)], stats.ByMonth); + Assert.SequenceEqual( + [new CameraBucket("Canon", "EOS R5", 3, 40, 4000), new CameraBucket("Nikon", "Z8", 1, 20, 2000)], + stats.ByCamera); + Assert.SequenceEqual([new FormatBucket(ImageFileFormat.Cr3, 2, 300), new FormatBucket(ImageFileFormat.Jpeg, 1, 10)], stats.ByFormat); + Assert.Equal(new ArchiveHealth(Unverified: 3, WithWarnings: 2, WithErrors: 1, NotAnalyzed: 2, MissingFrames: 1, CorruptFrames: 1, DuplicateFrames: 1), stats.Health); + + var everything = await db.Sequences.GetStatsAsync(cancellationToken: Ct); + Assert.Equal(5, everything.Sequences); + Assert.Equal(2L, everything.Health.MissingFrames); + Assert.Equal(2023, everything.ByYear[0].Year); + } + + [Test] + public async Task FramesBulkInsertPageAndFindDuplicates() + { + var db = await OpenTitanoAsync(); + var archive = TestData.Archive(); + await db.Archives.UpsertAsync(archive, Ct); + var sequence = TestData.Sequence(archive.Id); + await db.Sequences.UpsertAsync(sequence, Ct); + var frames = Enumerable.Range(0, 250).Select(i => TestData.Frame(sequence.Id, i)).ToList(); + frames[7] = frames[7] with + { + OriginalFileName = "DSC_7.NEF", + CapturedAt = new DateTime(2026, 9, 28, 18, 0, 35, 123), + UtcOffsetMinutes = 120, + ExposureBias = -0.3, + WhiteBalance = 5600, + Orientation = 6, + PreviewOffset = 1024, + PreviewLength = 65536, + MeanLogLuminance = -2.5, + ClipLow = 0.01, + ClipHigh = 0.02, + Flags = FrameFlags.Excluded, + Sha256 = "AB" + new string('c', 62), + }; + Assert.Equal(250L, await db.Frames.BulkInsertAsync(frames, Ct)); + var copy = TestData.Frame(sequence.Id, 1000) with { Sha256 = frames[7].Sha256 }; + await db.Frames.InsertAsync(copy, Ct); + + Assert.Equal(frames[7] with { Sha256 = frames[7].Sha256!.ToLowerInvariant() }, await db.Frames.GetAsync(frames[7].Id, Ct)); + var pageOne = await db.Frames.ListBySequenceAsync(sequence.Id, limit: 100, cancellationToken: Ct); + var pageThree = await db.Frames.ListBySequenceAsync(sequence.Id, afterIndex: 199, limit: 100, cancellationToken: Ct); + Assert.SequenceEqual(Enumerable.Range(0, 100), pageOne.Select(f => f.Index)); + Assert.SequenceEqual(Enumerable.Range(200, 50).Append(1000), pageThree.Select(f => f.Index)); + var duplicates = await db.Frames.FindBySha256Async(frames[7].Sha256!.ToUpperInvariant(), Ct); + Assert.SequenceEqual([7, 1000], duplicates.Select(f => f.Index)); + + var stats = Assert.NotNull(await db.Sequences.RefreshStatsAsync(sequence.Id, Ct)); + Assert.Equal(251, stats.FrameCount); + Assert.Equal(frames.Sum(f => f.Size) + copy.Size, stats.TotalBytes); + Assert.Equal(frames[0].CapturedAt, stats.FirstCapture); + Assert.Equal(copy.CapturedAt, stats.LastCapture); + Assert.Equal(1, stats.FramesVersion); + } + + [Test] + public async Task FrameAnalysisAndFlagsUpdateInBulk() + { + var db = await OpenTitanoAsync(); + var archive = TestData.Archive(); + await db.Archives.UpsertAsync(archive, Ct); + var sequence = TestData.Sequence(archive.Id); + await db.Sequences.UpsertAsync(sequence, Ct); + var frames = Enumerable.Range(0, 1200).Select(i => TestData.Frame(sequence.Id, i) with { Flags = FrameFlags.Missing }).ToList(); + await db.Frames.BulkInsertAsync(frames, Ct); + + var stats = frames.Select((f, i) => new FrameLightStats(f.Id, -i / 100.0, i % 2 == 0 ? null : 0.5, 0.001 * i)).ToList(); + Assert.Equal(1200, await db.Frames.UpdateLightStatsAsync(stats, Ct)); + var ids = frames.Where(f => f.Index % 3 == 0).Select(f => f.Id).ToList(); + Assert.Equal(400, await db.Frames.UpdateFlagsAsync(ids, FrameFlags.Duplicate | FrameFlags.Excluded, FrameFlags.Missing, Ct)); + + var read = new List(); + for (var after = -1; ; after = read[^1].Index) + { + var page = await db.Frames.ListBySequenceAsync(sequence.Id, after, 500, Ct); + if (page.Count == 0) break; + read.AddRange(page); + } + Assert.Equal(1200, read.Count); + foreach (var f in read) + { + Assert.Equal(-f.Index / 100.0, f.MeanLogLuminance); + Assert.Equal(f.Index % 2 == 0 ? null : 0.5, f.ClipLow); + Assert.Equal(f.Index % 3 == 0 ? FrameFlags.Duplicate | FrameFlags.Excluded : FrameFlags.Missing, f.Flags); + } + Assert.Equal(1200, await db.Frames.DeleteBySequenceAsync(sequence.Id, Ct)); + } + + [Test] + public async Task RendersKeepTheSequenceCountInStep() + { + var db = await OpenTitanoAsync(); + var archive = TestData.Archive(); + await db.Archives.UpsertAsync(archive, Ct); + var sequence = TestData.Sequence(archive.Id); + await db.Sequences.UpsertAsync(sequence, Ct); + var first = Render(sequence.Id) with { Created = TestData.Now }; + var second = Render(sequence.Id) with { Created = TestData.Now.AddMinutes(5), SettingsJson = null, Codec = null }; + await db.Renders.InsertAsync(first, Ct); + await db.Renders.InsertAsync(second, Ct); + Assert.Equal(2, (await db.Sequences.GetAsync(sequence.Id, Ct))!.RenderedCount); + await db.Sequences.UpsertAsync(sequence with { Title = "Renamed from a stale copy" }, Ct); + Assert.Equal(2, (await db.Sequences.GetAsync(sequence.Id, Ct))!.RenderedCount); + var list = await db.Renders.ListBySequenceAsync(sequence.Id, Ct); + Assert.SequenceEqual([second.Id, first.Id], list.Select(r => r.Id)); + Assert.Equal(second, list[0]); + Assert.True(await db.Renders.DeleteAsync(second.Id, Ct)); + Assert.False(await db.Renders.DeleteAsync(second.Id, Ct)); + Assert.Equal(1, (await db.Sequences.GetAsync(sequence.Id, Ct))!.RenderedCount); + } + + [Test] + public async Task TagsCanBeListedRenamedAndDeleted() + { + var db = await OpenTitanoAsync(); + var archive = TestData.Archive(); + await db.Archives.UpsertAsync(archive, Ct); + var one = TestData.Sequence(archive.Id) with { Tags = ["Alps", "snow"] }; + var two = TestData.Sequence(archive.Id) with { Tags = ["alps"] }; + await db.Sequences.UpsertAsync(one, Ct); + await db.Sequences.UpsertAsync(two, Ct); + Assert.False(await db.Sequences.SetTagsAsync(Guid.CreateVersion7(), ["x"], Ct)); + + var tags = await db.Tags.ListAsync(Ct); + Assert.SequenceEqual([("Alps", 2), ("snow", 1)], tags.Select(t => (t.Name, t.SequenceCount))); + var snow = tags.Single(t => t.Name == "snow"); + await Assert.ThrowsAsync(() => db.Tags.RenameAsync(snow.Id, "ALPS", Ct)); + Assert.True(await db.Tags.RenameAsync(snow.Id, "Snow fields", Ct)); + Assert.SequenceEqual(["Alps", "Snow fields"], (await db.Sequences.GetAsync(one.Id, Ct))!.Tags); + Assert.True(await db.Tags.DeleteAsync(snow.Id, Ct)); + Assert.SequenceEqual(["Alps"], (await db.Sequences.GetAsync(one.Id, Ct))!.Tags); + Assert.True(await db.Sequences.SetTagsAsync(two.Id, [], Ct)); + Assert.Equal(1, (await db.Tags.ListAsync(Ct)).Single().SequenceCount); + Assert.Throws(() => TagRepository.Normalize(" \t ")); + Assert.Throws(() => TagRepository.Normalize("bad\u0001tag")); + } + + [Test] + public async Task TransactionsGroupRepositoryCalls() + { + var db = await OpenTitanoAsync(); + var archive = TestData.Archive(); + await db.Archives.UpsertAsync(archive, Ct); + var sequence = TestData.Sequence(archive.Id); + + await using (var tx = await db.BeginAsync(Ct)) + { + await tx.Sequences.UpsertAsync(sequence, Ct); + await tx.Frames.InsertAsync(TestData.Frame(sequence.Id, 0), Ct); + Assert.NotNull(await tx.Sequences.GetAsync(sequence.Id, Ct)); + } + Assert.Null(await db.Sequences.GetAsync(sequence.Id, Ct)); + + await using (var tx = await db.BeginAsync(Ct)) + { + await tx.Sequences.UpsertAsync(sequence, Ct); + await tx.Frames.InsertAsync(TestData.Frame(sequence.Id, 0), Ct); + await tx.Sequences.RefreshStatsAsync(sequence.Id, Ct); + await tx.CommitAsync(Ct); + } + Assert.Equal(1, (await db.Sequences.GetAsync(sequence.Id, Ct))!.FrameCount); + } + + private static Render Render(Guid sequenceId) => new() + { + Id = Guid.CreateVersion7(), + SequenceId = sequenceId, + PresetName = "4K HEVC", + SettingsJson = "{\"crf\": 18}", + OutputPath = "exports/out.mp4", + Codec = "hevc", + Width = 3840, + Height = 2160, + Fps = 29.97, + DurationSeconds = 41.5, + Bytes = 123_456_789, + Created = TestData.Now, + ProducedBy = "node-1", + }; + + /// The order the database must produce: sort key with NULLS LAST, then id (as text) in the same direction. + private static IEnumerable Expected(List all, SequenceSort sort) + { + int ById(Sequence a, Sequence b) => string.CompareOrdinal(a.Id.ToString("D"), b.Id.ToString("D")); + int NullsLast(T? a, T? b, Comparison compare) where T : struct => + a is null ? (b is null ? 0 : 1) : b is null ? -1 : compare(a.Value, b.Value); + Comparison comparison = sort switch + { + SequenceSort.Newest => (a, b) => NullsLast(a.FirstCapture, b.FirstCapture, (x, y) => y.CompareTo(x)) is var c and not 0 ? c : -ById(a, b), + SequenceSort.Oldest => (a, b) => NullsLast(a.FirstCapture, b.FirstCapture, (x, y) => x.CompareTo(y)) is var c and not 0 ? c : ById(a, b), + SequenceSort.Title => (a, b) => string.CompareOrdinal(a.DisplayTitle.ToLowerInvariant(), b.DisplayTitle.ToLowerInvariant()) is var c and not 0 ? c : ById(a, b), + SequenceSort.FrameCount => (a, b) => b.FrameCount.CompareTo(a.FrameCount) is var c and not 0 ? c : -ById(a, b), + _ => (a, b) => b.TotalBytes.CompareTo(a.TotalBytes) is var c and not 0 ? c : -ById(a, b), + }; + var sorted = all.ToList(); + sorted.Sort(comparison); + return sorted; + } +} + +public sealed class SqliteCatalogRepositoryTests(TestContext context) : CatalogRepositoryTests(context) +{ + protected override Backend Backend => Backend.SqliteMemory; +} + +[RequiresEnvironment(PgTestServer.Variable)] +public sealed class PostgresCatalogRepositoryTests(TestContext context) : CatalogRepositoryTests(context) +{ + protected override Backend Backend => Backend.Postgres; +} diff --git a/tests/Titano.Data.Tests/Repositories/JobRepositoryTests.cs b/tests/Titano.Data.Tests/Repositories/JobRepositoryTests.cs new file mode 100644 index 00000000..cacf4de9 --- /dev/null +++ b/tests/Titano.Data.Tests/Repositories/JobRepositoryTests.cs @@ -0,0 +1,180 @@ +using System.Collections.Concurrent; +using Titano.Core.Model; +using Titano.Data.Tests.Infrastructure; +using Titano.Testing; + +namespace Titano.Data.Tests.Repositories; + +public abstract class JobRepositoryTests(TestContext context) : RepositoryTest(context) +{ + [Test] + public async Task JobsRoundTripEveryField() + { + var db = await OpenTitanoAsync(); + var job = TestData.Job(JobKind.Render, JobPriority.User) with + { + TargetIds = [Guid.CreateVersion7(), Guid.CreateVersion7()], + TargetLabel = "Harbour sunset", + ParametersJson = "{\"preset\": \"4K\"}", + ProgressDone = 5, + ProgressTotal = 10, + ItemsPerSecond = 2.5, + Eta = TimeSpan.FromSeconds(2), + Checkpoint = "frame:5", + LogTail = "line 1\nline 2", + CreatedBy = Guid.CreateVersion7(), + NodeId = "node-a", + Attempts = 1, + Error = "boom", + State = JobState.Failed, + Started = TestData.Now.AddMinutes(1), + Finished = TestData.Now.AddMinutes(2), + }; + await db.Jobs.EnqueueAsync(job, Ct); + var read = Assert.NotNull(await db.Jobs.GetAsync(job.Id, Ct)); + Assert.SequenceEqual(job.TargetIds, read.TargetIds); + Assert.Equal(job with { TargetIds = read.TargetIds }, read); + } + + [Test] + public async Task ClaimsByPriorityThenAgeAndKind() + { + var db = await OpenTitanoAsync(); + var oldBackground = TestData.Job(JobKind.Thumbs, JobPriority.Background, TestData.Now.AddMinutes(-10)); + var newUser = TestData.Job(JobKind.Render, JobPriority.User, TestData.Now); + var oldUser = TestData.Job(JobKind.Import, JobPriority.User, TestData.Now.AddMinutes(-1)); + var normal = TestData.Job(JobKind.Scan, JobPriority.Normal, TestData.Now.AddMinutes(-5)); + foreach (var job in new[] { oldBackground, newUser, oldUser, normal }) await db.Jobs.EnqueueAsync(job, Ct); + + var renderOnly = await db.Jobs.ClaimNextAsync("node-gpu", [JobKind.Render], Ct); + Assert.Equal(newUser.Id, renderOnly?.Id); + Assert.Equal(JobState.Running, renderOnly!.State); + Assert.Equal("node-gpu", renderOnly.NodeId); + Assert.Equal(1, renderOnly.Attempts); + Assert.NotNull(renderOnly.Started); + Assert.Null(await db.Jobs.ClaimNextAsync("node-gpu", [JobKind.Render], Ct)); + + var order = new List(); + while (await db.Jobs.ClaimNextAsync("server", cancellationToken: Ct) is { } claimed) order.Add(claimed.Id); + Assert.SequenceEqual([oldUser.Id, normal.Id, oldBackground.Id], order); + } + + [Test] + public async Task ConcurrentClaimersNeverShareAJob() + { + var db = await OpenTitanoAsync(multiConnection: true); + var jobs = Enumerable.Range(0, 40).Select(i => TestData.Job(created: TestData.Now.AddSeconds(i))).ToList(); + foreach (var job in jobs) await db.Jobs.EnqueueAsync(job, Ct); + + var claims = new ConcurrentBag<(string Worker, Guid Job)>(); + await Task.WhenAll(Enumerable.Range(0, 8).Select(w => Task.Run(async () => + { + var worker = "worker-" + w; + while (await db.Jobs.ClaimNextAsync(worker, cancellationToken: Ct) is { } job) claims.Add((worker, job.Id)); + }))); + + Assert.Equal(40, claims.Count); + Assert.Equal(40, claims.Select(c => c.Job).Distinct().Count()); + foreach (var (worker, id) in claims) + { + var stored = await db.Jobs.GetAsync(id, Ct); + Assert.Equal(worker, stored!.NodeId); + Assert.Equal(1, stored.Attempts); + } + } + + [Test] + public async Task ProgressIsRefusedOnceTheJobStopsRunning() + { + var db = await OpenTitanoAsync(); + var job = TestData.Job(); + await db.Jobs.EnqueueAsync(job, Ct); + Assert.False(await db.Jobs.UpdateProgressAsync(job.Id, 1, 10, null, null, null, null, Ct)); + await db.Jobs.ClaimNextAsync("w", cancellationToken: Ct); + Assert.True(await db.Jobs.UpdateProgressAsync(job.Id, 4, 10, 2.0, TimeSpan.FromSeconds(3), "cursor:4", "tail", Ct)); + var running = await db.Jobs.GetAsync(job.Id, Ct); + Assert.Equal((4L, 10L, "cursor:4", "tail"), (running!.ProgressDone, running.ProgressTotal, running.Checkpoint, running.LogTail)); + Assert.Equal(TimeSpan.FromSeconds(3), running.Eta); + + Assert.True(await db.Jobs.SetStateAsync(job.Id, JobState.Cancelled, cancellationToken: Ct)); + Assert.False(await db.Jobs.UpdateProgressAsync(job.Id, 5, 10, null, null, "cursor:5", null, Ct)); + var cancelled = await db.Jobs.GetAsync(job.Id, Ct); + Assert.Equal(JobState.Cancelled, cancelled!.State); + Assert.NotNull(cancelled.Finished); + + Assert.True(await db.Jobs.SetStateAsync(job.Id, JobState.Queued, cancellationToken: Ct)); + Assert.Null((await db.Jobs.GetAsync(job.Id, Ct))!.Finished); + Assert.Equal(2, (await db.Jobs.ClaimNextAsync("w", cancellationToken: Ct))!.Attempts); + Assert.False(await db.Jobs.SetStateAsync(Guid.CreateVersion7(), JobState.Done, cancellationToken: Ct)); + } + + [Test] + public async Task ListingPagesByStateNewestFirst() + { + var db = await OpenTitanoAsync(); + var jobs = Enumerable.Range(0, 7).Select(i => TestData.Job(created: TestData.Now.AddMinutes(i % 3))).ToList(); + foreach (var job in jobs) await db.Jobs.EnqueueAsync(job, Ct); + await db.Jobs.SetStateAsync(jobs[0].Id, JobState.Done, cancellationToken: Ct); + + var seen = new List(); + string? cursor = null; + do + { + var page = await db.Jobs.ListAsync(JobState.Queued, limit: 2, cursor: cursor, cancellationToken: Ct); + seen.AddRange(page.Items.Select(j => j.Id)); + cursor = page.NextCursor; + } + while (cursor is not null); + + var expected = jobs.Skip(1) + .OrderByDescending(j => j.Created) + .ThenByDescending(j => j.Id.ToString("D"), StringComparer.Ordinal) + .Select(j => j.Id); + Assert.SequenceEqual(expected, seen); + Assert.SequenceEqual([jobs[0].Id], (await db.Jobs.ListAsync(JobState.Done, cancellationToken: Ct)).Items.Select(j => j.Id)); + Assert.Equal(7, (await db.Jobs.ListAsync(cancellationToken: Ct)).Items.Count); + } + + [Test] + public async Task HistoryPurgeKeepsRecentAndActiveJobs() + { + var db = await OpenTitanoAsync(); + var old = TestData.Job() with { State = JobState.Done, Finished = TestData.Now.AddDays(-100) }; + var oldFailed = TestData.Job() with { State = JobState.Failed, Finished = TestData.Now.AddDays(-91) }; + var recent = TestData.Job() with { State = JobState.Done, Finished = TestData.Now.AddDays(-10) }; + var queued = TestData.Job(created: TestData.Now.AddDays(-200)); + foreach (var job in new[] { old, oldFailed, recent, queued }) await db.Jobs.EnqueueAsync(job, Ct); + Assert.Equal(2, await db.Jobs.PurgeHistoryAsync(TestData.Now.AddDays(-90), Ct)); + Assert.Equal(2, (await db.Jobs.ListAsync(cancellationToken: Ct)).Items.Count); + } + + [Test] + public async Task RunningJobsAreRequeuedAfterACrash() + { + var db = await OpenTitanoAsync(); + for (var i = 0; i < 3; i++) await db.Jobs.EnqueueAsync(TestData.Job(created: TestData.Now.AddSeconds(i)), Ct); + var a = await db.Jobs.ClaimNextAsync("node-a", cancellationToken: Ct); + var b = await db.Jobs.ClaimNextAsync("node-b", cancellationToken: Ct); + await db.Jobs.UpdateProgressAsync(a!.Id, 3, 9, null, null, "resume-here", null, Ct); + + Assert.Equal(1, await db.Jobs.RequeueRunningAsync("node-a", Ct)); + var requeued = await db.Jobs.GetAsync(a.Id, Ct); + Assert.Equal(JobState.Queued, requeued!.State); + Assert.Equal("resume-here", requeued.Checkpoint); + Assert.Null(requeued.NodeId); + Assert.Equal(JobState.Running, (await db.Jobs.GetAsync(b!.Id, Ct))!.State); + Assert.Equal(1, await db.Jobs.RequeueRunningAsync(cancellationToken: Ct)); + Assert.Equal(0, await db.Jobs.RequeueRunningAsync(cancellationToken: Ct)); + } +} + +public sealed class SqliteJobRepositoryTests(TestContext context) : JobRepositoryTests(context) +{ + protected override Backend Backend => Backend.SqliteMemory; +} + +[RequiresEnvironment(PgTestServer.Variable)] +public sealed class PostgresJobRepositoryTests(TestContext context) : JobRepositoryTests(context) +{ + protected override Backend Backend => Backend.Postgres; +} diff --git a/tests/Titano.Data.Tests/Repositories/MediaCardRepositoryTests.cs b/tests/Titano.Data.Tests/Repositories/MediaCardRepositoryTests.cs new file mode 100644 index 00000000..efc1352a --- /dev/null +++ b/tests/Titano.Data.Tests/Repositories/MediaCardRepositoryTests.cs @@ -0,0 +1,100 @@ +using Titano.Core.Model; +using Titano.Data.Repositories; +using Titano.Data.Tests.Infrastructure; +using Titano.Testing; + +namespace Titano.Data.Tests.Repositories; + +public abstract class MediaCardRepositoryTests(TestContext context) : RepositoryTest(context) +{ + [Test] + public async Task CardsRoundTripAndAreFoundByIdentity() + { + var db = await OpenTitanoAsync(); + var card = Card(); + await db.MediaCards.UpsertAsync(card, Ct); + Assert.Equal(card, await db.MediaCards.GetAsync(card.Id, Ct)); + Assert.Equal(card, await db.MediaCards.FindByIdentityAsync(card.Identity, Ct)); + Assert.Null(await db.MediaCards.FindByIdentityAsync("unknown", Ct)); + + var seen = TestData.Now.AddDays(2); + Assert.True(await db.MediaCards.TouchAsync(card.Id, seen, Ct)); + await db.MediaCards.UpsertAsync(card with { Nickname = "Card B", LastSeen = seen }, Ct); + var other = Card() with { Identity = "1-OTHER-64", LastSeen = TestData.Now.AddDays(5) }; + await db.MediaCards.UpsertAsync(other, Ct); + Assert.SequenceEqual([other.Id, card.Id], (await db.MediaCards.ListAsync(Ct)).Select(c => c.Id)); + Assert.Equal("Card B", (await db.MediaCards.GetAsync(card.Id, Ct))!.Nickname); + + var clash = await Assert.ThrowsAsync(() => db.MediaCards.UpsertAsync(Card() with { Identity = card.Identity }, Ct)); + Assert.True(clash.IsUniqueViolation); + } + + [Test] + public async Task ImportHistoryLetsReinsertsSkipKnownFiles() + { + var db = await OpenTitanoAsync(); + var card = Card(); + await db.MediaCards.UpsertAsync(card, Ct); + var archive = TestData.Archive(); + await db.Archives.UpsertAsync(archive, Ct); + var sequence = TestData.Sequence(archive.Id); + await db.Sequences.UpsertAsync(sequence, Ct); + var frame = TestData.Frame(sequence.Id, 0); + await db.Frames.InsertAsync(frame, Ct); + + // File-system times carry 100 ns ticks; keys compare at the database's microsecond precision. + var modified = new DateTimeOffset(2026, 9, 28, 18, 0, 0, TimeSpan.FromHours(2)).AddTicks(1234567); + var first = new ImportKey("DCIM/100CANON/IMG_0001.CR3", 25_000_000, modified); + var reused = new ImportKey("DCIM/100CANON/IMG_0001.CR3", 24_000_000, modified.AddDays(30)); + var job = Guid.CreateVersion7(); + await db.MediaCards.RecordImportsAsync( + [ + new ImportRecord(card.Id, first, new string('F', 64), frame.Id, job, TestData.Now), + new ImportRecord(card.Id, reused, null, null, job, TestData.Now.AddDays(30)), + ], Ct); + await db.MediaCards.RecordImportsAsync([new ImportRecord(card.Id, first, new string('F', 64), frame.Id, job, TestData.Now)], Ct); + + var keys = await db.MediaCards.GetImportedKeysAsync(card.Id, Ct); + Assert.Equal(2, keys.Count); + Assert.True(keys.Contains(new ImportKey("DCIM/100CANON/IMG_0001.CR3", 25_000_000, modified.AddTicks(2)))); + Assert.True(await db.MediaCards.IsImportedAsync(card.Id, first, Ct)); + Assert.False(await db.MediaCards.IsImportedAsync(card.Id, new ImportKey(first.Path, first.Size + 1, modified), Ct)); + + var history = await db.MediaCards.ListImportsAsync(card.Id, cancellationToken: Ct); + Assert.Equal(reused, history[0].Key); + Assert.Equal(new string('f', 64), history[1].Sha256); + Assert.Equal(frame.Id, history[1].FrameId); + + await db.Frames.DeleteBySequenceAsync(sequence.Id, Ct); + Assert.Null((await db.MediaCards.ListImportsAsync(card.Id, cancellationToken: Ct))[1].FrameId); + Assert.True(await db.MediaCards.DeleteAsync(card.Id, Ct)); + Assert.Equal(0, (await db.MediaCards.GetImportedKeysAsync(card.Id, Ct)).Count); + } + + private static MediaCard Card() => new() + { + Id = Guid.CreateVersion7(), + Identity = "3735928559-EOS_DIGITAL-128043712512", + VolumeSerial = 3735928559, + Label = "EOS_DIGITAL", + Capacity = 128_043_712_512, + CameraMake = "Canon", + CameraModel = "EOS R5", + CameraSerial = "0123", + ProfileJson = "{\"auto\": false}", + AutoImport = true, + FirstSeen = TestData.Now, + LastSeen = TestData.Now, + }; +} + +public sealed class SqliteMediaCardRepositoryTests(TestContext context) : MediaCardRepositoryTests(context) +{ + protected override Backend Backend => Backend.SqliteMemory; +} + +[RequiresEnvironment(PgTestServer.Variable)] +public sealed class PostgresMediaCardRepositoryTests(TestContext context) : MediaCardRepositoryTests(context) +{ + protected override Backend Backend => Backend.Postgres; +} diff --git a/tests/Titano.Data.Tests/Repositories/ServerRepositoryTests.cs b/tests/Titano.Data.Tests/Repositories/ServerRepositoryTests.cs new file mode 100644 index 00000000..6b3521f1 --- /dev/null +++ b/tests/Titano.Data.Tests/Repositories/ServerRepositoryTests.cs @@ -0,0 +1,253 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using Titano.Core.Model; +using Titano.Data.Repositories; +using Titano.Data.Tests.Infrastructure; +using Titano.Testing; + +namespace Titano.Data.Tests.Repositories; + +/// Users, tokens, render nodes, settings, audit log and uploads on both dialects. +public abstract class ServerRepositoryTests(TestContext context) : RepositoryTest(context) +{ + [Test] + public async Task UsersAreUniqueIgnoringCase() + { + var db = await OpenTitanoAsync(); + var alice = TestData.User("Alice") with { DisplayName = "Alice A.", QuotaBytes = 1L << 40, MustChangePassword = true, Role = UserRole.Admin, Permissions = Permissions.All }; + await db.Users.CreateAsync(alice, Ct); + var duplicate = await Assert.ThrowsAsync(() => db.Users.CreateAsync(TestData.User("ALICE"), Ct)); + Assert.True(duplicate.IsUniqueViolation); + + Assert.Equal(alice, await db.Users.GetByUsernameAsync(" alice ", Ct)); + Assert.True(await db.Users.UpdateAsync(alice with { Username = "alice2", Disabled = true, MustChangePassword = false }, Ct)); + Assert.True(await db.Users.RecordLoginAsync(alice.Id, TestData.Now, Ct)); + Assert.True(await db.Users.AddUsedBytesAsync(alice.Id, 5000, Ct)); + Assert.True(await db.Users.AddUsedBytesAsync(alice.Id, -1000, Ct)); + var read = Assert.NotNull(await db.Users.GetAsync(alice.Id, Ct)); + Assert.Equal(alice with { Username = "alice2", Disabled = true, MustChangePassword = false, LastLogin = TestData.Now, UsedBytes = 4000 }, read); + Assert.Null(await db.Users.GetByUsernameAsync("alice", Ct)); + Assert.Equal(1, await db.Users.CountAsync(Ct)); + Assert.Count(1, await db.Users.ListAsync(Ct)); + } + + [Test] + public async Task DeletingAUserRemovesTheirTokensNodesAndUploads() + { + var db = await OpenTitanoAsync(); + var user = TestData.User(); + await db.Users.CreateAsync(user, Ct); + await db.Tokens.InsertAsync(Token(user.Id, "h1"), Ct); + await db.RenderNodes.RegisterAsync(Node(user.Id), Ct); + await db.Uploads.CreateAsync(Upload(user.Id, 10), Ct); + Assert.True(await db.Users.DeleteAsync(user.Id, Ct)); + Assert.Null(await db.Tokens.GetAsync("h1", Ct)); + Assert.Empty(await db.RenderNodes.ListAsync(Ct)); + Assert.Empty(await db.Uploads.ListByUserAsync(user.Id, Ct)); + } + + [Test] + public async Task TokensSlideRevokeAndPurge() + { + var db = await OpenTitanoAsync(); + var user = TestData.User(); + await db.Users.CreateAsync(user, Ct); + var token = Token(user.Id, "hash-1"); + await db.Tokens.InsertAsync(token, Ct); + await db.Tokens.InsertAsync(Token(user.Id, "hash-2"), Ct); + await db.Tokens.InsertAsync(Token(user.Id, "expired") with { Expires = TestData.Now.AddDays(-1) }, Ct); + Assert.Equal(token, await db.Tokens.GetAsync("hash-1", Ct)); + + var later = TestData.Now.AddDays(3); + Assert.True(await db.Tokens.TouchAsync("hash-1", later, later.AddDays(30), Ct)); + var touched = await db.Tokens.GetAsync("hash-1", Ct); + Assert.Equal((later, later.AddDays(30)), (touched!.LastUsed, touched.Expires)); + Assert.False(await db.Tokens.TouchAsync("expired", TestData.Now, later, Ct)); + Assert.False(await db.Tokens.TouchAsync("missing", TestData.Now, later, Ct)); + + Assert.True(await db.Tokens.RevokeAsync("hash-1", Ct)); + Assert.False(await db.Tokens.RevokeAsync("hash-1", Ct)); + Assert.False(await db.Tokens.TouchAsync("hash-1", later, later.AddDays(30), Ct)); + Assert.True((await db.Tokens.GetAsync("hash-1", Ct))!.Revoked); + Assert.Equal(2, await db.Tokens.RevokeAllAsync(user.Id, Ct)); + Assert.Count(3, await db.Tokens.ListByUserAsync(user.Id, Ct)); + Assert.Equal(3, await db.Tokens.PurgeAsync(TestData.Now, Ct)); + } + + [Test] + public async Task RenderNodesReportHeartbeats() + { + var db = await OpenTitanoAsync(); + var user = TestData.User(); + await db.Users.CreateAsync(user, Ct); + var node = Node(user.Id); + await db.RenderNodes.RegisterAsync(node, Ct); + var stale = Node(user.Id) with { ClientName = "old-pc", LastHeartbeat = TestData.Now.AddHours(-1) }; + await db.RenderNodes.RegisterAsync(stale, Ct); + await db.RenderNodes.RegisterAsync(node with { CapabilitiesJson = "{\"encoders\": [\"nvenc\"]}" }, Ct); + Assert.Equal("{\"encoders\": [\"nvenc\"]}", (await db.RenderNodes.GetAsync(node.Id, Ct))!.CapabilitiesJson); + + Assert.SequenceEqual([node.Id], (await db.RenderNodes.ListOnlineAsync(TestData.Now.AddMinutes(-2), Ct)).Select(n => n.Id)); + Assert.True(await db.RenderNodes.HeartbeatAsync(stale.Id, "rendering", TestData.Now.AddMinutes(1), Ct)); + var online = await db.RenderNodes.ListOnlineAsync(TestData.Now.AddMinutes(-2), Ct); + Assert.SequenceEqual([stale.Id, node.Id], online.Select(n => n.Id)); + Assert.Equal("rendering", online[0].State); + Assert.True(await db.RenderNodes.DeleteAsync(stale.Id, Ct)); + Assert.False(await db.RenderNodes.HeartbeatAsync(stale.Id, "idle", TestData.Now, Ct)); + } + + [Test] + public async Task SettingsAreTypedAndScoped() + { + var db = await OpenTitanoAsync(); + var archive = Guid.CreateVersion7(); + var user = Guid.CreateVersion7(); + var preferences = new Preferences("it", 4, [1.5, 2]); + await db.Settings.SetAsync(SettingScope.App, null, "ui", preferences, TestJson.Default.Preferences, Ct); + await db.Settings.SetAsync(SettingScope.User, user, "ui", preferences with { Language = "en" }, TestJson.Default.Preferences, Ct); + await db.Settings.SetJsonAsync(SettingScope.Archive, archive, "proxy", "{\"longEdge\": 1920}", Ct); + + Assert.Equal(preferences, await db.Settings.GetAsync(SettingScope.App, null, "ui", TestJson.Default.Preferences, Ct), "app scope"); + Assert.Equal("en", (await db.Settings.GetAsync(SettingScope.User, user, "ui", TestJson.Default.Preferences, Ct))!.Language); + Assert.Null(await db.Settings.GetAsync(SettingScope.User, Guid.CreateVersion7(), "ui", TestJson.Default.Preferences, Ct)); + Assert.Equal(1920, JsonDocument.Parse((await db.Settings.GetJsonAsync(SettingScope.Archive, archive, "proxy", Ct))!).RootElement.GetProperty("longEdge").GetInt32()); + + await db.Settings.SetAsync(SettingScope.App, null, "ui", preferences with { Columns = 6 }, TestJson.Default.Preferences, Ct); + Assert.Equal(6, (await db.Settings.GetAsync(SettingScope.App, null, "ui", TestJson.Default.Preferences, Ct))!.Columns); + await db.Settings.SetAsync(SettingScope.App, null, "count", 42, TestJson.Default.Int32, Ct); + Assert.SequenceEqual(["count", "ui"], (await db.Settings.ListAsync(SettingScope.App, null, Ct)).Keys.Order(StringComparer.Ordinal)); + Assert.True(await db.Settings.DeleteAsync(SettingScope.App, null, "count", Ct)); + Assert.False(await db.Settings.DeleteAsync(SettingScope.App, null, "count", Ct)); + + await Assert.ThrowsAsync(() => db.Settings.GetJsonAsync(SettingScope.User, null, "ui", Ct)); + await Assert.ThrowsAsync(() => db.Settings.GetJsonAsync(SettingScope.App, user, "ui", Ct)); + await Assert.ThrowsAsync(() => db.Settings.SetJsonAsync(SettingScope.App, null, "bad", "{not json", Ct)); + } + + [Test] + public async Task AuditLogPagesNewestFirst() + { + var db = await OpenTitanoAsync(); + var user = Guid.CreateVersion7(); + var entries = Enumerable.Range(0, 9).Select(i => new AuditEntry + { + Id = Guid.CreateVersion7(), + At = TestData.Now.AddSeconds(i / 2), + Action = "sequence.delete", + UserId = i % 3 == 0 ? user : null, + Username = "alice", + TargetKind = "sequence", + TargetId = Guid.CreateVersion7().ToString(), + Details = "{\"frames\": 10}", + RemoteAddress = "10.0.0.1", + }).ToList(); + foreach (var e in entries) await db.Audit.AppendAsync(e, Ct); + + var seen = new List(); + string? cursor = null; + do + { + var page = await db.Audit.ListAsync(limit: 4, cursor: cursor, cancellationToken: Ct); + seen.AddRange(page.Items); + cursor = page.NextCursor; + } + while (cursor is not null); + Assert.SequenceEqual( + entries.OrderByDescending(e => e.At).ThenByDescending(e => e.Id.ToString("D"), StringComparer.Ordinal), + seen); + Assert.Equal(3, (await db.Audit.ListAsync(user, cancellationToken: Ct)).Items.Count); + } + + [Test] + public async Task UploadsTrackChunksAndStates() + { + var db = await OpenTitanoAsync(); + var user = TestData.User(); + await db.Users.CreateAsync(user, Ct); + var created = await db.Uploads.CreateAsync(Upload(user.Id, 8 * 1024 * 1024 * 9 + 1), Ct); + Assert.Equal(10, created.ChunkCount); + Assert.Equal(2, created.Received.Length); + Assert.Equal(created.Id, (await db.Uploads.FindReceivingAsync(user.Id, created.Sha256.ToUpperInvariant(), Ct))!.Id); + + foreach (var chunk in new[] { 0, 9, 3, 9 }) + { + var updated = await db.Uploads.MarkChunkReceivedAsync(created.Id, chunk, Ct); + Assert.True(updated!.HasChunk(chunk)); + } + await Assert.ThrowsAsync(() => db.Uploads.MarkChunkReceivedAsync(created.Id, 10, Ct)); + Assert.Null(await db.Uploads.MarkChunkReceivedAsync(Guid.CreateVersion7(), 0, Ct)); + + var stored = Assert.NotNull(await db.Uploads.GetAsync(created.Id, Ct)); + Assert.Equal(3, stored.ReceivedCount); + Assert.SequenceEqual([0, 3, 9], Enumerable.Range(0, 10).Where(stored.HasChunk)); + Assert.False(stored.IsComplete); + + await Task.WhenAll(Enumerable.Range(0, 10).Select(i => db.Uploads.MarkChunkReceivedAsync(created.Id, i, Ct))); + Assert.True((await db.Uploads.GetAsync(created.Id, Ct))!.IsComplete); + + Assert.Count(1, await db.Uploads.ListStaleAsync(TestData.Now.AddYears(10), Ct)); + var frameId = Guid.CreateVersion7(); + Assert.True(await db.Uploads.SetStateAsync(created.Id, UploadState.Committed, frameId, Ct)); + Assert.True(await db.Uploads.SetStateAsync(created.Id, UploadState.Committed, cancellationToken: Ct)); + var committed = await db.Uploads.GetAsync(created.Id, Ct); + Assert.Equal((UploadState.Committed, (Guid?)frameId), (committed!.State, committed.FrameId)); + Assert.Empty(await db.Uploads.ListStaleAsync(TestData.Now.AddYears(10), Ct)); + Assert.Null(await db.Uploads.FindReceivingAsync(user.Id, created.Sha256, Ct)); + Assert.True(await db.Uploads.DeleteAsync(created.Id, Ct)); + } + + private static SessionToken Token(Guid userId, string hash) => new() + { + TokenHash = hash, + UserId = userId, + ClientName = "Titano desktop", + Created = TestData.Now, + Expires = TestData.Now.AddDays(30), + LastUsed = TestData.Now, + }; + + private static RenderNode Node(Guid userId) => new() + { + Id = Guid.CreateVersion7(), + UserId = userId, + ClientName = "studio-pc", + CapabilitiesJson = "{\"encoders\": []}", + LastHeartbeat = TestData.Now, + }; + + private static Upload Upload(Guid userId, long size) => new() + { + Id = Guid.CreateVersion7(), + UserId = userId, + FileName = "IMG_0001.CR3", + Size = size, + Sha256 = new string('A', 64), + CapturedAt = new DateTime(2026, 9, 28, 18, 0, 0), + ChunkSize = 8 * 1024 * 1024, + Created = TestData.Now, + UpdatedAt = TestData.Now, + }; +} + +public sealed record Preferences(string Language, int Columns, double[] Zoom) +{ + public bool Equals(Preferences? other) => + other is not null && Language == other.Language && Columns == other.Columns && Zoom.SequenceEqual(other.Zoom); + + public override int GetHashCode() => HashCode.Combine(Language, Columns); +} + +[JsonSerializable(typeof(Preferences))] +[JsonSerializable(typeof(int))] +internal sealed partial class TestJson : JsonSerializerContext; + +public sealed class SqliteServerRepositoryTests(TestContext context) : ServerRepositoryTests(context) +{ + protected override Backend Backend => Backend.SqliteMemory; +} + +[RequiresEnvironment(PgTestServer.Variable)] +public sealed class PostgresServerRepositoryTests(TestContext context) : ServerRepositoryTests(context) +{ + protected override Backend Backend => Backend.Postgres; +} diff --git a/tests/Titano.Data.Tests/Sessions/SessionTests.cs b/tests/Titano.Data.Tests/Sessions/SessionTests.cs new file mode 100644 index 00000000..72b7706b --- /dev/null +++ b/tests/Titano.Data.Tests/Sessions/SessionTests.cs @@ -0,0 +1,260 @@ +using System.Diagnostics; +using Titano.Data.Tests.Infrastructure; +using Titano.Testing; + +namespace Titano.Data.Tests.Sessions; + +/// Behaviour every must share, run once per dialect. +public abstract class SessionTests(TestContext context) : DatabaseTest(context) +{ + private string AllTypesTable => ForDialect( + "CREATE TABLE t (id INTEGER PRIMARY KEY, s TEXT, i INTEGER, l INTEGER, d REAL, b INTEGER, g TEXT, ts TEXT, ldt TEXT, bytes BLOB, j TEXT)", + "CREATE TABLE t (id integer PRIMARY KEY, s text, i integer, l bigint, d double precision, b boolean, g uuid, ts timestamptz, ldt timestamp, bytes bytea, j jsonb)"); + + [Test] + public async Task ParametersRoundTripEveryType() + { + await using var session = await (await OpenDatabaseAsync()).OpenAsync(Ct); + await session.ExecuteScriptAsync(AllTypesTable, Ct); + var guid = Guid.CreateVersion7(); + var instant = new DateTimeOffset(2026, 9, 28, 18, 30, 15, 123, TimeSpan.FromHours(2)).AddTicks(4560); + var wallClock = new DateTime(2024, 2, 29, 23, 59, 58, 999).AddTicks(9990); + byte[] bytes = [0, 1, 2, 0x7F, 0x80, 0xFE, 0xFF, (byte)'\\', (byte)'\t']; + var text = "Città \"quoted\" 'single' \\ back\ttab\nnewline 🎞️ 時間"; + await session.ExecuteAsync( + "INSERT INTO t (id, s, i, l, d, b, g, ts, ldt, bytes, j) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)", + [1, text, int.MinValue, long.MaxValue, Math.PI, true, guid, instant, wallClock, bytes, DbParam.Json("{\"a\": [1, 2]}")], + Ct); + + var row = await session.QuerySingleAsync("SELECT s, i, l, d, b, g, ts, ldt, bytes, j FROM t WHERE id = $1", [1], Ct); + Assert.Equal(text, row.GetString(0)); + Assert.Equal(int.MinValue, row.GetInt32(1)); + Assert.Equal(long.MaxValue, row.GetInt64(2)); + Assert.Equal(Math.PI, row.GetDouble(3)); + Assert.True(row.GetBool(4)); + Assert.Equal(guid, row.GetGuid(5)); + Assert.Equal(instant, row.GetDateTimeOffset(6)); + Assert.Equal(TimeSpan.Zero, row.GetDateTimeOffset(6).Offset); + Assert.Equal(wallClock, row.GetDateTime(7)); + Assert.Equal(DateTimeKind.Unspecified, row.GetDateTime(7).Kind); + Assert.BytesEqual(bytes, row.GetBytes(8)); + Assert.Equal("{\"a\": [1, 2]}", row.GetString(9)); + Assert.Equal(text, row.GetString("S")); + } + + [Test] + public async Task TypedNullsRoundTrip() + { + await using var session = await (await OpenDatabaseAsync()).OpenAsync(Ct); + await session.ExecuteScriptAsync(AllTypesTable, Ct); + await session.ExecuteAsync( + "INSERT INTO t (id, s, i, l, d, b, g, ts, ldt, bytes, j) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)", + [1, (string?)null, (int?)null, (long?)null, (double?)null, (bool?)null, (Guid?)null, (DateTimeOffset?)null, (DateTime?)null, (byte[]?)null, DbParam.Json(null)], + Ct); + var row = await session.QuerySingleAsync("SELECT s, i, l, d, b, g, ts, ldt, bytes, j FROM t", [], Ct); + for (var i = 0; i < row.FieldCount; i++) Assert.True(row.IsNull(i), $"column {row.GetName(i)} should be NULL"); + Assert.Null(row.GetGuidOrNull(5)); + Assert.Null(row.GetDateTimeOffsetOrNull(6)); + Assert.Throws(() => row.GetInt32(1)); + } + + [Test] + public async Task PlaceholdersBindByNumberNotByOrder() + { + await using var session = await (await OpenDatabaseAsync()).OpenAsync(Ct); + var row = await session.QuerySingleAsync("SELECT $2 AS b, $1 AS a, $2 AS b2", [10, "x"], Ct); + Assert.Equal("x", row.GetString("b")); + Assert.Equal(10, row.GetInt32("a")); + Assert.Equal("x", row.GetString(2)); + } + + [Test] + public async Task ExecuteReportsChangedRowsOnly() + { + await using var session = await (await OpenDatabaseAsync()).OpenAsync(Ct); + Assert.Equal(0, await session.ExecuteAsync("CREATE TABLE n (id integer PRIMARY KEY, v integer)", [], Ct)); + for (var i = 0; i < 5; i++) await session.ExecuteAsync("INSERT INTO n (id, v) VALUES ($1, $2)", [i, i % 2], Ct); + Assert.Equal(3, await session.ExecuteAsync("UPDATE n SET v = 7 WHERE v = $1", [0], Ct)); + Assert.Equal(0, await session.ExecuteAsync("CREATE INDEX ix_n ON n (v)", [], Ct)); + Assert.Equal(2, await session.ExecuteAsync("DELETE FROM n WHERE v = $1", [1], Ct)); + Assert.Equal(3L, await session.ScalarAsync("SELECT count(*) FROM n", [], Ct)); + } + + [Test] + public async Task TransactionsCommitRollBackAndRollBackOnDispose() + { + var database = await OpenDatabaseAsync(); + await using var session = await database.OpenAsync(Ct); + await session.ExecuteScriptAsync("CREATE TABLE x (id integer PRIMARY KEY)", Ct); + + await using (var tx = await session.BeginAsync(Ct)) + { + Assert.True(session.InTransaction); + await session.ExecuteAsync("INSERT INTO x (id) VALUES ($1)", [1], Ct); + await tx.CommitAsync(Ct); + } + Assert.False(session.InTransaction); + + await using (var tx = await session.BeginAsync(Ct)) + { + await session.ExecuteAsync("INSERT INTO x (id) VALUES ($1)", [2], Ct); + await tx.RollbackAsync(Ct); + } + await using (await session.BeginAsync(Ct)) + { + await session.ExecuteAsync("INSERT INTO x (id) VALUES ($1)", [3], Ct); + await Assert.ThrowsAsync(() => session.BeginAsync(Ct)); + } + + await using var other = await database.OpenAsync(Ct); + Assert.Equal(1L, await other.ScalarAsync("SELECT count(*) FROM x", [], Ct)); + Assert.Equal(1, await other.ScalarAsync("SELECT max(id) FROM x", [], Ct)); + } + + [Test] + public async Task SessionDisposedInsideTransactionRollsBack() + { + var database = await OpenDatabaseAsync(); + await using (var setup = await database.OpenAsync(Ct)) + await setup.ExecuteScriptAsync("CREATE TABLE x (id integer PRIMARY KEY)", Ct); + var session = await database.OpenAsync(Ct); + await session.BeginAsync(Ct); + await session.ExecuteAsync("INSERT INTO x (id) VALUES ($1)", [1], Ct); + await session.DisposeAsync(); + + await using var check = await database.OpenAsync(Ct); + Assert.Equal(0L, await check.ScalarAsync("SELECT count(*) FROM x", [], Ct)); + await check.ExecuteAsync("INSERT INTO x (id) VALUES ($1)", [2], Ct); + } + + [Test] + public async Task ConstraintViolationsAreTyped() + { + await using var session = await (await OpenDatabaseAsync()).OpenAsync(Ct); + await session.ExecuteScriptAsync( + "CREATE TABLE p (id integer PRIMARY KEY, code text NOT NULL UNIQUE); " + + "CREATE TABLE c (id integer PRIMARY KEY, p_id integer NOT NULL REFERENCES p(id))", Ct); + await session.ExecuteAsync("INSERT INTO p (id, code) VALUES ($1, $2)", [1, "a"], Ct); + + var unique = await Assert.ThrowsAsync(() => session.ExecuteAsync("INSERT INTO p (id, code) VALUES ($1, $2)", [2, "a"], Ct)); + Assert.True(unique.IsUniqueViolation); + var primary = await Assert.ThrowsAsync(() => session.ExecuteAsync("INSERT INTO p (id, code) VALUES ($1, $2)", [1, "b"], Ct)); + Assert.True(primary.IsUniqueViolation); + var foreign = await Assert.ThrowsAsync(() => session.ExecuteAsync("INSERT INTO c (id, p_id) VALUES ($1, $2)", [1, 99], Ct)); + Assert.True(foreign.IsForeignKeyViolation); + + // The session stays usable after errors. + Assert.Equal(1L, await session.ScalarAsync("SELECT count(*) FROM p", [], Ct)); + } + + [Test] + public async Task BulkInsertKeepsSpecialCharactersAndNulls() + { + await using var session = await (await OpenDatabaseAsync()).OpenAsync(Ct); + await session.ExecuteScriptAsync(ForDialect( + "CREATE TABLE b (id INTEGER PRIMARY KEY, s TEXT, bytes BLOB, ts TEXT, ldt TEXT, d REAL, g TEXT, f INTEGER)", + "CREATE TABLE b (id integer PRIMARY KEY, s text, bytes bytea, ts timestamptz, ldt timestamp, d double precision, g uuid, f boolean)"), Ct); + string?[] texts = + [ + "tab\there", "new\nline", "carriage\rreturn", "back\\slash", "\\N", "", null, "unicode ✓ ñ 漢字 🎉", + "mixed \\t\t\\n\n end\\", "trailing tab\t", "x", + ]; + var instant = new DateTimeOffset(2025, 1, 2, 3, 4, 5, TimeSpan.Zero); + var rows = texts.Select((s, i) => new object?[] + { + i, s, i % 3 == 0 ? null : new byte[] { (byte)i, (byte)'\\', (byte)'\n', 0 }, instant.AddDays(i), + new DateTime(2020, 1, 1).AddHours(i), i / 3.0, Guid.CreateVersion7(), i % 2 == 0, + }).ToList(); + + var inserted = await session.BulkInsertAsync("b", ["id", "s", "bytes", "ts", "ldt", "d", "g", "f"], rows.ToAsyncEnumerable(), Ct); + Assert.Equal(texts.Length, (int)inserted); + + var read = await session.QueryListAsync("SELECT id, s, bytes, ts, ldt, d, g, f FROM b ORDER BY id", [], r => r, Ct); + Assert.Equal(texts.Length, read.Count); + for (var i = 0; i < texts.Length; i++) + { + var r = read[i]; + Assert.Equal(texts[i], r.GetStringOrNull(1), $"row {i}"); + if (rows[i][2] is byte[] expected) Assert.BytesEqual(expected, r.GetBytes(2)); + else Assert.True(r.IsNull(2)); + Assert.Equal(instant.AddDays(i), r.GetDateTimeOffset(3)); + Assert.Equal(new DateTime(2020, 1, 1).AddHours(i), r.GetDateTime(4)); + Assert.Equal(i / 3.0, r.GetDouble(5)); + Assert.Equal((Guid)rows[i][6]!, r.GetGuid(6)); + Assert.Equal(i % 2 == 0, r.GetBool(7)); + } + } + + [Test] + public async Task FailingBulkProducerLeavesTableUntouched() + { + await using var session = await (await OpenDatabaseAsync()).OpenAsync(Ct); + await session.ExecuteScriptAsync("CREATE TABLE b (id integer PRIMARY KEY)", Ct); + async IAsyncEnumerable Rows() + { + for (var i = 0; i < 1000; i++) + { + if (i == 700) throw new InvalidDataException("producer failed"); + yield return [i]; + await Task.Yield(); + } + } + await Assert.ThrowsAsync(() => session.BulkInsertAsync("b", ["id"], Rows(), Ct)); + Assert.Equal(0L, await session.ScalarAsync("SELECT count(*) FROM b", [], Ct)); + } + + [Test] + public async Task AbandonedQueryLeavesSessionUsable() + { + await using var session = await (await OpenDatabaseAsync()).OpenAsync(Ct); + await session.ExecuteScriptAsync("CREATE TABLE q (id integer PRIMARY KEY)", Ct); + await session.BulkInsertAsync("q", ["id"], Enumerable.Range(0, 2000).Select(i => new object?[] { i }).ToAsyncEnumerable(), Ct); + await foreach (var row in session.QueryAsync("SELECT id FROM q ORDER BY id", [], Ct)) + { + Assert.Equal(0, row.GetInt32(0)); + break; + } + Assert.Equal(1999, await session.ScalarAsync("SELECT max(id) FROM q", [], Ct)); + Assert.Equal(2000L, await session.ScalarAsync("SELECT count(*) FROM q", [], Ct)); + } + + [Test] + public async Task SingleRowHelpersEnforceCardinality() + { + await using var session = await (await OpenDatabaseAsync()).OpenAsync(Ct); + await session.ExecuteScriptAsync("CREATE TABLE s (id integer PRIMARY KEY); INSERT INTO s (id) VALUES (1); INSERT INTO s (id) VALUES (2)", Ct); + Assert.Null(await session.QuerySingleOrDefaultAsync("SELECT id FROM s WHERE id = $1", [9], Ct)); + await Assert.ThrowsAsync(() => session.QuerySingleAsync("SELECT id FROM s WHERE id = $1", [9], Ct)); + await Assert.ThrowsAsync(() => session.QuerySingleOrDefaultAsync("SELECT id FROM s", [], Ct)); + Assert.Equal(0, await session.ScalarAsync("SELECT id FROM s WHERE id = $1", [9], Ct)); + Assert.Null(await session.ScalarAsync("SELECT id FROM s WHERE id = $1", [9], Ct)); + Assert.Equal("2", await session.ScalarAsync("SELECT max(id) FROM s", [], Ct)); + } + + [Test] + public async Task CancellationStopsALongQueryQuickly() + { + var database = await OpenDatabaseAsync(); + await using var session = await database.OpenAsync(Ct); + var sql = ForDialect( + "WITH RECURSIVE r(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM r WHERE n < 2000000000) SELECT count(*) FROM r", + "SELECT pg_sleep(10)"); + using var cts = CancellationTokenSource.CreateLinkedTokenSource(Ct); + cts.CancelAfter(300); + var watch = Stopwatch.StartNew(); + await Assert.ThrowsAsync(() => session.ExecuteAsync(sql, [], cts.Token)); + Assert.Less(watch.Elapsed.TotalSeconds, 2.0, "cancellation latency"); + Assert.Equal(1, await session.ScalarAsync("SELECT 1", [], Ct)); + } +} + +public sealed class SqliteSessionTests(TestContext context) : SessionTests(context) +{ + protected override Backend Backend => Backend.SqliteMemory; +} + +[RequiresEnvironment(PgTestServer.Variable)] +public sealed class PostgresSessionTests(TestContext context) : SessionTests(context) +{ + protected override Backend Backend => Backend.Postgres; +} diff --git a/tests/Titano.Data.Tests/Sqlite/SqliteBindingTests.cs b/tests/Titano.Data.Tests/Sqlite/SqliteBindingTests.cs new file mode 100644 index 00000000..f0ddbc6b --- /dev/null +++ b/tests/Titano.Data.Tests/Sqlite/SqliteBindingTests.cs @@ -0,0 +1,178 @@ +using Titano.Data.Sqlite; +using Titano.Data.Tests.Infrastructure; +using Titano.Testing; + +namespace Titano.Data.Tests.Sqlite; + +public sealed class SqliteBindingTests(TestContext context) : DatabaseTest(context) +{ + protected override Backend Backend => Backend.SqliteFile; + + [Test] + public void SystemLibraryIsRecentEnough() + { + var parts = SqliteDatabase.LibraryVersion.Split('.').Select(int.Parse).ToArray(); + Assert.True(parts[0] > 3 || (parts[0] == 3 && parts[1] >= 31), $"SQLite {SqliteDatabase.LibraryVersion}"); + } + + [Test] + public async Task ConnectionsUseTheBriefPragmas() + { + await using var session = await (await OpenDatabaseAsync()).OpenAsync(Ct); + Assert.Equal("wal", await session.ScalarAsync("PRAGMA journal_mode", [], Ct)); + Assert.Equal(1L, await session.ScalarAsync("PRAGMA synchronous", [], Ct)); + Assert.Equal(1L, await session.ScalarAsync("PRAGMA foreign_keys", [], Ct)); + Assert.Equal(2L, await session.ScalarAsync("PRAGMA temp_store", [], Ct)); + Assert.Equal(-65536L, await session.ScalarAsync("PRAGMA cache_size", [], Ct)); + Assert.Equal(268435456L, await session.ScalarAsync("PRAGMA mmap_size", [], Ct)); + } + + [Test] + public async Task RejectsScriptsAndWrongParameterCounts() + { + await using var session = await (await OpenDatabaseAsync()).OpenAsync(Ct); + await Assert.ThrowsAsync(() => session.ExecuteAsync("SELECT 1; SELECT 2", [], Ct)); + await Assert.ThrowsAsync(() => session.ExecuteAsync("SELECT $1, $2", [1], Ct)); + Assert.Equal(1, await session.ScalarAsync("SELECT 1 -- trailing comment", [], Ct)); + var error = await Assert.ThrowsAsync(() => session.ExecuteAsync("SELEC 1", [], Ct)); + Assert.Equal(1, error.ResultCode); + } + + [Test] + public async Task WritersFromManySessionsAreSerialised() + { + var database = await OpenDatabaseAsync(multiConnection: true); + await using (var setup = await database.OpenAsync(Ct)) + await setup.ExecuteScriptAsync("CREATE TABLE counter (id INTEGER PRIMARY KEY, n INTEGER NOT NULL); INSERT INTO counter VALUES (1, 0)", Ct); + + await Task.WhenAll(Enumerable.Range(0, 8).Select(_ => Task.Run(async () => + { + for (var i = 0; i < 25; i++) + { + await using var session = await database.OpenAsync(Ct); + await using var tx = await session.BeginAsync(Ct); + var n = await session.ScalarAsync("SELECT n FROM counter WHERE id = 1", [], Ct); + await session.ExecuteAsync("UPDATE counter SET n = $1 WHERE id = 1", [n + 1], Ct); + await tx.CommitAsync(Ct); + } + }))); + + await using var check = await database.OpenAsync(Ct); + Assert.Equal(200L, await check.ScalarAsync("SELECT n FROM counter", [], Ct)); + } + + [Test] + public async Task ReadersSeeTheLastCommitWhileAWriterIsOpen() + { + var database = await OpenDatabaseAsync(multiConnection: true); + await using var writer = await database.OpenAsync(Ct); + await writer.ExecuteScriptAsync("CREATE TABLE r (id INTEGER PRIMARY KEY); INSERT INTO r VALUES (1)", Ct); + await using var tx = await writer.BeginAsync(Ct); + await writer.ExecuteAsync("INSERT INTO r VALUES ($1)", [2], Ct); + + await using var reader = await database.OpenAsync(Ct); + Assert.Equal(1L, await reader.ScalarAsync("SELECT count(*) FROM r", [], Ct)); + await tx.CommitAsync(Ct); + Assert.Equal(2L, await reader.ScalarAsync("SELECT count(*) FROM r", [], Ct)); + } + + [Test] + public async Task SameStatementCanRunNestedOnOneSession() + { + await using var session = await (await OpenDatabaseAsync()).OpenAsync(Ct); + await session.ExecuteScriptAsync("CREATE TABLE r (id INTEGER PRIMARY KEY); INSERT INTO r VALUES (1); INSERT INTO r VALUES (2)", Ct); + var pairs = 0; + await foreach (var outer in session.QueryAsync("SELECT id FROM r ORDER BY id", [], Ct)) + { + await foreach (var inner in session.QueryAsync("SELECT id FROM r ORDER BY id", [], Ct)) + { + pairs++; + Assert.True(inner.GetInt32(0) is 1 or 2 && outer.GetInt32(0) is 1 or 2); + } + } + Assert.Equal(4, pairs); + } + + [Test] + public async Task BackupKeepsTheThreeNewestAndRestoreBringsDataBack() + { + var path = Path.Combine(Context.CreateTempDirectory(), "titano.db"); + var backups = Context.CreateTempDirectory(); + var database = (SqliteDatabase)Own(DatabaseFactory.Open(DatabaseOptions.Sqlite(path))); + await using (var session = await database.OpenAsync(Ct)) + await session.ExecuteScriptAsync("CREATE TABLE b (id INTEGER PRIMARY KEY, v TEXT); INSERT INTO b VALUES (1, 'original')", Ct); + + var first = await database.BackupAsync(backups, cancellationToken: Ct); + Assert.FileExists(first); + for (var i = 0; i < 4; i++) await database.BackupAsync(backups, cancellationToken: Ct); + var kept = Directory.GetFiles(backups).OrderBy(f => f, StringComparer.Ordinal).ToList(); + Assert.Equal(3, kept.Count); + Assert.DoesNotContain(first, kept); + + await using (var session = await database.OpenAsync(Ct)) + await session.ExecuteAsync("UPDATE b SET v = $1", ["changed"], Ct); + await database.RestoreAsync(kept[^1], Ct); + + await using (var session = await database.OpenAsync(Ct)) + Assert.Equal("original", await session.ScalarAsync("SELECT v FROM b WHERE id = 1", [], Ct)); + } + + [Test] + public async Task RestoreWaitsForSessionsThatStillWrite() + { + var path = Path.Combine(Context.CreateTempDirectory(), "titano.db"); + var database = (SqliteDatabase)Own(DatabaseFactory.Open(DatabaseOptions.Sqlite(path))); + await using (var setup = await database.OpenAsync(Ct)) + await setup.ExecuteScriptAsync("CREATE TABLE b (id INTEGER PRIMARY KEY)", Ct); + var backup = await database.BackupAsync(Context.CreateTempDirectory(), cancellationToken: Ct); + + var session = await database.OpenAsync(Ct); + var restore = database.RestoreAsync(backup, Ct); + await Task.Delay(100, Ct); + Assert.False(restore.IsCompleted, "restore must wait for the open session"); + // The session can still take the write lock while the restore waits for its pool slot. + await session.ExecuteAsync("INSERT INTO b VALUES ($1)", [1], Ct); + await using (var tx = await session.BeginAsync(Ct)) await tx.CommitAsync(Ct); + await session.DisposeAsync(); + await restore.WaitAsync(TimeSpan.FromSeconds(10), Ct); + + await using var check = await database.OpenAsync(Ct); + Assert.Equal(0L, await check.ScalarAsync("SELECT count(*) FROM b", [], Ct)); + } + + [Test] + public async Task RestoreRefusesAFileThatIsNotADatabase() + { + var database = (SqliteDatabase)await OpenDatabaseAsync(); + var bogus = Path.Combine(Context.CreateTempDirectory(), "bogus.db"); + await File.WriteAllTextAsync(bogus, "not a database, just text that is long enough to have a header", Ct); + await Assert.ThrowsAsync(() => database.RestoreAsync(bogus, Ct)); + await using var session = await database.OpenAsync(Ct); + Assert.Equal(1, await session.ScalarAsync("SELECT 1", [], Ct)); + } + + [Test] + public async Task InMemoryDatabasesAreIsolated() + { + var a = Own(DatabaseFactory.Open(DatabaseOptions.SqliteInMemory())); + var b = Own(DatabaseFactory.Open(DatabaseOptions.SqliteInMemory())); + await using (var s = await a.OpenAsync(Ct)) await s.ExecuteScriptAsync("CREATE TABLE only_a (id INTEGER)", Ct); + await using var sb = await b.OpenAsync(Ct); + Assert.Equal(0L, await sb.ScalarAsync("SELECT count(*) FROM sqlite_master WHERE name = 'only_a'", [], Ct)); + await Assert.ThrowsAsync(() => ((SqliteDatabase)a).RestoreAsync("x.db", Ct)); + } +} + +public sealed class SqliteSqlTextTests +{ + [Theory] + [Case("SELECT $1", "SELECT ?1")] + [Case("SELECT $2, $1, $12", "SELECT ?2, ?1, ?12")] + [Case("SELECT '$1', \"$2\", [$3], `$4` FROM t WHERE a = $5", "SELECT '$1', \"$2\", [$3], `$4` FROM t WHERE a = ?5")] + [Case("SELECT 'it''s $1' || $1", "SELECT 'it''s $1' || ?1")] + [Case("SELECT $1 -- $2\n, $3 /* $4 */", "SELECT ?1 -- $2\n, ?3 /* $4 */")] + [Case("SELECT a$1 FROM t", "SELECT a$1 FROM t")] + [Case("SELECT 'unterminated $1", "SELECT 'unterminated $1")] + public void TranslatesPlaceholdersOutsideLiterals(string sql, string expected) => + Assert.Equal(expected, SqliteSqlText.TranslatePlaceholders(sql)); +}