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; /// A company to add to the registry. /// The company code. /// The company name. /// Where its database is (printed redacted). /// Whether it becomes the default company. /// Notes for administrators. public sealed record CompanyRegistration(string Code, string Name, DatabaseUrl Database, bool IsDefault = false, string? Notes = null); /// /// The company registry in the system database (SPEC §5.4): it resolves company code → (provider, connection /// string), decrypting the location stored in sys_companies. /// public interface ICompanyRegistry { /// All companies, by code. /// Cancellation. /// The companies (their location stays encrypted). Task> ListAsync(CancellationToken cancellationToken = default); /// A company by code. /// The code. /// Cancellation. /// The company, or . Task FindAsync(string code, CancellationToken cancellationToken = default); /// Adds a company whose database already exists or will be created by the caller. /// The company. /// Cancellation. /// The stored company. Task RegisterAsync(CompanyRegistration registration, CancellationToken cancellationToken = default); /// The database of a company. /// The code. /// Cancellation. /// The target. /// No company has that code. Task ResolveAsync(string code, CancellationToken cancellationToken = default); /// Changes the state of a company. /// The code. /// The new state. /// Cancellation. /// A task. Task SetStatusAsync(string code, CompanyStatus status, CancellationToken cancellationToken = default); } /// /// on sys_companies. The database URL is encrypted with /// for the purpose company:<code>:database, so a row copied to another company /// cannot be decrypted. Resolved targets are cached until the row changes through this registry. /// 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 _resolved = new(StringComparer.Ordinal); /// Creates the registry. /// The system database. /// The providers by engine. /// Encrypts the database locations. /// The entity maps, including . /// Clock, user and retry policy. 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; } /// The purpose used to encrypt the database location of a company. /// The normalized code. /// The purpose. public static string Purpose(string code) => "company:" + code + ":database"; /// public async Task> ListAsync(CancellationToken cancellationToken = default) { await using var unitOfWork = await OpenAsync(cancellationToken).ConfigureAwait(false); var page = await unitOfWork.Repository().ListAsync(Query.For().OrderBy(c => c.Code), cancellationToken).ConfigureAwait(false); return page.Items; } /// public async Task FindAsync(string code, CancellationToken cancellationToken = default) { var normalized = CompanyCodes.Normalize(code); await using var unitOfWork = await OpenAsync(cancellationToken).ConfigureAwait(false); return await unitOfWork.Repository().FindAsync(Query.For().Where(c => c.Code == normalized), cancellationToken) .ConfigureAwait(false); } /// public async Task 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(); await unitOfWork.InTransactionAsync( async ct => { if (await companies.CountAsync(Query.For().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; } /// public async Task 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; } /// 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(); var company = await companies.FindAsync(Query.For().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 OpenAsync(CancellationToken cancellationToken) => UnitOfWork.OpenAsync(_system, _maps, _context, cancellationToken); } /// Finds the system database, or a company database through the registry. /// The system database. /// The company registry. public sealed class DatabaseLocator(DatabaseTarget system, ICompanyRegistry companies) : IDatabaseLocator { /// public async ValueTask LocateAsync(DatabaseScope scope, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(scope); return scope.IsSystem ? system : await companies.ResolveAsync(scope.CompanyCode!, cancellationToken).ConfigureAwait(false); } }