Merge #949: deploy trigger ask timeout -> 202 OutcomeUnknown with pre-allocated DeploymentId (+Location poll); 409 names the in-flight id; AdminUI shows outcome-unknown; >3 s compose phase-timing warning

This commit is contained in:
Joseph Doherty
2026-12-01 19:27:27 -05:00
14 changed files with 333 additions and 15 deletions
+7
View File
@@ -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/<deploymentId> (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)
+3 -1
View File
@@ -1787,7 +1787,9 @@ curl -X POST https://<admin-host>/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": "<id>", "message": "…" }` and `Location: /api/deployments/<id>`. 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).
---
@@ -6,6 +6,15 @@ namespace ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin;
/// Request from the admin UI to the <c>AdminOperationsActor</c> singleton asking it to snapshot
/// the current live-edit state and start a deployment.
/// </summary>
/// <param name="CreatedBy">Who/what initiated the deploy (audit).</param>
/// <param name="CorrelationId">Request correlation id.</param>
/// <param name="DeploymentId">
/// Optional pre-allocated id the compose uses for the <c>Deployment</c> 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).
/// </param>
public sealed record StartDeployment(
string CreatedBy,
CorrelationId CorrelationId);
CorrelationId CorrelationId,
DeploymentId? DeploymentId = null);
@@ -8,6 +8,14 @@ public enum StartDeploymentOutcome
NoChanges,
AnotherDeploymentInFlight,
Rejected,
/// <summary>
/// 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). <c>DeploymentId</c> 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.
/// </summary>
OutcomeUnknown,
}
/// <summary>
@@ -142,7 +142,7 @@ public static class DeployApiEndpoints
}
/// <summary>Map a <see cref="StartDeploymentResult"/> to its HTTP result: Accepted → 202 (with a
/// Location), NoChanges → 200, AnotherDeploymentInFlight → 409, Rejected → 422, anything else → 500.</summary>
/// 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.</summary>
/// <param name="r">The deployment outcome from the admin-operations singleton.</param>
/// <returns>The corresponding HTTP result.</returns>
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
/// <param name="Outcome">The <see cref="StartDeploymentOutcome"/> name.</param>
/// <param name="DeploymentId">The new deployment id when one was created; otherwise null.</param>
/// <param name="RevisionHash">The config revision hash, when known.</param>
public sealed record DeployResponse(string Outcome, Guid? DeploymentId, string? RevisionHash);
/// <param name="Message">Explanation for <c>OutcomeUnknown</c>; omitted otherwise.</param>
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);
/// <summary>Response body for <c>GET /api/deployments/{id}</c>.</summary>
/// <param name="DeploymentId">The deployment id.</param>
@@ -14,24 +14,57 @@ namespace ZB.MOM.WW.OtOpcUa.AdminUI.Clients;
/// </summary>
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;
/// <summary>Initializes a new instance of the AdminOperationsClient.</summary>
/// <param name="registry">The actor registry to resolve the admin operations singleton proxy.</param>
public AdminOperationsClient(ActorRegistry registry)
public AdminOperationsClient(ActorRegistry registry) : this(registry, DefaultAskTimeout)
{
}
/// <summary>Test seam: the same client with a caller-chosen ask timeout.</summary>
/// <param name="registry">The actor registry to resolve the admin operations singleton proxy.</param>
/// <param name="askTimeout">How long to wait for the singleton's reply.</param>
internal AdminOperationsClient(ActorRegistry registry, TimeSpan askTimeout)
{
_proxy = registry.Get<AdminOperationsActorKey>();
AskTimeout = askTimeout;
}
/// <inheritdoc />
/// <remarks>
/// 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 <see cref="StartDeploymentOutcome.OutcomeUnknown"/> carrying that id, never as an
/// exception the caller would render as a plain failure. A caller-initiated cancellation still throws.
/// </remarks>
public async Task<StartDeploymentResult> 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<StartDeploymentResult>(msg, AskTimeout, linked.Token);
try
{
return await _proxy.Ask<StartDeploymentResult>(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);
}
}
/// <inheritdoc />
@@ -66,7 +66,7 @@
<DeploymentFeedback RequestOutcome="@_requestOutcome" RequestPending="@_requestPending" RequestResultUnavailable="@_requestResultUnavailable"
RequestMessage="@_requestMessage" Status="@(FeedbackRow?.Status)" FailureReason="@(FeedbackRow?.FailureReason)"
InitialLoading="@(_loading && !_hasLoaded)" HistoryAvailable="@_hasLoaded"
ContextLabel="@(_requestOutcome == StartDeploymentOutcome.Accepted ? "Requested deployment" : "Most recent recorded deployment")" />
ContextLabel="@(_requestOutcome is StartDeploymentOutcome.Accepted or StartDeploymentOutcome.OutcomeUnknown ? "Requested deployment" : "Most recent recorded deployment")" />
@if (_loadError is not null)
{
<section class="panel notice notice-alert p-3 mb-3" aria-label="History refresh error">
@@ -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();
@@ -14,7 +14,7 @@
}
else if (RequestResultUnavailable)
{
<p class="mb-2">The request result could not be confirmed. Refresh status before retrying.</p>
<p class="mb-2">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.</p>
}
else if (RequestOutcome == StartDeploymentOutcome.Accepted)
{
@@ -47,6 +47,10 @@
}
</div>
}
else if (RequestOutcome == StartDeploymentOutcome.OutcomeUnknown)
{
<p class="mb-0">The requested deployment is not in the loaded history yet — it may still be created. Refresh status to check.</p>
}
else if (RequestOutcome == StartDeploymentOutcome.Accepted)
{
<p class="mb-0">The requested deployment status is not yet observed in the loaded history. Refresh status to check application progress.</p>
@@ -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));
}
/// <summary>Per-phase wall-clock of one deploy compose; logs only when the compose is slow (lmxopcua#949).</summary>
private sealed class ComposePhaseTimer
{
/// <summary>A compose slower than this is logged with its phase breakdown (normal ones take 60-630 ms).</summary>
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")));
}
}
/// <summary>Outcome of the off-actor compose: the reply to send, and the dispatch to issue when Accepted.</summary>
private sealed record ComposeOutcome(StartDeploymentResult Result, DispatchDeployment? Dispatch);
@@ -389,6 +418,11 @@ public sealed class AdminOperationsActor : ReceiveActor
/// </summary>
private async Task<ComposeOutcome> 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.
@@ -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;
/// <summary>
/// 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 <c>OutcomeUnknown</c> carrying the id it
/// pre-allocated, and that id must be the one the late deployment ends up with.
/// </summary>
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);
}
/// <summary>A compose slower than the ask timeout yields OutcomeUnknown + the id the row later carries.</summary>
[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<IDriverProbe>()));
var registry = new ActorRegistry();
registry.Register<AdminOperationsActorKey>(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<ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy.DispatchDeployment>(
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);
}
/// <summary>A caller-initiated cancellation is still a cancellation, not an unknown outcome.</summary>
[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<IDriverProbe>()));
var registry = new ActorRegistry();
registry.Register<AdminOperationsActorKey>(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<OperationCanceledException>(() => pending);
gated.Release();
}
private sealed class GatedFactory(IDbContextFactory<OtOpcUaConfigDbContext> inner) : IDbContextFactory<OtOpcUaConfigDbContext>
{
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<OtOpcUaConfigDbContext> CreateDbContextAsync(CancellationToken cancellationToken = default)
{
if (_gate is { } gate) await gate.Task.WaitAsync(cancellationToken);
return inner.CreateDbContext();
}
}
}
@@ -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>();
((IStatusCodeHttpResult)result).StatusCode.ShouldBe(expectedStatus);
}
/// <summary>
/// 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.
/// </summary>
[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<Microsoft.AspNetCore.Http.HttpResults.Accepted<DeployApiEndpoints.DeployResponse>>();
accepted.Location.ShouldBe($"/api/deployments/{id}");
accepted.Value!.Outcome.ShouldBe("OutcomeUnknown");
accepted.Value.DeploymentId.ShouldBe(id);
accepted.Value.Message.ShouldBe("no reply");
}
/// <summary>A 409 for a compose still running names the deployment that is going ahead (#949).</summary>
[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<Microsoft.AspNetCore.Http.HttpResults.Conflict<DeployApiEndpoints.DeployResponse>>();
conflict.Value!.DeploymentId.ShouldBe(id);
}
}
@@ -117,6 +117,19 @@ public sealed class DeploymentRefreshTests : BunitContext
cut.Find("[role=status]").TextContent.ShouldNotContain("Request rejected");
}
/// <summary>lmxopcua#949: an ask timeout is shown as "may still be created", never as a failure or rejection, and names the id.</summary>
[Fact]
public void OutcomeUnknown_IsShownAsUnconfirmed_WithTheRequestedId()
{
Configure();var cut=Render<DeploymentPage>();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()
{
@@ -116,6 +116,34 @@ public sealed class AdminOperationsActorMailboxTests : ControlPlaneActorTestBase
coordinator.ExpectMsg<DispatchDeployment>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
}
/// <summary>
/// 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.
/// </summary>
[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<IDriverProbe>()));
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<StartDeploymentResult>(AckBudget, cancellationToken: TestContext.Current.CancellationToken);
refusal.Outcome.ShouldBe(StartDeploymentOutcome.AnotherDeploymentInFlight);
refusal.DeploymentId.ShouldBe(firstId);
gated.Release();
first.ExpectMsg<StartDeploymentResult>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken)
.DeploymentId.ShouldBe(firstId);
}
private sealed class BlockingProbe : IDriverProbe
{
private readonly TaskCompletionSource<DriverProbeResult> _tcs =
@@ -175,6 +175,28 @@ public sealed class AdminOperationsActorTests : ControlPlaneActorTestBase
db.ConfigEdits.Single().EntityType.ShouldBe("Deployment");
}
/// <summary>
/// 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.
/// </summary>
[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<IDriverProbe>()));
var id = DeploymentId.NewId();
actor.Tell(new StartDeployment("joe", CorrelationId.NewId(), id));
coordinator.ExpectMsg<DispatchDeployment>(TimeSpan.FromSeconds(3), cancellationToken: TestContext.Current.CancellationToken)
.DeploymentId.ShouldBe(id);
ExpectMsg<StartDeploymentResult>(TimeSpan.FromSeconds(3), cancellationToken: TestContext.Current.CancellationToken)
.DeploymentId.ShouldBe(id);
using var db = dbFactory.CreateDbContext();
db.Deployments.Single().DeploymentId.ShouldBe(id.Value);
}
/// <summary>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