From 88c9766ab508f988d1c5dfa2c7bdcbb80858e319 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 1 Dec 2026 19:27:13 -0500 Subject: [PATCH] fix(deploy): #949 ask timeout on the deploy trigger is OutcomeUnknown (202 + pre-allocated id), not a failure; slow-compose phase timings The id is allocated before the ask and travels in StartDeployment, so a timed-out caller can name and poll the deployment that may still go ahead. REST answers 202 OutcomeUnknown with a Location; the AdminUI shows 'could not be confirmed, may still be created'; a retry during a running compose gets 409 naming the same id. The actor logs per-phase timings for composes slower than 3 s. --- docker-dev/deploy.sh | 7 ++ docs/security.md | 4 +- .../Messages/Admin/StartDeployment.cs | 11 +- .../Messages/Admin/StartDeploymentResult.cs | 8 ++ .../Api/DeployApiEndpoints.cs | 18 +++- .../Clients/AdminOperationsClient.cs | 41 ++++++- .../Components/Pages/Deployments.razor | 11 +- .../Shared/DeploymentFeedback.razor | 6 +- .../AdminOperations/AdminOperationsActor.cs | 45 +++++++- ...AdminOperationsClientDeployTimeoutTests.cs | 102 ++++++++++++++++++ .../Api/DeployApiEndpointsTests.cs | 32 ++++++ .../Pages/DeploymentRefreshTests.cs | 13 +++ .../AdminOperationsActorMailboxTests.cs | 28 +++++ .../AdminOperationsActorTests.cs | 22 ++++ 14 files changed, 333 insertions(+), 15 deletions(-) create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/AdminOperationsClientDeployTimeoutTests.cs diff --git a/docker-dev/deploy.sh b/docker-dev/deploy.sh index 7d0892552..f46a3f22b 100755 --- a/docker-dev/deploy.sh +++ b/docker-dev/deploy.sh @@ -96,6 +96,13 @@ if [ -n "$body" ]; then printf '%s\n' "$body"; fi case "$status" in 2*) + # lmxopcua#949: 202 + outcome OutcomeUnknown = the trigger timed out waiting for the admin singleton + # (10 s); the deployment may STILL be created under the id in the body. Not a confirmed deployment. + if printf '%s' "$body" | grep -q '"outcome" *: *"OutcomeUnknown"'; then + echo "WARNING: the trigger timed out - the deployment may still go ahead (outcome unknown)." >&2 + echo " Poll GET $DEPLOY_URL/ (X-Api-Key): 200 = it exists; 404 for a couple of" >&2 + echo " minutes = it was not created and the trigger can be repeated." >&2 + fi exit 0 ;; 404) diff --git a/docs/security.md b/docs/security.md index e75f0bbba..4187bc67b 100644 --- a/docs/security.md +++ b/docs/security.md @@ -1787,7 +1787,9 @@ curl -X POST https:///api/deployments \ -d '{"createdBy":"ci-bot"}' ``` -Responses: `202 Accepted` (`{ outcome, deploymentId, revisionHash }`) when a deployment was sealed, `200` for `NoChanges`, `409` when another deployment is in flight, `422` when rejected, `401` for a missing/wrong key, `503` when unconfigured. Set the secret via `Security:DeployApiKey` (env `Security__DeployApiKey`) on admin nodes only; treat it like any deploy credential (rotate, keep out of source). +Responses: `202 Accepted` (`{ outcome, deploymentId, revisionHash }`) when a deployment was sealed, `200` for `NoChanges`, `409` when another deployment is in flight (the body's `deploymentId` names it when it is a compose still running), `422` when rejected, `401` for a missing/wrong key, `503` when unconfigured. + +**Outcome unknown (lmxopcua#949).** The trigger waits 10 s for the admin singleton. A slow compose (one gate run took 10.5 s) can outlast that and still create and apply the deployment, so a timeout is **not** reported as a failure: the id is pre-allocated before the ask and the response is `202 Accepted` with `{ "outcome": "OutcomeUnknown", "deploymentId": "", "message": "…" }` and `Location: /api/deployments/`. Poll that resource: `200` means the deployment exists (and carries exactly that id); `404` for a couple of minutes means it was not created and the trigger can be repeated (a repeat while the original compose is still running answers `409` naming the same id). Scripts must therefore check `outcome`, not just the 2xx status. The AdminUI Deployments page shows the same case as "could not be confirmed … may still be created", with the id. The admin singleton logs a Warning with the per-phase timings (`serializable-begin+scope-lock`, `snapshot-read`, `validate`, `compose`, `save+commit`) for any compose slower than 3 s. Set the secret via `Security:DeployApiKey` (env `Security__DeployApiKey`) on admin nodes only; treat it like any deploy credential (rotate, keep out of source). --- diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Messages/Admin/StartDeployment.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Messages/Admin/StartDeployment.cs index 797097c56..22d180843 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Messages/Admin/StartDeployment.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Messages/Admin/StartDeployment.cs @@ -6,6 +6,15 @@ namespace ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin; /// Request from the admin UI to the AdminOperationsActor singleton asking it to snapshot /// the current live-edit state and start a deployment. /// +/// Who/what initiated the deploy (audit). +/// Request correlation id. +/// +/// Optional pre-allocated id the compose uses for the Deployment row (lmxopcua#949). The caller +/// allocates it BEFORE the ask, so when the ask times out — and the deployment may still go ahead — it +/// can name the deployment and poll for it instead of reporting a plain failure. Null = the actor +/// allocates one (existing callers). +/// public sealed record StartDeployment( string CreatedBy, - CorrelationId CorrelationId); + CorrelationId CorrelationId, + DeploymentId? DeploymentId = null); diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Messages/Admin/StartDeploymentResult.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Messages/Admin/StartDeploymentResult.cs index 2c7fe3ec7..edf83e343 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Messages/Admin/StartDeploymentResult.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Messages/Admin/StartDeploymentResult.cs @@ -8,6 +8,14 @@ public enum StartDeploymentOutcome NoChanges, AnotherDeploymentInFlight, Rejected, + + /// + /// lmxopcua#949 — the request timed out waiting for the admin singleton, so the deployment may or may + /// not have been created. Produced client-side only (never by the actor). DeploymentId is the + /// id pre-allocated for the request: the deployment row, if it appears, carries exactly that id. + /// Appended last so the numeric values of the earlier members never move. + /// + OutcomeUnknown, } /// diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Api/DeployApiEndpoints.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Api/DeployApiEndpoints.cs index dcf60bee0..e0d4a6046 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Api/DeployApiEndpoints.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Api/DeployApiEndpoints.cs @@ -142,7 +142,7 @@ public static class DeployApiEndpoints } /// Map a to its HTTP result: Accepted → 202 (with a - /// Location), NoChanges → 200, AnotherDeploymentInFlight → 409, Rejected → 422, anything else → 500. + /// Location), NoChanges → 200, AnotherDeploymentInFlight → 409, Rejected → 422, OutcomeUnknown (ask timed out; the deployment may still go ahead) → 202 with a Location to poll, anything else → 500. /// The deployment outcome from the admin-operations singleton. /// The corresponding HTTP result. public static IResult ToResult(StartDeploymentResult r) => r.Outcome switch @@ -152,8 +152,16 @@ public static class DeployApiEndpoints new DeployResponse(r.Outcome.ToString(), r.DeploymentId?.Value, r.RevisionHash?.Value)), StartDeploymentOutcome.NoChanges => Results.Ok( new DeployResponse(r.Outcome.ToString(), r.DeploymentId?.Value, r.RevisionHash?.Value)), + // The in-flight id is set when it is a compose still running (lmxopcua#949) - the deployment a caller that + // timed out and retried is looking for. StartDeploymentOutcome.AnotherDeploymentInFlight => Results.Conflict( - new DeployResponse(r.Outcome.ToString(), DeploymentId: null, RevisionHash: null)), + new DeployResponse(r.Outcome.ToString(), r.DeploymentId?.Value, RevisionHash: null)), + // lmxopcua#949: the ask timed out, the deployment may still go ahead. 202 (not 5xx): the request was + // handed over, its outcome is unknown, and the Location names the deployment to poll - 404 there for a + // couple of minutes means it was not created and the trigger can be repeated. + StartDeploymentOutcome.OutcomeUnknown => Results.Accepted( + $"/api/deployments/{r.DeploymentId?.Value}", + new DeployResponse(r.Outcome.ToString(), r.DeploymentId?.Value, RevisionHash: null, r.Message)), StartDeploymentOutcome.Rejected => Results.Problem( r.Message ?? "Deployment rejected.", statusCode: StatusCodes.Status422UnprocessableEntity), _ => Results.Problem($"Unexpected deployment outcome: {r.Outcome}", @@ -197,7 +205,11 @@ public static class DeployApiEndpoints /// The name. /// The new deployment id when one was created; otherwise null. /// The config revision hash, when known. - public sealed record DeployResponse(string Outcome, Guid? DeploymentId, string? RevisionHash); + /// Explanation for OutcomeUnknown; omitted otherwise. + public sealed record DeployResponse( + string Outcome, Guid? DeploymentId, string? RevisionHash, + [property: System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)] + string? Message = null); /// Response body for GET /api/deployments/{id}. /// The deployment id. diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Clients/AdminOperationsClient.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Clients/AdminOperationsClient.cs index c33d1d625..f662b6b8c 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Clients/AdminOperationsClient.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Clients/AdminOperationsClient.cs @@ -14,24 +14,57 @@ namespace ZB.MOM.WW.OtOpcUa.AdminUI.Clients; /// public sealed class AdminOperationsClient : IAdminOperationsClient { - private static readonly TimeSpan AskTimeout = TimeSpan.FromSeconds(10); + private static readonly TimeSpan DefaultAskTimeout = TimeSpan.FromSeconds(10); private readonly IActorRef _proxy; + private readonly TimeSpan AskTimeout; /// Initializes a new instance of the AdminOperationsClient. /// The actor registry to resolve the admin operations singleton proxy. - public AdminOperationsClient(ActorRegistry registry) + public AdminOperationsClient(ActorRegistry registry) : this(registry, DefaultAskTimeout) + { + } + + /// Test seam: the same client with a caller-chosen ask timeout. + /// The actor registry to resolve the admin operations singleton proxy. + /// How long to wait for the singleton's reply. + internal AdminOperationsClient(ActorRegistry registry, TimeSpan askTimeout) { _proxy = registry.Get(); + AskTimeout = askTimeout; } /// + /// + /// lmxopcua#949: the deployment id is allocated HERE, before the ask, and travels in the message. An ask + /// timeout does not mean the deployment did not happen — the compose can be slow (one gate run took + /// 10.5 s) and the singleton goes on to create the row after this client has given up. So a timeout is + /// reported as carrying that id, never as an + /// exception the caller would render as a plain failure. A caller-initiated cancellation still throws. + /// public async Task StartDeploymentAsync(string createdBy, CancellationToken ct) { - var msg = new StartDeployment(createdBy, CorrelationId.NewId()); + var deploymentId = DeploymentId.NewId(); + var correlationId = CorrelationId.NewId(); + var msg = new StartDeployment(createdBy, correlationId, deploymentId); using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct); linked.CancelAfter(AskTimeout); - return await _proxy.Ask(msg, AskTimeout, linked.Token); + try + { + return await _proxy.Ask(msg, AskTimeout, linked.Token); + } + catch (Exception ex) when (ex is AskTimeoutException + || (ex is OperationCanceledException && !ct.IsCancellationRequested)) + { + return new StartDeploymentResult( + StartDeploymentOutcome.OutcomeUnknown, + deploymentId, + RevisionHash: null, + Message: $"No reply from the deployment service within {AskTimeout.TotalSeconds:0} s, so it is not known " + + $"whether the deployment was created. If it was, it carries id {deploymentId.Value}; check the " + + "deployment history (or GET /api/deployments/" + deploymentId.Value + ") before retrying.", + correlationId); + } } /// diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Deployments.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Deployments.razor index fc8099bda..9d6af1a4e 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Deployments.razor +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Deployments.razor @@ -66,7 +66,7 @@ + ContextLabel="@(_requestOutcome is StartDeploymentOutcome.Accepted or StartDeploymentOutcome.OutcomeUnknown ? "Requested deployment" : "Most recent recorded deployment")" /> @if (_loadError is not null) {
@@ -136,7 +136,7 @@ private DriftState _driftState; // A newly accepted request never borrows another historical deployment's terminal status. - private DeploymentRow? FeedbackRow => _requestOutcome == StartDeploymentOutcome.Accepted + private DeploymentRow? FeedbackRow => _requestOutcome is StartDeploymentOutcome.Accepted or StartDeploymentOutcome.OutcomeUnknown ? _deployments.FirstOrDefault(d => d.DeploymentId == _requestedDeploymentId) : _deployments.FirstOrDefault(); @@ -253,9 +253,14 @@ var result = await AdminOps.StartDeploymentAsync(createdBy: createdBy, ct: CancellationToken.None); if (_disposed) return; _requestPending = false; + // lmxopcua#949: OutcomeUnknown = the ask timed out and the deployment may still go ahead. Shown as + // "could not be confirmed" (never as a failure/rejection), with the pre-allocated id so the history + // row can be found; the reload below picks it up if it has appeared. + var unknown = result.Outcome == StartDeploymentOutcome.OutcomeUnknown; + _requestResultUnavailable = unknown; _requestOutcome = result.Outcome; _requestMessage = result.Message; - _requestedDeploymentId = result.Outcome == StartDeploymentOutcome.Accepted ? result.DeploymentId?.Value : null; + _requestedDeploymentId = result.Outcome == StartDeploymentOutcome.Accepted || unknown ? result.DeploymentId?.Value : null; _requestedRevisionHash = result.Outcome == StartDeploymentOutcome.Accepted ? result.RevisionHash?.Value : null; // A failed follow-up read cannot retroactively turn an accepted request into rejection. if (await ReloadAsync()) await RefreshDriftAsync(); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/DeploymentFeedback.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/DeploymentFeedback.razor index a5e578ee8..07175ec7b 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/DeploymentFeedback.razor +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/DeploymentFeedback.razor @@ -14,7 +14,7 @@ } else if (RequestResultUnavailable) { -

