Files
Alphaeus Mote 1520bafe41 perf(messaging): job states stored in batches, output keeps up with a burst [skip ci]
Job states (JetStream, sealed) are read ahead into a channel and stored up to
256 at a time, waiting 5 ms for more once one has arrived: opened and checked
side by side (arrival order kept), a replay acked and a refused one terminated
at once, the rest applied in one transaction and acked only after it commits,
then remembered (a redelivery is a replay) and relayed to browsers. When the
transaction fails nothing of it is kept and each state is stored on its own;
one that still fails is nak'd (offered again in 2 s), never acked.

Each state is one conditional update that only moves a job forward: Running
from Queued, Dispatched or Running (the first start kept), a final state from
any state that is not final, never over a final one. The check is the update's
own, so a cancel or another replica writing meanwhile cannot be overwritten.
Activity and job events go to browsers only for a state that was applied.
Run counts, last-run outcomes and the dashboards read the job rows as before.

Job output, which a burst now produces as fast as the states: lines are opened
side by side and stored by a second stage while the next are opened (up to
2,000 a transaction, through the prepared insert), and the subscription holds
131,072 lines meanwhile (NATS drops past that). Without this, a 5,000-device
burst on SQLite lost a quarter of its output lines.

Presence, output and state writes take the SQLite write gate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 06:49:02 -05:00

618 lines
27 KiB
C#

