Files
Chronos/tests/Chronos.Server.Tests/Hosting/StartupTests.cs
T
Alby96 0e84392f4f feat(logs): log level, retention, size limits and rotation on server and desktop
Owner review 2, R11 asked for more log settings. The file sink now writes daily or
hourly files, continues a full file in numbered parts and prunes by age and by the
total size (never the file being written); its options change while it runs.

Server: the file and console levels are separate and read by the logging filters
at every line, so the admin panel's new Logs group applies without a restart; the
engine's level follows the lower of the two. This also fixes a bug: the file logger
was fixed at Information, so CHRONOS_LOG_LEVEL=Debug or Trace never reached the
files. New variables CHRONOS_LOG_CONSOLE_LEVEL, CHRONOS_LOG_RETENTION_DAYS,
CHRONOS_LOG_MAX_FILE_MB, CHRONOS_LOG_MAX_TOTAL_MB, CHRONOS_LOG_ROTATION,
CHRONOS_AUDIT_RETENTION_DAYS and CHRONOS_DIAGNOSTICS_LOG_MB lock their settings like
the others; the diagnostics zip keeps the configured share of each log.

Desktop: Settings > Advanced gains Log level, Keep logs, File size, Logs total,
Rotation and Diagnostics logs, applied at every save; Advanced's Reset section
restores them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit cc875784e4952ee0e4c807b9d9c18496d3d5a8c3)
2026-10-27 02:08:09 +01:00

203 lines
11 KiB
C#

