refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s
The owner renamed the product and moved the repository to the self-hosted Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control, and asked for Actions and a first automatic release with the server package and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md). - Chronos everywhere: a byte-exact rename of contents and paths, then a per-language review of the forms the old name's ending had dictated. - Gitea instead of GitHub: the update check, licence, issue and support links read ChronosReleasesUrl; the update check takes the highest stable version, offers a pre-release build its final release and reports a repository it cannot see as a failed check. EULA, security policy and Gitea issue forms live at the repository root. - Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release, nightly image and performance gates in the .NET SDK container with git checkout and the system SQLite. The release cross-compiles the Windows programs, checks their icon, version and DPI manifest, packs installers and zips, publishes the Gitea release and pushes the server image (REGISTRY_TOKEN). Windows-only tests run in an opt-in job on a Windows runner (WINDOWS_RUNNER). - New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the docker-exec script, which Gitea's service containers do not allow; the throw-away server runs without durability) and pe-check. - Timed tests take their budget from TestTiming (CHRONOS_TEST_TIME_FACTOR, 3 on the shared runner; the weekly performance gates keep theirs). BREAKING CHANGE: programs, settings, data folders, file types, environment variables and the Docker image use the new name; nothing is migrated from Titano, which never had a release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #6.
This commit is contained in:
1 parent
c99842cc86
commit
f2b58522b9
1801 files changed
+11804
-10676
No files matched your search
@@ -0,0 +1,335 @@
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Chronos.Data;
|
||||
using Chronos.Server.Hosting;
|
||||
|
||||
namespace Chronos.Server.Configuration;
|
||||
|
||||
public enum TlsMode
|
||||
{
|
||||
/// <summary>Self-signed certificate generated at first start (stored under /data/tls).</summary>
|
||||
Auto,
|
||||
|
||||
/// <summary>Certificate and key from PEM files.</summary>
|
||||
Pem,
|
||||
|
||||
/// <summary>Plain HTTP behind a TLS-terminating reverse proxy.</summary>
|
||||
Proxy,
|
||||
}
|
||||
|
||||
public enum DatabaseKind
|
||||
{
|
||||
Postgres,
|
||||
Sqlite,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Server configuration (BRIEF §14.9): environment variables override <c>/data/server.json</c>, which overrides defaults.
|
||||
/// Settings applied from the environment are listed in <see cref="Locked"/>; the admin panel cannot change them.
|
||||
/// </summary>
|
||||
public sealed class ServerOptions
|
||||
{
|
||||
/// <summary>Environment variable → setting it fixes, and how its text is applied.</summary>
|
||||
private static readonly (string Variable, string Setting, Action<ServerOptions, string> Apply)[] Variables =
|
||||
[
|
||||
("CHRONOS_SERVER_NAME", nameof(ServerName), (o, v) => o.ServerName = v),
|
||||
("CHRONOS_ARCHIVE_PATH", nameof(ArchivePath), (o, v) => o.ArchivePath = v),
|
||||
("CHRONOS_ADMIN_USER", nameof(AdminUser), (o, v) => o.AdminUser = v),
|
||||
("CHRONOS_ADMIN_PASSWORD", nameof(AdminPassword), (o, v) => o.AdminPassword = v),
|
||||
("CHRONOS_DB", nameof(Database), (o, v) => o.ApplyDatabase(v)),
|
||||
("CHRONOS_DB_HOST", nameof(DbHost), (o, v) => o.DbHost = v),
|
||||
("CHRONOS_DB_PORT", nameof(DbPort), (o, v) => o.DbPort = Int("CHRONOS_DB_PORT", v)),
|
||||
("CHRONOS_DB_NAME", nameof(DbName), (o, v) => o.DbName = v),
|
||||
("CHRONOS_DB_USER", nameof(DbUser), (o, v) => o.DbUser = v),
|
||||
("CHRONOS_DB_PASSWORD", nameof(DbPassword), (o, v) => o.DbPassword = v),
|
||||
("CHRONOS_DB_SSLMODE", nameof(DbSslMode), (o, v) => o.DbSslMode = v),
|
||||
("CHRONOS_HTTP_PORT", nameof(HttpPort), (o, v) => o.HttpPort = Int("CHRONOS_HTTP_PORT", v)),
|
||||
("CHRONOS_HTTPS_PORT", nameof(HttpsPort), (o, v) => o.HttpsPort = Int("CHRONOS_HTTPS_PORT", v)),
|
||||
("CHRONOS_PUBLIC_HTTP_PORT", nameof(PublicHttpPort), (o, v) => o.PublicHttpPort = Int("CHRONOS_PUBLIC_HTTP_PORT", v)),
|
||||
("CHRONOS_PUBLIC_HTTPS_PORT", nameof(PublicHttpsPort), (o, v) => o.PublicHttpsPort = Int("CHRONOS_PUBLIC_HTTPS_PORT", v)),
|
||||
("CHRONOS_TLS_MODE", nameof(TlsMode), (o, v) => o.TlsMode = Enum.Parse<TlsMode>(v, ignoreCase: true)),
|
||||
("CHRONOS_TLS_CERT", nameof(TlsCert), (o, v) => o.TlsCert = v),
|
||||
("CHRONOS_TLS_KEY", nameof(TlsKey), (o, v) => o.TlsKey = v),
|
||||
("CHRONOS_TRUSTED_PROXIES", nameof(TrustedProxies), (o, v) => o.TrustedProxies = v),
|
||||
("CHRONOS_LANG", nameof(Language), (o, v) => o.Language = v),
|
||||
// The former name of CHRONOS_PARALLELISM (jobs run at once before owner review 1) still sets it, with a warning at start;
|
||||
// listed first, so CHRONOS_PARALLELISM wins when both are set.
|
||||
("CHRONOS_WORKERS", nameof(Parallelism), (o, v) =>
|
||||
{
|
||||
o.Parallelism = Int("CHRONOS_WORKERS", v);
|
||||
o.FormerWorkersVariable = true;
|
||||
}),
|
||||
("CHRONOS_PARALLELISM", nameof(Parallelism), (o, v) => o.Parallelism = Int("CHRONOS_PARALLELISM", v)),
|
||||
("CHRONOS_PRIORITY_QUEUE", nameof(PriorityQueue), (o, v) => o.PriorityQueue = bool.Parse(v)),
|
||||
("CHRONOS_DISCOVERY", nameof(Discovery), (o, v) => o.Discovery = bool.Parse(v)),
|
||||
("CHRONOS_LOG_LEVEL", nameof(LogLevel), (o, v) => o.LogLevel = Enum.Parse<LogLevel>(v, ignoreCase: true)),
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Reverse proxies whose <c>X-Forwarded-*</c> headers count in TLS mode proxy when none are configured: loopback only.
|
||||
/// A home network's machines reach the HTTP port directly from private addresses (also through Docker's port
|
||||
/// publishing, which keeps the client's address), so trusting a private network would let them pick their own
|
||||
/// address again; a proxy in another container or on another machine is listed by its address or network.
|
||||
/// </summary>
|
||||
public const string DefaultTrustedProxies = "127.0.0.0/8, ::1/128";
|
||||
|
||||
/// <summary>The environment variables the server reads (<c>--help</c> lists them all).</summary>
|
||||
public static IEnumerable<string> EnvironmentVariables => Variables.Select(v => v.Variable).Prepend("CHRONOS_DATA_PATH");
|
||||
|
||||
public string ServerName { get; set; } = "Chronos Server";
|
||||
public string ArchivePath { get; set; } = OperatingSystem.IsWindows() ? @"C:\ChronosArchive" : "/archive";
|
||||
public string DataPath { get; set; } = OperatingSystem.IsWindows() ? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Chronos Server") : "/data";
|
||||
public string? AdminUser { get; set; }
|
||||
public string? AdminPassword { get; set; }
|
||||
public DatabaseKind Database { get; set; } = OperatingSystem.IsWindows() ? DatabaseKind.Sqlite : DatabaseKind.Postgres;
|
||||
|
||||
/// <summary>Complete connection string (from <c>CHRONOS_DB</c> when it holds one); overrides the <c>Db*</c> parts.</summary>
|
||||
public string? DbConnectionString { get; set; }
|
||||
|
||||
public string DbHost { get; set; } = "postgres";
|
||||
public int DbPort { get; set; } = 5432;
|
||||
public string DbName { get; set; } = "chronos";
|
||||
public string DbUser { get; set; } = "chronos";
|
||||
public string? DbPassword { get; set; }
|
||||
public string DbSslMode { get; set; } = "prefer";
|
||||
public int HttpPort { get; set; } = 8080;
|
||||
public int HttpsPort { get; set; } = 8443;
|
||||
|
||||
/// <summary>
|
||||
/// Port clients reach the HTTP listener on, when it differs from <see cref="HttpPort"/> (a container port published
|
||||
/// as another host port); advertised by LAN discovery. Null: <see cref="HttpPort"/>.
|
||||
/// </summary>
|
||||
public int? PublicHttpPort { get; set; }
|
||||
|
||||
/// <summary>Port clients reach the HTTPS listener on (admin redirect, LAN discovery). Null: <see cref="HttpsPort"/>.</summary>
|
||||
public int? PublicHttpsPort { get; set; }
|
||||
|
||||
public TlsMode TlsMode { get; set; } = TlsMode.Auto;
|
||||
public string? TlsCert { get; set; }
|
||||
public string? TlsKey { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Addresses or networks (CIDR), separated by commas or spaces, of the reverse proxies trusted in TLS mode proxy.
|
||||
/// Forwarded headers from any other peer are ignored, so a client that reaches the HTTP port directly cannot choose
|
||||
/// the address the sign-in rate limit and the audit log see.
|
||||
/// </summary>
|
||||
public string TrustedProxies { get; set; } = DefaultTrustedProxies;
|
||||
public string Language { get; set; } = "en";
|
||||
|
||||
/// <summary>Highest <see cref="Parallelism"/>; a larger value from the environment or <c>server.json</c> is brought down to it.</summary>
|
||||
public const int MaxParallelism = 64;
|
||||
|
||||
/// <summary>
|
||||
/// Photos the running job processes at once (owner review 1: jobs run one at a time), 1 to <see cref="MaxParallelism"/>.
|
||||
/// Default: half the logical cores.
|
||||
/// </summary>
|
||||
public int Parallelism { get; set; } = Math.Clamp(Environment.ProcessorCount / 2, 1, MaxParallelism);
|
||||
|
||||
/// <summary>
|
||||
/// The priority queue (owner review 1): a job of a higher level makes the running one of a lower level yield, and that
|
||||
/// one resumes by itself afterwards. Off: jobs wait their turn (<see cref="Chronos.Data.Jobs.JobPriorityQueue"/>).
|
||||
/// </summary>
|
||||
public bool PriorityQueue { get; set; }
|
||||
|
||||
/// <summary>Levels of the priority queue that differ from the defaults, by job kind (<c>render</c> → <c>high</c>).</summary>
|
||||
public Dictionary<string, string> JobPriorities { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// The former name of <see cref="Parallelism"/> in <c>server.json</c> (jobs run at once before owner review 1): a file
|
||||
/// that still has it sets the parallelism. Never written; saving settings drops it.
|
||||
/// </summary>
|
||||
[JsonPropertyName("Workers")]
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
public int? FormerWorkers
|
||||
{
|
||||
get => null;
|
||||
set
|
||||
{
|
||||
if (value is { } workers) Parallelism = workers;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>CHRONOS_WORKERS, the former name of CHRONOS_PARALLELISM, set the parallelism: the start says to rename it.</summary>
|
||||
[JsonIgnore]
|
||||
public bool FormerWorkersVariable { get; private set; }
|
||||
public bool Discovery { get; set; } = true;
|
||||
|
||||
/// <summary>Least severe level written to the console and the log files.</summary>
|
||||
public LogLevel LogLevel { get; set; } = LogLevel.Information;
|
||||
public long MaxUploadBytes { get; set; } = 2L * 1024 * 1024 * 1024;
|
||||
public int ChunkSizeBytes { get; set; } = 8 * 1024 * 1024;
|
||||
public int JobHistoryDays { get; set; } = 90;
|
||||
public int TokenLifetimeDays { get; set; } = 30;
|
||||
|
||||
/// <summary>Uploads untouched for this long are abandoned: their partial files are deleted.</summary>
|
||||
public int UploadRetentionHours { get; set; } = 48;
|
||||
|
||||
/// <summary>Sign-in attempts accepted per minute and client address (BRIEF §14.2: 5).</summary>
|
||||
public int LoginAttemptsPerMinute { get; set; } = 5;
|
||||
|
||||
/// <summary>Consecutive failed sign-ins that lock an account name for <see cref="LockoutMinutes"/>.</summary>
|
||||
public int LockoutThreshold { get; set; } = 10;
|
||||
|
||||
public int LockoutMinutes { get; set; } = 15;
|
||||
|
||||
/// <summary>A render node silent for this long is offline and its jobs go back to the queue.</summary>
|
||||
public int NodeTimeoutSeconds { get; set; } = 90;
|
||||
|
||||
/// <summary>Chunk uploads one user may run at the same time; more are answered 429.</summary>
|
||||
public int ConcurrentChunksPerUser { get; set; } = 8;
|
||||
|
||||
/// <summary>Settings fixed by environment variables (names of the properties above).</summary>
|
||||
[JsonIgnore]
|
||||
public IReadOnlyCollection<string> Locked { get; private set; } = [];
|
||||
|
||||
[JsonIgnore]
|
||||
public string LogPath => Path.Combine(DataPath, "logs");
|
||||
|
||||
[JsonIgnore]
|
||||
public string TlsPath => Path.Combine(DataPath, "tls");
|
||||
|
||||
[JsonIgnore]
|
||||
public string UploadsPath => Path.Combine(DataPath, "uploads");
|
||||
|
||||
[JsonIgnore]
|
||||
public string SettingsFile => Path.Combine(DataPath, "server.json");
|
||||
|
||||
/// <summary>Verified uploads wait here, on the archive volume, until the archive ingest moves them into place.</summary>
|
||||
[JsonIgnore]
|
||||
public string StagingPath => Path.Combine(ArchivePath, ".chronos", "staging");
|
||||
|
||||
/// <summary>Deleted sequences are moved here (never erased by the server).</summary>
|
||||
[JsonIgnore]
|
||||
public string TrashPath => Path.Combine(ArchivePath, ".chronos", "trash");
|
||||
|
||||
/// <summary>Loads <c>{DataPath}/server.json</c> (if present) then applies <c>CHRONOS_*</c> environment variables.</summary>
|
||||
public static ServerOptions Load(IReadOnlyDictionary<string, string?>? environment = null)
|
||||
{
|
||||
var env = environment ?? ReadEnvironment();
|
||||
string? Env(string name) => env.TryGetValue(name, out var v) && !string.IsNullOrWhiteSpace(v) ? v : null;
|
||||
|
||||
var dataPath = Env("CHRONOS_DATA_PATH") ?? new ServerOptions().DataPath;
|
||||
var options = new ServerOptions();
|
||||
var file = Path.Combine(dataPath, "server.json");
|
||||
if (File.Exists(file))
|
||||
{
|
||||
try
|
||||
{
|
||||
// Its owner is checked first: a file another user planted would choose the archive, database and TLS key.
|
||||
options = JsonSerializer.Deserialize(DataFolderAccess.ReadTrustedText(file), ServerOptionsJson.Default.ServerOptions) ?? options;
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
throw new InvalidOperationException($"{file} is not valid JSON: {ex.Message}", ex);
|
||||
}
|
||||
}
|
||||
options.DataPath = dataPath;
|
||||
|
||||
var locked = new List<string>();
|
||||
foreach (var (variable, setting, apply) in Variables)
|
||||
{
|
||||
if (Env(variable) is not { } value) continue;
|
||||
try
|
||||
{
|
||||
apply(options, value);
|
||||
}
|
||||
catch (Exception ex) when (ex is FormatException or ArgumentException)
|
||||
{
|
||||
throw new InvalidOperationException($"{variable} has an invalid value.", ex);
|
||||
}
|
||||
locked.Add(setting);
|
||||
}
|
||||
options.Locked = [.. locked.Distinct(StringComparer.Ordinal)];
|
||||
// The admin panel saves only values it accepts: one it cannot change (an environment variable) must be one of them.
|
||||
options.Parallelism = Math.Clamp(options.Parallelism, 1, MaxParallelism);
|
||||
options.Validate();
|
||||
return options;
|
||||
}
|
||||
|
||||
/// <summary>The database to open: <see cref="DbConnectionString"/>, the SQLite file in the data folder, or PostgreSQL from the parts.</summary>
|
||||
public DatabaseOptions ToDatabaseOptions()
|
||||
{
|
||||
if (DbConnectionString is { Length: > 0 } cs) return DatabaseOptions.Parse(cs);
|
||||
if (Database == DatabaseKind.Sqlite) return DatabaseOptions.Sqlite(Path.Combine(DataPath, "chronos.db"));
|
||||
var builder = new System.Text.StringBuilder()
|
||||
.Append("Host=").Append(Quote(DbHost))
|
||||
.Append(";Port=").Append(DbPort.ToString(CultureInfo.InvariantCulture))
|
||||
.Append(";Database=").Append(Quote(DbName))
|
||||
.Append(";Username=").Append(Quote(DbUser))
|
||||
.Append(";SslMode=").Append(Quote(DbSslMode));
|
||||
if (DbPassword is not null) builder.Append(";Password=").Append(Quote(DbPassword));
|
||||
return DatabaseOptions.Postgres(builder.ToString());
|
||||
}
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows() && Database == DatabaseKind.Sqlite)
|
||||
throw new InvalidOperationException("CHRONOS_DB=sqlite is supported on Windows only; use postgres (BRIEF §14.9).");
|
||||
if (TlsMode == TlsMode.Pem && (string.IsNullOrEmpty(TlsCert) || string.IsNullOrEmpty(TlsKey)))
|
||||
throw new InvalidOperationException("CHRONOS_TLS_MODE=pem requires CHRONOS_TLS_CERT and CHRONOS_TLS_KEY.");
|
||||
// Port 0 asks the OS for a free port (used by the in-process test host).
|
||||
if (HttpPort is < 0 or > 65535 || HttpsPort is < 0 or > 65535)
|
||||
throw new InvalidOperationException("Ports must be between 0 and 65535.");
|
||||
if (PublicHttpPort is < 1 or > 65535 || PublicHttpsPort is < 1 or > 65535)
|
||||
throw new InvalidOperationException("CHRONOS_PUBLIC_HTTP_PORT and CHRONOS_PUBLIC_HTTPS_PORT must be between 1 and 65535.");
|
||||
try
|
||||
{
|
||||
TrustedProxyNetworks();
|
||||
}
|
||||
catch (FormatException ex)
|
||||
{
|
||||
throw new InvalidOperationException($"CHRONOS_TRUSTED_PROXIES must list IP addresses (such as 172.30.0.10) or networks in CIDR form: {ex.Message}", ex);
|
||||
}
|
||||
if (ChunkSizeBytes is < 64 * 1024 or > 64 * 1024 * 1024)
|
||||
throw new InvalidOperationException("The chunk size must be between 64 KiB and 64 MiB.");
|
||||
if (MaxUploadBytes < 1 || TokenLifetimeDays < 1 || JobHistoryDays < 1 || UploadRetentionHours < 1)
|
||||
throw new InvalidOperationException("Upload size, token lifetime, job history and upload retention must be positive.");
|
||||
}
|
||||
|
||||
/// <summary>The parsed <see cref="TrustedProxies"/>; a single address is a network of one.</summary>
|
||||
/// <exception cref="FormatException">An entry is neither an IP address nor a network in CIDR notation.</exception>
|
||||
public IReadOnlyList<IPNetwork> TrustedProxyNetworks()
|
||||
{
|
||||
var networks = new List<IPNetwork>();
|
||||
foreach (var entry in TrustedProxies.Split([',', ';', ' ', '\t'], StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
if (IPNetwork.TryParse(entry, out var network)) networks.Add(network);
|
||||
else if (!entry.Contains('/', StringComparison.Ordinal) && IPAddress.TryParse(entry, out var address)
|
||||
&& (address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetworkV6 || address.ScopeId == 0))
|
||||
networks.Add(new IPNetwork(address, address.GetAddressBytes().Length * 8));
|
||||
else throw new FormatException($"'{entry}' is neither an address nor a network.");
|
||||
}
|
||||
return networks;
|
||||
}
|
||||
|
||||
/// <summary>CHRONOS_DB is <c>postgres</c>, <c>sqlite</c> or a complete connection string (<c>Host=…</c> / <c>Data Source=…</c>).</summary>
|
||||
private void ApplyDatabase(string value)
|
||||
{
|
||||
if (value.Contains('=', StringComparison.Ordinal))
|
||||
{
|
||||
DbConnectionString = value;
|
||||
Database = DatabaseOptions.Parse(value).Dialect == Dialect.Postgres ? DatabaseKind.Postgres : DatabaseKind.Sqlite;
|
||||
return;
|
||||
}
|
||||
Database = Enum.Parse<DatabaseKind>(value, ignoreCase: true);
|
||||
}
|
||||
|
||||
private static int Int(string variable, string value) =>
|
||||
int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var n) ? n : throw new FormatException($"{variable} must be a number.");
|
||||
|
||||
private static string Quote(string value) => "'" + value.Replace("'", "''", StringComparison.Ordinal) + "'";
|
||||
|
||||
private static Dictionary<string, string?> ReadEnvironment()
|
||||
{
|
||||
// Variables may differ only by case on Linux (no_proxy/NO_PROXY); the last one wins.
|
||||
var result = new Dictionary<string, string?>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (System.Collections.DictionaryEntry e in Environment.GetEnvironmentVariables()) result[(string)e.Key] = (string?)e.Value;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(WriteIndented = true, UseStringEnumConverter = true, PropertyNameCaseInsensitive = true)]
|
||||
[JsonSerializable(typeof(ServerOptions))]
|
||||
internal sealed partial class ServerOptionsJson : JsonSerializerContext;
|
||||
@@ -0,0 +1,149 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Protocol;
|
||||
|
||||
namespace Chronos.Server.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// The admin panel's view of the configuration (BRIEF §14.8 Settings). Saving writes <c>/data/server.json</c> (only the
|
||||
/// edited keys; secrets and environment values are never written) and applies what can change while running, the
|
||||
/// parallelism and the priority queue included (owner review 1); ports, TLS, chunk size and job history wait for a restart.
|
||||
/// </summary>
|
||||
public sealed class ServerSettingsStore(ServerOptions options)
|
||||
{
|
||||
/// <summary>The kinds of job the server runs, in the order the admin panel lists their levels (downloads and uploads are a client's).</summary>
|
||||
public static IReadOnlyList<JobKind> Kinds { get; } =
|
||||
[
|
||||
JobKind.Render, JobKind.Import, JobKind.Scan, JobKind.Rebuild, JobKind.Verify, JobKind.LightAnalyse, JobKind.DeepAnalyse, JobKind.Thumbs,
|
||||
JobKind.Proxies, JobKind.Maintenance, JobKind.Duplicates, JobKind.Orphans, JobKind.Adopt, JobKind.Move,
|
||||
];
|
||||
|
||||
private readonly Lock _gate = new();
|
||||
private ServerSettingsDto? _saved;
|
||||
|
||||
public ServerSettingsDto Current()
|
||||
{
|
||||
lock (_gate) return _saved ?? Snapshot(options, restartRequired: false);
|
||||
}
|
||||
|
||||
/// <summary>The priority queue as the settings have it now (<see cref="ServerOptions.PriorityQueue"/>, <see cref="ServerOptions.JobPriorities"/>).</summary>
|
||||
public static JobPriorityQueue PriorityQueue(ServerOptions options) => JobPriorityQueue.From(options.PriorityQueue, options.JobPriorities);
|
||||
|
||||
/// <summary>Validates and saves; returns the error code and the offending setting, or null on success.</summary>
|
||||
public (string Code, string Setting)? Save(ServerSettingsDto request)
|
||||
{
|
||||
if (Validate(request) is { } invalid) return ("invalid_setting", invalid);
|
||||
lock (_gate)
|
||||
{
|
||||
var current = _saved ?? Snapshot(options, restartRequired: false);
|
||||
var changes = Changes(current, request);
|
||||
if (changes.FirstOrDefault(c => options.Locked.Contains(c.Name)) is { Name: { } locked }) return ("setting_locked", locked);
|
||||
if (changes.Count == 0) return null;
|
||||
|
||||
var file = File.Exists(options.SettingsFile) ? JsonNode.Parse(File.ReadAllText(options.SettingsFile)) as JsonObject ?? [] : [];
|
||||
foreach (var (name, value) in changes) file[name] = value;
|
||||
// The former name of the parallelism (jobs run at once before owner review 1) would set it again at the next start.
|
||||
if (changes.Any(c => c.Name == nameof(ServerOptions.Parallelism))) file.Remove("Workers");
|
||||
Directory.CreateDirectory(options.DataPath);
|
||||
AtomicFile.WriteAllText(options.SettingsFile, file.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));
|
||||
|
||||
options.ServerName = request.ServerName.Trim();
|
||||
options.Discovery = request.Discovery;
|
||||
options.Language = request.Language;
|
||||
options.MaxUploadBytes = request.MaxUploadBytes;
|
||||
options.TokenLifetimeDays = request.TokenLifetimeDays;
|
||||
options.UploadRetentionHours = request.UploadRetentionHours;
|
||||
options.Parallelism = request.Parallelism;
|
||||
options.PriorityQueue = request.PriorityQueue;
|
||||
options.JobPriorities = JobPriorityQueue.Changed(Levels(request.JobPriorities));
|
||||
var restart = request.HttpPort != options.HttpPort || request.HttpsPort != options.HttpsPort
|
||||
|| !string.Equals(request.TlsMode, options.TlsMode.ToString(), StringComparison.OrdinalIgnoreCase)
|
||||
|| request.TlsCert != options.TlsCert || request.TlsKey != options.TlsKey
|
||||
|| request.ChunkSizeBytes != options.ChunkSizeBytes || request.JobHistoryDays != options.JobHistoryDays;
|
||||
_saved = request with
|
||||
{
|
||||
ServerName = request.ServerName.Trim(),
|
||||
JobPriorities = Priorities(PriorityQueue(options)),
|
||||
Locked = [.. options.Locked],
|
||||
RestartRequired = restart,
|
||||
ProxyWarning = false,
|
||||
};
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static ServerSettingsDto Snapshot(ServerOptions o, bool restartRequired) => new(
|
||||
o.ServerName, o.HttpPort, o.HttpsPort, o.TlsMode.ToString().ToLowerInvariant(), o.TlsCert, o.TlsKey, o.Language, o.Parallelism, o.PriorityQueue,
|
||||
Priorities(PriorityQueue(o)), o.Discovery, o.MaxUploadBytes, o.ChunkSizeBytes, o.JobHistoryDays, o.TokenLifetimeDays, o.UploadRetentionHours,
|
||||
[.. o.Locked], restartRequired, ProxyWarning: false);
|
||||
|
||||
/// <summary>The level of every kind the server runs in <paramref name="queue"/>.</summary>
|
||||
private static List<JobPriorityDto> Priorities(JobPriorityQueue queue) =>
|
||||
[.. Kinds.Select(k => new JobPriorityDto(JobWire.Kind(k), JobPriorityQueue.Wire(queue.LevelOf(k))))];
|
||||
|
||||
/// <summary>The levels a request sets; <see cref="Validate"/> has checked their names.</summary>
|
||||
private static Dictionary<JobKind, JobKindPriority> Levels(IReadOnlyList<JobPriorityDto>? priorities)
|
||||
{
|
||||
var levels = new Dictionary<JobKind, JobKindPriority>();
|
||||
foreach (var p in priorities ?? [])
|
||||
{
|
||||
if (JobWire.TryParseKind(p.Kind, out var kind) && JobPriorityQueue.TryParse(p.Level, out var level)) levels[kind] = level;
|
||||
}
|
||||
return levels;
|
||||
}
|
||||
|
||||
private static string? Validate(ServerSettingsDto r)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(r.ServerName) || r.ServerName.Trim().Length > 60) return nameof(ServerOptions.ServerName);
|
||||
if (r.HttpPort is < 1 or > 65535) return nameof(ServerOptions.HttpPort);
|
||||
if (r.HttpsPort is < 1 or > 65535 || r.HttpsPort == r.HttpPort) return nameof(ServerOptions.HttpsPort);
|
||||
if (!Enum.TryParse<TlsMode>(r.TlsMode, ignoreCase: true, out var tls) || !Enum.IsDefined(tls)) return nameof(ServerOptions.TlsMode);
|
||||
if (tls == TlsMode.Pem && (string.IsNullOrWhiteSpace(r.TlsCert) || !File.Exists(r.TlsCert))) return nameof(ServerOptions.TlsCert);
|
||||
if (tls == TlsMode.Pem && (string.IsNullOrWhiteSpace(r.TlsKey) || !File.Exists(r.TlsKey))) return nameof(ServerOptions.TlsKey);
|
||||
if (!Languages.Shipped.Contains(r.Language, StringComparer.OrdinalIgnoreCase)) return nameof(ServerOptions.Language);
|
||||
if (r.Parallelism is < 1 or > ServerOptions.MaxParallelism) return nameof(ServerOptions.Parallelism);
|
||||
if ((r.JobPriorities ?? []).Any(p => !JobWire.TryParseKind(p.Kind, out var kind) || !Kinds.Contains(kind) || !JobPriorityQueue.TryParse(p.Level, out _)))
|
||||
return nameof(ServerOptions.JobPriorities);
|
||||
if (r.MaxUploadBytes < 1024 * 1024) return nameof(ServerOptions.MaxUploadBytes);
|
||||
if (r.ChunkSizeBytes is < 64 * 1024 or > 64 * 1024 * 1024) return nameof(ServerOptions.ChunkSizeBytes);
|
||||
if (r.JobHistoryDays is < 1 or > 3650) return nameof(ServerOptions.JobHistoryDays);
|
||||
if (r.TokenLifetimeDays is < 1 or > 365) return nameof(ServerOptions.TokenLifetimeDays);
|
||||
if (r.UploadRetentionHours is < 1 or > 8760) return nameof(ServerOptions.UploadRetentionHours);
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Settings whose value differs, as server.json keys and JSON values.</summary>
|
||||
private static List<(string Name, JsonNode? Value)> Changes(ServerSettingsDto a, ServerSettingsDto b)
|
||||
{
|
||||
var changes = new List<(string, JsonNode?)>();
|
||||
void Add<T>(string name, T before, T after, Func<T, JsonNode?> json)
|
||||
{
|
||||
if (!EqualityComparer<T>.Default.Equals(before, after)) changes.Add((name, json(after)));
|
||||
}
|
||||
Add(nameof(ServerOptions.ServerName), a.ServerName, b.ServerName.Trim(), v => JsonValue.Create(v));
|
||||
Add(nameof(ServerOptions.HttpPort), a.HttpPort, b.HttpPort, v => JsonValue.Create(v));
|
||||
Add(nameof(ServerOptions.HttpsPort), a.HttpsPort, b.HttpsPort, v => JsonValue.Create(v));
|
||||
Add(nameof(ServerOptions.TlsMode), a.TlsMode.ToLowerInvariant(), b.TlsMode.ToLowerInvariant(), v => JsonValue.Create(v));
|
||||
Add(nameof(ServerOptions.TlsCert), a.TlsCert, b.TlsCert, v => v is null ? null : JsonValue.Create(v));
|
||||
Add(nameof(ServerOptions.TlsKey), a.TlsKey, b.TlsKey, v => v is null ? null : JsonValue.Create(v));
|
||||
Add(nameof(ServerOptions.Language), a.Language, b.Language, v => JsonValue.Create(v));
|
||||
Add(nameof(ServerOptions.Parallelism), a.Parallelism, b.Parallelism, v => JsonValue.Create(v));
|
||||
Add(nameof(ServerOptions.PriorityQueue), a.PriorityQueue, b.PriorityQueue, v => JsonValue.Create(v));
|
||||
// Only levels that differ from the defaults are stored, as the desktop does.
|
||||
var before = JobPriorityQueue.Changed(Levels(a.JobPriorities));
|
||||
var after = JobPriorityQueue.Changed(Levels(b.JobPriorities));
|
||||
if (!before.OrderBy(l => l.Key).SequenceEqual(after.OrderBy(l => l.Key)))
|
||||
changes.Add((nameof(ServerOptions.JobPriorities), new JsonObject(after.Select(l => KeyValuePair.Create(l.Key, (JsonNode?)JsonValue.Create(l.Value))))));
|
||||
Add(nameof(ServerOptions.Discovery), a.Discovery, b.Discovery, v => JsonValue.Create(v));
|
||||
Add(nameof(ServerOptions.MaxUploadBytes), a.MaxUploadBytes, b.MaxUploadBytes, v => JsonValue.Create(v));
|
||||
Add(nameof(ServerOptions.ChunkSizeBytes), a.ChunkSizeBytes, b.ChunkSizeBytes, v => JsonValue.Create(v));
|
||||
Add(nameof(ServerOptions.JobHistoryDays), a.JobHistoryDays, b.JobHistoryDays, v => JsonValue.Create(v));
|
||||
Add(nameof(ServerOptions.TokenLifetimeDays), a.TokenLifetimeDays, b.TokenLifetimeDays, v => JsonValue.Create(v));
|
||||
Add(nameof(ServerOptions.UploadRetentionHours), a.UploadRetentionHours, b.UploadRetentionHours, v => JsonValue.Create(v));
|
||||
return changes;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user