Files
Chronos/tests/Titano.Server.Tests/Api/AdminTests.cs
T
Claude 56aa4da674 fix(settings): restore before the index opens; archive rows edit only their archive; parallelism follows the brief
Index restore (ENG-06, UI-09):
- A staged restore now runs on the files before the index is opened, so it also
  recovers an index that no longer opens; Settings > Advanced > Restore works
  without an open index (the current one is shown as unreadable).
- The staged copy passes PRAGMA quick_check (before migration, in a scratch copy)
  ahead of any backup: a damaged copy is set aside as .failed and never renews the
  daily copies. The index it replaces is kept as a VACUUM INTO copy, or, when it
  cannot be read, copied whole with its WAL as titano-replaced-<stamp>.db outside the
  rotation. The staged file is renamed over the index, so it is never applied twice.
- Archive > Maintenance gains Restore database..., which opens Settings > Advanced.

Archive settings (UI-03, ENG-03):
- An archive.json with an empty or overlong name (drive roots) can be edited again:
  the name read is made usable as at creation.
- Proxy and thumbnail sizes outside the presets (an admin's 3840) are listed and
  shown with their number.
- Changing the archive folder retargets the rows: an archive there is registered
  and rescanned; with none, the rows edit only the defaults of new archives. The
  rows never fall back to another archive of the index.
- Reset all and Import settings no longer rewrite the shared archive.json; Archive >
  Reset section asks first, naming the archive.
- PUT /api/v1/archive/settings: 409 archive_busy on a lease conflict, 409
  archive_manifest for a damaged, newer or foreign archive.json (was 500).

Parallelism (UI-02):
- Auto is the job engine's default, half the logical cores (BRIEF 14.6), with each
  job's own decode and analysis threads; a value the user sets is the number of
  workers and caps those threads. The memory budget is shared: each job's frame
  window gets budget / workers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-12 11:06:27 +00:00

182 lines
10 KiB
C#

using System.Net;
using System.Net.Http.Json;
using System.Text.Json.Nodes;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Titano.Protocol;
using Titano.Server.Hosting;
using Titano.Testing;
namespace Titano.Server.Tests.Api;
[Category("server")]
public sealed class AdminTests(TestContext context)
{
[Test]
public async Task TheDashboardSummarisesTheServer()
{
await using var server = await TestServer.StartAsync(context, o => o.ServerName = "Studio NAS");
var (editor, _, _) = await server.UserAsync("alberto", "editor");
await Uploads.UploadAsync(editor, Uploads.Photo(4000, 61));
var admin = await server.AdminAsync();
using var response = await admin.GetAsync("/api/v1/server/dashboard");
await response.ExpectAsync(HttpStatusCode.OK);
var dashboard = await response.ReadAsync(ProtocolJson.Default.DashboardDto);
Assert.Equal(("Studio NAS", 2, 1L, 1L), (dashboard.ServerName, dashboard.Users, dashboard.Archive.Sequences, dashboard.Archive.Photos));
Assert.True(dashboard.Database.StartsWith("SQLite ", StringComparison.Ordinal), dashboard.Database);
Assert.Equal(1L, dashboard.Uploads.Single().Frames);
Assert.Contains(dashboard.Activity, a => a.Action == "user_created");
Assert.True(dashboard.Archive.CapacityBytes > 0);
}
[Test]
public async Task SettingsAreSavedAndRestartOnlyValuesFlagged()
{
await using var server = await TestServer.StartAsync(context);
var admin = await server.AdminAsync();
using var read = await admin.GetAsync("/api/v1/server/settings");
var settings = await read.ReadAsync(ProtocolJson.Default.ServerSettingsDto);
Assert.False(settings.RestartRequired);
var edited = settings with { ServerName = "Rooftop", Discovery = true, HttpPort = 18080, HttpsPort = 18443 };
using (var saved = await admin.PutAsJsonAsync("/api/v1/server/settings", edited, ProtocolJson.Default.ServerSettingsDto))
Assert.True((await saved.ReadAsync(ProtocolJson.Default.ServerSettingsDto)).RestartRequired);
// Name and discovery apply at once; ports wait for the restart.
Assert.Equal(("Rooftop", true, 0), (server.Options.ServerName, server.Options.Discovery, server.Options.HttpPort));
using (var again = await admin.GetAsync("/api/v1/server/settings"))
Assert.Equal(18080, (await again.ReadAsync(ProtocolJson.Default.ServerSettingsDto)).HttpPort);
var file = JsonNode.Parse(await File.ReadAllTextAsync(server.Options.SettingsFile))!.AsObject();
Assert.Equal(("Rooftop", 18080), (file["ServerName"]!.GetValue<string>(), file["HttpPort"]!.GetValue<int>()));
Assert.False(file.ContainsKey("AdminPassword"));
using var invalid = await admin.PutAsJsonAsync("/api/v1/server/settings", edited with { Language = "tlh" }, ProtocolJson.Default.ServerSettingsDto);
Assert.Equal("Language", (await invalid.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_setting")).Details);
}
[Test]
public async Task LogsAreReadableButOnlyByName()
{
await using var server = await TestServer.StartAsync(context, o => o.LogLevel = Microsoft.Extensions.Logging.LogLevel.Information);
var admin = await server.AdminAsync();
using var tail = await admin.GetAsync("/api/v1/logs?lines=20");
var lines = await tail.ReadAsync(ProtocolJson.Default.LogTailDto);
Assert.NotEmpty(lines.Lines);
Assert.True(lines.Lines.Count <= 20);
using var files = await admin.GetAsync("/api/v1/logs/files");
var name = (await files.ReadAsync(ProtocolJson.Default.ListLogFileDto)).First().Name;
using (var download = await admin.GetAsync($"/api/v1/logs/files/{name}")) await download.ExpectAsync(HttpStatusCode.OK);
using var traversal = await admin.GetAsync("/api/v1/logs/files/..%2Fserver.json");
await traversal.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found");
}
[Test]
public async Task TheCurrentLogDownloadsWhileTheServerKeepsLogging()
{
await using var server = await TestServer.StartAsync(context, o => o.LogLevel = Microsoft.Extensions.Logging.LogLevel.Information);
var admin = await server.AdminAsync();
using var files = await admin.GetAsync("/api/v1/logs/files");
var name = (await files.ReadAsync(ProtocolJson.Default.ListLogFileDto)).First().Name;
// Jobs, uploads and sign-ins keep writing to the file an administrator downloads: a log of a few megabytes takes
// a while to send, and a line lands about every millisecond meanwhile. Only to the file and never in a tight loop:
// engine code of every test server in this process logs through the last one started, so this server's console
// and file lock are shared with the tests running alongside.
var logger = server.Services.GetServices<ILoggerProvider>().OfType<FileLoggerProvider>().Single().CreateLogger("Titano.Server.Tests");
var block = new string('x', 64 * 1024);
for (var i = 0; i < 32; i++) logger.LogInformation("{Block}", block);
using var stop = new CancellationTokenSource();
var logging = Task.Factory.StartNew(() =>
{
while (!stop.IsCancellationRequested)
{
logger.LogInformation("Busy");
Thread.Sleep(1);
}
}, TaskCreationOptions.LongRunning);
try
{
for (var i = 0; i < 5; i++)
{
using var download = await admin.GetAsync($"/api/v1/logs/files/{name}");
await download.ExpectAsync(HttpStatusCode.OK);
Assert.Equal(download.Content.Headers.ContentLength, (await download.Content.ReadAsByteArrayAsync()).LongLength);
}
}
finally
{
await stop.CancelAsync();
await logging;
}
}
[Test]
public async Task ArchiveSettingsValidateTemplatesAndJobsNeedHandlers()
{
await using var server = await TestServer.StartAsync(context);
var admin = await server.AdminAsync();
using var read = await admin.GetAsync("/api/v1/archive/settings");
var archive = await read.ReadAsync(ProtocolJson.Default.ArchiveSettingsDto);
Assert.Equal(Path.GetFullPath(server.Options.ArchivePath), archive.RootPath);
using (var bad = await admin.PutAsJsonAsync("/api/v1/archive/settings", archive with { FolderTemplate = "{year/{date" }, ProtocolJson.Default.ArchiveSettingsDto))
Assert.Equal("folderTemplate", (await bad.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_template")).Details);
using (var good = await admin.PutAsJsonAsync("/api/v1/archive/settings", archive with { Name = "Studio", ProxyLongEdge = 2560 }, ProtocolJson.Default.ArchiveSettingsDto))
{
var saved = await good.ReadAsync(ProtocolJson.Default.ArchiveSettingsDto);
Assert.Equal(("Studio", 2560), (saved.Name, saved.ProxyLongEdge));
}
using var scan = await admin.PostAsync("/api/v1/archive/scan", null);
await scan.ExpectErrorAsync(HttpStatusCode.Conflict, "job_unavailable");
using var stats = await admin.GetAsync("/api/v1/archive/stats");
await stats.ExpectAsync(HttpStatusCode.OK);
}
[Test]
public async Task ArchiveSettingsAreWrittenToArchiveJsonAndSurviveARestart()
{
await using var server = await TestServer.StartAsync(context);
var admin = await server.AdminAsync();
using var read = await admin.GetAsync("/api/v1/archive/settings");
var archive = await read.ReadAsync(ProtocolJson.Default.ArchiveSettingsDto);
var changed = archive with { Name = "Studio", FolderTemplate = "{year}/{camera}", FileTemplate = "{name}", ProxyLongEdge = -1 };
using (var put = await admin.PutAsJsonAsync("/api/v1/archive/settings", changed, ProtocolJson.Default.ArchiveSettingsDto))
await put.ExpectAsync(HttpStatusCode.OK);
// archive.json is the truth (BRIEF §7): the proxy jobs read it, and the next start registers the archive from it.
var manifest = Titano.Core.Archiving.ManifestStore.ReadArchive(new Titano.Core.Archiving.ArchivePaths(server.Options.ArchivePath).ManifestPath);
Assert.Equal(("Studio", "{year}/{camera}", "{name}", -1), (manifest.Name, manifest.LayoutTemplates.Folder, manifest.LayoutTemplates.File, manifest.ProxyPolicy.LongEdge));
var restarted = await Titano.Server.Storage.ServerArchive.OpenAsync(server.Database, server.Options, context.Cancellation);
Assert.Equal(("Studio", "{name}", -1), (restarted.Current.Name, restarted.Current.FileTemplate, restarted.Current.ProxyLongEdge));
using var again = await admin.GetAsync("/api/v1/archive/settings");
Assert.Equal(changed, await again.ReadAsync(ProtocolJson.Default.ArchiveSettingsDto));
// The archive drive is gone: nothing is written and the admin hears why.
var path = new Titano.Core.Archiving.ArchivePaths(server.Options.ArchivePath).ManifestPath;
File.Move(path, path + ".away");
try
{
using var offline = await admin.PutAsJsonAsync("/api/v1/archive/settings", changed with { ProxyLongEdge = 1280 }, ProtocolJson.Default.ArchiveSettingsDto);
await offline.ExpectErrorAsync(HttpStatusCode.ServiceUnavailable, "archive_offline");
}
finally
{
File.Move(path + ".away", path);
}
Assert.Equal(-1, Titano.Core.Archiving.ManifestStore.ReadArchive(path).ProxyPolicy.LongEdge);
// A damaged archive.json is reported as such (not as an internal error) and left as it is.
var saved = await File.ReadAllBytesAsync(path, context.Cancellation);
await File.WriteAllTextAsync(path, "{ not json", context.Cancellation);
try
{
using var damaged = await admin.PutAsJsonAsync("/api/v1/archive/settings", changed with { ProxyLongEdge = 1280 }, ProtocolJson.Default.ArchiveSettingsDto);
await damaged.ExpectErrorAsync(HttpStatusCode.Conflict, "archive_manifest");
Assert.Equal("{ not json", await File.ReadAllTextAsync(path, context.Cancellation));
}
finally
{
await File.WriteAllBytesAsync(path, saved, context.Cancellation);
}
}
}