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>
240 lines
10 KiB
C#
240 lines
10 KiB
C#
using System.Globalization;
|
|
using System.Runtime.CompilerServices;
|
|
using System.Threading.Channels;
|
|
using Chronos.App.Server;
|
|
using Chronos.Core.Localization;
|
|
using Chronos.Core.Model;
|
|
using Chronos.Data.Jobs;
|
|
using Chronos.Protocol;
|
|
using Chronos.Testing;
|
|
|
|
namespace Chronos.App.Tests.Jobs;
|
|
|
|
/// <summary>The Server section's list of the server's jobs (owner review 5, #65, the owner's answer to Q2).</summary>
|
|
public sealed class ServerJobsListTests
|
|
{
|
|
private static readonly DateTimeOffset T0 = new(2026, 9, 28, 10, 0, 0, TimeSpan.Zero);
|
|
|
|
[Test]
|
|
public async Task AReadOnlyAccountSeesRunningAndPausedJobsWithoutActions()
|
|
{
|
|
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
|
|
var api = new FakeJobsApi();
|
|
var verify = api.Add("verify", "Harbour sunset", "running", new JobDetailDto("verify", "Harbour sunset", 812, 2_400, 3, 41, "sequence"));
|
|
api.Add("proxies", "Lake", "paused", new JobDetailDto("proxies", "Lake", 300, 1_800));
|
|
api.Add("thumbs", "Queued one", "queued");
|
|
using var vm = new ServerJobsViewModel(() => new ServerJobsAccount("a", CanControl: false), () => api, new IdleContext());
|
|
|
|
await UpdatedAsync(vm, vm.Refresh);
|
|
Assert.True(vm.IsWatching);
|
|
Assert.False(vm.CanControl);
|
|
Assert.Equal(Loc.L("Tooltips.Server.Jobs.ReadOnly"), vm.TitleToolTip);
|
|
Assert.Equal(2, vm.Rows.Count);
|
|
Assert.True(vm.HasRows);
|
|
var running = vm.Rows[0];
|
|
Assert.Equal(verify, running.Id);
|
|
Assert.Equal("Verifying photo 812 of 2,400 · Harbour sunset · sequence 3 of 41", running.StatusText);
|
|
Assert.Equal(StatusKindOf(JobState.Running), running.StateKind);
|
|
Assert.Empty(running.Actions);
|
|
Assert.Equal("Stopped at Proxy 300 of 1,800 · Lake", vm.Rows[1].StatusText);
|
|
Assert.Empty(vm.Rows[1].Actions);
|
|
// Without the right, nothing reaches the server.
|
|
await vm.ActAsync(verify, (a, id, ct) => a.PauseJobAsync(id, ct));
|
|
Assert.Equal(0, api.Actions);
|
|
}
|
|
|
|
[Test]
|
|
public async Task ProgressEventsMoveTheLineAndAFinishedJobLeaves()
|
|
{
|
|
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
|
|
var api = new FakeJobsApi();
|
|
var id = api.Add("verify", "Harbour sunset", "running", new JobDetailDto("verify", "Harbour sunset", 1, 2_400, 3, 41, "sequence"));
|
|
using var vm = new ServerJobsViewModel(() => new ServerJobsAccount("a", false), () => api, new IdleContext());
|
|
await UpdatedAsync(vm, vm.Refresh);
|
|
|
|
await UpdatedAsync(vm, () => api.Events.Writer.TryWrite(new JobProgressEvent(id, 900, 2_400, 52, 60,
|
|
new JobDetailDto("verify", "Alpine lake", 20, 100, 4, 41, "sequence"))));
|
|
var row = vm.Rows.Single();
|
|
Assert.Equal("Verifying photo 20 of 100 · Alpine lake · sequence 4 of 41", row.StatusText);
|
|
Assert.Equal(900d / 2_400, row.Progress);
|
|
Assert.Equal("1 min", row.LeftText);
|
|
|
|
await UpdatedAsync(vm, () => api.Events.Writer.TryWrite(new JobStateEvent(id, "done", null)));
|
|
Assert.Empty(vm.Rows);
|
|
Assert.False(vm.HasRows);
|
|
}
|
|
|
|
[Test]
|
|
public async Task AJobThatStartedBeforeTheEventsOpenedJoinsOnItsProgress()
|
|
{
|
|
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
|
|
var api = new FakeJobsApi();
|
|
using var vm = new ServerJobsViewModel(() => new ServerJobsAccount("a", false), () => api, new IdleContext());
|
|
await UpdatedAsync(vm, vm.Refresh);
|
|
Assert.Empty(vm.Rows);
|
|
|
|
// Started between the list and the event socket: its running state was never told, its progress is.
|
|
var id = api.Add("thumbs", "Lake", "running");
|
|
await UpdatedAsync(vm, () => api.Events.Writer.TryWrite(new JobProgressEvent(id, 40, 100, 3, 20,
|
|
new JobDetailDto("thumbs", "Lake", 40, 100))));
|
|
var row = vm.Rows.Single();
|
|
Assert.Equal(id, row.Id);
|
|
Assert.Equal(40d / 100, row.Progress);
|
|
}
|
|
|
|
[Test]
|
|
public async Task AManagingAccountPausesResumesAndCancels()
|
|
{
|
|
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
|
|
var api = new FakeJobsApi();
|
|
var id = api.Add("thumbs", "Lake", "running");
|
|
using var vm = new ServerJobsViewModel(() => new ServerJobsAccount("a", CanControl: true), () => api, new IdleContext());
|
|
await UpdatedAsync(vm, vm.Refresh);
|
|
Assert.True(vm.CanControl);
|
|
Assert.Equal(Loc.L("Tooltips.Server.Jobs"), vm.TitleToolTip);
|
|
Assert.SequenceEqual(new[] { Loc.L("Jobs.Action.Pause"), Loc.L("Jobs.Action.Cancel") }, vm.Rows.Single().Actions.Select(a => a.Text));
|
|
|
|
await vm.ActAsync(id, (a, job, ct) => a.PauseJobAsync(job, ct));
|
|
Assert.Equal(StatusKindOf(JobState.Paused), vm.Rows.Single().StateKind);
|
|
Assert.SequenceEqual(new[] { Loc.L("Jobs.Action.Resume"), Loc.L("Jobs.Action.Cancel") }, vm.Rows.Single().Actions.Select(a => a.Text));
|
|
|
|
await vm.ActAsync(id, (a, job, ct) => a.CancelJobAsync(job, ct));
|
|
Assert.Empty(vm.Rows);
|
|
Assert.Equal(2, api.Actions);
|
|
}
|
|
|
|
[Test]
|
|
public async Task ARefusedActionIsSaidAndTheListStays()
|
|
{
|
|
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
|
|
var api = new FakeJobsApi { Refuse = true };
|
|
var id = api.Add("thumbs", "Lake", "running");
|
|
string? said = null;
|
|
using var vm = new ServerJobsViewModel(() => new ServerJobsAccount("a", true), () => api, new IdleContext(), (title, reason) => said = $"{title}: {reason}");
|
|
await UpdatedAsync(vm, vm.Refresh);
|
|
|
|
await vm.ActAsync(id, (a, job, ct) => a.PauseJobAsync(job, ct));
|
|
Assert.Equal($"{Loc.L("Server.Jobs.NotChanged")}: The job cannot do that in its current state.", said);
|
|
Assert.Equal(StatusKindOf(JobState.Running), vm.Rows.Single().StateKind);
|
|
}
|
|
|
|
[Test]
|
|
public async Task SigningOutEmptiesTheListAndClosesTheConnection()
|
|
{
|
|
var api = new FakeJobsApi();
|
|
api.Add("verify", "Harbour sunset", "running");
|
|
ServerJobsAccount? account = new("a", false);
|
|
using var vm = new ServerJobsViewModel(() => account, () => api, new IdleContext());
|
|
await UpdatedAsync(vm, vm.Refresh);
|
|
Assert.Equal(1, vm.Rows.Count);
|
|
|
|
account = null;
|
|
vm.Refresh();
|
|
Assert.False(vm.IsWatching);
|
|
Assert.Empty(vm.Rows);
|
|
await api.Disposed.Task.WaitAsync(TimeSpan.FromSeconds(10));
|
|
|
|
// Without an account nothing is opened.
|
|
var opened = 0;
|
|
using var signedOut = new ServerJobsViewModel(() => null, () => { opened++; return api; }, new IdleContext());
|
|
signedOut.Refresh();
|
|
Assert.Equal(0, opened);
|
|
Assert.False(signedOut.HasRows);
|
|
}
|
|
|
|
private static Chronos.Ui.Controls.StatusKind StatusKindOf(JobState state) =>
|
|
state == JobState.Paused ? Chronos.Ui.Controls.StatusKind.Paused : Chronos.Ui.Controls.StatusKind.Running;
|
|
|
|
/// <summary>Runs <paramref name="act"/>, waits for the listener to post what follows, then applies it as the UI would.</summary>
|
|
private static async Task UpdatedAsync(ServerJobsViewModel vm, Action act)
|
|
{
|
|
var posted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
void OnPosted() => posted.TrySetResult();
|
|
vm.Posted += OnPosted;
|
|
try
|
|
{
|
|
act();
|
|
await posted.Task.WaitAsync(TimeSpan.FromSeconds(10));
|
|
}
|
|
finally
|
|
{
|
|
vm.Posted -= OnPosted;
|
|
}
|
|
vm.Flush();
|
|
}
|
|
|
|
/// <summary>A UI context that never runs what is posted to it: the test applies the updates itself.</summary>
|
|
private sealed class IdleContext : SynchronizationContext
|
|
{
|
|
public override void Post(SendOrPostCallback d, object? state)
|
|
{
|
|
}
|
|
}
|
|
|
|
private sealed class FakeJobsApi : IServerJobsApi
|
|
{
|
|
private readonly List<JobDto> _jobs = [];
|
|
|
|
public Channel<ServerEvent> Events { get; } = Channel.CreateUnbounded<ServerEvent>();
|
|
|
|
public TaskCompletionSource Disposed { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
|
|
public bool Refuse { get; init; }
|
|
|
|
public int Actions { get; private set; }
|
|
|
|
public Guid Add(string kind, string target, string state, JobDetailDto? detail = null)
|
|
{
|
|
var id = Guid.CreateVersion7();
|
|
lock (_jobs)
|
|
{
|
|
_jobs.Add(new JobDto(id, kind, [], target, state, "background", 10, 100, null, null, null, null, 1, null, T0, T0.AddMinutes(_jobs.Count), null, null,
|
|
detail));
|
|
}
|
|
return id;
|
|
}
|
|
|
|
public Task<Page<JobDto>> ListJobsAsync(string state, string? cursor, CancellationToken cancellationToken)
|
|
{
|
|
lock (_jobs)
|
|
{
|
|
var items = _jobs.Where(j => j.State == state).ToList();
|
|
return Task.FromResult(new Page<JobDto>(items, null, items.Count));
|
|
}
|
|
}
|
|
|
|
public Task<JobDto> GetJobAsync(Guid id, CancellationToken cancellationToken)
|
|
{
|
|
lock (_jobs) return Task.FromResult(_jobs.Single(j => j.Id == id));
|
|
}
|
|
|
|
public Task<JobDto> PauseJobAsync(Guid id, CancellationToken cancellationToken) => Set(id, "paused");
|
|
|
|
public Task<JobDto> ResumeJobAsync(Guid id, CancellationToken cancellationToken) => Set(id, "running");
|
|
|
|
public Task<JobDto> CancelJobAsync(Guid id, CancellationToken cancellationToken) => Set(id, "cancelled");
|
|
|
|
public async IAsyncEnumerable<ServerEvent> EventsAsync([EnumeratorCancellation] CancellationToken cancellationToken)
|
|
{
|
|
await foreach (var e in Events.Reader.ReadAllAsync(cancellationToken)) yield return e;
|
|
}
|
|
|
|
public void Dispose() => Disposed.TrySetResult();
|
|
|
|
private Task<JobDto> Set(Guid id, string state)
|
|
{
|
|
if (Refuse)
|
|
throw new Chronos.Protocol.Client.ChronosApiException(System.Net.HttpStatusCode.Conflict,
|
|
new ApiError("invalid_state", "The job cannot do that in its current state.", null));
|
|
Actions++;
|
|
lock (_jobs)
|
|
{
|
|
var index = _jobs.FindIndex(j => j.Id == id);
|
|
var job = _jobs[index] with { State = state };
|
|
_jobs[index] = job;
|
|
return Task.FromResult(job);
|
|
}
|
|
}
|
|
}
|
|
}
|