using System.Text.Json; using Chronos.Data; using Chronos.Data.Repositories; using Chronos.Protocol; using Chronos.Server.Hosting; using Chronos.Testing; namespace Chronos.Server.Tests.Api; /// The server's stable id announced by /server/info (owner review 5, #66). [Category("server")] public sealed class ServerInfoIdTests(TestContext context) { private static async Task InfoAsync(TestServer server) { using var response = await server.Client.GetAsync("/api/v1/server/info"); return await response.ReadAsync(ProtocolJson.Default.ServerInfo); } [Test] public async Task TheIdIsMadeOnceAndKeptAcrossRestarts() { var root = context.CreateTempDirectory("kept"); void Same(Configuration.ServerOptions o) { o.DataPath = Path.Combine(root, "data"); o.ArchivePath = Path.Combine(root, "archive"); } Guid first; await using (var server = await TestServer.StartAsync(context, Same)) { first = Assert.NotNull((await InfoAsync(server)).ServerId); Assert.NotEqual(Guid.Empty, first); var stored = await server.Database.Settings.GetJsonAsync(SettingScope.App, null, ServerHost.ServerIdKey, context.Cancellation); Assert.Equal("\"" + first.ToString("D") + "\"", stored); } await using (var again = await TestServer.StartAsync(context, Same)) Assert.Equal((Guid?)first, (await InfoAsync(again)).ServerId); // Another server (another database) has another id. await using (var other = await TestServer.StartAsync(context)) Assert.NotEqual((Guid?)first, (await InfoAsync(other)).ServerId); } [Test] public async Task TheIdSurvivesARestoreOfTheIndex() { var folder = context.CreateTempDirectory("restore"); Guid id; string backup; await using (var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(folder, "chronos.db")), context.Cancellation)) { id = await ServerHost.ServerIdAsync(db, null, context.Cancellation); backup = await db.BackupAsync(Path.Combine(folder, "backups"), cancellationToken: context.Cancellation); } // A new index (the disk replaced), then the backup put back. await using var restored = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(folder, "new.db")), context.Cancellation); await restored.RestoreAsync(backup, context.Cancellation); Assert.Equal(id, await ServerHost.ServerIdAsync(restored, null, context.Cancellation)); } [Test] public async Task AStoredIdThatIsNotOneIsMadeAgain() { var folder = context.CreateTempDirectory("damaged"); await using var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(folder, "chronos.db")), context.Cancellation); foreach (var damaged in new[] { "\"not a guid\"", "\"" + Guid.Empty.ToString("D") + "\"", "42" }) { await db.Settings.SetJsonAsync(SettingScope.App, null, ServerHost.ServerIdKey, damaged, context.Cancellation); var made = await ServerHost.ServerIdAsync(db, null, context.Cancellation); Assert.NotEqual(Guid.Empty, made); Assert.Equal(made, await ServerHost.ServerIdAsync(db, null, context.Cancellation)); } } [Test] [RequiresEnvironment("CHRONOS_TEST_PG")] public async Task TheIdIsKeptOnPostgres() { var baseConnection = Environment.GetEnvironmentVariable("CHRONOS_TEST_PG")!; var admin = DatabaseFactory.Open(DatabaseOptions.Postgres(baseConnection)); var schema = "chronos_s_" + Guid.NewGuid().ToString("N")[..16]; await using (var session = await admin.OpenAsync(context.Cancellation)) await session.ExecuteScriptAsync($"CREATE SCHEMA {schema}", context.Cancellation); try { var options = DatabaseOptions.Postgres(baseConnection.TrimEnd(';', ' ') + $";Search Path={schema}"); Guid id; await using (var db = await ChronosDatabase.OpenAsync(options, context.Cancellation)) id = await ServerHost.ServerIdAsync(db, null, context.Cancellation); await using (var db = await ChronosDatabase.OpenAsync(options, context.Cancellation)) Assert.Equal(id, await ServerHost.ServerIdAsync(db, null, context.Cancellation)); } finally { await using (var session = await admin.OpenAsync(CancellationToken.None)) await session.ExecuteScriptAsync($"DROP SCHEMA IF EXISTS {schema} CASCADE", CancellationToken.None); await admin.DisposeAsync(); } } [Test] public void AnOlderClientAndAnOlderServerReadEachOther() { var id = Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01"); var info = new ServerInfo("Studio NAS", "1.1.0", 1, ["sync"], null, ["jpeg"], new ServerLimits(1, 1), null, 3, id); var json = JsonSerializer.Serialize(info, ProtocolJson.Default.ServerInfo); Assert.Contains("\"serverId\":\"" + id.ToString("D") + "\"", json); Assert.Equal(info.ServerId, Assert.NotNull(JsonSerializer.Deserialize(json, ProtocolJson.Default.ServerInfo)).ServerId); // A 1.0 server sends no id: it reads as null, and a 1.0 client ignores the member it does not know. const string older = """{"name":"NAS","version":"1.0.0","apiVersion":1,"capabilities":["sync"],"formats":["jpeg"],"limits":{"maxUploadBytes":1,"chunkSizeBytes":1}}"""; Assert.Null(Assert.NotNull(JsonSerializer.Deserialize(older, ProtocolJson.Default.ServerInfo)).ServerId); Assert.False(JsonSerializer.Serialize(info with { ServerId = null }, ProtocolJson.Default.ServerInfo).Contains("serverId", StringComparison.Ordinal)); using var parsed = JsonDocument.Parse(json); Assert.Equal("Studio NAS", parsed.RootElement.GetProperty("name").GetString()); } }