The request result could not be confirmed. Refresh status before retrying.

+

The request result could not be confirmed. @(RequestOutcome == StartDeploymentOutcome.OutcomeUnknown ? "The deployment may still be created; this is not a failure. " : "")Refresh status before retrying.

} else if (RequestOutcome == StartDeploymentOutcome.Accepted) { @@ -47,6 +47,10 @@ } } + else if (RequestOutcome == StartDeploymentOutcome.OutcomeUnknown) + { +

The requested deployment is not in the loaded history yet — it may still be created. Refresh status to check.

+ } else if (RequestOutcome == StartDeploymentOutcome.Accepted) {

The requested deployment status is not yet observed in the loaded history. Refresh status to check application progress.

diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AdminOperationsActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AdminOperationsActor.cs index 5b40d7cf1..c1ef6579c 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AdminOperationsActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AdminOperationsActor.cs @@ -233,7 +233,9 @@ public sealed class AdminOperationsActor : ReceiveActor { replyTo.Tell(new StartDeploymentResult( StartDeploymentOutcome.AnotherDeploymentInFlight, - DeploymentId: null, + // The in-flight request's pre-allocated id (#949): a caller retrying after an ask timeout + // learns which deployment is going ahead instead of getting a bare refusal. + DeploymentId: inFlightRequest.DeploymentId, RevisionHash: null, Message: $"A deployment requested by {inFlightRequest.CreatedBy} is still being composed.", msg.CorrelationId)); @@ -373,6 +375,33 @@ public sealed class AdminOperationsActor : ReceiveActor msg.Request.CorrelationId)); } + /// Per-phase wall-clock of one deploy compose; logs only when the compose is slow (lmxopcua#949). + private sealed class ComposePhaseTimer + { + /// A compose slower than this is logged with its phase breakdown (normal ones take 60-630 ms). + private static readonly TimeSpan SlowThreshold = TimeSpan.FromSeconds(3); + + private readonly System.Diagnostics.Stopwatch _total = System.Diagnostics.Stopwatch.StartNew(); + private readonly List<(string Phase, TimeSpan Elapsed)> _phases = new(); + private TimeSpan _last = TimeSpan.Zero; + + internal void Mark(string phase) + { + var now = _total.Elapsed; + _phases.Add((phase, now - _last)); + _last = now; + } + + internal void LogIfSlow(Akka.Event.ILoggingAdapter log, StartDeployment msg, string outcome) + { + if (_total.Elapsed < SlowThreshold) return; + log.Warning( + "StartDeployment compose was slow ({Total:F1}s, {Outcome}) for {CreatedBy} (correlation {CorrelationId}, deployment {DeploymentId}); phases: {Phases}", + _total.Elapsed.TotalSeconds, outcome, msg.CreatedBy, msg.CorrelationId, msg.DeploymentId?.ToString() ?? "(unallocated)", + string.Join(", ", _phases.Select(p => $"{p.Phase}={p.Elapsed.TotalMilliseconds:F0}ms"))); + } + } + /// Outcome of the off-actor compose: the reply to send, and the dispatch to issue when Accepted. private sealed record ComposeOutcome(StartDeploymentResult Result, DispatchDeployment? Dispatch); @@ -389,6 +418,11 @@ public sealed class AdminOperationsActor : ReceiveActor /// private async Task ComposeDeploymentAsync(StartDeployment msg, string sourceNode) { + // lmxopcua#949: phase timings, logged only when the compose is slow. The one observed 10.5 s compose + // (H4 gate, 2026-11-28) was never explained — the Deployment row's CreatedAtUtc is stamped AFTER the + // snapshot read, so the time went into the lock / read / validate / compose phases, not the insert — + // and nothing recorded which. A repeat now names the phase. + var phases = new ComposePhaseTimer(); await using var db = await _dbFactory.CreateDbContextAsync(); // The singleton update obtains a write lock BEFORE reading the draft. The revision and // deployment row remain in this same transaction until the sealed artifact is committed. @@ -401,6 +435,7 @@ public sealed class AdminOperationsActor : ReceiveActor var locked = await db.Database.ExecuteSqlRawAsync("UPDATE DataConnectionScopeState SET ScopeVersion = ScopeVersion WHERE Id = 1"); if (locked != 1) throw new InvalidOperationException("Authoritative data scope state is unavailable."); scopeState = await db.DataConnectionScopeStates.SingleAsync(x => x.Id == 1); + phases.Mark("serializable-begin+scope-lock"); } else { @@ -420,6 +455,7 @@ public sealed class AdminOperationsActor : ReceiveActor // committed/visible when the snapshot is read — operators seeing a spurious one should // check ExternalIdReservation state before re-submitting. var draft = await DraftSnapshotFactory.FromConfigDbAsync(db); + phases.Mark("snapshot-read"); var errors = DraftValidator.Validate(draft).ToList(); // Cluster-topology guard. The SQL @@ -493,8 +529,10 @@ public sealed class AdminOperationsActor : ReceiveActor foreach (var w in DataConnectionValidator.DeployWarnings(draft)) _log.Warning("StartDeployment: data-connection warning (non-blocking): {Warning}", w); + phases.Mark("validate"); if (errors.Count > 0) { + phases.LogIfSlow(_log, msg, outcome: "rejected"); var summary = string.Join("; ", errors.Select(e => $"[{e.Code}] {e.Message}")); _log.Warning("StartDeployment rejected ({Count} validation error(s)): {Summary}", errors.Count, summary); @@ -550,7 +588,8 @@ public sealed class AdminOperationsActor : ReceiveActor scopeState.Fingerprint = scope.Fingerprint; draft.DataConnectionScopeVersion = scope.Version; var artifact = ConfigComposer.Compose(draft); - var deploymentId = DeploymentId.NewId(); + phases.Mark("compose"); + var deploymentId = msg.DeploymentId ?? DeploymentId.NewId(); var revHash = RevisionHash.Parse(artifact.RevisionHash); db.Deployments.Add(new Deployment @@ -574,6 +613,8 @@ public sealed class AdminOperationsActor : ReceiveActor await db.SaveChangesAsync(); if (transaction is not null) await transaction.CommitAsync(); + phases.Mark("save+commit"); + phases.LogIfSlow(_log, msg, outcome: "accepted"); // Accepted message = the compile-cost advisory (if any) + any Warn-mode TagConfig warnings, so // the operator sees the non-blocking strictness findings on a successful deploy. diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/AdminOperationsClientDeployTimeoutTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/AdminOperationsClientDeployTimeoutTests.cs new file mode 100644 index 000000000..a6df40c42 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/AdminOperationsClientDeployTimeoutTests.cs @@ -0,0 +1,102 @@ +using Akka.Hosting; +using Akka.TestKit.Xunit; +using Microsoft.EntityFrameworkCore; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.AdminUI.Clients; +using ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Acls; +using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin; +using ZB.MOM.WW.OtOpcUa.Configuration; +using ZB.MOM.WW.OtOpcUa.ControlPlane; +using ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; + +namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests; + +/// +/// lmxopcua#949 — an ask timeout on the deploy trigger is not a failure: the slow compose goes on to create +/// the row after the client gave up. The client must report OutcomeUnknown carrying the id it +/// pre-allocated, and that id must be the one the late deployment ends up with. +/// +public sealed class AdminOperationsClientDeployTimeoutTests : TestKit +{ + // The deploy handler reads Cluster.Get(system).SelfAddress (the audit SourceNode), so the system needs the + // cluster provider; without it the actor throws on the first StartDeployment and the message is lost. + private const string ClusterHocon = """ + akka { + loglevel = "WARNING" + actor.provider = "Akka.Cluster.ClusterActorRefProvider, Akka.Cluster" + remote.dot-netty.tcp { hostname = "127.0.0.1", port = 0 } + cluster { seed-nodes = [], roles = ["admin"], min-nr-of-members = 1, run-coordinated-shutdown-when-down = off } + } + """; + + public AdminOperationsClientDeployTimeoutTests() : base(ClusterHocon) + { + var cluster = Akka.Cluster.Cluster.Get(Sys); + cluster.Join(cluster.SelfAddress); + } + + /// A compose slower than the ask timeout yields OutcomeUnknown + the id the row later carries. + [Fact] + public async Task Ask_timeout_reports_OutcomeUnknown_with_the_id_the_late_deployment_carries() + { + var gated = new GatedFactory(AclScopeTestDb.Factory($"deploy-timeout-{Guid.NewGuid():N}")); + var coordinator = CreateTestProbe("coordinator"); + var actor = Sys.ActorOf(AdminOperationsActor.Props(gated, coordinator.Ref, Enumerable.Empty())); + var registry = new ActorRegistry(); + registry.Register(actor); + var client = new AdminOperationsClient(registry, TimeSpan.FromMilliseconds(500)); + + gated.Hold(); + var result = await client.StartDeploymentAsync("ci", CancellationToken.None); + + result.Outcome.ShouldBe(StartDeploymentOutcome.OutcomeUnknown); + result.DeploymentId.ShouldNotBeNull(); + result.Message.ShouldNotBeNull().ShouldContain(result.DeploymentId!.Value.Value.ToString()); + + // The compose was only slow: once it finishes, the deployment exists under exactly that id. + gated.Release(); + var dispatch = coordinator.ExpectMsg( + TimeSpan.FromSeconds(10), cancellationToken: TestContext.Current.CancellationToken); + dispatch.DeploymentId.ShouldBe(result.DeploymentId!.Value); + await using var db = await gated.CreateDbContextAsync(TestContext.Current.CancellationToken); + (await db.Deployments.AsNoTracking().SingleAsync(TestContext.Current.CancellationToken)) + .DeploymentId.ShouldBe(result.DeploymentId.Value.Value); + } + + /// A caller-initiated cancellation is still a cancellation, not an unknown outcome. + [Fact] + public async Task Caller_cancellation_still_throws() + { + var gated = new GatedFactory(AclScopeTestDb.Factory($"deploy-cancel-{Guid.NewGuid():N}")); + var actor = Sys.ActorOf(AdminOperationsActor.Props( + gated, CreateTestProbe("coordinator").Ref, Enumerable.Empty())); + var registry = new ActorRegistry(); + registry.Register(actor); + var client = new AdminOperationsClient(registry, TimeSpan.FromSeconds(30)); + using var cts = new CancellationTokenSource(); + + gated.Hold(); + var pending = client.StartDeploymentAsync("ci", cts.Token); + await cts.CancelAsync(); + + await Should.ThrowAsync(() => pending); + gated.Release(); + } + + private sealed class GatedFactory(IDbContextFactory inner) : IDbContextFactory + { + private volatile TaskCompletionSource? _gate; + + public void Hold() => _gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + public void Release() => _gate?.TrySetResult(); + public OtOpcUaConfigDbContext CreateDbContext() => inner.CreateDbContext(); + + public async Task CreateDbContextAsync(CancellationToken cancellationToken = default) + { + if (_gate is { } gate) await gate.Task.WaitAsync(cancellationToken); + return inner.CreateDbContext(); + } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Api/DeployApiEndpointsTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Api/DeployApiEndpointsTests.cs index 6d7c30a2b..b2c2468e1 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Api/DeployApiEndpointsTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Api/DeployApiEndpointsTests.cs @@ -46,6 +46,7 @@ public sealed class DeployApiEndpointsTests [InlineData(StartDeploymentOutcome.NoChanges, StatusCodes.Status200OK)] [InlineData(StartDeploymentOutcome.AnotherDeploymentInFlight, StatusCodes.Status409Conflict)] [InlineData(StartDeploymentOutcome.Rejected, StatusCodes.Status422UnprocessableEntity)] + [InlineData(StartDeploymentOutcome.OutcomeUnknown, StatusCodes.Status202Accepted)] public void ToResult_maps_outcome_to_status(StartDeploymentOutcome outcome, int expectedStatus) { var result = DeployApiEndpoints.ToResult( @@ -55,4 +56,35 @@ public sealed class DeployApiEndpointsTests result.ShouldBeAssignableTo(); ((IStatusCodeHttpResult)result).StatusCode.ShouldBe(expectedStatus); } + + /// + /// lmxopcua#949: an ask timeout is not a failure. The REST trigger answers 202 with the pre-allocated id in + /// the body and the Location, so the caller can poll for the deployment that may still go ahead. + /// + [Fact] + public void ToResult_OutcomeUnknown_is_202_with_the_preallocated_id_and_a_pollable_Location() + { + var id = Guid.NewGuid(); + var result = DeployApiEndpoints.ToResult(new StartDeploymentResult( + StartDeploymentOutcome.OutcomeUnknown, new DeploymentId(id), RevisionHash: null, + Message: "no reply", CorrelationId: CorrelationId.NewId())); + + var accepted = result.ShouldBeOfType>(); + accepted.Location.ShouldBe($"/api/deployments/{id}"); + accepted.Value!.Outcome.ShouldBe("OutcomeUnknown"); + accepted.Value.DeploymentId.ShouldBe(id); + accepted.Value.Message.ShouldBe("no reply"); + } + + /// A 409 for a compose still running names the deployment that is going ahead (#949). + [Fact] + public void ToResult_InFlight_carries_the_in_flight_id() + { + var id = Guid.NewGuid(); + var result = DeployApiEndpoints.ToResult(new StartDeploymentResult( + StartDeploymentOutcome.AnotherDeploymentInFlight, new DeploymentId(id), null, "busy", CorrelationId.NewId())); + + var conflict = result.ShouldBeOfType>(); + conflict.Value!.DeploymentId.ShouldBe(id); + } } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Pages/DeploymentRefreshTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Pages/DeploymentRefreshTests.cs index bed623e80..76b4702fc 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Pages/DeploymentRefreshTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Pages/DeploymentRefreshTests.cs @@ -117,6 +117,19 @@ public sealed class DeploymentRefreshTests : BunitContext cut.Find("[role=status]").TextContent.ShouldNotContain("Request rejected"); } + /// lmxopcua#949: an ask timeout is shown as "may still be created", never as a failure or rejection, and names the id. + [Fact] + public void OutcomeUnknown_IsShownAsUnconfirmed_WithTheRequestedId() + { + Configure();var cut=Render();var id=Guid.NewGuid(); + Request.Start=()=>Task.FromResult(new StartDeploymentResult(StartDeploymentOutcome.OutcomeUnknown,new(id),null,"no reply",new(Guid.NewGuid()))); + cut.Find("[data-testid=deployment-request]").Click(); + cut.WaitForAssertion(()=>cut.Find("[role=status]").TextContent.ShouldContain("could not be confirmed")); + var text=cut.Find("[role=status]").TextContent; + text.ShouldContain("may still be created");text.ShouldNotContain("rejected");text.ShouldNotContain("No deployment history"); + cut.Markup.ShouldContain(id.ToString()); + } + [Fact] public async Task DelayedInitialHistory_ComposesDriftOnceAfterRowsBecomeAvailable() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorMailboxTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorMailboxTests.cs index 2d14b2c09..907215841 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorMailboxTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorMailboxTests.cs @@ -116,6 +116,34 @@ public sealed class AdminOperationsActorMailboxTests : ControlPlaneActorTestBase coordinator.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); } + /// + /// lmxopcua#949: the refusal for a second request names the deployment that is being composed — a caller + /// whose first ask timed out and who retries learns the id of the deployment going ahead. + /// + [Fact] + public void Refusal_during_an_in_flight_compose_names_the_deployment_being_composed() + { + var gated = new GatedDbFactory(NewInMemoryDbFactory()); + var coordinator = CreateTestProbe("coord"); + var actor = Sys.ActorOf(AdminOperationsActor.Props(gated, coordinator.Ref, Enumerable.Empty())); + var first = CreateTestProbe("first"); + var second = CreateTestProbe("second"); + var firstId = DeploymentId.NewId(); + + gated.Hold(); + first.Send(actor, new StartDeployment("joe", CorrelationId.NewId(), firstId)); + gated.Entered.Wait(PresenceBudget, TestContext.Current.CancellationToken).ShouldBeTrue(); + + second.Send(actor, new StartDeployment("kim", CorrelationId.NewId(), DeploymentId.NewId())); + var refusal = second.ExpectMsg(AckBudget, cancellationToken: TestContext.Current.CancellationToken); + refusal.Outcome.ShouldBe(StartDeploymentOutcome.AnotherDeploymentInFlight); + refusal.DeploymentId.ShouldBe(firstId); + + gated.Release(); + first.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken) + .DeploymentId.ShouldBe(firstId); + } + private sealed class BlockingProbe : IDriverProbe { private readonly TaskCompletionSource _tcs = diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorTests.cs index 237f68dd2..ab653e6d0 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorTests.cs @@ -175,6 +175,28 @@ public sealed class AdminOperationsActorTests : ControlPlaneActorTestBase db.ConfigEdits.Single().EntityType.ShouldBe("Deployment"); } + /// + /// lmxopcua#949: a pre-allocated deployment id on the request is the id of the row, the reply and the + /// dispatch — what lets a caller whose ask timed out name (and poll for) the deployment that goes ahead. + /// + [Fact] + public void StartDeployment_uses_the_preallocated_deployment_id() + { + var dbFactory = NewInMemoryDbFactory(); + var coordinator = CreateTestProbe("coord"); + var actor = Sys.ActorOf(AdminOperationsActor.Props(dbFactory, coordinator.Ref, Enumerable.Empty())); + var id = DeploymentId.NewId(); + + actor.Tell(new StartDeployment("joe", CorrelationId.NewId(), id)); + + coordinator.ExpectMsg(TimeSpan.FromSeconds(3), cancellationToken: TestContext.Current.CancellationToken) + .DeploymentId.ShouldBe(id); + ExpectMsg(TimeSpan.FromSeconds(3), cancellationToken: TestContext.Current.CancellationToken) + .DeploymentId.ShouldBe(id); + using var db = dbFactory.CreateDbContext(); + db.Deployments.Single().DeploymentId.ShouldBe(id.Value); + } + /// Verifies the full DraftValidator gate (reject on ANY error): a v3 UNS effective-name /// collision — a UnsTagReference (surfacing a raw Tag under an equipment) and a VirtualTag sharing the /// same effective leaf name in that equipment's UNS NodeId space — rejects the deploy (422-mapped