Files
Alphaeus Mote 9e3d70f176 Merge multi-trigger schedules, At Logon, On Demand and the device CLI [skip ci]
# Conflicts:
#	src/Agent/PowerShell/ExternalScriptRunner.cs
#	src/Agent/PowerShell/PowerShellJobHandler.cs
#	src/Agent/Service/AgentSession.cs
#	src/Backend/Jobs/JobRunner.cs
#	src/Backend/Jobs/RunSnapshot.cs
#	src/Shared.Contracts/Messages/Payloads.cs
2026-11-06 16:09:14 -05:00

213 lines
8.7 KiB
C#

using System.Collections.Concurrent;
using Agent.LocalRun;
using Agent.Messaging;
using Agent.PowerShell;
using Agent.Storage;
using Microsoft.Extensions.Logging.Abstractions;
using Shared.Contracts.Messages;
using Shared.Contracts.Models;
using Xunit;
namespace Agent.Tests;
internal sealed class ManualClock(DateTimeOffset now) : TimeProvider
{
public DateTimeOffset Now { get; set; } = now;
public override DateTimeOffset GetUtcNow() => Now;
}
/// <summary>Records what a job publishes, with the device clock at the time.</summary>
internal sealed class RecordingPublisher(Func<DateTimeOffset> clock) : IAgentPublisher
{
public ConcurrentQueue<(object Payload, DateTimeOffset At)> Published { get; } = new();
public string ClientId => "client-1";
public IEnumerable<JobStatePayload> States => Published.Select(p => p.Payload).OfType<JobStatePayload>();
public IEnumerable<JobOutputPayload> Output => Published.Select(p => p.Payload).OfType<JobOutputPayload>();
public ValueTask PublishAsync<TPayload>(
string subject, string messageType, TPayload payload, EndpointRef? target = null, Guid? correlationId = null,
Guid? causationId = null, CancellationToken cancellationToken = default)
{
Published.Enqueue((payload!, clock()));
return ValueTask.CompletedTask;
}
}
public sealed class JobStartTests : IDisposable
{
private static readonly DateTimeOffset Logon = new(2026, 11, 6, 8, 0, 0, TimeSpan.Zero);
private readonly string root = Path.Combine(Path.GetTempPath(), "executer-jobstart-tests", Guid.NewGuid().ToString("N"));
private readonly ManualClock clock = new(Logon);
private readonly RecordingPublisher publisher;
private readonly JobHistoryStore history;
private readonly JobObservers observers = new();
public JobStartTests()
{
publisher = new RecordingPublisher(() => clock.Now);
history = new JobHistoryStore(Path.Combine(root, "jobs.db"));
}
public void Dispose()
{
history.Dispose();
try
{
Directory.Delete(root, recursive: true);
}
catch (IOException)
{
}
}
private PowerShellJobHandler Handler(Func<TimeSpan, CancellationToken, Task> delay)
=> new(new PowerShellExecutionService(), publisher, history, new Agent.Files.ServerDownloads(null, false), NullLogger.Instance,
observers: observers, clock: new JobStartClock(clock, delay));
private static ScriptCommandPayload Command(string content, DateTimeOffset? notBefore = null, JobTrigger? trigger = null)
=> new(Guid.NewGuid(), Guid.NewGuid(), "Test", content, 60, NotBeforeUtc: notBefore, Trigger: trigger);
[Fact]
public async Task AFutureStartTimeHoldsTheJobUntilTheDeviceClockReachesIt()
{
var delays = new List<TimeSpan>();
var notBefore = Logon.AddSeconds(150);
var handler = Handler((span, _) =>
{
delays.Add(span);
clock.Now += span;
return Task.CompletedTask;
});
await handler.RunJobAsync(Command("'hello'", notBefore), Guid.NewGuid(), null, CancellationToken.None);
Assert.Equal([TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(30)], delays);
var states = publisher.Published.Where(p => p.Payload is JobStatePayload).ToList();
Assert.Equal(JobState.Running, ((JobStatePayload)states[0].Payload).State);
Assert.Equal(notBefore, states[0].At);
Assert.Equal(JobState.Succeeded, ((JobStatePayload)states[^1].Payload).State);
}
[Fact]
public async Task NothingIsPublishedWhileWaitingAndItStartsRightAfter()
{
var waiting = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var notBefore = Logon.AddSeconds(30);
var handler = Handler(async (_, ct) =>
{
waiting.TrySetResult();
await release.Task.WaitAsync(ct);
});
var job = handler.RunJobAsync(Command("'hello'", notBefore), Guid.NewGuid(), null, CancellationToken.None);
await waiting.Task.WaitAsync(TimeSpan.FromSeconds(10));
await Task.Delay(100);
Assert.Empty(publisher.Published);
Assert.Equal(0, handler.ActiveJobs);
clock.Now = notBefore;
release.SetResult();
await job.WaitAsync(TimeSpan.FromSeconds(60));
Assert.Equal([JobState.Running, JobState.Succeeded], publisher.States.Select(s => s.State));
Assert.Contains(publisher.Output, o => o.Text == "hello");
}
[Fact]
public async Task APastStartTimeStartsAtOnce()
{
var handler = Handler((_, _) => throw new InvalidOperationException("No wait expected."));
await handler.RunJobAsync(Command("'hello'", Logon.AddMinutes(-3)), Guid.NewGuid(), null, CancellationToken.None);
Assert.Equal([JobState.Running, JobState.Succeeded], publisher.States.Select(s => s.State));
}
[Fact]
public async Task OnlyAnAgentStopEndsTheWait()
{
using var stop = new CancellationTokenSource();
var waiting = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var handler = Handler(async (span, ct) =>
{
waiting.TrySetResult();
await Task.Delay(Timeout.InfiniteTimeSpan, ct);
});
var job = handler.RunJobAsync(Command("'hello'", Logon.AddMinutes(10)), Guid.NewGuid(), null, stop.Token);
await waiting.Task.WaitAsync(TimeSpan.FromSeconds(10));
await stop.CancelAsync();
await job.WaitAsync(TimeSpan.FromSeconds(10));
var state = Assert.Single(publisher.States);
Assert.Equal(JobState.Cancelled, state.State);
}
[Fact]
public async Task TheScriptSeesItsTriggerAndTheLocalObserverSeesTheOutcome()
{
var requestId = Guid.NewGuid();
var schedule = Guid.NewGuid();
using var observation = observers.Register(requestId);
var handler = Handler((_, _) => Task.CompletedTask);
var trigger = new JobTrigger(JobTriggerKinds.Logon, @"CONTOSO\ann", 2, Logon, requestId, schedule);
await handler.RunJobAsync(
Command("\"$($Trigger.kind)|$($Trigger.User)|$($Trigger.SessionId)|$($Trigger.OccurredUtc.ToString('o'))|$($Trigger.ScheduleId)\"; exit 3", trigger: trigger),
Guid.NewGuid(), null, CancellationToken.None);
var expected = $@"logon|CONTOSO\ann|2|{Logon:o}|{schedule:D}";
Assert.Contains(publisher.Output, o => o.Text == expected);
var seen = new List<JobTapEvent>();
await foreach (var tap in observation.Events.ReadAllAsync().WithCancellation(new CancellationTokenSource(TimeSpan.FromSeconds(10)).Token))
{
seen.Add(tap);
}
Assert.Contains(seen, t => t is JobTapOutput { Text: var text } && text == expected);
var exit = Assert.IsType<JobTapExit>(seen[^1]);
Assert.Equal(JobState.Failed, exit.State);
Assert.Equal(3, exit.ExitCode);
}
[Fact]
public void TriggerEnvironmentHasOnlyWhatIsKnown()
{
var full = JobTriggerContext.ToEnvironment(new JobTrigger(JobTriggerKinds.Logon, "ann", 2, Logon, null, null));
Assert.Equal("logon", full[JobTriggerContext.KindVariable]);
Assert.Equal("ann", full[JobTriggerContext.UserVariable]);
Assert.Equal("2", full[JobTriggerContext.SessionIdVariable]);
Assert.Equal("2026-11-06T08:00:00.0000000+00:00", full[JobTriggerContext.OccurredUtcVariable]);
var bare = JobTriggerContext.ToEnvironment(new JobTrigger(JobTriggerKinds.DeviceCli));
Assert.Equal([JobTriggerContext.KindVariable], bare.Keys);
}
[Fact]
public async Task WindowsPowerShell51GetsTheTriggerAsEnvironmentAndVariable()
{
Assert.SkipUnless(OperatingSystem.IsWindows(), "powershell.exe is Windows-only");
var records = new List<NormalizedOutputRecord>();
var result = await ExternalScriptRunner.RunAsync(
ScriptEngine.WindowsPowerShell,
"Write-Output \"$env:EXECUTER_TRIGGER_KIND|$env:EXECUTER_TRIGGER_USER|$env:EXECUTER_TRIGGER_SESSION_ID|$env:EXECUTER_TRIGGER_OCCURRED_UTC|$($Trigger.user)|$($Trigger.OccurredUtc.UtcDateTime.Hour)\"",
prelude: null,
parameters: new Dictionary<string, object?>(),
secrets: null,
secretsVariableName: "Secrets",
onRecord: r => { lock (records) records.Add(r); },
CancellationToken.None,
trigger: new JobTrigger(JobTriggerKinds.Logon, @"CONTOSO\ann", 2, Logon));
Assert.Equal(0, result.ExitCode);
Assert.Contains(records, r => r.Text == @"logon|CONTOSO\ann|2|2026-11-06T08:00:00.0000000+00:00|CONTOSO\ann|8");
}
}