Files
Khaemhat/src/Khaemhat.Data/Companies/CompanyRegistry.cs
T
Alby96andClaude Opus 5.5 738c43ba0a
CI / Build and test (SQLite) (pull_request) Successful in 45s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / YAML check (pull_request) Successful in 3s
CI / Docker image (pull_request) Successful in 51s
feat: data layer with SQLite and PostgreSQL providers, migrations and encrypted company registry (M1)
Every later milestone stores its data through this layer, so it has to behave the same on both engines and be safe
by construction:

- Khaemhat.Data: explicit entity maps, typed queries over a safe expression subset, SqlFragment where every
  interpolated value becomes a parameter, unit of work with transactions, repositories with audit columns and
  optimistic concurrency on row_version, retries on transient errors.
- SQLite provider (STRICT tables, WAL, exact decimals as integers scaled by 10^6, Unicode case-insensitive LIKE,
  serialised writes) and PostgreSQL 16+ provider (numeric(19,6), timestamptz, jsonb, advisory locks, database
  creation and server info). Databases are configured from postgres:// and sqlite:// URLs whose password never
  appears in messages.
- C# migrations with system and company catalogues, schema_version with checksums, one transaction per migration
  under a lock, refusal of unknown applied versions; first system tables sys_companies and sys_settings.
- CompanyRegistry stores each company's database URL encrypted with the instance key (AES-256-GCM, HKDF-derived key,
  purpose as associated data), so a copied row cannot be read for another company.
- tools/Khaemhat.DataModelTool, scripts/gen-datamodel.sh and scripts/new-migration.sh: the current schema section of
  docs/DATA-MODEL.md is generated from the migrations and a test fails when it is stale.
- C# 14 binds array.Contains to MemoryExtensions over spans; the query translator unwraps the span conversion.
- Tests run every data scenario on SQLite and PostgreSQL (PostgreSQL in CI); ADR 0018 records where the contracts
  differ from SPEC 5.1. Docs, wiki, changelog and status updated.

Closes #7, #8, #9, #10, #11, #12, #13, #14

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 13:11:34 +01:00

201 lines
9.5 KiB
C#

