diff --git a/CHANGELOG.md b/CHANGELOG.md index 98b093ca..4279747d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,7 @@ The next SDK version is **2.0.0**, on the same opencode **2.3.0** pin already re ### 🔧 Changes - `StopAsync` and the `EnsureAsync` version-mismatch replacement treat a failed persistent-terminal handoff or clear as best-effort, whatever the exception type, as opencode's CLI does. Before: a failure other than an `OpenCodeServerException` ended `StopAsync` before it terminated the old service, and ended `EnsureAsync` at once. After: `StopAsync` terminates the old service; `EnsureAsync` keeps polling, and the last replacement failure becomes the inner exception of its timeout. The caller's cancellation still ends both. (#871) +- `StopAsync` with `Pty = Handoff` and the `EnsureAsync` replacement treat every persistent-terminal ticket-request, shutdown fallback or sidecar-publish failure as best-effort, as opencode's CLI does. Before: a failure other than an `OpenCodeException` could end the handoff preparation before terminal shutdown or empty-ticket publication completed. After: a failed ticket request still takes the terminal-shutdown fallback and publishes the empty handoff ticket; a failed shutdown no longer skips publication, and a failed publish no longer ends the preparation. The caller's cancellation still ends it. (#895) - The packages' .NET dependency floors move from `10.0.13` to the `10.0.15` servicing release: on `net472` and `netstandard2.0`, `System.Text.Json`, `System.Threading.Channels`, `System.Collections.Immutable`, `Microsoft.Bcl.AsyncInterfaces`, `Microsoft.Bcl.Memory` and `Microsoft.Bcl.TimeProvider`; in `OpenCodeDotNet.Sdk.Extensions`, on every target, `Microsoft.Extensions.DependencyInjection.Abstractions` and `Microsoft.Extensions.Options.ConfigurationExtensions`. No security advisory of the .NET 10.0.14 or 10.0.15 release lists these packages. - Event Types are copied and validated at the call and selected locally; physical attempts send no Types query. The whole bus is decoded once, so malformed unselected traffic reconnects every subscriber. Event and metadata instances are shared references, not deep-frozen graphs; consumers treat them as read-only. Queue bounds count events, not bytes, and subscriber count remains unbounded. - Event subscriptions accept but no longer forward per-call Location. Every shared attempt sends only the client's ambient header snapshot; other operations retain their existing override behavior. diff --git a/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Handoff/ServicePtyHandoff.cs b/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Handoff/ServicePtyHandoff.cs index f68d27a9..f38850f1 100644 --- a/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Handoff/ServicePtyHandoff.cs +++ b/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Handoff/ServicePtyHandoff.cs @@ -62,8 +62,9 @@ public async Task PrepareAsync( { throw FailureClassification.CallerCancellation(failure, "The persistent-terminal handoff request was canceled.", cancellationToken); } - catch (Exception failure) when (failure is OpenCodeException or OperationCanceledException or ArgumentException { ParamName: "endpoint" }) + catch (Exception failure) when (failure is not OperationCanceledException || !cancellationToken.IsCancellationRequested) { + // The SDK drops request failures where upstream warns (prepare in pty-handoff.ts); it has no warning channel here. // Another caller may already have prepared and stopped this server; otherwise the // daemon's terminals are shut down and the replacement starts without a handoff. if (await IsFreshMatchAsync(sidecarPath, registration, cancellationToken).ConfigureAwait(false)) @@ -190,7 +191,7 @@ private PtyHandoffSidecar Parse(ServiceHandoffTicketResponse answer, ServiceRegi /// [SlopwatchSuppress( "SW003", - "The pinned client's shutdown .catch(() => {}) is best-effort (prepare in pty-handoff.ts): endpoint refusal or a failed shutdown leads to a null sidecar and replacement without these terminals.")] + "The pinned client's prepare drops every shutdown fallback failure with .catch(() => {}) (prepare in pty-handoff.ts); the SDK drops it silently as upstream does. Only the caller's cancellation propagates, and a null sidecar is published next.")] private async Task ShutdownAsync(ServiceRegistration registration, TimeSpan timeout, CancellationToken cancellationToken) { using var deadline = TimedCancellation.Create(timeout, time); @@ -203,7 +204,7 @@ private async Task ShutdownAsync(ServiceRegistration registration, TimeSpan time { throw FailureClassification.CallerCancellation(failure, "The persistent-terminal shutdown fallback was canceled.", cancellationToken); } - catch (Exception failure) when (failure is OpenCodeException or OperationCanceledException or ArgumentException { ParamName: "endpoint" }) + catch (Exception failure) when (failure is not OperationCanceledException || !cancellationToken.IsCancellationRequested) { // Best-effort: the replacement starts without these terminals. } @@ -211,18 +212,18 @@ private async Task ShutdownAsync(ServiceRegistration registration, TimeSpan time /// /// publish(...).catch(warn): a sidecar that cannot be written leaves the replacement - /// without a handoff; it never fails the preparation. + /// without a handoff; only the caller's cancellation fails the preparation. /// [SlopwatchSuppress( "SW003", - "The pinned client only warns when publishing the handoff fails (prepare in pty-handoff.ts): the replacement then starts without the terminals, which is the best-effort contract.")] + "The pinned client's prepare catches every sidecar publish failure and only warns (prepare in pty-handoff.ts); the SDK has no warning channel here, so the failure is dropped. Only the caller's cancellation propagates, so the replacement starts without the terminals.")] private async Task TryPublishAsync(string sidecarPath, PtyHandoffSidecar sidecar, CancellationToken cancellationToken) { try { await PublishAsync(sidecarPath, sidecar, cancellationToken).ConfigureAwait(false); } - catch (OpenCodeServerException) + catch (Exception failure) when (failure is not OperationCanceledException || !cancellationToken.IsCancellationRequested) { // Best-effort: no sidecar means no handoff. } diff --git a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Handoff/ServicePtyHandoffBestEffortTests.cs b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Handoff/ServicePtyHandoffBestEffortTests.cs new file mode 100644 index 00000000..f1cf0fa5 --- /dev/null +++ b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Handoff/ServicePtyHandoffBestEffortTests.cs @@ -0,0 +1,289 @@ +using System.Net; +using NSubstitute; +using NSubstitute.ExceptionExtensions; +using OpenCode.Sdk.Internal; +using OpenCode.Sdk.Tests.Harness; +using OpenCode.Sdk.Tests.Support; +using TUnit.Assertions.Enums; +using static OpenCode.Sdk.Tests.Hosting.BackgroundService.Handoff.ServicePtyHandoffScenario; + +namespace OpenCode.Sdk.Tests.Hosting.BackgroundService.Handoff; + +/// Failed inner preparation steps are best-effort; only the caller's cancellation propagates. +public sealed class ServicePtyHandoffBestEffortTests +{ + private readonly ServicePtyHandoffScenario _scenario = new(); + + [Test] + public async Task PrepareAsync_Should_Expire_The_Ticket_On_The_Injected_Clock() + { + _scenario.EnsureSidecarDirectory(); + var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + await using var server = LoopbackHttpServer.Start(_ => Pending(entered)); + var shutdown = Substitute.For(); + shutdown.ShutdownAsync(Arg.Any(), Arg.Any()).Returns(Task.CompletedTask); + using var caller = new CancellationTokenSource(); + var registration = ServicePtyHandoffScenario.Registration(server.Endpoint); + var pending = new ServicePtyHandoff(new TestablyServiceFileSystem(_scenario.FileSystem), _scenario.Clock, shutdown) + .PrepareAsync(_scenario.RegistrationPath(), registration, RequestTimeout, caller.Token); + try + { + await entered.Task.WaitAsync(PreparationHangGuard); + await AdvanceToJustBeforeRequestTimeoutAsync(); + await Assert.That(pending.IsCompleted).IsFalse(); + _ = shutdown.DidNotReceiveWithAnyArgs().ShutdownAsync(default!, default); + _scenario.Clock.Advance(TimeSpan.FromTicks(1)); + await pending.WaitAsync(PreparationHangGuard); + + _ = shutdown.Received(1).ShutdownAsync(registration, Arg.Any()); + await AssertNullSidecarAfterExpiryAsync(); + } + finally + { + await caller.CancelOnWorkerAsync(); + server.ReleaseResponses(); + } + } + + [Test] + public async Task PrepareAsync_Should_Expire_The_Fallback_On_The_Injected_Clock() + { + _scenario.EnsureSidecarDirectory(); + await using var server = LoopbackHttpServer.Start(static _ => Json(HttpStatusCode.NotFound, "{}")); + var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var shutdown = Substitute.For(); + CancellationToken received = default; + shutdown.ShutdownAsync(Arg.Any(), Arg.Any()).Returns(async call => + { + received = call.Arg(); + var held = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var cancellation = received.Register(() => held.TrySetCanceled(received)); + entered.TrySetResult(); + await held.Task; + }); + using var caller = new CancellationTokenSource(); + var pending = new ServicePtyHandoff(new TestablyServiceFileSystem(_scenario.FileSystem), _scenario.Clock, shutdown) + .PrepareAsync(_scenario.RegistrationPath(), ServicePtyHandoffScenario.Registration(server.Endpoint), RequestTimeout, caller.Token); + try + { + await entered.Task.WaitAsync(PreparationHangGuard); + await AdvanceToJustBeforeRequestTimeoutAsync(); + await Assert.That(received.IsCancellationRequested).IsFalse(); + await Assert.That(pending.IsCompleted).IsFalse(); + _scenario.Clock.Advance(TimeSpan.FromTicks(1)); + await pending.WaitAsync(PreparationHangGuard); + + await Assert.That(received.IsCancellationRequested).IsTrue(); + await AssertNullSidecarAfterExpiryAsync(); + } + finally + { + await caller.CancelOnWorkerAsync(); + } + } + + [Test] + public async Task PrepareAsync_Should_Shut_The_Daemon_Down_And_Publish_A_Null_Sidecar_When_The_Daemon_Answers_An_Error() + { + _scenario.EnsureSidecarDirectory(); + await using var server = LoopbackHttpServer.Start(static path => path == ShutdownPath + ? NoContent() + : Json(HttpStatusCode.InternalServerError, "{}")); + + await _scenario.PrepareAsync(server.Endpoint); + + await Assert.That(_scenario.ReadSidecar()!.Handoff).IsNull(); + await Assert.That(server.RequestPaths).IsEquivalentTo([HandoffPath, ShutdownPath], CollectionOrdering.Matching); + } + + [Test] + [Arguments("options")] + [Arguments("io")] + public async Task PrepareAsync_Should_Swallow_A_Failed_Shutdown_Fallback(string? parameterName) + { + _scenario.EnsureSidecarDirectory(); + await using var server = LoopbackHttpServer.Start(static _ => Json(HttpStatusCode.NotFound, "{}")); + Exception failure = parameterName == "io" + ? new IOException("The shutdown failed.") + : new ArgumentException("The shutdown implementation rejected another parameter.", parameterName); + var shutdown = Substitute.For(); + shutdown.ShutdownAsync(Arg.Any(), Arg.Any()).Returns(Task.FromException(failure)); + var handoff = new ServicePtyHandoff(new TestablyServiceFileSystem(_scenario.FileSystem), _scenario.Clock, shutdown); + + await Assert.That(async () => await handoff.PrepareAsync( + _scenario.RegistrationPath(), ServicePtyHandoffScenario.Registration(server.Endpoint), RequestTimeout, CancellationToken.None)).ThrowsNothing(); + + _ = shutdown.Received(1).ShutdownAsync(Arg.Any(), Arg.Any()); + _ = await _scenario.AssertNullSidecarAsync(); + } + + [Test] + public async Task PrepareAsync_Should_Take_The_Shutdown_Fallback_When_The_Ticket_Request_Fails_With_An_IO_Error() + { + _scenario.EnsureSidecarDirectory(); + await using var server = LoopbackHttpServer.Start(static _ => Json(HttpStatusCode.NotFound, "{}")); + var files = new TestablyServiceFileSystem(_scenario.FileSystem); + var fileSystem = Substitute.For(); + fileSystem.TryReadAllBytesAsync(Arg.Any(), Arg.Any()) + .Returns(call => files.TryReadAllBytesAsync(call.Arg(), call.Arg())); + fileSystem.TryCreateExclusiveAsync(Arg.Any(), Arg.Any>(), Arg.Any()) + .Returns(call => files.TryCreateExclusiveAsync(call.Arg(), call.Arg>(), call.Arg())); + fileSystem.When(static system => system.Rename(Arg.Any(), Arg.Any())) + .Do(call => files.Rename(call.ArgAt(0), call.ArgAt(1))); + var time = Substitute.For(); + time.GetUtcNow().Returns(_scenario.Clock.GetUtcNow()); + // Fail the ticket request's bound once, before transport can wrap the IOException; + // the shutdown fallback gets a working bound from the same clock seam. + time.CreateTimer(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => throw new IOException("The ticket request's timer could not be created."), + call => _scenario.Clock.CreateTimer(call.Arg(), call.Arg(), call.ArgAt(2), call.ArgAt(3))); + var shutdown = Substitute.For(); + shutdown.ShutdownAsync(Arg.Any(), Arg.Any()).Returns(Task.CompletedTask); + var registration = ServicePtyHandoffScenario.Registration(server.Endpoint); + + await Assert.That(async () => await new ServicePtyHandoff(fileSystem, time, shutdown).PrepareAsync( + _scenario.RegistrationPath(), registration, RequestTimeout, CancellationToken.None)).ThrowsNothing(); + + await Assert.That(server.Requests).IsEmpty(); + _ = fileSystem.Received(2).TryReadAllBytesAsync(_scenario.SidecarPath(), CancellationToken.None); + _ = shutdown.Received(1).ShutdownAsync(registration, Arg.Any()); + _ = await _scenario.AssertNullSidecarAsync(); + } + + [Test] + [Arguments("io")] + [Arguments("argument")] + public async Task PrepareAsync_Should_Complete_Without_A_Sidecar_When_The_Publish_Fails(string failureKind) + { + await using var server = LoopbackHttpServer.Start(static _ => + Json(HttpStatusCode.OK, Fixtures.LoadJson("BackgroundService.pty-handoff-response-ticket.json"))); + var fileSystem = Substitute.For(); + fileSystem.TryReadAllBytesAsync(Arg.Any(), Arg.Any()).Returns((byte[]?)null); + Exception failure = failureKind == "io" + ? new IOException("The sidecar directory vanished.") + : new ArgumentException("The sidecar write was refused.", nameof(failureKind)); + fileSystem.TryCreateExclusiveAsync(Arg.Any(), Arg.Any>(), Arg.Any()) + .ThrowsAsync(failure); + + await Assert.That(async () => await new ServicePtyHandoff(fileSystem, _scenario.Clock, new ServicePtyShutdown()).PrepareAsync( + _scenario.RegistrationPath(), ServicePtyHandoffScenario.Registration(server.Endpoint), RequestTimeout, CancellationToken.None)).ThrowsNothing(); + + _ = fileSystem.Received(1).TryCreateExclusiveAsync(Arg.Any(), Arg.Any>(), Arg.Any()); + fileSystem.DidNotReceiveWithAnyArgs().Rename(default!, default!); + } + + [Test] + public async Task PrepareAsync_Should_Rethrow_Caller_Cancellation_During_The_Publish() + { + await using var server = LoopbackHttpServer.Start(static _ => + Json(HttpStatusCode.OK, Fixtures.LoadJson("BackgroundService.pty-handoff-response-ticket.json"))); + using var caller = new CancellationTokenSource(); + var fileSystem = Substitute.For(); + fileSystem.TryReadAllBytesAsync(Arg.Any(), Arg.Any()).Returns((byte[]?)null); + fileSystem.TryCreateExclusiveAsync(Arg.Any(), Arg.Any>(), Arg.Any()) + .Returns(async call => + { + await caller.CancelOnWorkerAsync(); + return await Task.FromCanceled(call.Arg()); + }); + + var exception = await Assert.That(async () => await new ServicePtyHandoff(fileSystem, _scenario.Clock, new ServicePtyShutdown()).PrepareAsync( + _scenario.RegistrationPath(), ServicePtyHandoffScenario.Registration(server.Endpoint), RequestTimeout, caller.Token)).Throws(); + + await Assert.That(exception!.CancellationToken).IsEqualTo(caller.Token); + fileSystem.DidNotReceiveWithAnyArgs().Rename(default!, default!); + } + + [Test] + public async Task PrepareAsync_Should_Take_The_Fallback_When_The_Request_Bound_Expires() + { + // The ticket request and the shutdown both outlive their bound; neither expiry is the + // caller's cancellation, so both are failures the best-effort path absorbs. The shutdown + // seam records the call and holds it until its own bound cancels it, so the proof rests on + // the two timers alone, not on how fast a loaded host delivers a request. + _scenario.EnsureSidecarDirectory(); + await using var server = LoopbackHttpServer.Start(static _ => Hold(HttpStatusCode.OK, "{}")); + var shutdown = new BoundOutlivingShutdown(); + var registration = ServicePtyHandoffScenario.Registration(server.Endpoint); + + await new ServicePtyHandoff(new TestablyServiceFileSystem(_scenario.FileSystem), TimeProvider.System, shutdown).PrepareAsync( + _scenario.RegistrationPath(), registration, TimeSpan.FromMilliseconds(200), CancellationToken.None); + + await Assert.That(_scenario.ReadSidecar()!.Handoff).IsNull(); + await Assert.That(shutdown.Calls).IsEqualTo(1); + await Assert.That(shutdown.Received).IsSameReferenceAs(registration); + await Assert.That(shutdown.EndedByItsBound).IsTrue(); + server.ReleaseResponses(); + } + + [Test] + public async Task PrepareAsync_Should_Publish_A_Null_Sidecar_When_The_Shutdown_Fails() + { + _scenario.EnsureSidecarDirectory(); + await using var server = LoopbackHttpServer.Start(static path => path == ShutdownPath + ? Json(HttpStatusCode.InternalServerError, "{}") + : Json(HttpStatusCode.NotFound, "{}")); + + await _scenario.PrepareAsync(server.Endpoint); + + await Assert.That(_scenario.ReadSidecar()!.Handoff).IsNull(); + await Assert.That(server.RequestPaths).Contains(ShutdownPath); + } + + [Test] + public async Task PrepareAsync_Should_Publish_A_Null_Sidecar_When_The_Shutdown_Route_Is_Absent_Too() + { + _scenario.EnsureSidecarDirectory(); + await using var server = LoopbackHttpServer.Start(static _ => Json(HttpStatusCode.NotFound, "{}")); + + await _scenario.PrepareAsync(server.Endpoint); + + await Assert.That(_scenario.ReadSidecar()!.Handoff).IsNull(); + } + + private async Task AdvanceToJustBeforeRequestTimeoutAsync() + { + await _scenario.Clock.WaitForArmedAsync(RequestTimeout, PreparationHangGuard); + _scenario.Clock.Advance(RequestTimeout - TimeSpan.FromTicks(1)); + } + + private async Task AssertNullSidecarAfterExpiryAsync() + { + await Assert.That(_scenario.ReadSidecar()!.Handoff).IsNull(); + await Assert.That(_scenario.ReadSidecar()!.ExpiresAt) + .IsEqualTo(_scenario.Clock.GetUtcNow().ToUnixTimeMilliseconds() + 30_000d); + } + + /// A shutdown seam that records its call and answers only when its token is cancelled. + private sealed class BoundOutlivingShutdown : IServicePtyShutdown + { + public int Calls { get; private set; } + + public ServiceRegistration? Received { get; private set; } + + public bool EndedByItsBound { get; private set; } + + public async Task ShutdownAsync(ServiceRegistration registration, CancellationToken cancellationToken) + { + Calls++; + Received = registration; + var held = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using (cancellationToken.Register(() => held.TrySetCanceled(cancellationToken))) + { + try + { + _ = await held.Task.ConfigureAwait(false); + } + catch (OperationCanceledException) + { + EndedByItsBound = true; + throw; + } + } + } + } + + /// An answer the server sends only after . + private static LoopbackHttpResponse Hold(HttpStatusCode status, string body) => + new() { StatusCode = status, ContentType = "application/json", Body = body, KeepOpen = true }; +} diff --git a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Handoff/ServicePtyHandoffScenario.cs b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Handoff/ServicePtyHandoffScenario.cs index 9a76f13c..3af6dbe6 100644 --- a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Handoff/ServicePtyHandoffScenario.cs +++ b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Handoff/ServicePtyHandoffScenario.cs @@ -1,5 +1,6 @@ using System.Net; using OpenCode.Sdk.Internal; +using OpenCode.Sdk.Tests.Harness; using OpenCode.Sdk.Tests.Hosting.BackgroundService.Support; using OpenCode.Sdk.Tests.Support; using Testably.Abstractions.Testing; @@ -13,9 +14,21 @@ internal sealed class ServicePtyHandoffScenario public const string Version = "2.0.3"; public const string Password = "s3cr3t-p455w0rd"; public const string HandoffPath = "/api/experimental/persistent-pty/handoff"; + public const string ShutdownPath = "/api/experimental/persistent-pty/shutdown"; + public const string FixedUrl = "http://127.0.0.1:49374"; public const long NowMilliseconds = 1_700_000_000_000; private static readonly DateTimeOffset Now = DateTimeOffset.FromUnixTimeMilliseconds(NowMilliseconds); + public static readonly FixtureLoader Fixtures = new(); + + /// + /// Bounds a wait for an event; it decides no verdict. A ticket request's arrival is awaited under it + /// too: the preparation's own bound runs on the scenario's manual clock, which these tests never + /// advance, so only this guard ends a wait for a request that never arrives, and the arrival + /// assertion after it names the miss. + /// + public static readonly TimeSpan PreparationHangGuard = TimeSpan.FromSeconds(10); + /// /// The request bound every preparation test hands the product, far past any loopback exchange a /// loaded runner still completes: the daemon double's answer, a recorded request, or the caller's @@ -31,6 +44,25 @@ internal sealed class ServicePtyHandoffScenario public static ServiceRegistration Registration(Uri endpoint) => new(SourceId, Version, endpoint.ToString(), endpoint, RegisteredPid, Password); + public static ServiceRegistration FixedRegistration() => + new(SourceId, Version, FixedUrl, new Uri(FixedUrl), RegisteredPid, Password); + + public Task PrepareAsync(Uri endpoint) => PrepareAsync(Registration(endpoint)); + + public async Task PrepareAsync(ServiceRegistration registration) => + await Handoff().PrepareAsync(RegistrationPath(), registration, RequestTimeout, CancellationToken.None); + + public ServicePtyHandoff Handoff() => new(new TestablyServiceFileSystem(FileSystem), Clock, new ServicePtyShutdown()); + + public async Task AssertNullSidecarAsync() + { + var sidecar = ReadSidecar(); + await Assert.That(sidecar).IsNotNull(); + await Assert.That(sidecar!.Handoff).IsNull(); + await Assert.That(sidecar.ExpiresAt).IsEqualTo(NowMilliseconds + 30_000d); + return sidecar; + } + public static LoopbackHttpResponse Pending(TaskCompletionSource arrived) { _ = arrived.TrySetResult(true); @@ -46,6 +78,8 @@ public static LoopbackHttpResponse Pending(TaskCompletionSource arrived) public static LoopbackHttpResponse Json(HttpStatusCode status, string body) => new() { StatusCode = status, ContentType = "application/json", Body = body }; + public static LoopbackHttpResponse NoContent() => new() { StatusCode = HttpStatusCode.NoContent }; + public string RegistrationPath() => FileSystem.Path.Combine(FileSystem.Path.GetTempPath(), "service-handoff", "service.json"); diff --git a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Handoff/ServicePtyHandoffTests.cs b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Handoff/ServicePtyHandoffTests.cs index a052b32d..64e862b9 100644 --- a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Handoff/ServicePtyHandoffTests.cs +++ b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Handoff/ServicePtyHandoffTests.cs @@ -16,97 +16,18 @@ namespace OpenCode.Sdk.Tests.Hosting.BackgroundService.Handoff; /// /// The pinned client's sidecar orchestration (pty-handoff.ts) over the Testably /// filesystem double and a real loopback HTTP daemon double: publication through a temporary plus -/// rename, the skip-when-current fast path, the best-effort shutdown fallback that every failed or -/// refused ticket takes, the concurrent-prepare recheck, the environment adoption matrix, +/// rename, the skip-when-current fast path, the null-sidecar fallback for an unusable ticket, +/// the concurrent-prepare recheck, the environment adoption matrix, /// completion by source, and the idempotent clear. /// public sealed class ServicePtyHandoffTests { - private const string FixedUrl = "http://127.0.0.1:49374"; - private const string ShutdownPath = "/api/experimental/persistent-pty/shutdown"; private const long TicketExpiry = 1700000060000; - private static readonly FixtureLoader Fixtures = new(); private static readonly JsonElement Ticket = LoadTicket(); private readonly ServicePtyHandoffScenario _scenario = new(); - /// - /// Bounds a wait for an event; it decides no verdict. A ticket request's arrival is awaited under it - /// too: the preparation's own bound runs on the scenario's manual clock, which these tests never - /// advance, so only this guard ends a wait for a request that never arrives, and the arrival - /// assertion after it names the miss. - /// - private static readonly TimeSpan HangGuard = TimeSpan.FromSeconds(10); - - [Test] - public async Task PrepareAsync_Should_Expire_The_Ticket_On_The_Injected_Clock() - { - _scenario.EnsureSidecarDirectory(); - var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - await using var server = LoopbackHttpServer.Start(_ => Pending(entered)); - var shutdown = Substitute.For(); - shutdown.ShutdownAsync(Arg.Any(), Arg.Any()).Returns(Task.CompletedTask); - using var caller = new CancellationTokenSource(); - var registration = ServicePtyHandoffScenario.Registration(server.Endpoint); - var pending = new ServicePtyHandoff(new TestablyServiceFileSystem(_scenario.FileSystem), _scenario.Clock, shutdown) - .PrepareAsync(_scenario.RegistrationPath(), registration, RequestTimeout, caller.Token); - try - { - await entered.Task.WaitAsync(HangGuard); - await AdvanceToJustBeforeRequestTimeoutAsync(); - await Assert.That(pending.IsCompleted).IsFalse(); - _ = shutdown.DidNotReceiveWithAnyArgs().ShutdownAsync(default!, default); - _scenario.Clock.Advance(TimeSpan.FromTicks(1)); - await pending.WaitAsync(HangGuard); - - _ = shutdown.Received(1).ShutdownAsync(registration, Arg.Any()); - await AssertNullSidecarAfterExpiryAsync(); - } - finally - { - await caller.CancelOnWorkerAsync(); - server.ReleaseResponses(); - } - } - - [Test] - public async Task PrepareAsync_Should_Expire_The_Fallback_On_The_Injected_Clock() - { - _scenario.EnsureSidecarDirectory(); - await using var server = LoopbackHttpServer.Start(static _ => Json(HttpStatusCode.NotFound, "{}")); - var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var shutdown = Substitute.For(); - CancellationToken received = default; - shutdown.ShutdownAsync(Arg.Any(), Arg.Any()).Returns(async call => - { - received = call.Arg(); - var held = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - using var cancellation = received.Register(() => held.TrySetCanceled(received)); - entered.TrySetResult(); - await held.Task; - }); - using var caller = new CancellationTokenSource(); - var pending = new ServicePtyHandoff(new TestablyServiceFileSystem(_scenario.FileSystem), _scenario.Clock, shutdown) - .PrepareAsync(_scenario.RegistrationPath(), ServicePtyHandoffScenario.Registration(server.Endpoint), RequestTimeout, caller.Token); - try - { - await entered.Task.WaitAsync(HangGuard); - await AdvanceToJustBeforeRequestTimeoutAsync(); - await Assert.That(received.IsCancellationRequested).IsFalse(); - await Assert.That(pending.IsCompleted).IsFalse(); - _scenario.Clock.Advance(TimeSpan.FromTicks(1)); - await pending.WaitAsync(HangGuard); - - await Assert.That(received.IsCancellationRequested).IsTrue(); - await AssertNullSidecarAfterExpiryAsync(); - } - finally - { - await caller.CancelOnWorkerAsync(); - } - } - [Test] public async Task PrepareAsync_Should_Publish_A_Sidecar_From_The_Handoff_Ticket() { @@ -115,7 +36,7 @@ public async Task PrepareAsync_Should_Publish_A_Sidecar_From_The_Handoff_Ticket( Json(HttpStatusCode.OK, Fixtures.LoadJson("BackgroundService.pty-handoff-response-ticket.json"))); var registration = ServicePtyHandoffScenario.Registration(server.Endpoint); - await PrepareAsync(registration); + await _scenario.PrepareAsync(registration); await Assert.That(server.RequestPaths).IsEquivalentTo([HandoffPath], CollectionOrdering.Matching); var sidecar = _scenario.ReadSidecar(); @@ -136,7 +57,7 @@ public async Task PrepareAsync_Should_Reuse_A_Fresh_Matching_Sidecar_Without_Con var registration = ServicePtyHandoffScenario.Registration(server.Endpoint); Seed(_scenario.SidecarPath(), Sidecar(registration, handoff: null, NowMilliseconds + 60_000).ToUtf8Json()); - await PrepareAsync(registration); + await _scenario.PrepareAsync(registration); await Assert.That(server.Requests).IsEmpty(); await Assert.That(_scenario.ReadSidecar()).IsNotNull(); @@ -151,9 +72,9 @@ public async Task PrepareAsync_Should_Shut_The_Daemon_Down_And_Publish_A_Null_Si : Json(HttpStatusCode.NotFound, "{}")); var registration = ServicePtyHandoffScenario.Registration(server.Endpoint); - await PrepareAsync(registration); + await _scenario.PrepareAsync(registration); - _ = await AssertNullSidecarAsync(); + _ = await _scenario.AssertNullSidecarAsync(); await Assert.That(server.RequestPaths).Contains(ShutdownPath); } @@ -168,7 +89,7 @@ public async Task PrepareAsync_Should_Shut_The_Daemon_Down_And_Publish_A_Null_Si _scenario.EnsureSidecarDirectory(); await using var server = StartShutdownFallbackServer(fixture); - await PrepareAsync(server.Endpoint); + await _scenario.PrepareAsync(server.Endpoint); await AssertShutdownFallbackAsync(server); } @@ -181,7 +102,7 @@ public async Task PrepareAsync_Should_Take_The_Shutdown_Fallback_For_A_Ticket_Wi _scenario.EnsureSidecarDirectory(); await using var server = StartShutdownFallbackServer(fixture); - await PrepareAsync(server.Endpoint); + await _scenario.PrepareAsync(server.Endpoint); await AssertShutdownFallbackAsync(server); await Assert.That(_scenario.TemporaryFiles()).IsEmpty(); @@ -189,7 +110,7 @@ public async Task PrepareAsync_Should_Take_The_Shutdown_Fallback_For_A_Ticket_Wi private async Task AssertShutdownFallbackAsync(LoopbackHttpServer server) { - _ = await AssertNullSidecarAsync(); + _ = await _scenario.AssertNullSidecarAsync(); await Assert.That(server.RequestPaths).IsEquivalentTo([HandoffPath, ShutdownPath], CollectionOrdering.Matching); } @@ -201,7 +122,7 @@ public async Task PrepareAsync_Should_Admit_Trailing_Whitespace_And_Publish_The_ using var expected = JsonDocument.Parse(body); await using var server = LoopbackHttpServer.Start(_ => Json(HttpStatusCode.OK, body)); - await PrepareAsync(server.Endpoint); + await _scenario.PrepareAsync(server.Endpoint); var sidecar = _scenario.ReadSidecar(); await Assert.That(sidecar).IsNotNull(); @@ -209,20 +130,6 @@ public async Task PrepareAsync_Should_Admit_Trailing_Whitespace_And_Publish_The_ await Assert.That(server.RequestPaths).IsEquivalentTo([HandoffPath], CollectionOrdering.Matching); } - [Test] - public async Task PrepareAsync_Should_Shut_The_Daemon_Down_And_Publish_A_Null_Sidecar_When_The_Daemon_Answers_An_Error() - { - _scenario.EnsureSidecarDirectory(); - await using var server = LoopbackHttpServer.Start(static path => path == ShutdownPath - ? NoContent() - : Json(HttpStatusCode.InternalServerError, "{}")); - - await PrepareAsync(server.Endpoint); - - await Assert.That(_scenario.ReadSidecar()!.Handoff).IsNull(); - await Assert.That(server.RequestPaths).IsEquivalentTo([HandoffPath, ShutdownPath], CollectionOrdering.Matching); - } - [Test] [Arguments("http://127.0.0.1:49374?query=1")] [Arguments("http://127.0.0.1:49374#fragment")] @@ -242,46 +149,11 @@ public async Task PrepareAsync_Should_Fall_Back_When_The_Registered_Endpoint_Is_ .PrepareAsync(_scenario.RegistrationPath(), registration!, RequestTimeout, CancellationToken.None); _ = shutdown.Received(1).ShutdownAsync(registration!, Arg.Any()); - var sidecar = await AssertNullSidecarAsync(); + var sidecar = await _scenario.AssertNullSidecarAsync(); await Assert.That(sidecar.SourceUrl).IsEqualTo(registration!.Url); await Assert.That(_scenario.TemporaryFiles()).IsEmpty(); } - [Test] - [Arguments("options")] - [Arguments(null)] - public async Task PrepareAsync_Should_Propagate_An_Unrelated_Shutdown_Argument_Error(string? parameterName) - { - await using var server = LoopbackHttpServer.Start(static _ => Json(HttpStatusCode.NotFound, "{}")); - var failure = new ArgumentException("The shutdown implementation rejected another parameter.", parameterName); - var shutdown = Substitute.For(); - shutdown.ShutdownAsync(Arg.Any(), Arg.Any()).Returns(Task.FromException(failure)); - var handoff = new ServicePtyHandoff(new TestablyServiceFileSystem(_scenario.FileSystem), _scenario.Clock, shutdown); - - var exception = await Assert.That(async () => await handoff.PrepareAsync( - _scenario.RegistrationPath(), ServicePtyHandoffScenario.Registration(server.Endpoint), RequestTimeout, CancellationToken.None)).Throws(); - - await Assert.That(exception).IsSameReferenceAs(failure); - await Assert.That(_scenario.ReadSidecar()).IsNull(); - } - - [Test] - public async Task PrepareAsync_Should_Complete_Without_A_Sidecar_When_The_Publish_Fails() - { - await using var server = LoopbackHttpServer.Start(static _ => - Json(HttpStatusCode.OK, Fixtures.LoadJson("BackgroundService.pty-handoff-response-ticket.json"))); - var fileSystem = Substitute.For(); - fileSystem.TryReadAllBytesAsync(Arg.Any(), Arg.Any()).Returns((byte[]?)null); - fileSystem.TryCreateExclusiveAsync(Arg.Any(), Arg.Any>(), Arg.Any()) - .ThrowsAsync(new IOException("The sidecar directory vanished.")); - - await new ServicePtyHandoff(fileSystem, _scenario.Clock, new ServicePtyShutdown()).PrepareAsync( - _scenario.RegistrationPath(), ServicePtyHandoffScenario.Registration(server.Endpoint), RequestTimeout, CancellationToken.None); - - _ = fileSystem.Received(1).TryCreateExclusiveAsync(Arg.Any(), Arg.Any>(), Arg.Any()); - fileSystem.DidNotReceiveWithAnyArgs().Rename(default!, default!); - } - /// /// The concurrent caller's sidecar lands once the ticket request has reached the daemon double and /// before its failed answer is released, so the recheck finds it: the preparation returns without @@ -312,10 +184,10 @@ public async Task PrepareAsync_Should_Return_When_A_Concurrent_Caller_Published_ respondingServer = server; registration = ServicePtyHandoffScenario.Registration(server.Endpoint); - var pending = Handoff().PrepareAsync(_scenario.RegistrationPath(), registration, RequestTimeout, CancellationToken.None); + var pending = _scenario.Handoff().PrepareAsync(_scenario.RegistrationPath(), registration, RequestTimeout, CancellationToken.None); await AssertTicketRequestArrivedAsync(arrived, pending); - await pending.WaitAsync(HangGuard); + await pending.WaitAsync(PreparationHangGuard); await Assert.That(server.RequestPaths).DoesNotContain(ShutdownPath); await Assert.That(_scenario.ReadSidecar()!.Handoff).IsNotNull(); @@ -423,7 +295,7 @@ public async Task CompleteAsync_Should_Clear_A_Foreign_Source_Sidecar() SeedFreshSidecar(Ticket); var winner = new ServiceRegistration(SourceId, ServicePtyHandoffScenario.Version, FixedUrl, new Uri(FixedUrl), RegisteredPid + 1, Password); - await Handoff().CompleteAsync(_scenario.RegistrationPath(), winner, CancellationToken.None); + await _scenario.Handoff().CompleteAsync(_scenario.RegistrationPath(), winner, CancellationToken.None); await Assert.That(_scenario.ReadSidecar()).IsNull(); } @@ -433,7 +305,7 @@ public async Task CompleteAsync_Should_Keep_A_Same_Source_Sidecar_Even_When_Stal { Seed(_scenario.SidecarPath(), Sidecar(FixedRegistration(), Ticket, NowMilliseconds - 1).ToUtf8Json()); - await Handoff().CompleteAsync(_scenario.RegistrationPath(), FixedRegistration(), CancellationToken.None); + await _scenario.Handoff().CompleteAsync(_scenario.RegistrationPath(), FixedRegistration(), CancellationToken.None); await Assert.That(_scenario.ReadSidecar()).IsNotNull(); } @@ -441,7 +313,7 @@ public async Task CompleteAsync_Should_Keep_A_Same_Source_Sidecar_Even_When_Stal [Test] public async Task CompleteAsync_Should_Do_Nothing_When_The_Sidecar_Is_Absent() { - await Handoff().CompleteAsync(_scenario.RegistrationPath(), FixedRegistration(), CancellationToken.None); + await _scenario.Handoff().CompleteAsync(_scenario.RegistrationPath(), FixedRegistration(), CancellationToken.None); await Assert.That(_scenario.ReadSidecar()).IsNull(); } @@ -451,10 +323,10 @@ public async Task ClearAsync_Should_Remove_The_Sidecar_And_Be_Idempotent() { SeedFreshSidecar(handoff: null); - await Handoff().ClearAsync(_scenario.RegistrationPath(), CancellationToken.None); + await _scenario.Handoff().ClearAsync(_scenario.RegistrationPath(), CancellationToken.None); await Assert.That(_scenario.ReadSidecar()).IsNull(); - await Handoff().ClearAsync(_scenario.RegistrationPath(), CancellationToken.None); + await _scenario.Handoff().ClearAsync(_scenario.RegistrationPath(), CancellationToken.None); } [Test] @@ -476,7 +348,7 @@ public async Task PrepareAsync_Should_Rethrow_Caller_Cancellation() var cancelled = new CancellationToken(canceled: true); _ = await Assert - .That(async () => await Handoff().PrepareAsync(_scenario.RegistrationPath(), FixedRegistration(), RequestTimeout, cancelled)) + .That(async () => await _scenario.Handoff().PrepareAsync(_scenario.RegistrationPath(), FixedRegistration(), RequestTimeout, cancelled)) .Throws(); } @@ -492,7 +364,7 @@ public async Task PrepareAsync_Should_Rethrow_Caller_Cancellation_During_The_Tic await using var server = LoopbackHttpServer.Start(path => path == ShutdownPath ? NoContent() : Pending(arrived)); using var caller = new CancellationTokenSource(); - var pending = Handoff().PrepareAsync(_scenario.RegistrationPath(), ServicePtyHandoffScenario.Registration(server.Endpoint), RequestTimeout, caller.Token); + var pending = _scenario.Handoff().PrepareAsync(_scenario.RegistrationPath(), ServicePtyHandoffScenario.Registration(server.Endpoint), RequestTimeout, caller.Token); await AssertTicketRequestArrivedAsync(arrived, pending); await caller.CancelOnWorkerAsync(); @@ -524,28 +396,6 @@ public async Task EnvironmentAsync_Should_Remove_The_Variable_For_A_Fresh_Matchi await Assert.That(overlay["KEEP"]).IsEqualTo("1"); } - [Test] - public async Task PrepareAsync_Should_Take_The_Fallback_When_The_Request_Bound_Expires() - { - // The ticket request and the shutdown both outlive their bound; neither expiry is the - // caller's cancellation, so both are failures the best-effort path absorbs. The shutdown - // seam records the call and holds it until its own bound cancels it, so the proof rests on - // the two timers alone, not on how fast a loaded host delivers a request. - _scenario.EnsureSidecarDirectory(); - await using var server = LoopbackHttpServer.Start(static _ => Hold(HttpStatusCode.OK, "{}")); - var shutdown = new BoundOutlivingShutdown(); - var registration = ServicePtyHandoffScenario.Registration(server.Endpoint); - - await new ServicePtyHandoff(new TestablyServiceFileSystem(_scenario.FileSystem), TimeProvider.System, shutdown).PrepareAsync( - _scenario.RegistrationPath(), registration, TimeSpan.FromMilliseconds(200), CancellationToken.None); - - await Assert.That(_scenario.ReadSidecar()!.Handoff).IsNull(); - await Assert.That(shutdown.Calls).IsEqualTo(1); - await Assert.That(shutdown.Received).IsSameReferenceAs(registration); - await Assert.That(shutdown.EndedByItsBound).IsTrue(); - server.ReleaseResponses(); - } - [Test] public async Task PrepareAsync_Should_Publish_The_Ticket_Exactly_As_The_Route_Answered_It() { @@ -555,7 +405,7 @@ public async Task PrepareAsync_Should_Publish_The_Ticket_Exactly_As_The_Route_An _scenario.EnsureSidecarDirectory(); await using var server = LoopbackHttpServer.Start(static _ => Json(HttpStatusCode.OK, "{\"handoff\":" + ticket + "}")); - await PrepareAsync(server.Endpoint); + await _scenario.PrepareAsync(server.Endpoint); // The exchange first, so a recorded shutdown identifies the null-sidecar fallback. await Assert.That(server.RequestPaths).IsEquivalentTo([HandoffPath], CollectionOrdering.Matching); @@ -569,9 +419,9 @@ public async Task PrepareAsync_Should_Publish_A_Null_Sidecar_When_The_Route_Answ await using var server = LoopbackHttpServer.Start(static _ => Json(HttpStatusCode.OK, Fixtures.LoadJson("BackgroundService.pty-handoff-response-null.json"))); - await PrepareAsync(server.Endpoint); + await _scenario.PrepareAsync(server.Endpoint); - _ = await AssertNullSidecarAsync(); + _ = await _scenario.AssertNullSidecarAsync(); } [Test] @@ -581,37 +431,12 @@ public async Task PrepareAsync_Should_Send_The_Registration_Credential() await using var server = LoopbackHttpServer.Start(static _ => Json(HttpStatusCode.OK, Fixtures.LoadJson("BackgroundService.pty-handoff-response-ticket.json"))); - await PrepareAsync(server.Endpoint); + await _scenario.PrepareAsync(server.Endpoint); await Assert.That(server.Requests.Single().Headers["Authorization"]) .IsEqualTo("Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes("opencode:" + Password))); } - [Test] - public async Task PrepareAsync_Should_Publish_A_Null_Sidecar_When_The_Shutdown_Fails() - { - _scenario.EnsureSidecarDirectory(); - await using var server = LoopbackHttpServer.Start(static path => path == ShutdownPath - ? Json(HttpStatusCode.InternalServerError, "{}") - : Json(HttpStatusCode.NotFound, "{}")); - - await PrepareAsync(server.Endpoint); - - await Assert.That(_scenario.ReadSidecar()!.Handoff).IsNull(); - await Assert.That(server.RequestPaths).Contains(ShutdownPath); - } - - [Test] - public async Task PrepareAsync_Should_Publish_A_Null_Sidecar_When_The_Shutdown_Route_Is_Absent_Too() - { - _scenario.EnsureSidecarDirectory(); - await using var server = LoopbackHttpServer.Start(static _ => Json(HttpStatusCode.NotFound, "{}")); - - await PrepareAsync(server.Endpoint); - - await Assert.That(_scenario.ReadSidecar()!.Handoff).IsNull(); - } - [Test] public async Task PrepareAsync_Should_Recheck_For_A_Concurrent_Sidecar_Before_Shutting_The_Daemon_Down() { @@ -631,7 +456,7 @@ public async Task PrepareAsync_Should_Recheck_For_A_Concurrent_Sidecar_Before_Sh }); registration = ServicePtyHandoffScenario.Registration(server.Endpoint); - await PrepareAsync(registration); + await _scenario.PrepareAsync(registration); await Assert.That(server.RequestPaths).DoesNotContain(ShutdownPath); await Assert.That(_scenario.ReadSidecar()!.Handoff).IsNotNull(); @@ -645,7 +470,7 @@ public async Task CompleteAsync_Should_Clear_A_Sidecar_Whose_Source_Differs_In_O SeedFreshSidecar(Ticket); var winner = new ServiceRegistration(id, ServicePtyHandoffScenario.Version, address, new Uri(address), RegisteredPid, Password); - await Handoff().CompleteAsync(_scenario.RegistrationPath(), winner, CancellationToken.None); + await _scenario.Handoff().CompleteAsync(_scenario.RegistrationPath(), winner, CancellationToken.None); await Assert.That(_scenario.ReadSidecar()).IsNull(); } @@ -667,58 +492,26 @@ public async Task EnvironmentAsync_Should_Adopt_When_The_Registration_Cannot_Be_ private static async Task AssertTicketRequestArrivedAsync(TaskCompletionSource arrived, Task pending) { Task[] arrival = [arrived.Task, pending]; - _ = await BoundedWait.CompletesWithinAsync(Task.WhenAny(arrival), HangGuard, TimeProvider.System); + _ = await BoundedWait.CompletesWithinAsync(Task.WhenAny(arrival), PreparationHangGuard, TimeProvider.System); await Assert.That(arrived.Task.IsCompleted).IsTrue(); } - private async Task AdvanceToJustBeforeRequestTimeoutAsync() - { - await _scenario.Clock.WaitForArmedAsync(RequestTimeout, HangGuard); - _scenario.Clock.Advance(RequestTimeout - TimeSpan.FromTicks(1)); - } - - private async Task AssertNullSidecarAfterExpiryAsync() - { - await Assert.That(_scenario.ReadSidecar()!.Handoff).IsNull(); - await Assert.That(_scenario.ReadSidecar()!.ExpiresAt) - .IsEqualTo(_scenario.Clock.GetUtcNow().ToUnixTimeMilliseconds() + 30_000d); - } - private static JsonElement LoadTicket() { using var document = JsonDocument.Parse(Fixtures.LoadJson("BackgroundService.pty-handoff-valid.json")); return document.RootElement.GetProperty("handoff").Clone(); } - private Task PrepareAsync(Uri endpoint) => PrepareAsync(ServicePtyHandoffScenario.Registration(endpoint)); - - private async Task PrepareAsync(ServiceRegistration registration) => - await Handoff().PrepareAsync(_scenario.RegistrationPath(), registration, RequestTimeout, CancellationToken.None); - private static LoopbackHttpServer StartShutdownFallbackServer(string fixture) => LoopbackHttpServer.Start(path => path == ShutdownPath ? NoContent() : Json(HttpStatusCode.OK, Fixtures.LoadJson(fixture))); - private async Task AssertNullSidecarAsync() - { - var sidecar = _scenario.ReadSidecar(); - await Assert.That(sidecar).IsNotNull(); - await Assert.That(sidecar!.Handoff).IsNull(); - await Assert.That(sidecar.ExpiresAt).IsEqualTo(NowMilliseconds + 30_000d); - return sidecar; - } - private void SeedFreshSidecar(JsonElement? handoff) => Seed(_scenario.SidecarPath(), Sidecar(FixedRegistration(), handoff, NowMilliseconds + 60_000).ToUtf8Json()); private Task> EnvironmentAsync(IReadOnlyDictionary? caller) => - Handoff().EnvironmentAsync(_scenario.RegistrationPath(), caller, CancellationToken.None); - - private ServicePtyHandoff Handoff() => new(new TestablyServiceFileSystem(_scenario.FileSystem), _scenario.Clock, new ServicePtyShutdown()); - - private static ServiceRegistration FixedRegistration() => - new(SourceId, ServicePtyHandoffScenario.Version, FixedUrl, new Uri(FixedUrl), RegisteredPid, Password); + _scenario.Handoff().EnvironmentAsync(_scenario.RegistrationPath(), caller, CancellationToken.None); private static PtyHandoffSidecar Sidecar(ServiceRegistration registration, JsonElement? handoff, double expiresAt) => new() @@ -738,41 +531,6 @@ private static string FractionalSourceSidecar() => private static Dictionary Caller() => new(StringComparer.Ordinal) { ["KEEP"] = "1" }; - /// A shutdown seam that records its call and answers only when its token is cancelled. - private sealed class BoundOutlivingShutdown : IServicePtyShutdown - { - public int Calls { get; private set; } - - public ServiceRegistration? Received { get; private set; } - - public bool EndedByItsBound { get; private set; } - - public async Task ShutdownAsync(ServiceRegistration registration, CancellationToken cancellationToken) - { - Calls++; - Received = registration; - var held = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - using (cancellationToken.Register(() => held.TrySetCanceled(cancellationToken))) - { - try - { - _ = await held.Task.ConfigureAwait(false); - } - catch (OperationCanceledException) - { - EndedByItsBound = true; - throw; - } - } - } - } - - /// An answer the server sends only after . - private static LoopbackHttpResponse Hold(HttpStatusCode status, string body) => - new() { StatusCode = status, ContentType = "application/json", Body = body, KeepOpen = true }; - - private static LoopbackHttpResponse NoContent() => new() { StatusCode = HttpStatusCode.NoContent }; - private void Seed(string path, string content) => Seed(path, Encoding.UTF8.GetBytes(content)); private void Seed(string path, byte[] bytes)