using System.Globalization;
using Khaemhat.Application.Audit;
using Khaemhat.Application.Configuration;
using Khaemhat.Application.Dashboard;
using Khaemhat.Application.Files;
using Khaemhat.Application.Instance;
using Khaemhat.Application.Jobs;
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Localization;
using Khaemhat.Application.Modules;
using Khaemhat.Application.Notifications;
using Khaemhat.Application.Preferences;
using Khaemhat.Application.Security;
using Khaemhat.Core.Caching;
using Khaemhat.Core.Files;
using Khaemhat.Core.Logging;
using Khaemhat.Core.Security;
using Khaemhat.Data;
using Khaemhat.Data.Companies;
using Khaemhat.Data.Execution;
using Khaemhat.Data.Mapping;
using Khaemhat.Data.Migrations;
using Khaemhat.Data.PostgreSql;
using Khaemhat.Data.Sqlite;
using Khaemhat.Infrastructure.Caching;
using Khaemhat.Infrastructure.Files;
using Khaemhat.Infrastructure.Licensing;
using Khaemhat.Infrastructure.Logging;
using Khaemhat.Infrastructure.Security;
using Khaemhat.Web.Security;
using Khaemhat.Web.Shell;
namespace Khaemhat.Web.Hosting;
///
/// The composition of the instance (SPEC §3): data access on the configured databases, security, licences, log and
/// the start sequence. Services are singletons: they hold no per-request state and open a unit of work per call.
///
internal static class KhaemhatServices
{
/// The culture of the interface and of number and date formats (SPEC §10.8).
internal static readonly CultureInfo ItalianCulture = CultureInfo.GetCultureInfo("it-IT");
/// Registers every service of the instance.
/// The container.
/// The validated variables.
/// The database log queue, already plugged into the logging pipeline.
/// The container.
public static IServiceCollection AddKhaemhat(this IServiceCollection services, KhaemhatOptions options, DbLogSink logSink)
{
var dataAssembly = typeof(CompanyRegistry).Assembly;
services.AddSingleton(options);
services.AddSingleton(logSink);
services.AddSingleton(TimeProvider.System);
services.AddSingleton();
services.AddHttpContextAccessor();
services.AddSingleton();
// Secrets and data access.
services.AddSingleton(SecretKey.FromBase64(options.SecretKey!));
services.AddSingleton();
services.AddSingleton(sp => sp.GetRequiredService());
services.AddSingleton(new DbProviderCatalog(new SqliteProvider(), new PostgresProvider()));
services.AddSingleton(new MapRegistry().AddFromAssembly(dataAssembly));
services.AddSingleton(sp =>
{
var slow = sp.GetRequiredService().CreateLogger("Khaemhat.Performance.SlowQueries");
var user = sp.GetRequiredService();
return new DataAccessContext(sp.GetRequiredService(), user.Get)
{
SlowQueryObserver = query =>
{
using var section = slow.BeginScope(LogSections.Scope(LogSection.Performance));
slow.LogWarning(
"Slow query on {Database}: {Milliseconds} ms. {Sql}",
query.Database, (long)query.Duration.TotalMilliseconds, query.Sql.Length > 2000 ? query.Sql[..2000] : query.Sql);
},
};
});
services.AddSingleton(sp => sp.GetRequiredService().Resolve(options.SystemDatabase));
services.AddSingleton(sp => new CompanyRegistry(
sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService(),
sp.GetRequiredService(), sp.GetRequiredService()));
services.AddSingleton(sp => new DatabaseLocator(sp.GetRequiredService(), sp.GetRequiredService()));
services.AddSingleton();
services.AddSingleton();
services.AddSingleton(new InstanceDatabases(
options.SystemDatabase, options.CompanyServer, MigrationCatalog.ForSystem(dataAssembly), MigrationCatalog.ForCompany(dataAssembly)));
// Cache: in memory, or on Redis when KHAEMHAT_REDIS is set (falling back to memory while Redis is down).
if (options.Redis is { } redis)
{
services.AddSingleton(new RedisClient(RedisEndpoint.Parse(redis)));
services.AddSingleton(sp => new RedisCacheProvider(
sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService>()));
}
else
{
services.AddSingleton(sp => new MemoryCacheProvider(sp.GetRequiredService()));
}
// Security.
services.AddSingleton(new SecurityPolicyOptions());
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton(ModuleRegistry.Default);
services.AddSingleton(LicenseVerifier.Product);
services.AddSingleton(new LicenseSettings(options.License, options.Mode));
services.AddSingleton();
services.AddSingleton(sp => sp.GetRequiredService());
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
// Companies and start.
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddScoped();
services.AddSingleton(sp => new StartupOrchestrator(
sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService(),
sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService(),
sp.GetRequiredService(), sp.GetRequiredService(), options, sp.GetRequiredService(),
logSink, sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService>()));
services.AddHostedService();
// History of the records and scheduled tasks.
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddHostedService();
// Interface (SPEC §10): texts, preferences and the per-circuit state of the shell.
services.AddSingleton(JsonTextProvider.FromAssembly(typeof(KhaemhatServices).Assembly, ItalianCulture));
services.AddSingleton();
services.AddSingleton();
// Dashboard (SPEC §10.3): the sources of the lists join from the modules that feed them.
services.AddSingleton();
services.AddSingleton();
services.AddSingleton(sp => sp.GetRequiredService());
services.AddSingleton(sp => sp.GetRequiredService());
services.AddSingleton();
services.AddSingleton();
services.AddSingleton(sp => sp.GetRequiredService());
services.AddSingleton(sp => sp.GetRequiredService());
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
// Files and attachments (#34): store on the data volume, antivirus hook, attachments, generators, trash job.
services.AddSingleton(FileStoreOptions.ForDataDirectory(options.DataDir));
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
return services;
}
}
/// The user name written in the audit columns: the signed-in user of the current request, else system.
/// The current request.
internal sealed class CurrentUserName(IHttpContextAccessor accessor)
{
/// The name.
/// The user name, or outside requests.
public string? Get() => accessor.HttpContext?.User.Identity is { IsAuthenticated: true, Name: { } name } ? name : null;
}