using System.Collections.Concurrent;
using Khaemhat.Core.Instance;
using Khaemhat.Core.Security;
using Khaemhat.Data.Execution;
using Khaemhat.Data.Mapping;
using Khaemhat.Data.Querying;
namespace Khaemhat.Data.Companies;
/// <summary>A company to add to the registry.</summary>
/// <param name="Code">The company code.</param>
/// <param name="Name">The company name.</param>
/// <param name="Database">Where its database is (printed redacted).</param>
/// <param name="IsDefault">Whether it becomes the default company.</param>
/// <param name="Notes">Notes for administrators.</param>
public sealed record CompanyRegistration(string Code, string Name, DatabaseUrl Database, bool IsDefault = false, string? Notes = null);
/// <summary>
/// The company registry in the system database (SPEC §5.4): it resolves <c>company code → (provider, connection
/// string)</c>, decrypting the location stored in <c>sys_companies</c>.
/// </summary>
public interface ICompanyRegistry
{
/// <summary>All companies, by code.</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The companies (their location stays encrypted).</returns>
Task<IReadOnlyList<Company>> ListAsync(CancellationToken cancellationToken = default);
/// <summary>A company by code.</summary>
/// <param name="code">The code.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The company, or <see langword="null"/>.</returns>
Task<Company?> FindAsync(string code, CancellationToken cancellationToken = default);
/// <summary>Adds a company whose database already exists or will be created by the caller.</summary>
/// <param name="registration">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The stored company.</returns>
Task<Company> RegisterAsync(CompanyRegistration registration, CancellationToken cancellationToken = default);
/// <summary>The database of a company.</summary>
/// <param name="code">The code.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The target.</returns>
/// <exception cref="KeyNotFoundException">No company has that code.</exception>
Task<DatabaseTarget> ResolveAsync(string code, CancellationToken cancellationToken = default);
/// <summary>Changes the state of a company.</summary>
/// <param name="code">The code.</param>
/// <param name="status">The new state.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
Task SetStatusAsync(string code, CompanyStatus status, CancellationToken cancellationToken = default);
}
/// <summary>
/// <see cref="ICompanyRegistry"/> on <c>sys_companies</c>. The database URL is encrypted with
/// <see cref="ISecretProtector"/> for the purpose <c>company:&lt;code&gt;:database</c>, so a row copied to another company
/// cannot be decrypted. Resolved targets are cached until the row changes through this registry.
/// </summary>
public sealed class CompanyRegistry : ICompanyRegistry
{
private readonly DatabaseTarget _system;
private readonly DbProviderCatalog _providers;
private readonly ISecretProtector _protector;
private readonly MapRegistry _maps;
private readonly DataAccessContext _context;
private readonly ConcurrentDictionary<string, DatabaseTarget> _resolved = new(StringComparer.Ordinal);
/// <summary>Creates the registry.</summary>
/// <param name="system">The system database.</param>
/// <param name="providers">The providers by engine.</param>
/// <param name="protector">Encrypts the database locations.</param>
/// <param name="maps">The entity maps, including <see cref="SystemDatabase.CompanyMap"/>.</param>
/// <param name="context">Clock, user and retry policy.</param>
public CompanyRegistry(DatabaseTarget system, DbProviderCatalog providers, ISecretProtector protector, MapRegistry maps, DataAccessContext context)
{
ArgumentNullException.ThrowIfNull(system);
ArgumentNullException.ThrowIfNull(providers);
ArgumentNullException.ThrowIfNull(protector);
ArgumentNullException.ThrowIfNull(maps);
ArgumentNullException.ThrowIfNull(context);
_system = system;
_providers = providers;
_protector = protector;
_maps = maps;
_context = context;
}
/// <summary>The purpose used to encrypt the database location of a company.</summary>
/// <param name="code">The normalized code.</param>
/// <returns>The purpose.</returns>
public static string Purpose(string code) => "company:" + code + ":database";
/// <inheritdoc />
public async Task<IReadOnlyList<Company>> ListAsync(CancellationToken cancellationToken = default)
{
await using var unitOfWork = await OpenAsync(cancellationToken).ConfigureAwait(false);
var page = await unitOfWork.Repository<Company, long>().ListAsync(Query.For<Company>().OrderBy(c => c.Code), cancellationToken).ConfigureAwait(false);
return page.Items;
}
/// <inheritdoc />
public async Task<Company?> FindAsync(string code, CancellationToken cancellationToken = default)
{
var normalized = CompanyCodes.Normalize(code);
await using var unitOfWork = await OpenAsync(cancellationToken).ConfigureAwait(false);
return await unitOfWork.Repository<Company, long>().FindAsync(Query.For<Company>().Where(c => c.Code == normalized), cancellationToken)
.ConfigureAwait(false);
}
/// <inheritdoc />
public async Task<Company> RegisterAsync(CompanyRegistration registration, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(registration);
ArgumentException.ThrowIfNullOrWhiteSpace(registration.Name);
var code = CompanyCodes.Normalize(registration.Code);
_ = _providers.Get(registration.Database.Engine);
var company = new Company
{
Code = code,
Name = registration.Name.Trim(),
Engine = registration.Database.Engine.ToString(),
ConnectionString = _protector.Protect(registration.Database.ToUnredactedString(), Purpose(code)),
Status = CompanyStatus.Active,
IsDefault = registration.IsDefault,
Notes = registration.Notes,
};
await using var unitOfWork = await OpenAsync(cancellationToken).ConfigureAwait(false);
var companies = unitOfWork.Repository<Company, long>();
await unitOfWork.InTransactionAsync(
async ct =>
{
if (await companies.CountAsync(Query.For<Company>().Where(c => c.Code == code), ct).ConfigureAwait(false) > 0)
{
throw new InvalidOperationException($"A company with code {code} already exists.");
}
if (company.IsDefault)
{
await unitOfWork.ExecuteAsync(
SqlFragment.Of($"UPDATE {SqlFragment.Identifier("sys_companies")} SET is_default = {false} WHERE is_default = {true}"), ct)
.ConfigureAwait(false);
}
await companies.InsertAsync(company, ct).ConfigureAwait(false);
},
cancellationToken).ConfigureAwait(false);
_resolved.TryRemove(code, out _);
return company;
}
/// <inheritdoc />
public async Task<DatabaseTarget> ResolveAsync(string code, CancellationToken cancellationToken = default)
{
var normalized = CompanyCodes.Normalize(code);
if (_resolved.TryGetValue(normalized, out var cached))
{
return cached;
}
var company = await FindAsync(normalized, cancellationToken).ConfigureAwait(false)
?? throw new KeyNotFoundException($"No company has code {normalized}.");
var url = DatabaseUrl.Parse(_protector.Unprotect(company.ConnectionString, Purpose(normalized)));
var target = _providers.Resolve(url);
_resolved[normalized] = target;
return target;
}
/// <inheritdoc />
public async Task SetStatusAsync(string code, CompanyStatus status, CancellationToken cancellationToken = default)
{
var normalized = CompanyCodes.Normalize(code);
await using var unitOfWork = await OpenAsync(cancellationToken).ConfigureAwait(false);
var companies = unitOfWork.Repository<Company, long>();
var company = await companies.FindAsync(Query.For<Company>().Where(c => c.Code == normalized), cancellationToken).ConfigureAwait(false)
?? throw new KeyNotFoundException($"No company has code {normalized}.");
company.Status = status;
await companies.UpdateAsync(company, cancellationToken).ConfigureAwait(false);
_resolved.TryRemove(normalized, out _);
}
private Task<UnitOfWork> OpenAsync(CancellationToken cancellationToken) => UnitOfWork.OpenAsync(_system, _maps, _context, cancellationToken);
}
/// <summary>Finds the system database, or a company database through the registry.</summary>
/// <param name="system">The system database.</param>
/// <param name="companies">The company registry.</param>
public sealed class DatabaseLocator(DatabaseTarget system, ICompanyRegistry companies) : IDatabaseLocator
{
/// <inheritdoc />
public async ValueTask<DatabaseTarget> LocateAsync(DatabaseScope scope, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(scope);
return scope.IsSystem ? system : await companies.ResolveAsync(scope.CompanyCode!, cancellationToken).ConfigureAwait(false);
}
}