feat: single setup, mass-pass progress, per-server homes, Desktop shares its library (owner review 5, v1.1.0) (#68)
CI / Build and test (push) Successful in 11m36s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 12s
Release / Build, test and publish (push) Successful in 14m56s
CI / PostgreSQL 16 integration (push) Successful in 10m11s
CI / PostgreSQL 17 integration (push) Successful in 10m15s
CI / Docker image (push) Successful in 45s
Release / Server image (push) Successful in 4m55s
CI / Build and test (push) Successful in 11m36s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 12s
Release / Build, test and publish (push) Successful in 14m56s
CI / PostgreSQL 16 integration (push) Successful in 10m11s
CI / PostgreSQL 17 integration (push) Successful in 10m15s
CI / Docker image (push) Successful in 45s
Release / Server image (push) Successful in 4m55s
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #68.
This commit is contained in:
1 parent
988068ee8e
commit
20d64af4a4
793 files changed
+23882
-2096
No files matched your search
@@ -0,0 +1,117 @@
|
||||
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;
|
||||
|
||||
/// <summary>The server's stable id announced by <c>/server/info</c> (owner review 5, #66).</summary>
|
||||
[Category("server")]
|
||||
public sealed class ServerInfoIdTests(TestContext context)
|
||||
{
|
||||
private static async Task<ServerInfo> 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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Events;
|
||||
using Chronos.Server.Jobs;
|
||||
using Chronos.Server.Tests.Jobs;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Server.Tests.Events;
|
||||
|
||||
/// <summary>
|
||||
/// What a job does now on the wire (owner review 5, #65): the progress event, the job and a render node's report carry an
|
||||
/// optional detail, older and newer peers read each other, and the event socket gets a job's progress at most twice a second.
|
||||
/// </summary>
|
||||
[Category("server")]
|
||||
public sealed class ProgressEventTests(TestContext context)
|
||||
{
|
||||
private static readonly JobDetailDto Verify = new("verify", "Harbour sunset", 812, 2400, 3, 41, "sequence");
|
||||
|
||||
[Test]
|
||||
public void TheProgressEventCarriesItsDetailInCamelCase()
|
||||
{
|
||||
var id = Guid.CreateVersion7();
|
||||
var json = JsonSerializer.Serialize<ServerEvent>(new JobProgressEvent(id, 3, 10, 2.5, 4, Verify), ProtocolJson.Default.ServerEvent);
|
||||
Assert.Contains("\"type\":\"jobProgress\"", json);
|
||||
Assert.Contains("\"detail\":{\"step\":\"verify\",\"item\":\"Harbour sunset\",\"itemDone\":812,\"itemTotal\":2400,\"part\":3,\"parts\":41,\"partUnit\":\"sequence\"}", json);
|
||||
Assert.Equal(new JobProgressEvent(id, 3, 10, 2.5, 4, Verify), JsonSerializer.Deserialize(json, ProtocolJson.Default.ServerEvent));
|
||||
// None is left out.
|
||||
var plain = JsonSerializer.Serialize<ServerEvent>(new JobProgressEvent(id, 3, 10, null, null), ProtocolJson.Default.ServerEvent);
|
||||
Assert.False(plain.Contains("detail", StringComparison.Ordinal), plain);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AnOlderPeersPayloadReadsWithoutADetail()
|
||||
{
|
||||
var id = Guid.CreateVersion7();
|
||||
var progress = JsonSerializer.Deserialize($$"""{"type":"jobProgress","jobId":"{{id}}","done":1,"total":4,"itemsPerSecond":null,"etaSeconds":null}""",
|
||||
ProtocolJson.Default.ServerEvent);
|
||||
Assert.Equal(new JobProgressEvent(id, 1, 4, null, null), progress);
|
||||
Assert.Equal(new NodeProgress(120, 3600, 40, "encoding"),
|
||||
JsonSerializer.Deserialize("""{"done":120,"total":3600,"itemsPerSecond":40,"logLine":"encoding"}""", ProtocolJson.Default.NodeProgress));
|
||||
var job = JsonSerializer.Deserialize($$"""
|
||||
{"id":"{{id}}","kind":"verify","targetIds":[],"state":"running","priority":"normal","progressDone":1,"progressTotal":4,
|
||||
"attempts":1,"created":"2026-11-15T10:00:00Z"}
|
||||
""", ProtocolJson.Default.JobDto)!;
|
||||
Assert.Null(job.Detail);
|
||||
Assert.Null(JobWire.FromDto(job)!.Detail);
|
||||
// A detail of fewer fields (a newer peer's that drops some, or a sparse one) reads with zeros.
|
||||
Assert.Equal(new JobDetailDto("backup"), JsonSerializer.Deserialize("""{"step":"backup"}""", ProtocolJson.Default.JobDetailDto));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ANewerPayloadReadsIntoAnOlderRecord()
|
||||
{
|
||||
var id = Guid.CreateVersion7();
|
||||
var web = new JsonSerializerOptions(JsonSerializerDefaults.Web);
|
||||
var json = JsonSerializer.Serialize<ServerEvent>(new JobProgressEvent(id, 3, 10, 2.5, 4, Verify), ProtocolJson.Default.ServerEvent);
|
||||
Assert.Equal(new JobProgressBefore(id, 3, 10, 2.5, 4), JsonSerializer.Deserialize<JobProgressBefore>(json, web));
|
||||
var node = JsonSerializer.Serialize(new NodeProgress(120, 3600, 40, "encoding", new JobDetailDto("encode", null, 120, 3600)), ProtocolJson.Default.NodeProgress);
|
||||
Assert.Equal(new NodeProgressBefore(120, 3600, 40, "encoding"), JsonSerializer.Deserialize<NodeProgressBefore>(node, web));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheGateLetsAJobsProgressOutTwiceASecondButForNewStepsAndCompletedCounts()
|
||||
{
|
||||
var clock = new TimestampClock();
|
||||
var gate = new ProgressGate(clock);
|
||||
var job = Guid.CreateVersion7();
|
||||
Assert.True(gate.Passes(job, 1, 100, JobStep.Verify), "the first");
|
||||
clock.Advance(TimeSpan.FromMilliseconds(100));
|
||||
Assert.False(gate.Passes(job, 2, 100, JobStep.Verify));
|
||||
Assert.True(gate.Passes(job, 3, 100, JobStep.Replace), "a new step");
|
||||
Assert.True(gate.Passes(job, 100, 100, JobStep.Replace), "a completed count");
|
||||
Assert.True(gate.Passes(Guid.CreateVersion7(), 1, 100, JobStep.Verify), "another job");
|
||||
clock.Advance(TimeSpan.FromMilliseconds(300));
|
||||
Assert.False(gate.Passes(job, 4, 100, JobStep.Replace));
|
||||
// The engine spaces its reports by the same half second, measured a moment before: they are not dropped.
|
||||
clock.Advance(TimeSpan.FromMilliseconds(160));
|
||||
Assert.True(gate.Passes(job, 5, 100, JobStep.Replace), "on time");
|
||||
Assert.False(gate.Passes(job, 6, 100, JobStep.Replace));
|
||||
// A job that stops running is forgotten; its next run starts afresh.
|
||||
gate.Forget(job);
|
||||
Assert.True(gate.Passes(job, 7, 100, JobStep.Replace), "after a pause");
|
||||
gate.Forget(job);
|
||||
Assert.Equal(1, gate.Count);
|
||||
Assert.Equal(TimeSpan.FromMilliseconds(500), ProgressGate.Interval);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AJobThatAlternatesStepsStillGoesOutAFewTimesASecond()
|
||||
{
|
||||
var clock = new TimestampClock();
|
||||
var gate = new ProgressGate(clock);
|
||||
var job = Guid.CreateVersion7();
|
||||
// An incremental scan: every other folder changed, checked and indexed in turn, 200 reports in a second.
|
||||
var passed = 0;
|
||||
for (var i = 0; i < 200; i++)
|
||||
{
|
||||
if (gate.Passes(job, i, 10_000, i % 2 == 0 ? JobStep.Check : JobStep.Index)) passed++;
|
||||
clock.Advance(TimeSpan.FromMilliseconds(5));
|
||||
}
|
||||
Assert.True(passed <= 14, $"{passed} passed");
|
||||
Assert.True(passed >= 4, $"{passed} passed: a new step still goes out early");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheServerSendsAndSavesWhatItsJobsDo()
|
||||
{
|
||||
var handler = new DetailJobHandler();
|
||||
await using var server = await TestServer.StartAsync(context, services: s => s.AddSingleton<IJobHandler>(handler));
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
var sequence = await JobApiTests.CreateSequenceAsync(editor);
|
||||
var hub = server.Services.GetRequiredService<EventHub>();
|
||||
using var subscription = hub.Subscribe();
|
||||
|
||||
var job = await JobApiTests.CreateAsync(editor, "deep-analyse", sequence);
|
||||
await handler.Started.Task.WaitAsync(TimeSpan.FromSeconds(10));
|
||||
var running = await JobApiTests.GetAsync(editor, job.Id);
|
||||
Assert.Equal(DetailJobHandler.Expected, running.Detail);
|
||||
handler.Release();
|
||||
var done = await JobApiTests.WaitForAsync(editor, job.Id, "done");
|
||||
// Kept once the job ends, as it was last saved.
|
||||
Assert.Equal(DetailJobHandler.Expected with { ItemDone = 4 }, done.Detail);
|
||||
using (var list = await editor.GetAsync("/api/v1/jobs"))
|
||||
{
|
||||
var page = await list.ReadAsync(ProtocolJson.Default.PageJobDto);
|
||||
Assert.Equal(DetailJobHandler.Expected with { ItemDone = 4 }, page.Items.Single(j => j.Id == job.Id).Detail);
|
||||
}
|
||||
|
||||
var progress = new List<JobProgressEvent>();
|
||||
while (subscription.Reader.TryRead(out var e))
|
||||
{
|
||||
if (e is JobProgressEvent p && p.JobId == job.Id) progress.Add(p);
|
||||
}
|
||||
Assert.SequenceEqual([1L, 4L], progress.Select(p => p.Done));
|
||||
Assert.SequenceEqual([DetailJobHandler.Expected, DetailJobHandler.Expected with { ItemDone = 4 }], progress.Select(p => p.Detail));
|
||||
// The ended job is forgotten once its state goes out.
|
||||
var gate = server.Services.GetRequiredService<JobEngineHost>().Gate;
|
||||
for (var i = 0; i < 200 && gate.Count > 0; i++) await Task.Delay(25, context.Cancellation);
|
||||
Assert.Equal(0, gate.Count);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ARenderNodeSendsWhatItDoesAndAnOlderNodeNothing()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor", renderNode: true);
|
||||
var sequence = await JobApiTests.CreateSequenceAsync(editor);
|
||||
var job = await JobApiTests.CreateAsync(editor, "render", sequence, RenderNodeTests.HevcJob);
|
||||
var node = await RenderNodeTests.RegisterAsync(editor, "studio-pc", "hevc", 8192);
|
||||
using (var claim = await editor.PostAsync($"/api/v1/nodes/{node.Id}/claim", null)) await claim.ExpectAsync(HttpStatusCode.OK);
|
||||
using var subscription = server.Services.GetRequiredService<EventHub>().Subscribe();
|
||||
|
||||
var encode = new JobDetailDto("encode", "Harbour sunset", 120, 3600, 1, 1, "render");
|
||||
await ReportAsync(new NodeProgress(120, 3600, 40, "encoding", encode));
|
||||
Assert.Equal(encode, (await JobApiTests.GetAsync(editor, job.Id)).Detail);
|
||||
// A step or unit this server does not know is stored as none, with its counts.
|
||||
await ReportAsync(new NodeProgress(130, 3600, 40, null, new JobDetailDto("teleport", null, 130, 3600, 0, 0, "galaxy")));
|
||||
Assert.Equal(new JobDetailDto("none", null, 130, 3600), (await JobApiTests.GetAsync(editor, job.Id)).Detail);
|
||||
// An older node sends none: the counts alone.
|
||||
await ReportAsync(new NodeProgress(140, 3600, 40, null));
|
||||
var stored = await JobApiTests.GetAsync(editor, job.Id);
|
||||
Assert.Equal((140L, (JobDetailDto?)null), (stored.ProgressDone, stored.Detail));
|
||||
|
||||
var events = new List<JobProgressEvent>();
|
||||
while (subscription.Reader.TryRead(out var e))
|
||||
{
|
||||
if (e is JobProgressEvent p) events.Add(p);
|
||||
}
|
||||
Assert.Equal(encode, events[0].Detail);
|
||||
Assert.True(events.All(e => e.JobId == job.Id), "only the node's job");
|
||||
|
||||
async Task ReportAsync(NodeProgress progress)
|
||||
{
|
||||
using var response = await editor.PostAsJsonAsync($"/api/v1/nodes/{node.Id}/jobs/{job.Id}/progress", progress, ProtocolJson.Default.NodeProgress);
|
||||
await response.ExpectAsync(HttpStatusCode.NoContent);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A progress event as a 1.0 client reads it.</summary>
|
||||
private sealed record JobProgressBefore(Guid JobId, long Done, long Total, double? ItemsPerSecond, double? EtaSeconds);
|
||||
|
||||
/// <summary>A node's report as a 1.0 server reads it.</summary>
|
||||
private sealed record NodeProgressBefore(long Done, long Total, double? ItemsPerSecond, string? LogLine);
|
||||
|
||||
/// <summary>A monotonic clock the test moves by hand.</summary>
|
||||
private sealed class TimestampClock : TimeProvider
|
||||
{
|
||||
private long _ticks;
|
||||
|
||||
public override long TimestampFrequency => TimeSpan.TicksPerSecond;
|
||||
|
||||
public override long GetTimestamp() => Interlocked.Read(ref _ticks);
|
||||
|
||||
public void Advance(TimeSpan by) => Interlocked.Add(ref _ticks, by.Ticks);
|
||||
}
|
||||
|
||||
/// <summary>A deep analysis that says what it does, waits to be released, then completes.</summary>
|
||||
private sealed class DetailJobHandler : IJobHandler
|
||||
{
|
||||
public static readonly JobDetailDto Expected = new("analyse", "Harbour sunset", 1, 4, 1, 1, "sequence");
|
||||
|
||||
private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
public JobKind Kind => JobKind.DeepAnalyse;
|
||||
|
||||
public TaskCompletionSource Started { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
public void Release() => _release.TrySetResult();
|
||||
|
||||
public async Task RunAsync(JobContext context)
|
||||
{
|
||||
await context.CheckpointAsync("1", 1, 4, JobWire.FromDto(Expected)!);
|
||||
Started.TrySetResult();
|
||||
await _release.Task.WaitAsync(context.Cancellation);
|
||||
await context.ReportItemAsync(4, 4, 4, 4);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Server.Tests.Hosting;
|
||||
|
||||
/// <summary>
|
||||
/// What a job does now in the admin panel (owner review 5, #65; <c>Admin/web/jobs.js</c>): the Jobs page and the dashboard
|
||||
/// draw the status line under the target and move it with every progress event, and every step, part and sub-step the
|
||||
/// server can send is worded in English and Italian.
|
||||
/// </summary>
|
||||
[Category("server")]
|
||||
public sealed class AdminJobDetailTests(TestContext context)
|
||||
{
|
||||
private static readonly string[] MaintenanceSteps = ["Leases", "Temp", "Packs", "Duplicates", "Vacuum"];
|
||||
|
||||
[Test]
|
||||
public async Task TheJobsPageAndTheDashboardShowTheStatusLine()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
var jobs = await server.Client.GetStringAsync("/admin/jobs.js");
|
||||
foreach (var helper in new[] { "statusText(detail)", "rowStatus(job)", "speedText(kind, rate)", "leftText(seconds)", "targetCell(job)", "statusLine(job)", "updateStatus(row, job)" })
|
||||
Assert.Contains($"export function {helper}", jobs);
|
||||
// Items are data: they read in their own direction, and the whole line is the tooltip.
|
||||
Assert.Contains(@"<span class=""progress-detail"" dir=""auto"" title=""${attr(tip)}"">", jobs);
|
||||
foreach (var page in new[] { "/admin/pages/jobs.js", "/admin/pages/dashboard.js" })
|
||||
{
|
||||
var text = await server.Client.GetStringAsync(page);
|
||||
Assert.Contains(@"<span class=""target-cell"" role=""cell"">${targetCell(j)}</span>", text);
|
||||
Assert.Contains("if (e.detail) job.detail = e.detail;", text);
|
||||
Assert.Contains("updateStatus(row, job);", text);
|
||||
Assert.True(!text.Contains(" style=", StringComparison.Ordinal), "inline style");
|
||||
}
|
||||
Assert.Contains(".progress-detail {", await server.Client.GetStringAsync("/admin/admin.css"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task EveryStepAndPartIsInEnglishAndItalian()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
var jobs = await server.Client.GetStringAsync("/admin/jobs.js");
|
||||
var en = Assert.NotNull(await server.Client.GetFromJsonAsync("/api/v1/i18n/en", ProtocolJson.Default.DictionaryStringString));
|
||||
var it = Assert.NotNull(await server.Client.GetFromJsonAsync("/api/v1/i18n/it", ProtocolJson.Default.DictionaryStringString));
|
||||
var keys = Regex.Matches(jobs, @"""(Admin\.[A-Za-z]+(?:\.[A-Za-z]+)*)""").Select(m => m.Groups[1].Value).ToList();
|
||||
Assert.Contains("Admin.Job.Detail.StoppedAt", keys);
|
||||
// The keys built from what the server sends.
|
||||
keys.AddRange(Enum.GetValues<JobStep>().Where(s => s != JobStep.None).Select(s => $"Admin.Job.Step.{s}"));
|
||||
keys.AddRange(Enum.GetValues<JobPartUnit>().Where(u => u != JobPartUnit.None).Select(u => $"Admin.Job.Part.{u}"));
|
||||
keys.AddRange(MaintenanceSteps.Select(s => $"Admin.Job.Maintenance.Step.{s}"));
|
||||
foreach (var key in keys.Distinct())
|
||||
Assert.True(en.ContainsKey(key) && it.ContainsKey(key), key);
|
||||
// The step and the unit keys are the wire names in PascalCase, as the panel builds them.
|
||||
Assert.Equal("copy-photo", JobWire.Step(JobStep.CopyPhoto));
|
||||
Assert.Equal("Copia foto {0} di {1}", it["Admin.Job.Step.CopyPhoto.Count"]);
|
||||
Assert.Equal("Verifying photo {0} of {1}", en["Admin.Job.Step.Verify.Count"]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,390 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Imaging.Decoders;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Video.Managed;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Processing;
|
||||
using Chronos.Data.Scheduling;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Api;
|
||||
using Chronos.Server.Configuration;
|
||||
using Chronos.Server.Hosting;
|
||||
using Chronos.Server.Jobs;
|
||||
using Chronos.Server.Security;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Server.Tests.Hosting;
|
||||
|
||||
/// <summary>
|
||||
/// The server Chronos Desktop hosts to share this PC's library (owner review 5, #67): built over an index, engines, a job
|
||||
/// engine and a scheduler the test owns, as the desktop does, which it never creates, starts, stops or disposes.
|
||||
/// </summary>
|
||||
[Category("server")]
|
||||
[Serial] // Log.Sink is process-wide: the standalone server tests running beside these set their own
|
||||
public sealed class HostedServerTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public async Task ItAnswersWithTheCertificateOfItsDataFolderAndKeepsItsIdAcrossRestarts()
|
||||
{
|
||||
await using var desktop = await DesktopFixture.StartAsync(context);
|
||||
Guid? firstId;
|
||||
string? fingerprint;
|
||||
await using (var shared = await desktop.ShareAsync())
|
||||
{
|
||||
using var http = desktop.Client(shared);
|
||||
using var health = await http.GetAsync("/health");
|
||||
Assert.Equal(HttpStatusCode.OK, health.StatusCode);
|
||||
var info = Assert.NotNull(await http.GetFromJsonAsync("/api/v1/server/info", ProtocolJson.Default.ServerInfo));
|
||||
var pfx = X509CertificateLoader.LoadPkcs12FromFile(Path.Combine(desktop.ShareData, "tls", "server.pfx"), null);
|
||||
Assert.Equal(CertificateStore.Fingerprint(pfx), shared.Fingerprint);
|
||||
Assert.Equal(shared.ServerId, info.ServerId);
|
||||
Assert.True(shared.HttpsPort > 0, "the HTTPS listener's port");
|
||||
firstId = shared.ServerId;
|
||||
fingerprint = shared.Fingerprint;
|
||||
}
|
||||
// A second start on the same folder and index: the same certificate, id and administrator.
|
||||
await using var again = await desktop.ShareAsync();
|
||||
Assert.Equal(fingerprint, again.Fingerprint);
|
||||
Assert.Equal(firstId, again.ServerId);
|
||||
Assert.Count(1, (await desktop.Database.Users.ListAsync()).Where(u => u.Role == UserRole.Admin));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task JobsQueuedByClientsRunOnTheDesktopsEngineWhichOutlivesTheServer()
|
||||
{
|
||||
await using var desktop = await DesktopFixture.StartAsync(context);
|
||||
var sink = Log.Sink;
|
||||
await using (var shared = await desktop.ShareAsync())
|
||||
{
|
||||
Assert.Same(desktop.Engine, shared.Services.GetRequiredService<JobEngineHost>().Engine);
|
||||
Assert.True(shared.Services.GetRequiredService<JobEngineHost>().Hosted, "hosted");
|
||||
using var admin = await desktop.AdminAsync(shared);
|
||||
using var created = await admin.PostAsJsonAsync("/api/v1/jobs", new CreateJobRequest("scan", [], null), ProtocolJson.Default.CreateJobRequest);
|
||||
Assert.Equal(HttpStatusCode.Accepted, created.StatusCode);
|
||||
var job = Assert.NotNull(await created.Content.ReadFromJsonAsync(ProtocolJson.Default.JobDto));
|
||||
var done = await desktop.WaitAsync(job.Id);
|
||||
Assert.Equal(JobState.Done, done.State);
|
||||
Assert.Equal(DesktopFixture.WorkerId, done.NodeId);
|
||||
Assert.Same(sink, Log.Sink);
|
||||
}
|
||||
// Stopped: the index answers, the engine runs jobs, the scheduler still works, the log sink is the desktop's.
|
||||
Assert.Same(sink, Log.Sink);
|
||||
var after = await desktop.Engine.EnqueueAsync(JobKind.Scan, [desktop.Archive.Id], "after");
|
||||
Assert.Equal(JobState.Done, (await desktop.WaitAsync(after.Id)).State);
|
||||
Assert.NotNull(await desktop.Scheduler.ListAsync(context.Cancellation));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheServerAddsOnlyItsOwnSystemSchedulesToTheDesktops()
|
||||
{
|
||||
await using var desktop = await DesktopFixture.StartAsync(context);
|
||||
var before = (await desktop.Scheduler.ListAsync(context.Cancellation)).Items.Select(s => s.SystemKey).OfType<string>().ToHashSet();
|
||||
await using var shared = await desktop.ShareAsync();
|
||||
var after = (await desktop.Scheduler.ListAsync(context.Cancellation)).Items.Select(s => s.SystemKey).OfType<string>().ToHashSet();
|
||||
Assert.SequenceEqual([ServerScheduleHost.AuditCleanup, ServerScheduleHost.UploadCleanup], after.Except(before).Order(StringComparer.Ordinal));
|
||||
Assert.SequenceEqual([DesktopFixture.ScanKey], before);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ItServesTheDesktopsArchiveAloneAndHidesItsPrivateJobs()
|
||||
{
|
||||
await using var desktop = await DesktopFixture.StartAsync(context);
|
||||
var mine = await desktop.SequenceAsync(desktop.Archive);
|
||||
var other = await desktop.Archives.CreateAsync(context.CreateTempDirectory("other"), "Another archive", cancellationToken: context.Cancellation);
|
||||
var theirs = await desktop.SequenceAsync(other);
|
||||
var workspace = await desktop.Engine.EnqueueAsync(JobKind.WorkspaceCopy, [mine.Id], "workspace");
|
||||
await using var shared = await desktop.ShareAsync();
|
||||
using var admin = await desktop.AdminAsync(shared);
|
||||
|
||||
using (var ok = await admin.GetAsync($"/api/v1/sequences/{mine.Id}")) Assert.Equal(HttpStatusCode.OK, ok.StatusCode);
|
||||
foreach (var path in new[] { $"/api/v1/sequences/{theirs.Id}", $"/api/v1/sequences/{theirs.Id}/projects", $"/api/v1/sequences/{theirs.Id}/frames" })
|
||||
{
|
||||
using var hidden = await admin.GetAsync(path);
|
||||
Assert.Equal(HttpStatusCode.NotFound, hidden.StatusCode, path);
|
||||
}
|
||||
using (var job = await admin.PostAsJsonAsync("/api/v1/jobs", new CreateJobRequest("thumbs", [theirs.Id], null), ProtocolJson.Default.CreateJobRequest))
|
||||
Assert.Equal(HttpStatusCode.NotFound, job.StatusCode);
|
||||
|
||||
var listed = Assert.NotNull(await admin.GetFromJsonAsync("/api/v1/jobs", ProtocolJson.Default.PageJobDto));
|
||||
Assert.False(listed.Items.Any(j => j.Id == workspace.Id), "a workspace job is the desktop's own");
|
||||
using (var get = await admin.GetAsync($"/api/v1/jobs/{workspace.Id}")) Assert.Equal(HttpStatusCode.NotFound, get.StatusCode);
|
||||
using (var cancel = await admin.PostAsync($"/api/v1/jobs/{workspace.Id}/cancel", null)) Assert.Equal(HttpStatusCode.NotFound, cancel.StatusCode);
|
||||
Assert.Equal(JobState.Queued, (await desktop.Database.Jobs.GetAsync(workspace.Id))!.State);
|
||||
|
||||
// The events say nothing of the desktop's own jobs, nor of its work on its other archive; the shared archive's go out.
|
||||
using var events = shared.Events.Subscribe();
|
||||
await desktop.Engine.CancelAsync(workspace.Id);
|
||||
var elsewhere = await desktop.Engine.EnqueueAsync(JobKind.Thumbs, [theirs.Id], "theirs");
|
||||
await desktop.WaitAsync(elsewhere.Id);
|
||||
var served = await desktop.Engine.EnqueueAsync(JobKind.Thumbs, [mine.Id], "mine");
|
||||
var finished = JobWire.State((await desktop.WaitAsync(served.Id)).State);
|
||||
var seen = new List<ServerEvent>();
|
||||
using (var wait = CancellationTokenSource.CreateLinkedTokenSource(context.Cancellation))
|
||||
{
|
||||
wait.CancelAfter(TimeSpan.FromSeconds(30));
|
||||
while (await events.Reader.ReadAsync(wait.Token) is var e)
|
||||
{
|
||||
seen.Add(e);
|
||||
if (e is JobStateEvent { State: var state } done && done.JobId == served.Id && state == finished) break;
|
||||
}
|
||||
}
|
||||
Assert.Contains(seen, e => e is JobStateEvent s && s.JobId == served.Id);
|
||||
Assert.False(seen.Any(e => e is JobStateEvent s && (s.JobId == workspace.Id || s.JobId == elsewhere.Id)), "a private job's state went out");
|
||||
Assert.False(seen.Any(e => e is JobProgressEvent p && (p.JobId == workspace.Id || p.JobId == elsewhere.Id)), "a private job's progress went out");
|
||||
Assert.False(seen.Any(e => e is SequenceChangedEvent c && c.SequenceId == theirs.Id), "another archive's sequence went out");
|
||||
var all = Assert.NotNull(await admin.GetFromJsonAsync("/api/v1/jobs", ProtocolJson.Default.PageJobDto));
|
||||
Assert.False(all.Items.Any(j => j.Id == elsewhere.Id), "a job on the desktop's other archive is listed");
|
||||
Assert.True(all.Items.Any(j => j.Id == served.Id), "the shared archive's job is listed");
|
||||
using (var get = await admin.GetAsync($"/api/v1/jobs/{elsewhere.Id}")) Assert.Equal(HttpStatusCode.NotFound, get.StatusCode);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task RenderNodesTakeOnlyTheRendersClientsQueuedOnTheSharedArchive()
|
||||
{
|
||||
await using var desktop = await DesktopFixture.StartAsync(context);
|
||||
var mine = await desktop.SequenceAsync(desktop.Archive);
|
||||
var other = await desktop.Archives.CreateAsync(context.CreateTempDirectory("other"), "Another archive", cancellationToken: context.Cancellation);
|
||||
var theirs = await desktop.SequenceAsync(other);
|
||||
await using var shared = await desktop.ShareAsync();
|
||||
using var admin = await desktop.AdminAsync(shared);
|
||||
var hevc = Jobs.RenderNodeTests.HevcJob;
|
||||
// Older and as urgent as the client's: the desktop's own render (its export goes where its user chose), and one of
|
||||
// a sequence of the desktop's other archive.
|
||||
await desktop.Engine.EnqueueAsync(JobKind.Render, [mine.Id], "desktop", hevc, JobPriority.User);
|
||||
await desktop.Engine.EnqueueAsync(JobKind.Render, [theirs.Id], "elsewhere", hevc, JobPriority.User, Guid.CreateVersion7());
|
||||
using var created = await admin.PostAsJsonAsync("/api/v1/jobs", new CreateJobRequest("render", [mine.Id], hevc), ProtocolJson.Default.CreateJobRequest);
|
||||
Assert.Equal(HttpStatusCode.Accepted, created.StatusCode);
|
||||
var client = Assert.NotNull(await created.Content.ReadFromJsonAsync(ProtocolJson.Default.JobDto));
|
||||
|
||||
var node = await Jobs.RenderNodeTests.RegisterAsync(admin, "studio-node", "hevc", 8192);
|
||||
using (var claim = await admin.PostAsync($"/api/v1/nodes/{node.Id}/claim", null))
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.OK, claim.StatusCode);
|
||||
var claimed = Assert.NotNull(await claim.Content.ReadFromJsonAsync(ProtocolJson.Default.ClaimedJob));
|
||||
Assert.Equal(client.Id, claimed.Job.Id);
|
||||
}
|
||||
using (var none = await admin.PostAsync($"/api/v1/nodes/{node.Id}/claim", null)) Assert.Equal(HttpStatusCode.NoContent, none.StatusCode);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheDesktopOwnsItsSettingsAndTheFirstAdministratorsPasswordIsInTheShareFolder()
|
||||
{
|
||||
await using var desktop = await DesktopFixture.StartAsync(context);
|
||||
Environment.SetEnvironmentVariable("CHRONOS_SERVER_NAME", "from a variable");
|
||||
try
|
||||
{
|
||||
var options = ServerOptions.ForHosted(desktop.ShareData, desktop.Settings with { ServerName = "Studio PC" });
|
||||
Assert.Equal("Studio PC", options.ServerName);
|
||||
Assert.True(options.Hosted, "hosted");
|
||||
Assert.Contains(nameof(ServerOptions.HttpsPort), options.Locked);
|
||||
Assert.Equal(ServerOptions.DesktopLock, options.LockedBy[nameof(ServerOptions.Parallelism)]);
|
||||
Assert.False(options.Locked.Contains(nameof(ServerOptions.TokenLifetimeDays)), "the admin panel owns the token lifetime");
|
||||
Assert.Equal(Microsoft.Extensions.Logging.LogLevel.None, options.ConsoleLogLevel);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Environment.SetEnvironmentVariable("CHRONOS_SERVER_NAME", null);
|
||||
}
|
||||
await using var shared = await desktop.ShareAsync();
|
||||
Assert.True(File.Exists(shared.AdminPasswordFile), "the temporary password's file");
|
||||
Assert.Equal(Path.Combine(desktop.ShareData, AdminBootstrap.PasswordFileName), shared.AdminPasswordFile);
|
||||
Assert.NotNull(shared.AdminPassword());
|
||||
using var admin = await desktop.AdminAsync(shared);
|
||||
Assert.Null(shared.AdminPassword());
|
||||
var settings = Assert.NotNull(await admin.GetFromJsonAsync("/api/v1/server/settings", ProtocolJson.Default.ServerSettingsDto));
|
||||
Assert.Equal(ServerOptions.DesktopLock, settings.LockedBy["HttpsPort"]);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ClientsAreKeptForFiveMinutes()
|
||||
{
|
||||
var time = new ManualTime(DateTimeOffset.Parse("2026-11-15T10:00:00Z", System.Globalization.CultureInfo.InvariantCulture));
|
||||
var activity = new ClientActivity(time);
|
||||
var user = new User { Id = Guid.CreateVersion7(), Username = "alberto", PasswordHash = "x", Role = UserRole.Editor, Created = time.GetUtcNow() };
|
||||
activity.Record(new Caller(user, "hash", CredentialSource.Bearer, "Chronos Uploader (Studio)"), "192.168.1.20");
|
||||
activity.Record(new Caller(user, "hash", CredentialSource.Cookie, null), "192.168.1.21");
|
||||
var seen = activity.Recent();
|
||||
Assert.Count(2, seen);
|
||||
Assert.Contains("Chronos Uploader (Studio)", seen.Select(s => s.Client));
|
||||
Assert.Contains(ClientActivity.AdminPanel, seen.Select(s => s.Client));
|
||||
time.Advance(TimeSpan.FromMinutes(6));
|
||||
Assert.Count(0, activity.Recent());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ARenderNeverKeepsTheExportFolderAClientChose()
|
||||
{
|
||||
var parameters = new RenderJobParameters("1080p", """{"preset":"1080p","Folder":"C:\\Users\\someone","nameTemplate":"{title}"}""", "h264", 1920, 1080, false, null);
|
||||
var stripped = JobEndpoints.WithoutExportFolder(parameters);
|
||||
Assert.False(stripped.PresetJson.Contains("Users", StringComparison.Ordinal), stripped.PresetJson);
|
||||
Assert.True(stripped.PresetJson.Contains("nameTemplate", StringComparison.Ordinal), stripped.PresetJson);
|
||||
var plain = parameters with { PresetJson = """{"preset":"1080p"}""" };
|
||||
Assert.Same(plain, JobEndpoints.WithoutExportFolder(plain));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheServiceSwitchesAreGone()
|
||||
{
|
||||
var parsed = ServerCommandLine.Parse(["--service", "--install-service", "--uninstall-service"]);
|
||||
Assert.Equal(ServerCommand.Run, parsed.Command);
|
||||
Assert.SequenceEqual(["--service", "--install-service", "--uninstall-service"], parsed.HostArguments);
|
||||
Assert.False(ServerCommandLine.Usage.Contains("service", StringComparison.OrdinalIgnoreCase), "usage names a service");
|
||||
}
|
||||
|
||||
/// <summary>A clock the test moves.</summary>
|
||||
private sealed class ManualTime(DateTimeOffset start) : TimeProvider
|
||||
{
|
||||
private DateTimeOffset _now = start;
|
||||
|
||||
public override DateTimeOffset GetUtcNow() => _now;
|
||||
|
||||
public void Advance(TimeSpan by) => _now += by;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What Chronos Desktop has when it shares its library: a SQLite index, the archive and processing services (managed
|
||||
/// codecs), a started job engine and a started scheduler with one system schedule of its own.
|
||||
/// </summary>
|
||||
internal sealed class DesktopFixture : IAsyncDisposable
|
||||
{
|
||||
public const string WorkerId = "STUDIO-PC";
|
||||
public const string ScanKey = "archive-scan";
|
||||
|
||||
private readonly TestContext _context;
|
||||
|
||||
private DesktopFixture(TestContext context, string root, ChronosDatabase db, ArchiveService archives, ProcessingService processing, JobEngine engine,
|
||||
Scheduler scheduler, Archive archive)
|
||||
{
|
||||
_context = context;
|
||||
Root = root;
|
||||
Database = db;
|
||||
Archives = archives;
|
||||
Processing = processing;
|
||||
Engine = engine;
|
||||
Scheduler = scheduler;
|
||||
Archive = archive;
|
||||
}
|
||||
|
||||
public string Root { get; }
|
||||
public ChronosDatabase Database { get; }
|
||||
public ArchiveService Archives { get; }
|
||||
public ProcessingService Processing { get; }
|
||||
public JobEngine Engine { get; }
|
||||
public Scheduler Scheduler { get; }
|
||||
public Archive Archive { get; }
|
||||
public string ShareData => Path.Combine(Root, "data", "server");
|
||||
|
||||
public HostedSettings Settings => new(null, 0, 0, null, null, Discovery: false, Archive.RootPath, null, 2, false, new Dictionary<string, string>(), "en",
|
||||
LogLevel.Warning, 14, 50, 1024, LogRotation.Daily, 4);
|
||||
|
||||
public static async Task<DesktopFixture> StartAsync(TestContext context)
|
||||
{
|
||||
var root = context.CreateTempDirectory("desktop");
|
||||
Directory.CreateDirectory(Path.Combine(root, "data"));
|
||||
var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(root, "data", "chronos.db")), context.Cancellation);
|
||||
var archiveOptions = new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer(), Parallelism = () => 2 };
|
||||
var archives = new ArchiveService(db, archiveOptions);
|
||||
var processing = new ProcessingService(db, new ProcessingOptions { Archive = archiveOptions, Encoders = [new ManagedEncoderProvider()] });
|
||||
var archive = await archives.CreateAsync(Path.Combine(root, "archive"), "Studio", cancellationToken: context.Cancellation);
|
||||
var handlers = archives.CreateJobHandlers().Concat(processing.CreateJobHandlers()).ToList();
|
||||
var engine = new JobEngine(db, handlers, new JobEngineOptions
|
||||
{
|
||||
WorkerId = WorkerId,
|
||||
Kinds = [.. handlers.Select(h => h.Kind).Distinct()],
|
||||
PollInterval = TimeSpan.FromMilliseconds(100),
|
||||
});
|
||||
await engine.StartAsync(context.Cancellation);
|
||||
var scheduler = new Scheduler(db, engine);
|
||||
await scheduler.StartAsync(new Host(archives, archive), context.Cancellation);
|
||||
return new DesktopFixture(context, root, db, archives, processing, engine, scheduler, archive);
|
||||
}
|
||||
|
||||
public async Task<HostedServer> ShareAsync()
|
||||
{
|
||||
var options = ServerOptions.ForHosted(ShareData, Settings);
|
||||
options.LoginAttemptsPerMinute = 1000;
|
||||
var server = ServerHost.BuildHosted(options, new HostedEngine(Database, Archives, Processing, Engine, Scheduler, Archive));
|
||||
await server.StartAsync(_context.Cancellation);
|
||||
return server;
|
||||
}
|
||||
|
||||
public HttpClient Client(HostedServer server, string? token = null)
|
||||
{
|
||||
var client = new HttpClient { BaseAddress = new Uri($"http://127.0.0.1:{server.HttpPort}"), Timeout = TimeSpan.FromSeconds(60) };
|
||||
if (token is not null) client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||
return client;
|
||||
}
|
||||
|
||||
/// <summary>The first administrator, signed in with its temporary password, which it then replaces.</summary>
|
||||
public async Task<HttpClient> AdminAsync(HostedServer server)
|
||||
{
|
||||
var temporary = server.AdminPassword() ?? throw new InvalidOperationException("No temporary password");
|
||||
using var anonymous = Client(server);
|
||||
using var login = await anonymous.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest("admin", temporary, "tests"), ProtocolJson.Default.LoginRequest);
|
||||
login.EnsureSuccessStatusCode();
|
||||
var token = (await login.Content.ReadFromJsonAsync(ProtocolJson.Default.LoginResponse))!.Token!;
|
||||
var client = Client(server, token);
|
||||
using var changed = await client.PostAsJsonAsync("/api/v1/auth/password", new ChangePasswordRequest(temporary, "a-good-password-1"),
|
||||
ProtocolJson.Default.ChangePasswordRequest);
|
||||
changed.EnsureSuccessStatusCode();
|
||||
return client;
|
||||
}
|
||||
|
||||
public async Task<Sequence> SequenceAsync(Archive archive)
|
||||
{
|
||||
var sequence = new Sequence
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
ArchiveId = archive.Id,
|
||||
Title = "Roof " + archive.Name,
|
||||
Folder = string.Empty,
|
||||
Origin = SequenceOrigin.Server,
|
||||
UpdatedAt = DateTimeOffset.UtcNow,
|
||||
};
|
||||
await Database.Sequences.UpsertAsync(sequence, _context.Cancellation);
|
||||
return sequence;
|
||||
}
|
||||
|
||||
public async Task<Job> WaitAsync(Guid id)
|
||||
{
|
||||
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
|
||||
while (true)
|
||||
{
|
||||
if (await Database.Jobs.GetAsync(id, _context.Cancellation) is { State: JobState.Done or JobState.Failed or JobState.Cancelled } job) return job;
|
||||
Assert.True(DateTime.UtcNow < until, "the job did not finish");
|
||||
await Task.Delay(50, _context.Cancellation);
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await Scheduler.DisposeAsync();
|
||||
await Engine.DisposeAsync();
|
||||
await Database.DisposeAsync();
|
||||
}
|
||||
|
||||
/// <summary>A desktop's schedule host: one archive scan schedule, the archive service's clean-up steps.</summary>
|
||||
private sealed class Host(ArchiveService archives, Archive archive) : IScheduleHost
|
||||
{
|
||||
public TimeZoneInfo TimeZone => TimeZoneInfo.Utc;
|
||||
|
||||
public IReadOnlyList<SystemSchedule> SystemSchedules =>
|
||||
[new(ScanKey, "Archive scan", ScheduleActions.Scan, ScheduleRecurrence.Interval(10, RecurrenceUnit.Minutes), CatchUp: false)];
|
||||
|
||||
public IReadOnlyList<string> CleanupSteps => [.. archives.CleanupSteps.Select(s => s.Name)];
|
||||
|
||||
public bool DeepAnalysisAfterScan => false;
|
||||
|
||||
public ValueTask<Archive?> GetArchiveAsync(CancellationToken cancellationToken) => ValueTask.FromResult<Archive?>(archive);
|
||||
|
||||
public string? Unavailable(string action) => null;
|
||||
}
|
||||
}
|
||||
@@ -1,152 +0,0 @@
|
||||
using System.Diagnostics.Eventing.Reader;
|
||||
using System.Security.AccessControl;
|
||||
using System.Security.Principal;
|
||||
using Chronos.Server.Hosting;
|
||||
using Chronos.Server.Hosting.Windows;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Server.Tests.Hosting;
|
||||
|
||||
public sealed class WindowsServiceTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public void CommandSwitchesAreParsedAndTheRestPassedOn()
|
||||
{
|
||||
Assert.Equal(ServerCommand.Run, ServerCommandLine.Parse([]).Command);
|
||||
var service = ServerCommandLine.Parse(["--service", "--urls", "x"]);
|
||||
Assert.Equal(ServerCommand.Service, service.Command);
|
||||
Assert.SequenceEqual(["--urls", "x"], service.HostArguments);
|
||||
Assert.Equal(ServerCommand.InstallService, ServerCommandLine.Parse(["--install-service"]).Command);
|
||||
Assert.Equal(ServerCommand.UninstallService, ServerCommandLine.Parse(["--uninstall-service"]).Command);
|
||||
Assert.Equal(ServerCommand.HealthCheck, ServerCommandLine.Parse(["--healthcheck"]).Command);
|
||||
Assert.Equal(ServerCommand.Help, ServerCommandLine.Parse(["/?"]).Command);
|
||||
Assert.NotNull(ServerCommandLine.Parse(["--install-service", "--uninstall-service"]).Error);
|
||||
Assert.Null(ServerCommandLine.Parse(["--service", "--service"]).Error);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void StatusReportsFollowTheServiceControlManagerRules()
|
||||
{
|
||||
var tracker = new ServiceStatusTracker();
|
||||
var start = tracker.StartPending(60_000);
|
||||
Assert.Equal((ServiceState.StartPending, 0u, 1u, 60_000u), (start.State, start.ControlsAccepted, start.CheckPoint, start.WaitHintMilliseconds));
|
||||
Assert.Equal(2u, tracker.StartPending(60_000).CheckPoint);
|
||||
var running = tracker.Running();
|
||||
Assert.Equal((ServiceState.Running, ServiceStatusTracker.AcceptStop | ServiceStatusTracker.AcceptShutdown, 0u), (running.State, running.ControlsAccepted, running.CheckPoint));
|
||||
Assert.Throws<InvalidOperationException>(() => tracker.Running());
|
||||
Assert.Equal(1u, tracker.StopPending(35_000).CheckPoint);
|
||||
Assert.Equal(2u, tracker.StopPending(35_000).CheckPoint);
|
||||
var stopped = tracker.Stopped(0);
|
||||
Assert.Equal((ServiceState.Stopped, 0u, 0u), (stopped.State, stopped.ControlsAccepted, stopped.CheckPoint));
|
||||
Assert.Throws<InvalidOperationException>(() => tracker.StopPending(1));
|
||||
Assert.Equal(1064u, new ServiceStatusTracker().Stopped(1064).ExitCode);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AServiceFailureLeadsWithTheReasonTheServerGave()
|
||||
{
|
||||
var refused = new InvalidOperationException(@"C:\ProgramData\Chronos Server belongs to PC\ada, not to SYSTEM, Administrators or the account Chronos Server runs as.");
|
||||
var text = ServiceEventLog.Describe("Chronos Server did not start:", refused);
|
||||
Assert.True(text.StartsWith(@"Chronos Server did not start: C:\ProgramData\Chronos Server belongs to PC\ada", StringComparison.Ordinal), text);
|
||||
Assert.Contains("System.InvalidOperationException", text);
|
||||
|
||||
// ReportEvent refuses a longer string: the text is cut, never between the halves of a surrogate pair.
|
||||
var cut = ServiceEventLog.Describe("x", new InvalidOperationException(new string('a', ServiceEventLog.MaxLength)));
|
||||
Assert.Equal(ServiceEventLog.MaxLength, cut.Length);
|
||||
Assert.True(cut.EndsWith("a\u2026", StringComparison.Ordinal), cut[^5..]);
|
||||
var pair = ServiceEventLog.Describe("x", new InvalidOperationException(new string('a', ServiceEventLog.MaxLength - 4) + "\uD83D\uDE00" + new string('b', 99)));
|
||||
Assert.Equal(ServiceEventLog.MaxLength - 1, pair.Length);
|
||||
Assert.True(pair.EndsWith("a\u2026", StringComparison.Ordinal), pair[^5..]);
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void AServiceFailureReachesTheApplicationEventLog()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
// Written as a source of its own, so a test run never looks like a failed service in Event Viewer.
|
||||
const string source = "Chronos.Server.Tests";
|
||||
var marker = source + " " + Guid.NewGuid().ToString("N");
|
||||
Assert.True(ServiceEventLog.Error(source, ServiceEventLog.StartFailed, marker), "the Application log takes the event");
|
||||
var filter = $"*[System[Provider[@Name='{source}'] and EventID={ServiceEventLog.StartFailed}]]";
|
||||
var query = new EventLogQuery("Application", PathType.LogName, filter) { ReverseDirection = true };
|
||||
for (var attempt = 0; attempt < 50; attempt++)
|
||||
{
|
||||
using (var reader = new EventLogReader(query))
|
||||
{
|
||||
for (var read = 0; read < 100 && reader.ReadEvent() is { } record; read++)
|
||||
{
|
||||
using (record)
|
||||
{
|
||||
// The event's one string, which Event Viewer shows whole.
|
||||
if (record.Properties.Count != 1 || record.Properties[0].Value as string != marker) continue;
|
||||
Assert.Equal((byte?)2, record.Level, "an error");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
Thread.Sleep(100);
|
||||
}
|
||||
Assert.Fail($"No {source} event carries '{marker}'.");
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void TheServiceIsRegisteredOnlyFromInsideProgramFiles()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
var programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
|
||||
Assert.True(ServiceInstaller.IsUnderProgramFiles(Path.Combine(programFiles, "Chronos", "Chronos.Server.exe")));
|
||||
Assert.False(ServiceInstaller.IsUnderProgramFiles(programFiles));
|
||||
Assert.False(ServiceInstaller.IsUnderProgramFiles(programFiles + " Tools\\Chronos"));
|
||||
Assert.False(ServiceInstaller.IsUnderProgramFiles(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs", "Chronos")));
|
||||
Assert.False(ServiceInstaller.IsUnderProgramFiles(Path.Combine(programFiles, "..", "Chronos")));
|
||||
// The test build is not under Program Files: registering it is refused, naming the folder.
|
||||
Assert.Contains(Path.TrimEndingDirectorySeparator(AppContext.BaseDirectory), Assert.NotNull(ServiceInstaller.UnsafeLocation()));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void AnyFileOrdinaryUsersCanChangeIsFound()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
using var identity = WindowsIdentity.GetCurrent();
|
||||
if (!new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator)) Assert.Inconclusive("registering a service needs an administrator");
|
||||
var folder = new DirectoryInfo(context.CreateTempDirectory("program"));
|
||||
File.WriteAllBytes(Path.Combine(folder.FullName, "Chronos.Server.exe"), [1]);
|
||||
var satellite = new FileInfo(Path.Combine(folder.CreateSubdirectory("it").FullName, "Chronos.Core.resources.dll"));
|
||||
File.WriteAllBytes(satellite.FullName, [1]);
|
||||
|
||||
// Like Program Files: administrators may change the folder, users only read it.
|
||||
var locked = new DirectorySecurity();
|
||||
locked.SetAccessRuleProtection(isProtected: true, preserveInheritance: false);
|
||||
var everything = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
|
||||
foreach (var account in new[] { new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null), identity.User! })
|
||||
locked.AddAccessRule(new FileSystemAccessRule(account, FileSystemRights.FullControl, everything, PropagationFlags.None, AccessControlType.Allow));
|
||||
locked.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), FileSystemRights.ReadAndExecute, everything,
|
||||
PropagationFlags.None, AccessControlType.Allow));
|
||||
folder.SetAccessControl(locked);
|
||||
Assert.Null(ServiceInstaller.FindChangeable(folder, recursive: true));
|
||||
|
||||
// One satellite assembly users may replace is enough: the service would load it as SYSTEM.
|
||||
var open = satellite.GetAccessControl();
|
||||
open.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), FileSystemRights.Modify, AccessControlType.Allow));
|
||||
satellite.SetAccessControl(open);
|
||||
Assert.Equal(satellite.FullName, ServiceInstaller.FindChangeable(folder, recursive: true));
|
||||
Assert.Null(ServiceInstaller.FindChangeable(folder, recursive: false));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void TheDispatcherDeclinesAConsoleProcess()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
var built = false;
|
||||
Assert.False(WindowsServiceHost.Run(() =>
|
||||
{
|
||||
built = true;
|
||||
throw new InvalidOperationException("never built outside the SCM");
|
||||
}));
|
||||
Assert.False(built);
|
||||
}
|
||||
}
|
||||
@@ -233,6 +233,32 @@ public sealed class ServerWorkspaceTests(TestContext context)
|
||||
Assert.Null(a.Store.Find(main.Id)!.ReadMedia());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ACopyQueuedUnderTheAddressRunsOnAProjectReKeyedToTheServersId()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
var (_, _, token) = await server.UserAsync("alberto", "editor");
|
||||
var sid = await SequenceAsync(server, token, 2);
|
||||
var id = Guid.CreateVersion7();
|
||||
var idKey = ServerIdentity.IdKey(id);
|
||||
ServerIdentity? identity = null;
|
||||
await using var a = await WorkspaceClient.StartAsync(context, server, token, "PC-A", sameServer: (x, y) => identity!.Same(x, y));
|
||||
identity = ServerIdentity.None.With(id, a.Server);
|
||||
// The project's home names the server by its id (re-keyed at sign-in, owner review 5); the job still names the address.
|
||||
var home = new ServerProjectHome(a.Client, sid, "Test server", server: idKey);
|
||||
var main = (await home.ListAsync(context.Cancellation)).Single();
|
||||
var project = await a.Sync.CheckoutAsync(home, main.Id, cancellationToken: context.Cancellation);
|
||||
Assert.Equal(idKey, project.ReadBundle().Workspace!.Home.Server);
|
||||
|
||||
var job = await a.EnqueueAsync(WorkspaceJobs.CopyFromServer(sid, Title, a.Server, a.Store.Root, main.Id));
|
||||
await a.WaitAsync(job.Id, JobState.Done);
|
||||
Assert.Equal(2, Assert.NotNull(project.ReadMedia()).Frames.Count);
|
||||
|
||||
// Another server is still another home.
|
||||
var other = await a.EnqueueAsync(WorkspaceJobs.CopyFromServer(sid, Title, "https://elsewhere:8443", a.Store.Root, main.Id));
|
||||
Assert.Equal(Loc.L("Errors.Workspace.OtherHome"), (await a.WaitAsync(other.Id, JobState.Failed)).Error);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheOriginalsAreDownloadedCheckedAndKeptBesideTheProxies()
|
||||
{
|
||||
@@ -560,7 +586,7 @@ public sealed class ServerWorkspaceTests(TestContext context)
|
||||
public bool Connected { get; set; } = true;
|
||||
|
||||
public static async Task<WorkspaceClient> StartAsync(TestContext context, TestServer server, string token, string name, HttpMessageHandler? handler = null,
|
||||
Func<bool>? hold = null)
|
||||
Func<bool>? hold = null, Func<string?, string?, bool>? sameServer = null)
|
||||
{
|
||||
var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory(name + "-db"), "chronos.db")), context.Cancellation);
|
||||
var archives = new ArchiveService(db, new ArchiveServiceOptions { Owner = name });
|
||||
@@ -568,7 +594,8 @@ public sealed class ServerWorkspaceTests(TestContext context)
|
||||
var archive = await archives.CreateAsync(context.CreateTempDirectory(name + "-archive"), "Local", cancellationToken: context.Cancellation);
|
||||
var client = new ChronosClient(server.HttpBase, new CertificatePinning([]), name, handler) { Token = token };
|
||||
WorkspaceClient? created = null;
|
||||
var options = hold is null ? WorkspaceJobOptions.For(archives) : WorkspaceJobOptions.For(archives) with { HoldTransfers = hold };
|
||||
var options = WorkspaceJobOptions.For(archives) with { SameServer = sameServer };
|
||||
if (hold is not null) options = options with { HoldTransfers = hold };
|
||||
var engine = new JobEngine(db, WorkspaceJobs.CreateHandlers(db, archives, new Connector(client, () => created?.Connected ?? true), options),
|
||||
new JobEngineOptions { Workers = 1, WorkerId = name, PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
|
||||
await engine.StartAsync(context.Cancellation);
|
||||
|
||||
Reference in new issue
Block a user