CI / Build and test (SQLite) (pull_request) Successful in 55s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / YAML check (pull_request) Successful in 5s
CI / Docker image (pull_request) Failing after 2m4s
The instance now starts on its own from KHAEMHAT_* variables: it migrates the system and company databases, creates the super user and the first company, and only then reports ready. Users sign in with password and TOTP through revocable database sessions, and licences decide which modules and how many companies are available. - Configuration: every wrong variable reported at once (exit code 2), _FILE variants - Accounts, password policy and lockout, TOTP with recovery codes, session states with token rotation, security audit with a hash chain - Sign-in pages (mockups 001-003), authorization attributes, security headers and a CSP without inline scripts, login rate limit - Signed licences, activation codes, test mode, licence tool - DataProtection keys in the system database, encrypted with the instance key - Memory or Redis cache (in-house RESP client) that falls back to memory - Database log by section with trace id; cron scheduler with locks and system jobs; record history (audit_log) - Company creation, states, company context and X-Company, 503 in maintenance - In-memory SQLite databases stay alive for the process (tests, demo) - Tests for all of the above, ADR 0019, wiki, SECURITY, CHANGELOG, STATUS, DATA-MODEL Refs #15 #16 #17 #18 #19 #20 #21 #22 #23 #24 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
169 lines
7.4 KiB
C#
169 lines
7.4 KiB
C#
using System.Collections.Concurrent;
|
|
using System.Data;
|
|
using System.Data.Common;
|
|
using System.Globalization;
|
|
using Khaemhat.Data.Schema;
|
|
using Microsoft.Data.Sqlite;
|
|
|
|
namespace Khaemhat.Data.Sqlite;
|
|
|
|
/// <summary>
|
|
/// The SQLite engine (SPEC §1.3, §5.2): tests, demo, trial and read-only archives. Every connection gets
|
|
/// <c>foreign_keys=ON</c> and <c>busy_timeout=5000</c>; file databases use <c>journal_mode=WAL</c>. Databases are files
|
|
/// under <c>KHAEMHAT_DATA_DIR</c>, or in-memory databases shared by the connections of the process (tests).
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// An in-memory database disappears with its last connection: <see cref="EnsureDatabaseExistsAsync"/> opens one that
|
|
/// stays open for the life of the process (or until <see cref="DropDatabaseAsync"/>), so the database lives as long as
|
|
/// the instance that created it.
|
|
/// </remarks>
|
|
public sealed class SqliteProvider : IDbProvider
|
|
{
|
|
private const int BusyTimeoutMilliseconds = 5000;
|
|
private static readonly ConcurrentDictionary<string, SqliteConnection> MemoryKeepers = new(StringComparer.Ordinal);
|
|
|
|
/// <inheritdoc />
|
|
public DbEngine Engine => DbEngine.Sqlite;
|
|
|
|
/// <inheritdoc />
|
|
public ISqlDialect Dialect => SqliteDialect.Instance;
|
|
|
|
/// <inheritdoc />
|
|
public DdlGenerator Ddl { get; } = new SqliteSchemaBuilder();
|
|
|
|
/// <inheritdoc />
|
|
public string BuildConnectionString(DatabaseUrl url)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(url);
|
|
if (url.Engine != DbEngine.Sqlite)
|
|
{
|
|
throw new ArgumentException("Not a SQLite URL.", nameof(url));
|
|
}
|
|
|
|
var builder = url.IsInMemory
|
|
? new SqliteConnectionStringBuilder { DataSource = url.Database, Mode = SqliteOpenMode.Memory, Cache = SqliteCacheMode.Shared }
|
|
: new SqliteConnectionStringBuilder { DataSource = Path.GetFullPath(url.Database), Mode = SqliteOpenMode.ReadWriteCreate };
|
|
builder.Pooling = true;
|
|
builder.DefaultTimeout = 30;
|
|
return builder.ToString();
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public DbConnection CreateConnection(string connectionString)
|
|
{
|
|
var connection = new SqliteConnection(connectionString);
|
|
connection.CreateFunction<string?, string?>(SqliteDialect.LowerFunction, static s => s?.ToLowerInvariant(), isDeterministic: true);
|
|
var isFile = IsFile(connectionString);
|
|
connection.StateChange += (sender, args) =>
|
|
{
|
|
if (args.CurrentState == ConnectionState.Open && sender is SqliteConnection open)
|
|
{
|
|
ApplyPragmas(open, isFile);
|
|
}
|
|
};
|
|
return connection;
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public async Task EnsureDatabaseExistsAsync(string connectionString, CancellationToken cancellationToken = default)
|
|
{
|
|
if (!IsFile(connectionString))
|
|
{
|
|
var name = new SqliteConnectionStringBuilder(connectionString).DataSource;
|
|
if (!MemoryKeepers.ContainsKey(name))
|
|
{
|
|
var keeper = new SqliteConnection(connectionString);
|
|
await keeper.OpenAsync(cancellationToken).ConfigureAwait(false);
|
|
if (!MemoryKeepers.TryAdd(name, keeper))
|
|
{
|
|
await keeper.DisposeAsync().ConfigureAwait(false);
|
|
}
|
|
}
|
|
|
|
return;
|
|
}
|
|
|
|
var path = new SqliteConnectionStringBuilder(connectionString).DataSource;
|
|
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!);
|
|
await using var connection = CreateConnection(connectionString);
|
|
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public Task DropDatabaseAsync(string connectionString, CancellationToken cancellationToken = default)
|
|
{
|
|
if (!IsFile(connectionString))
|
|
{
|
|
if (MemoryKeepers.TryRemove(new SqliteConnectionStringBuilder(connectionString).DataSource, out var keeper))
|
|
{
|
|
keeper.Dispose();
|
|
}
|
|
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
using (var connection = new SqliteConnection(connectionString))
|
|
{
|
|
SqliteConnection.ClearPool(connection);
|
|
}
|
|
|
|
var path = new SqliteConnectionStringBuilder(connectionString).DataSource;
|
|
foreach (var file in new[] { path, path + "-wal", path + "-shm", path + "-journal" })
|
|
{
|
|
File.Delete(file);
|
|
}
|
|
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public Task<bool> DatabaseExistsAsync(string connectionString, CancellationToken cancellationToken = default) =>
|
|
Task.FromResult(!IsFile(connectionString) || File.Exists(new SqliteConnectionStringBuilder(connectionString).DataSource));
|
|
|
|
/// <inheritdoc />
|
|
public async Task<DbServerInfo> GetServerInfoAsync(string connectionString, CancellationToken cancellationToken = default)
|
|
{
|
|
await using var connection = CreateConnection(connectionString);
|
|
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
|
|
var version = (string)(await ScalarAsync(connection, "SELECT sqlite_version()", cancellationToken).ConfigureAwait(false))!;
|
|
var pages = Convert.ToInt64(await ScalarAsync(connection, "PRAGMA page_count", cancellationToken).ConfigureAwait(false), CultureInfo.InvariantCulture);
|
|
var pageSize = Convert.ToInt64(await ScalarAsync(connection, "PRAGMA page_size", cancellationToken).ConfigureAwait(false), CultureInfo.InvariantCulture);
|
|
var journal = Convert.ToString(await ScalarAsync(connection, "PRAGMA journal_mode", cancellationToken).ConfigureAwait(false), CultureInfo.InvariantCulture);
|
|
var parts = version.Split('.').Select(p => int.Parse(p, CultureInfo.InvariantCulture)).Concat([0, 0, 0]).ToArray();
|
|
var source = new SqliteConnectionStringBuilder(connectionString).DataSource;
|
|
return new DbServerInfo(
|
|
DbEngine.Sqlite, version, (parts[0] * 1_000_000) + (parts[1] * 1_000) + parts[2],
|
|
IsFile(connectionString) ? Path.GetFileNameWithoutExtension(source) : source, pages * pageSize)
|
|
{
|
|
Details = ["journal_mode=" + journal],
|
|
};
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public bool IsTransient(Exception exception) =>
|
|
exception is SqliteException { SqliteErrorCode: 5 or 6 }; // SQLITE_BUSY, SQLITE_LOCKED
|
|
|
|
/// <inheritdoc />
|
|
public ValueTask<IAsyncDisposable> EnterWriteScopeAsync(string connectionString, CancellationToken cancellationToken = default) =>
|
|
SqliteWriteLock.AcquireAsync(new SqliteConnectionStringBuilder(connectionString).DataSource, cancellationToken);
|
|
|
|
private static bool IsFile(string connectionString) =>
|
|
new SqliteConnectionStringBuilder(connectionString).Mode != SqliteOpenMode.Memory;
|
|
|
|
private static void ApplyPragmas(SqliteConnection connection, bool isFile)
|
|
{
|
|
using var command = connection.CreateCommand();
|
|
command.CommandText = isFile
|
|
? $"PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout={BusyTimeoutMilliseconds};"
|
|
: $"PRAGMA foreign_keys=ON; PRAGMA busy_timeout={BusyTimeoutMilliseconds};";
|
|
command.ExecuteNonQuery();
|
|
}
|
|
|
|
private static async Task<object?> ScalarAsync(DbConnection connection, string sql, CancellationToken cancellationToken)
|
|
{
|
|
await using var command = connection.CreateCommand();
|
|
command.CommandText = sql;
|
|
return await command.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false);
|
|
}
|
|
}
|