using System.Net;
using System.Text.RegularExpressions;
using Chronos.Data;
using Chronos.Server.Configuration;
using Chronos.Server.Hosting;
using Chronos.Testing;
namespace Chronos.Server.Tests.Hosting;
[Category("server")]
public sealed class StartupTests(TestContext context)
{
[Test]
public void TheServerRefusesToStartWithoutTheArchiveModule()
{
var root = context.CreateTempDirectory("bare");
var options = new ServerOptions
{
DataPath = Path.Combine(root, "data"),
ArchivePath = Path.Combine(root, "archive"),
HttpPort = 0,
HttpsPort = 0,
Database = DatabaseKind.Sqlite,
Discovery = false,
};
var error = Assert.Throws<InvalidOperationException>(() => ServerHost.Build(options, []));
Assert.Contains("IArchiveIngest", error.Message);
Assert.Contains("IFrameAssetLocator", error.Message);
}
[Test]
public void ChronosDbAcceptsAConnectionString()
{
var root = context.CreateTempDirectory("env");
var options = ServerOptions.Load(new Dictionary<string, string?>
{
["CHRONOS_DATA_PATH"] = root,
["CHRONOS_DB"] = "Host=db.lan;Port=6543;Database=archive;Username=chronos;Password=secret",
});
Assert.Equal(DatabaseKind.Postgres, options.Database);
var database = options.ToDatabaseOptions();
Assert.Equal(Dialect.Postgres, database.Dialect);
Assert.Equal(6543, Chronos.Data.Postgres.PostgresSettings.Parse(database.ConnectionString).Port);
}
[Test]
public void PartsBuildAQuotedPostgresConnectionString()
{
var options = new ServerOptions
{
Database = DatabaseKind.Postgres, // the Windows default is SQLite
DbHost = "postgres",
DbName = "chronos",
DbUser = "chronos",
DbPassword = "it's;secret",
DbSslMode = "disable",
};
var settings = Chronos.Data.Postgres.PostgresSettings.Parse(options.ToDatabaseOptions().ConnectionString);
Assert.Equal(("postgres", "chronos", "it's;secret"), (settings.Host, settings.Database, settings.Password));
Assert.Equal(Chronos.Data.Postgres.SslMode.Disable, settings.SslMode);
}
[Test]
public void EnvironmentVariablesLockTheirSettings()
{
var root = context.CreateTempDirectory("locked");
var options = ServerOptions.Load(new Dictionary<string, string?>
{
["CHRONOS_DATA_PATH"] = root,
["CHRONOS_DB"] = "postgres",
["CHRONOS_HTTP_PORT"] = "9090",
["CHRONOS_DISCOVERY"] = "false",
});
Assert.SequenceEqual(["Database", "HttpPort", "Discovery"], options.Locked);
Assert.Throws<InvalidOperationException>(() => ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres", ["CHRONOS_WORKERS"] = "many" }));
}
[Test]
public void TheFormerWorkersSettingStillSetsTheParallelism()
{
// Owner review 1: "workers" (jobs at once) became the parallelism (photos the running job processes at once).
var root = context.CreateTempDirectory("workers");
File.WriteAllText(Path.Combine(root, "server.json"), """{ "Workers": 6 }""");
Assert.Equal(6, ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres" }).Parallelism);
var former = ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres", ["CHRONOS_WORKERS"] = "5" });
Assert.Equal((5, true), (former.Parallelism, former.FormerWorkersVariable));
Assert.SequenceEqual(["Database", "Parallelism"], former.Locked);
var both = ServerOptions.Load(new Dictionary<string, string?>
{
["CHRONOS_DATA_PATH"] = root,
["CHRONOS_DB"] = "postgres",
["CHRONOS_WORKERS"] = "5",
["CHRONOS_PARALLELISM"] = "7",
["CHRONOS_PRIORITY_QUEUE"] = "true",
});
Assert.Equal((7, true), (both.Parallelism, both.PriorityQueue));
Assert.SequenceEqual(["Database", "Parallelism", "PriorityQueue"], both.Locked);
Assert.False(ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres", ["CHRONOS_PARALLELISM"] = "2" })
.FormerWorkersVariable);
Assert.Throws<InvalidOperationException>(() => ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres", ["CHRONOS_PRIORITY_QUEUE"] = "often" }));
// A value the admin panel would refuse is brought within its range, so the panel can still save the other settings.
Assert.Equal(ServerOptions.MaxParallelism,
ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres", ["CHRONOS_PARALLELISM"] = "96" }).Parallelism);
Assert.Equal(1, ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres", ["CHRONOS_WORKERS"] = "0" }).Parallelism);
Assert.InRange(new ServerOptions().Parallelism, 1, ServerOptions.MaxParallelism);
}
[Test]
public void TrustedProxiesAreAddressesOrNetworks()
{
var root = context.CreateTempDirectory("proxies");
// Loopback only: machines of the home network reach the HTTP port directly from private addresses.
var defaults = ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres" }).TrustedProxyNetworks();
foreach (var address in new[] { "127.0.0.1", "127.0.0.53", "::1" })
Assert.True(defaults.Any(n => n.Contains(IPAddress.Parse(address))), address);
foreach (var address in new[] { "10.20.30.40", "172.18.0.3", "192.168.1.2", "fd00::7", "203.0.113.5" })
Assert.False(defaults.Any(n => n.Contains(IPAddress.Parse(address))), address);
var options = ServerOptions.Load(new Dictionary<string, string?>
{
["CHRONOS_DATA_PATH"] = root,
["CHRONOS_DB"] = "postgres",
["CHRONOS_TRUSTED_PROXIES"] = "10.1.2.3, 2001:db8::/32;172.20.0.5/16",
});
Assert.Contains("TrustedProxies", options.Locked);
Assert.SequenceEqual(["10.1.2.3/32", "2001:db8::/32", "172.20.0.0/16"], options.TrustedProxyNetworks().Select(n => n.ToString()));
foreach (var invalid in new[] { "proxy.lan", "10.0.0.0/33", "fe80::1%2" })
{
var error = Assert.Throws<InvalidOperationException>(() => ServerOptions.Load(new Dictionary<string, string?>
{
["CHRONOS_DATA_PATH"] = root,
["CHRONOS_DB"] = "postgres",
["CHRONOS_TRUSTED_PROXIES"] = "127.0.0.1," + invalid,
}));
Assert.Contains(invalid, error.Message);
}
}
[Test]
public void PublicPortsComeFromTheEnvironment()
{
var root = context.CreateTempDirectory("public");
var options = ServerOptions.Load(new Dictionary<string, string?>
{
["CHRONOS_DATA_PATH"] = root,
["CHRONOS_DB"] = "postgres",
["CHRONOS_PUBLIC_HTTP_PORT"] = "18080",
["CHRONOS_PUBLIC_HTTPS_PORT"] = "18443",
});
Assert.Equal((18080, 18443), (options.PublicHttpPort, options.PublicHttpsPort));
Assert.Null(ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres" }).PublicHttpsPort);
foreach (var invalid in new[] { "0", "70000", "https" })
Assert.Throws<InvalidOperationException>(() => ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres", ["CHRONOS_PUBLIC_HTTPS_PORT"] = invalid }));
}
[Test]
public void TheLogVariablesSetTheirSettingsAndLockThem()
{
// Owner review 2, R11: CHRONOS_LOG_LEVEL sets the files and the console, CHRONOS_LOG_CONSOLE_LEVEL the console alone.
var root = context.CreateTempDirectory("log-variables");
Dictionary<string, string?> Env(params (string Name, string Value)[] variables)
{
var env = new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres" };
foreach (var (name, value) in variables) env[name] = value;
return env;
}
var defaults = ServerOptions.Load(Env());
Assert.Equal((Microsoft.Extensions.Logging.LogLevel.Information, Microsoft.Extensions.Logging.LogLevel.Information, 14, 50, 1024),
(defaults.LogLevel, defaults.ConsoleLogLevel, defaults.LogRetentionDays, defaults.LogMaxFileMb, defaults.LogMaxTotalMb));
Assert.Equal((Chronos.Core.Diagnostics.LogRotation.Daily, 0, 4), (defaults.LogRotation, defaults.AuditRetentionDays, defaults.DiagnosticsLogMb));
var both = ServerOptions.Load(Env(("CHRONOS_LOG_LEVEL", "debug")));
Assert.Equal((Microsoft.Extensions.Logging.LogLevel.Debug, Microsoft.Extensions.Logging.LogLevel.Debug), (both.LogLevel, both.ConsoleLogLevel));
Assert.SequenceEqual(["Database", "LogLevel", "ConsoleLogLevel"], both.Locked);
var all = ServerOptions.Load(Env(("CHRONOS_LOG_LEVEL", "Trace"), ("CHRONOS_LOG_CONSOLE_LEVEL", "warn"), ("CHRONOS_LOG_RETENTION_DAYS", "30"),
("CHRONOS_LOG_MAX_FILE_MB", "0"), ("CHRONOS_LOG_MAX_TOTAL_MB", "2048"), ("CHRONOS_LOG_ROTATION", "Hourly"), ("CHRONOS_AUDIT_RETENTION_DAYS", "365"),
("CHRONOS_DIAGNOSTICS_LOG_MB", "16")));
Assert.Equal((Microsoft.Extensions.Logging.LogLevel.Trace, Microsoft.Extensions.Logging.LogLevel.Warning, 30, 0, 2048),
(all.LogLevel, all.ConsoleLogLevel, all.LogRetentionDays, all.LogMaxFileMb, all.LogMaxTotalMb));
Assert.Equal((Chronos.Core.Diagnostics.LogRotation.Hourly, 365, 16), (all.LogRotation, all.AuditRetentionDays, all.DiagnosticsLogMb));
Assert.SequenceEqual(["Database", "LogLevel", "ConsoleLogLevel", "LogRetentionDays", "LogMaxFileMb", "LogMaxTotalMb", "LogRotation", "AuditRetentionDays",
"DiagnosticsLogMb"], all.Locked);
foreach (var invalid in new[]
{
("CHRONOS_LOG_LEVEL", "verbose"), ("CHRONOS_LOG_LEVEL", "2"), ("CHRONOS_LOG_CONSOLE_LEVEL", "loud"), ("CHRONOS_LOG_ROTATION", "weekly"),
("CHRONOS_LOG_RETENTION_DAYS", "0"), ("CHRONOS_LOG_MAX_FILE_MB", "-1"), ("CHRONOS_LOG_MAX_TOTAL_MB", "10"), ("CHRONOS_AUDIT_RETENTION_DAYS", "-1"),
("CHRONOS_DIAGNOSTICS_LOG_MB", "0"),
})
Assert.Throws<InvalidOperationException>(() => ServerOptions.Load(Env(invalid)), invalid.Item1 + "=" + invalid.Item2);
}
[Test]
public void HelpListsEveryVariable()
{
foreach (var variable in ServerOptions.EnvironmentVariables.Concat(["PUID", "PGID", "TZ"]))
Assert.True(Regex.IsMatch(ServerCommandLine.Usage, $@"\b{variable}\b"), variable);
}
}