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,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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user