using ClawdDotNet.Core.Instances; using Microsoft.Extensions.Logging.Abstractions; using Shouldly; namespace ClawdDotNet.Manager.Tests; /// Counts for whom a token was obtained. internal sealed class FakeTokenSource : IInstanceTokenSource { public List Fuer { get; } = []; public bool Erfolg { get; set; } = true; public Task EnsureTokenAsync(string instanceDirectory, CancellationToken ct = default) { Fuer.Add(Path.GetFullPath(instanceDirectory)); return Task.FromResult(Erfolg); } } /// /// The instance manager as a whole (#528, stage 3). /// /// The license is checked here without a license server, and that is intentional: the /// promise is not "the gatekeeper works" — that is the SDK's job —, /// but "a verdict leads to stopping all instances, an outage does not". Exactly /// this path is taken here, triggered via /// . /// public sealed class ManagerCoreTests : IAsyncDisposable { private readonly string _root = Path.Combine( Path.GetTempPath(), "clawd-tests", "core-" + Guid.NewGuid().ToString("N")[..8]); private readonly FakeLauncher _launcher = new(); private readonly FakeChannel _channel = new(); private readonly FakeTokenSource _tokens = new(); private readonly InstanceDirectoryManager _directories; private static readonly SupervisionOptions Options = new( ProbeInterval: TimeSpan.FromMilliseconds(50), StartTimeout: TimeSpan.FromMilliseconds(600), SilentChecksBeforeAlarm: 3, StopGrace: TimeSpan.FromMilliseconds(300), SilentKillGrace: TimeSpan.FromMilliseconds(300), MaxDrainWait: TimeSpan.FromSeconds(2)); public ManagerCoreTests() { Directory.CreateDirectory(_root); _directories = new InstanceDirectoryManager(Path.Combine(_root, "Instances")); // The socket only answers if a process is really running - exactly as in // operation (see FakeChannel.Launcher). _channel.Launcher = _launcher; } private ManagerCore Manager() { var register = new InstanceRegistry( _directories, _launcher, _channel, NullLoggerFactory.Instance, Options); return new ManagerCore( new ManagerSettingsStore(_root), register, _tokens, NullLoggerFactory.Instance); } public async ValueTask DisposeAsync() { await Task.CompletedTask; try { Directory.Delete(_root, recursive: true); } catch { /* A leftover test folder does not turn a run red. */ } } /// /// Lets the instance answer from now on — and checks that it was really /// started afterwards and not merely taken over. /// /// The difference is not a subtlety. Whoever stores the answer before /// the manager comes up says with it "this instance is already running" — the /// manager then takes it over (E-M6), the launcher is never touched, and the test /// checks something other than it claims. Exactly that happened to me here twice. /// private async Task StartAndCheck(ManagerCore manager, string path, string name) { var before = _launcher.Starts; _channel.AnswerFor[Path.GetFullPath(path)] = new InstanceIdentity("i-1", name, "0.1.2"); var result = await manager.StartInstanceAsync(path); _launcher.Starts.ShouldBe(before + 1, "Gestartet, nicht uebernommen."); return result; } // ─── Starting up ─── [Fact] public async Task Without_license_check_the_manager_works() { // No gatekeeper means no lock - otherwise there would be a chicken-and-egg lock // before anyone can even enter a key. await using var manager = Manager(); (await manager.StartAsync()).ShouldBeTrue(); manager.LicenseHolds.ShouldBeTrue(); } [Fact] public async Task Nothing_is_started_on_startup() { _directories.CreateInstance("Alpha"); await using var manager = Manager(); await manager.StartAsync(); manager.Instances.Instances.Count.ShouldBe(1); _launcher.Starts.ShouldBe(0); } // ─── Token ─── [Fact] public async Task A_new_instance_gets_its_own_token_right_away() { // At creation and not at the first start: then the instance file belongs // to nobody without doubt. await using var manager = Manager(); var path = await manager.CreateInstanceAsync("Frisch"); _tokens.Fuer.ShouldBe([Path.GetFullPath(path)]); } [Fact] public async Task Before_the_start_the_token_is_fetched() { // The case of an instance that existed before the manager - or for which the // Deploymentcenter was not reachable at creation. var path = _directories.CreateInstance("Alt"); await using var manager = Manager(); await manager.StartAsync(); (await StartAndCheck(manager, path, "Alt")).ShouldBe(StartRefusal.None); _tokens.Fuer.ShouldContain(Path.GetFullPath(path)); } [Fact] public async Task A_failed_token_fetch_does_not_prevent_the_start() { // Monitoring that only runs with perfect permissions is silent exactly // when you need it. _tokens.Erfolg = false; var path = _directories.CreateInstance("Alt"); await using var manager = Manager(); await manager.StartAsync(); (await StartAndCheck(manager, path, "Alt")).ShouldBe(StartRefusal.None); } // ─── The verdict ─── /// /// The only case in which the manager stops instances on its own initiative. /// /// A server outage explicitly does not belong here — the SDK separates verdict and /// failed attempt, and only the verdict arrives here. Otherwise a /// network problem would take all installations down at the same time. /// [Fact] public async Task A_license_revocation_pauses_all_running_instances() { var path = _directories.CreateInstance("Alpha"); await using var manager = Manager(); await manager.StartAsync(); await StartAndCheck(manager, path, "Alpha"); manager.Instances.Instances.Single().Condition.ShouldBe(InstanceCondition.Running); // The instance ends upon the request. var process = _launcher.Last!; _channel.OnStopRequest = _ => { _channel.AnswerFor[Path.GetFullPath(path)] = null; process.Exit(0); }; await manager.HandleLicenseRevokedAsync("Widerrufen durch den Hersteller"); manager.LicenseHolds.ShouldBeFalse(); manager.Instances.Instances.Single().Condition.ShouldBe(InstanceCondition.Stopped); _channel.StopRequests.ShouldBe(1, "Erst bitten, nicht schiessen."); } [Fact] public async Task After_a_revocation_no_instance_starts() { var path = _directories.CreateInstance("Alpha"); await using var manager = Manager(); await manager.StartAsync(); await manager.HandleLicenseRevokedAsync("Widerrufen"); (await manager.StartInstanceAsync(path)).ShouldBe(StartRefusal.NoLicense); _launcher.Starts.ShouldBe(0); _tokens.Fuer.ShouldBeEmpty("Ohne Lizenz wird auch kein Token verbraucht."); } // ─── When the start fails ─── [Fact] public async Task An_instance_that_does_not_report_counts_as_not_started() { var path = _directories.CreateInstance("Stumm"); await using var manager = Manager(); await manager.StartAsync(); // The process runs, the instance never reports in. (await manager.StartInstanceAsync(path)).ShouldBe(StartRefusal.DidNotStart); } }