Files
Chronos/tests/Chronos.Server.Tests/Hosting/StartupTests.cs
T
Alby96 ac121acf7c fix(logs): apply log settings from the first line and name the locking variable
The desktop opened its log files with the default limits and wrote its first
line, which prunes, before Settings › Advanced › Logs were applied. Every start,
and every launch that only hands its file to the running Chronos, deleted logs
older than 14 days and cut the folder to 1 GB whatever the user kept.
AppLogging.Open now builds the sink from the stored settings before that line;
the settings are read again once the launch owns the data folder.

A total below one file deleted each finished file as the next one opened. The
rule now lives in LogFileOptions.TotalBelowFile: the server keeps refusing it,
the desktop raises the total to the file size and its rows no longer offer the
combination.

The desktop log rows threw on negative sizes from an imported or hand-edited
file and showed raw values the files never got; they now show the applied ones.

Upgraded Unraid and compose installs keep CHRONOS_LOG_LEVEL=Information, which
locks both levels. The lock stays; the server now reports which variable fixes
each locked setting (LockedBy), so the panel's tooltip names it exactly and says
to remove it to change the value there. The releases README tells upgraders.

The former-constructor log test no longer fails across midnight UTC.

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

210 lines
12 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);
// The admin panel names the variable that fixes each of them.
Assert.Equal(("CHRONOS_DB", "CHRONOS_HTTP_PORT", "CHRONOS_DISCOVERY"), (options.LockedBy["Database"], options.LockedBy["HttpPort"], options.LockedBy["Discovery"]));
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);
Assert.Equal("CHRONOS_WORKERS", former.LockedBy["Parallelism"]);
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.Equal("CHRONOS_PARALLELISM", both.LockedBy["Parallelism"]);
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);
// The earlier compose file and Unraid template set CHRONOS_LOG_LEVEL: the panel names it on both levels.
Assert.Equal(("CHRONOS_LOG_LEVEL", "CHRONOS_LOG_LEVEL"), (both.LockedBy["LogLevel"], both.LockedBy["ConsoleLogLevel"]));
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);
Assert.Equal(("CHRONOS_LOG_LEVEL", "CHRONOS_LOG_CONSOLE_LEVEL"), (all.LockedBy["LogLevel"], all.LockedBy["ConsoleLogLevel"]));
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);
}
}