using System.Globalization; using System.Reflection; using Chronos.Core.Imaging; using Chronos.Core.Localization; using Chronos.Data; using Chronos.Protocol; using Chronos.Server.Configuration; using Chronos.Server.Security; namespace Chronos.Server.Api; /// /health, /api/v1/server/info and /api/v1/i18n/{culture} (all anonymous). public static class SystemEndpoints { private static readonly string[] AdminAreas = ["Common", "Admin"]; /// Languages with translated resources (English plus every satellite of the catalog), for the admin language menu. private static readonly Lazy AdminLanguages = new(() => string.Join(',', Languages.Shipped.Where(code => { if (code == "en") return true; try { typeof(Loc).Assembly.GetSatelliteAssembly(CultureInfo.GetCultureInfo(code)); return true; } catch (FileNotFoundException) { return false; } }))); /// The extensions the archive scanner files as photos (BRIEF ยง8.1), which the admin panel's uploads keep to. private static readonly string[] PhotoExtensions = [.. ImageFormatInfo.Known.SelectMany(f => f.Extensions)]; public static string Version { get; } = typeof(SystemEndpoints).Assembly.GetCustomAttribute()?.InformationalVersion ?? "0.0.0"; public static void Map(WebApplication app, RouteGroupBuilder api) { app.MapGet("/health", HealthAsync); api.MapGet("/server/info", (ServerOptions options, ServerState state) => Results.Json(new ServerInfo( options.ServerName, Version, ApiVersion.Current, state.Capabilities, state.TlsFingerprint, ["jpeg", "png", "tiff", "dng", "cr2", "cr3", "nef", "arw", "raf", "orf", "rw2", "pef", "heic", "webp"], new ServerLimits(options.MaxUploadBytes, options.ChunkSizeBytes, PasswordHasher.MinimumLength), PhotoExtensions), ProtocolJson.Default.ServerInfo)).AllowAnonymousCaller(); api.MapGet("/i18n/{culture}", (string culture) => { CultureInfo ci; try { ci = Languages.BestMatch(CultureInfo.GetCultureInfo(culture)); } catch (CultureNotFoundException) { ci = CultureInfo.GetCultureInfo("en"); } var strings = new Dictionary(StringComparer.Ordinal); foreach (var area in AdminAreas) foreach (var (k, v) in Loc.GetArea(area, ci)) strings[k] = v; strings["$culture"] = ci.Name; strings["$rtl"] = ci.TextInfo.IsRightToLeft ? "true" : "false"; strings["$languages"] = AdminLanguages.Value; return Results.Json(strings, ProtocolJson.Default.DictionaryStringString); }).AllowAnonymousCaller(); } /// Liveness for the container health check: 503 while the database cannot be reached. private static async Task HealthAsync(HttpContext context, ServerOptions options, ChronosDatabase db) { var checks = new Dictionary(StringComparer.Ordinal) { ["archive"] = Directory.Exists(options.ArchivePath) ? "ok" : "missing", ["data"] = Directory.Exists(options.DataPath) ? "ok" : "missing", }; using var timeout = CancellationTokenSource.CreateLinkedTokenSource(context.RequestAborted); timeout.CancelAfter(TimeSpan.FromSeconds(3)); try { await using var session = await db.Database.OpenAsync(timeout.Token); await session.ExecuteAsync("SELECT 1", [], timeout.Token); checks["database"] = "ok"; } catch (Exception ex) when (ex is DatabaseException or OperationCanceledException or IOException) { checks["database"] = "unavailable"; } var healthy = checks["database"] == "ok"; return Results.Json(new HealthStatus(healthy ? "ok" : "unavailable", Version, checks), ProtocolJson.Default.HealthStatus, statusCode: healthy ? StatusCodes.Status200OK : StatusCodes.Status503ServiceUnavailable); } } /// Process-wide facts computed at startup. public sealed class ServerState { public string? TlsFingerprint { get; init; } /// Engine and version of the database ("PostgreSQL 17.2", "SQLite 3.45.1"). public string Database { get; init; } = string.Empty; /// What this server offers clients (; names those clients act on). public List Capabilities { get; } = ["uploads", "sync", "jobs", "render-nodes", "events", ServerCapabilities.Projects]; public DateTimeOffset StartedAt { get; } = DateTimeOffset.UtcNow; }