using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using Backend.Data;
using Backend.Jobs;
using Backend.Messaging;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Shared.Contracts.Api;
using Shared.Contracts.Messages;
using Shared.Contracts.Models;
using Shared.Contracts.Serialization;
using Xunit;
namespace Backend.Tests;
public class JobStaggerPlanTests
{
[Theory]
[InlineData(10, 1, 10)]
[InlineData(10, 3, 4)]
[InlineData(10, 5, 2)]
[InlineData(10, 10, 1)]
[InlineData(10, 25, 1)]
[InlineData(1, 1, 1)]
[InlineData(0, 1, 0)]
public void SlotsAreTargetsOverBatchRoundedUp(int targets, int batch, int slots)
=> Assert.Equal(slots, JobStagger.Slots(targets, batch));
[Theory]
[InlineData(600, 1, 10, true)]
[InlineData(0, 1, 10, false)]
[InlineData(600, 10, 10, false)]
[InlineData(600, 1, 1, false)]
public void AStaggerOnlyAppliesWhenThereIsMoreThanOneSlot(int seconds, int batch, int targets, bool applies)
=> Assert.Equal(applies, JobStagger.Applies(seconds, batch, targets));
[Fact]
public void TheFirstSlotIsNowAndTheLastIsTheEndOfTheSpread()
{
var offsets = JobStagger.Plan(Guid.NewGuid(), Ids(5), 100, 1).Select(p => p.Offset.TotalSeconds).ToList();
Assert.Equal([0, 25, 50, 75, 100], offsets);
}
[Fact]
public void BatchesShareAStartAndTheLastBatchMayBeShort()
{
var offsets = JobStagger.Plan(Guid.NewGuid(), Ids(7), 90, 3).Select(p => p.Offset.TotalSeconds).ToList();
Assert.Equal([0, 0, 0, 45, 45, 45, 90], offsets);
}
[Fact]
public void AnIntervalThatDoesNotDivideEvenlyStillEndsOnTheSpread()
{
var offsets = JobStagger.Plan(Guid.NewGuid(), Ids(4), 100, 1).Select(p => p.Offset).ToList();
Assert.Equal(TimeSpan.Zero, offsets[0]);
Assert.Equal(TimeSpan.FromTicks(100 * TimeSpan.TicksPerSecond / 3), offsets[1]);
Assert.Equal(TimeSpan.FromSeconds(100), offsets[3]);
}
[Fact]
public void TheLargestSettingsDoNotOverflow()
{
var last = JobStagger.SlotOffset(99_999, 100_000, JobStagger.MaxSeconds);
Assert.Equal(TimeSpan.FromSeconds(JobStagger.MaxSeconds), last);
}
[Fact]
public void TheOrderIsRepeatableForARunAndDiffersBetweenRuns()
{
var run = Guid.NewGuid();
var once = JobStagger.Plan(run, Ids(50), 100, 1).Select(p => p.ClientId).ToList();
var again = JobStagger.Plan(run, Ids(50).OrderDescending(), 100, 1).Select(p => p.ClientId).ToList();
var other = JobStagger.Plan(Guid.NewGuid(), Ids(50), 100, 1).Select(p => p.ClientId).ToList();
Assert.Equal(once, again);
Assert.NotEqual(once, other);
Assert.NotEqual(Ids(50), once);
}
[Theory]
[InlineData(-1, 1, false)]
[InlineData(86_401, 1, false)]
[InlineData(600, 0, false)]
[InlineData(600, 10_001, false)]
[InlineData(0, 1, true)]
[InlineData(86_400, 10_000, true)]
public void ValuesOutsideTheRangesAreRefused(int seconds, int batch, bool valid)
=> Assert.Equal(valid, JobStagger.Validate(seconds, batch) is null);
private static List<string> Ids(int count) => Enumerable.Range(0, count).Select(i => $"device-{i:00}").ToList();
}
/// <summary>Records script commands instead of publishing them; refuses them (no NATS) until told otherwise.</summary>
public sealed class RecordingScriptSender : IScriptCommandSender
{
public List<(string ClientId, ScriptCommandPayload Command)> Sent { get; } = [];
public bool Accept { get; set; }
public Task<bool> DispatchScriptAsync(string clientId, ScriptCommandPayload command, CancellationToken cancellationToken)
{
lock (Sent)
{
if (!Accept)
{
return Task.FromResult(false);
}
Sent.Add((clientId, command));
return Task.FromResult(true);
}
}
}
/// <summary>On its own fixture: the jobs it leaves waiting would crowd every other test's dispatcher pass.</summary>
public class StaggerScaleTests(BackendTestFixture fixture) : IClassFixture<BackendTestFixture>
{
[Fact]
public async Task ThousandsOfTargetsStartAndLeaveInLimitedPasses()
{
fixture.Scripts.Accept = true;
using var client = await fixture.SignedInAsync("stagger-scale");
var scriptId = await fixture.SeedScriptAsync("thousands");
var ids = Enumerable.Range(0, 2000).Select(i => $"thousands{i:0000}").ToList();
await fixture.WithDbAsync(async db =>
{
db.Devices.AddRange(ids.Select(id => new DeviceEntity
{
ClientId = id,
Hostname = id,
NkeyPublic = id,
EnrolledUtc = DateTimeOffset.UtcNow,
}));
await db.SaveChangesAsync();
});
var timer = System.Diagnostics.Stopwatch.StartNew();
var response = await client.PostAsJsonAsync(
ApiRoutes.Jobs, new CreateJobRequest(null, scriptId, ClientIds: ids, StaggerSeconds: 3600, StaggerBatchSize: 50), JsonDefaults.Options);
timer.Stop();
response.EnsureSuccessStatusCode();
var run = (await response.Content.ReadFromJsonAsync<GroupRunDto>(JsonDefaults.Options))!;
Assert.Equal(2000, run.Jobs.Count);
Assert.Empty(fixture.Scripts.Sent);
Assert.True(timer.Elapsed < TimeSpan.FromSeconds(20), $"took {timer.Elapsed}");
var starts = await fixture.WithDbAsync(db => db.Jobs.AsNoTracking()
.Where(j => j.RunId == run.RunId).Select(j => j.NotBeforeUtc).ToListAsync());
Assert.Equal(40, starts.Distinct().Count());
var dispatcher = new JobDispatcher(fixture.Services.GetRequiredService<IServiceScopeFactory>(), NullLogger<JobDispatcher>.Instance);
var pass = await dispatcher.RunPassAsync(starts.Max()!.Value, CancellationToken.None);
Assert.Equal(JobDispatcher.PassLimit, pass.Sent);
Assert.True(pass.More);
Assert.Equal(JobDispatcher.PassLimit, fixture.Scripts.Sent.Select(s => s.ClientId).Distinct().Count());
}
}
public class StaggerTests(BackendTestFixture fixture) : IClassFixture<BackendTestFixture>
{
private RecordingScriptSender Sender => fixture.Scripts;
// Each test has its own script and devices; the dispatcher's passes span all
// of them, so a test only looks at what happened to its own run.
private JobDispatcher Dispatcher() => new(fixture.Services.GetRequiredService<IServiceScopeFactory>(), NullLogger<JobDispatcher>.Instance);
private async Task<(HttpClient Client, Guid ScriptId)> ArrangeAsync(string name)
{
Sender.Accept = true;
return (await fixture.SignedInAsync("stagger-admin"), await fixture.SeedScriptAsync(name));
}
private async Task<List<string>> SeedDevicesAsync(string prefix, int count, bool online = false)
{
var ids = new List<string>();
for (var i = 0; i < count; i++)
{
ids.Add(await fixture.SeedDeviceAsync($"{prefix}-{i}", online));
}
return ids;
}
private static async Task<GroupRunDto> StartAsync(HttpClient client, CreateJobRequest request)
{
var response = await client.PostAsJsonAsync(ApiRoutes.Jobs, request, JsonDefaults.Options);
response.EnsureSuccessStatusCode();
return (await response.Content.ReadFromJsonAsync<GroupRunDto>(JsonDefaults.Options))!;
}
private Task<List<JobEntity>> JobsAsync(Guid? runId)
=> fixture.WithDbAsync(db => db.Jobs.AsNoTracking().Where(j => j.RunId == runId).ToListAsync());
private Task<RunEntity> RunAsync(Guid? runId)
=> fixture.WithDbAsync(db => db.Runs.AsNoTracking().SingleAsync(r => r.RunId == runId));
private List<string> SentTo(IEnumerable<string> clientIds)
{
lock (Sender.Sent)
{
var mine = clientIds.ToHashSet();
return Sender.Sent.Where(s => mine.Contains(s.ClientId)).Select(s => s.ClientId).ToList();
}
}
[Fact]
public async Task AStaggeredRunWaitsAndReturnsWithoutSendingAnything()
{
var (client, scriptId) = await ArrangeAsync("waits");
var devices = await SeedDevicesAsync("WAITS", 5);
var run = await StartAsync(client, new CreateJobRequest(null, scriptId, ClientIds: devices, StaggerSeconds: 3600));
Assert.Equal(5, run.Jobs.Count);
Assert.Empty(SentTo(devices));
var jobs = await JobsAsync(run.RunId);
Assert.All(jobs, j => Assert.Equal(JobState.Queued, j.State));
var starts = jobs.Select(j => j.NotBeforeUtc!.Value).Order().ToList();
Assert.Equal(TimeSpan.FromHours(1), starts[^1] - starts[0]);
var detail = (await client.GetFromJsonAsync<ExecutionDetailDto>(ApiRoutes.For.Execution(run.RunId!.Value), JsonDefaults.Options))!;
Assert.NotNull(detail.ServerTimeUtc);
Assert.All(detail.Targets, t => Assert.NotNull(t.NotBeforeUtc));
Assert.Equal(1, detail.Counts!.Pending);
Assert.Equal(4, detail.Counts.Waiting);
}
[Fact]
public async Task NoStaggerBehavesAsBefore()
{
var (client, scriptId) = await ArrangeAsync("no-stagger");
var devices = await SeedDevicesAsync("NOSTAGGER", 3);
var run = await StartAsync(client, new CreateJobRequest(null, scriptId, ClientIds: devices));
Assert.Equal(3, SentTo(devices).Count);
var jobs = await JobsAsync(run.RunId);
Assert.All(jobs, j =>
{
Assert.Equal(JobState.Dispatched, j.State);
Assert.Null(j.NotBeforeUtc);
});
Assert.Null((await RunAsync(run.RunId)).SnapshotProtected);
}
[Fact]
public async Task OneBatchHoldingEveryDeviceHasNothingToSpread()
{
var (client, scriptId) = await ArrangeAsync("one-batch");
var devices = await SeedDevicesAsync("ONEBATCH", 3);
await StartAsync(client, new CreateJobRequest(null, scriptId, ClientIds: devices, StaggerSeconds: 600, StaggerBatchSize: 3));
Assert.Equal(3, SentTo(devices).Count);
}
[Theory]
[InlineData(-1, 1)]
[InlineData(86_401, 1)]
[InlineData(60, 0)]
public async Task BadSettingsAreRefused(int seconds, int batch)
{
var (client, scriptId) = await ArrangeAsync($"bad-{seconds}-{batch}");
var devices = await SeedDevicesAsync($"BAD{seconds}{batch}", 2);
var response = await client.PostAsJsonAsync(
ApiRoutes.Jobs, new CreateJobRequest(null, scriptId, ClientIds: devices, StaggerSeconds: seconds, StaggerBatchSize: batch), JsonDefaults.Options);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
}
[Fact]
public async Task EachPassSendsOnlyWhatIsDueAndSurvivesARestart()
{
var (client, scriptId) = await ArrangeAsync("passes");
var devices = await SeedDevicesAsync("PASSES", 4);
var run = await StartAsync(client, new CreateJobRequest(null, scriptId, ClientIds: devices, StaggerSeconds: 300));
var jobs = (await JobsAsync(run.RunId)).OrderBy(j => j.NotBeforeUtc).ToList();
var start = jobs[0].NotBeforeUtc!.Value;
await Dispatcher().RunPassAsync(start.AddSeconds(1), CancellationToken.None);
Assert.Equal([jobs[0].ClientId], SentTo(devices));
// A new dispatcher and new scopes, as after a restart: only the database carries over.
await Dispatcher().RunPassAsync(start.AddSeconds(101), CancellationToken.None);
Assert.Equal([jobs[0].ClientId, jobs[1].ClientId], SentTo(devices));
await Dispatcher().RunPassAsync(start.AddSeconds(301), CancellationToken.None);
Assert.Equal(4, SentTo(devices).Count);
Assert.Equal(4, SentTo(devices).Distinct().Count());
Assert.All(await JobsAsync(run.RunId), j => Assert.Equal(JobState.Dispatched, j.State));
// Nothing is sent twice.
await Dispatcher().RunPassAsync(start.AddSeconds(400), CancellationToken.None);
Assert.Equal(4, SentTo(devices).Count);
}
[Fact]
public async Task EveryDeviceRunsTheScriptAsItWasAtTheStart()
{
var (client, scriptId) = await ArrangeAsync("as-it-was");
var devices = await SeedDevicesAsync("ASITWAS", 2);
await fixture.WithDbAsync(async db =>
{
var script = await db.Scripts.SingleAsync(s => s.Id == scriptId);
script.ParametersJson = JsonDefaults.Serialize(new[] { new ScriptParameter("Token", ScriptParameterType.String) });
await db.SaveChangesAsync();
});
var arguments = new Dictionary<string, JsonElement> { ["Token"] = JsonSerializer.SerializeToElement("s3cret-value") };
var run = await StartAsync(client, new CreateJobRequest(null, scriptId, arguments, ClientIds: devices, StaggerSeconds: 60));
var original = await fixture.WithDbAsync(db => db.Scripts.AsNoTracking().Where(s => s.Id == scriptId).Select(s => s.Content).SingleAsync());
// The arguments never reach the database in the clear.
var sealedValue = (await RunAsync(run.RunId)).SnapshotProtected;
Assert.NotNull(sealedValue);
Assert.DoesNotContain("s3cret-value", sealedValue);
await fixture.WithDbAsync(async db =>
{
var script = await db.Scripts.SingleAsync(s => s.Id == scriptId);
script.Content = "'edited after the run started'";
script.Name = "renamed";
await db.SaveChangesAsync();
});
await Dispatcher().RunPassAsync(DateTimeOffset.UtcNow.AddMinutes(2), CancellationToken.None);
List<ScriptCommandPayload> sent;
lock (Sender.Sent)
{
sent = Sender.Sent.Where(s => devices.Contains(s.ClientId)).Select(s => s.Command).ToList();
}
Assert.Equal(2, sent.Count);
Assert.All(sent, command =>
{
Assert.Equal(original, command.Content);
Assert.Equal("as-it-was", command.ScriptName);
Assert.Equal("s3cret-value", command.Arguments!["Token"].GetString());
});
}
[Fact]
public async Task TheSnapshotIsClearedOnceNothingWaits()
{
var (client, scriptId) = await ArrangeAsync("clears");
var devices = await SeedDevicesAsync("CLEARS", 2);
var run = await StartAsync(client, new CreateJobRequest(null, scriptId, ClientIds: devices, StaggerSeconds: 600));
Assert.NotNull((await RunAsync(run.RunId)).SnapshotProtected);
// The first device goes; the second still needs it.
var first = (await JobsAsync(run.RunId)).Min(j => j.NotBeforeUtc)!.Value;
await Dispatcher().RunPassAsync(first.AddSeconds(1), CancellationToken.None);
Assert.NotNull((await RunAsync(run.RunId)).SnapshotProtected);
await Dispatcher().RunPassAsync(first.AddSeconds(601), CancellationToken.None);
Assert.Null((await RunAsync(run.RunId)).SnapshotProtected);
}
[Fact]
public async Task ADeletedScriptFailsTheJobsStillWaiting()
{
var (client, scriptId) = await ArrangeAsync("deleted");
var devices = await SeedDevicesAsync("DELETED", 2);
var run = await StartAsync(client, new CreateJobRequest(null, scriptId, ClientIds: devices, StaggerSeconds: 60));
await fixture.WithDbAsync(db => db.Scripts.Where(s => s.Id == scriptId).ExecuteDeleteAsync());
await Dispatcher().RunPassAsync(DateTimeOffset.UtcNow.AddMinutes(2), CancellationToken.None);
Assert.Empty(SentTo(devices));
Assert.All(await JobsAsync(run.RunId), j =>
{
Assert.Equal(JobState.Failed, j.State);
Assert.Contains("deleted", j.OutputSummary);
Assert.NotNull(j.CompletedUtc);
});
}
[Fact]
public async Task OnlineOnlyIsCheckedAgainAtTheSlot()
{
var (client, scriptId) = await ArrangeAsync("online-at-slot");
var devices = await SeedDevicesAsync("ONLINESLOT", 3, online: true);
var run = await StartAsync(client, new CreateJobRequest(null, scriptId, ClientIds: devices, OnlineOnly: true, StaggerSeconds: 600));
Assert.Equal(3, run.Jobs.Count);
var gone = devices[1];
await fixture.WithDbAsync(db => db.Devices.Where(d => d.ClientId == gone)
.ExecuteUpdateAsync(s => s.SetProperty(d => d.LastSeenUtc, DateTimeOffset.UtcNow.AddDays(-1))));
var now = DateTimeOffset.UtcNow.AddMinutes(11);
var others = devices.Where(d => d != gone).ToList();
await fixture.WithDbAsync(db => db.Devices.Where(d => others.Contains(d.ClientId))
.ExecuteUpdateAsync(s => s.SetProperty(d => d.LastSeenUtc, now)));
await Dispatcher().RunPassAsync(now, CancellationToken.None);
Assert.Equal(others.Order(), SentTo(devices).Order());
var jobs = await JobsAsync(run.RunId);
Assert.Equal(others.Order(), jobs.Select(j => j.ClientId).Order());
var detail = (await client.GetFromJsonAsync<ExecutionDetailDto>(ApiRoutes.For.Execution(run.RunId!.Value), JsonDefaults.Options))!;
var skip = Assert.Single(detail.Skipped!);
Assert.Equal((gone, SkipReasons.Offline), (skip.ClientId, skip.Reason));
Assert.Equal(3, detail.Counts!.Targets);
Assert.Equal(1, detail.Counts.Skipped);
}
[Fact]
public async Task ARunWithEveryDeviceSkippedAtItsSlotCanStillBeOpenedAndListed()
{
var (client, scriptId) = await ArrangeAsync("all-skipped");
var devices = await SeedDevicesAsync("ALLSKIPPED", 2, online: true);
var run = await StartAsync(client, new CreateJobRequest(null, scriptId, ClientIds: devices, OnlineOnly: true, StaggerSeconds: 60));
var now = DateTimeOffset.UtcNow.AddHours(2);
await Dispatcher().RunPassAsync(now, CancellationToken.None);
Assert.Empty(await JobsAsync(run.RunId));
var detail = (await client.GetFromJsonAsync<ExecutionDetailDto>(ApiRoutes.For.Execution(run.RunId!.Value), JsonDefaults.Options))!;
Assert.Equal(2, detail.Skipped!.Count);
Assert.Equal(scriptId, detail.ScriptId);
var listed = await client.GetFromJsonAsync<List<ExecutionSummaryDto>>($"{ApiRoutes.Executions}?scriptId={scriptId}", JsonDefaults.Options);
Assert.Equal(2, Assert.Single(listed!).Counts!.Skipped);
}
[Fact]
public async Task CancelWaitingStopsWhatHasNotBeenSent()
{
var (client, scriptId) = await ArrangeAsync("cancel");
var devices = await SeedDevicesAsync("CANCEL", 3);
var run = await StartAsync(client, new CreateJobRequest(null, scriptId, ClientIds: devices, StaggerSeconds: 600));
var first = (await JobsAsync(run.RunId)).Min(j => j.NotBeforeUtc)!.Value;
await Dispatcher().RunPassAsync(first.AddSeconds(1), CancellationToken.None);
var response = await client.PostAsync(ApiRoutes.For.ExecutionCancelWaiting(run.RunId!.Value), null);
response.EnsureSuccessStatusCode();
Assert.Equal(2, (await response.Content.ReadFromJsonAsync<CancelWaitingResultDto>(JsonDefaults.Options))!.Cancelled);
var jobs = await JobsAsync(run.RunId);
Assert.Equal(1, jobs.Count(j => j.State == JobState.Dispatched));
Assert.Equal(2, jobs.Count(j => j.State == JobState.Cancelled));
Assert.All(jobs.Where(j => j.State == JobState.Cancelled), j => Assert.NotNull(j.CompletedUtc));
Assert.Null((await RunAsync(run.RunId)).SnapshotProtected);
await Dispatcher().RunPassAsync(first.AddSeconds(700), CancellationToken.None);
Assert.Single(SentTo(devices));
var audited = await fixture.WithDbAsync(db => db.AuditEvents.AsNoTracking()
.AnyAsync(e => e.Action == "cancel-waiting" && e.Detail!.Contains(run.RunId.Value.ToString())));
Assert.True(audited);
}
[Fact]
public async Task CancelWaitingStaysInsideTheCallersScope()
{
var (admin, scriptId) = await ArrangeAsync("cancel-scope");
var mine = await fixture.SeedDeviceAsync("CANCELSCOPE-MINE");
var theirs = await fixture.SeedDeviceAsync("CANCELSCOPE-THEIRS");
var outside = await fixture.SeedDeviceAsync("CANCELSCOPE-OUTSIDE");
var run = await StartAsync(admin, new CreateJobRequest(null, scriptId, ClientIds: [mine, theirs], StaggerSeconds: 600));
using var scoped = await fixture.ScopedSignedInAsync("cancel-scoped", mine);
using var stranger = await fixture.ScopedSignedInAsync("cancel-stranger", outside);
Assert.Equal(
HttpStatusCode.NotFound,
(await stranger.PostAsync(ApiRoutes.For.ExecutionCancelWaiting(run.RunId!.Value), null)).StatusCode);
var response = await scoped.PostAsync(ApiRoutes.For.ExecutionCancelWaiting(run.RunId!.Value), null);
response.EnsureSuccessStatusCode();
var jobs = await JobsAsync(run.RunId);
Assert.Equal(JobState.Cancelled, jobs.Single(j => j.ClientId == mine).State);
Assert.Equal(JobState.Queued, jobs.Single(j => j.ClientId == theirs).State);
}
[Fact]
public async Task APublishThatFailsIsRetriedAndOthersKeepTheirPlace()
{
var (client, scriptId) = await ArrangeAsync("retry");
var devices = await SeedDevicesAsync("RETRY", 2);
// Without a stagger too: NATS is down when the run starts.
Sender.Accept = false;
var run = await StartAsync(client, new CreateJobRequest(null, scriptId, ClientIds: devices));
var jobs = await JobsAsync(run.RunId);
Assert.All(jobs, j =>
{
Assert.Equal(JobState.Queued, j.State);
Assert.NotNull(j.NotBeforeUtc);
});
var now = jobs.Max(j => j.NotBeforeUtc)!.Value;
var refused = await Dispatcher().RunPassAsync(now, CancellationToken.None);
Assert.True(refused.Refused);
Assert.False(refused.More);
Assert.All(await JobsAsync(run.RunId), j => Assert.Equal(JobState.Queued, j.State));
Sender.Accept = true;
var sent = await Dispatcher().RunPassAsync(now.AddSeconds(4), CancellationToken.None);
Assert.False(sent.Refused);
Assert.Equal(2, SentTo(devices).Count);
Assert.All(await JobsAsync(run.RunId), j => Assert.Equal(JobState.Dispatched, j.State));
Assert.Null((await RunAsync(run.RunId)).SnapshotProtected);
}
[Fact]
public async Task AJobThatCouldNotBeSentForADayFails()
{
var (client, scriptId) = await ArrangeAsync("expires");
var devices = await SeedDevicesAsync("EXPIRES", 2);
var run = await StartAsync(client, new CreateJobRequest(null, scriptId, ClientIds: devices, StaggerSeconds: 60));
Sender.Accept = false;
await Dispatcher().RunPassAsync(DateTimeOffset.UtcNow.AddHours(25), CancellationToken.None);
Sender.Accept = true;
Assert.All(await JobsAsync(run.RunId), j => Assert.Equal(JobState.Failed, j.State));
}
[Fact]
public async Task AnAgentFasterThanTheDispatcherIsNotOverwritten()
{
var (client, scriptId) = await ArrangeAsync("race");
var device = await fixture.SeedDeviceAsync("RACE");
// The agent's Running lands before the backend records Dispatched.
await fixture.WithDbAsync(async db =>
{
var script = await db.Scripts.AsNoTracking().SingleAsync(s => s.Id == scriptId);
using var scope = fixture.Services.CreateScope();
var runner = scope.ServiceProvider.GetRequiredService<JobRunner>();
var prepared = await runner.PrepareAsync(script, CancellationToken.None);
var job = await runner.CreateJobAsync(script, device, "test", CancellationToken.None);
await db.Jobs.Where(j => j.JobId == job.JobId).ExecuteUpdateAsync(s => s.SetProperty(j => j.State, JobState.Running));
Assert.True(await runner.DispatchAsync(prepared, job, null, "race", CancellationToken.None));
Assert.Equal(JobState.Running, job.State);
var stored = await db.Jobs.AsNoTracking().SingleAsync(j => j.JobId == job.JobId);
Assert.Equal(JobState.Running, stored.State);
});
}
[Fact]
public async Task SchedulesStaggerEachFiring()
{
var (client, scriptId) = await ArrangeAsync("schedule");
var devices = await SeedDevicesAsync("SCHEDULE", 4);
var groupId = Guid.NewGuid();
await fixture.WithDbAsync(async db =>
{
db.DeviceGroups.Add(new DeviceGroupEntity { Id = groupId, Name = "schedule-stagger", Kind = GroupKind.Static, CreatedUtc = DateTimeOffset.UtcNow, UpdatedUtc = DateTimeOffset.UtcNow });
db.DeviceGroupMembers.AddRange(devices.Select(d => new DeviceGroupMemberEntity { GroupId = groupId, ClientId = d, AddedUtc = DateTimeOffset.UtcNow }));
await db.SaveChangesAsync();
});
var created = await client.PostAsJsonAsync(ApiRoutes.Triggers, new SaveScriptTriggerRequest(
scriptId, ScriptTriggerType.Scheduled, GroupIds: [groupId], CronExpression: "0 3 * * *",
StaggerSeconds: 900, StaggerBatchSize: 2), JsonDefaults.Options);
created.EnsureSuccessStatusCode();
var listed = await client.GetFromJsonAsync<List<ScriptTriggerDto>>(ApiRoutes.Triggers, JsonDefaults.Options);
var dto = listed!.Single(t => t.ScriptId == scriptId);
Assert.Equal((900, 2), (dto.StaggerSeconds, dto.StaggerBatchSize));
var fired = await client.PostAsync(ApiRoutes.For.TriggerRun(dto.Id), null);
fired.EnsureSuccessStatusCode();
var result = (await fired.Content.ReadFromJsonAsync<TriggerRunResultDto>(JsonDefaults.Options))!;
Assert.Equal(4, result.Queued);
Assert.Empty(SentTo(devices));
var offsets = (await JobsAsync(result.RunId)).Select(j => j.NotBeforeUtc!.Value).Order().ToList();
Assert.Equal(TimeSpan.FromMinutes(15), offsets[^1] - offsets[0]);
Assert.Equal(2, offsets.Distinct().Count());
}
[Fact]
public async Task ASchedulesBadStaggerIsRefusedAndEventTriggersDoNotKeepOne()
{
var (client, scriptId) = await ArrangeAsync("schedule-rules");
var bad = await client.PostAsJsonAsync(ApiRoutes.Triggers, new SaveScriptTriggerRequest(
scriptId, ScriptTriggerType.Scheduled, AllDevices: true, CronExpression: "0 3 * * *", StaggerSeconds: 90_000), JsonDefaults.Options);
Assert.Equal(HttpStatusCode.BadRequest, bad.StatusCode);
var onEvent = await client.PostAsJsonAsync(ApiRoutes.Triggers, new SaveScriptTriggerRequest(
scriptId, ScriptTriggerType.OnAgentReady, AllDevices: true, StaggerSeconds: 900, StaggerBatchSize: 5), JsonDefaults.Options);
onEvent.EnsureSuccessStatusCode();
var listed = await client.GetFromJsonAsync<List<ScriptTriggerDto>>(ApiRoutes.Triggers, JsonDefaults.Options);
var dto = listed!.Single(t => t.ScriptId == scriptId);
Assert.Equal((0, 1), (dto.StaggerSeconds, dto.StaggerBatchSize));
}
[Fact]
public void ASnapshotOpensOnlyWithItsKeys()
{
var snapshots = fixture.Services.GetRequiredService<RunSnapshots>();
var snapshot = new RunSnapshot(Guid.NewGuid(), "n", "powershell", "content", null, null, null, null, null, null);
var sealedValue = snapshots.Seal(snapshot);
Assert.Equal("content", snapshots.Open(sealedValue)!.Content);
Assert.Null(snapshots.Open(null));
Assert.Null(snapshots.Open("not a sealed value"));
var other = fixture.Services.GetRequiredService<IDataProtectionProvider>().CreateProtector("other").Protect("{}");
Assert.Null(snapshots.Open(other));
}
}