diff --git a/docs/plans/evidence/followups/955.md b/docs/plans/evidence/followups/955.md new file mode 100644 index 000000000..676be1622 --- /dev/null +++ b/docs/plans/evidence/followups/955.md @@ -0,0 +1,60 @@ +# #955 — the ~10 s StartDeployment stall (#923 gate) + +Follow-up to #949 (`88c9766ab`), which made the caller-facing symptom honest (202 OutcomeUnknown) but left the cause open. +The leading hypothesis was lock contention around the compose's SERIALIZABLE transaction. + +## What the compose's transaction actually did + +`ComposeDeploymentAsync` (added in `47960a6d5`) opened a SERIALIZABLE transaction for the `DataConnectionScopeState` row +lock, and `DraftSnapshotFactory.FromConfigDbAsync` reads **inside an existing transaction** rather than opening its own +SNAPSHOT one. So the "one consistent SNAPSHOT read" described in the factory's remarks had silently become a SERIALIZABLE +read of ~22 config tables, whose key-range S locks were held through validate + compose + gzip + insert. Consequences: + +- an uncommitted edit of any config row makes the deploy wait for it; +- a running deploy makes every edit of an already-read table wait for the deploy; +- an edit touching a table the deploy has already read **and** one it has not yet read deadlocks with it. + +## Reproduction (central SQL Server, throwaway DB, 300 tags; deploys driven through the real actor) + +Exploratory probe, 10 deploys per row (5 for the last), same machine, before and after the fix: + +| Concurrent writer (own connection, loop) | SERIALIZABLE (before) | SNAPSHOT + app lock (after) | +|---|---|---| +| none | p50 206 ms, max 482 ms | p50 199 ms, max 258 ms | +| AdminUI-style save (UPDATE Tag + INSERT ConfigEdit) | p50 277 ms, max 468 ms | p50 296 ms, max 679 ms | +| cross-table edit (UPDATE Tag, then UPDATE ClusterNode) | **max 5 092 ms; 9 of 10 deploys failed 1205 (deadlock victim) → "StartDeployment failed on the server"**; first deadlock waited one 5 s lock-monitor cycle | p50 383 ms, max 946 ms, 0 deadlocks | +| deploy bookkeeping (UPDATE Deployment + INSERT ConfigAuditLog) | p50 242 ms, max 350 ms | p50 176 ms, max 580 ms | +| edit holding a row lock 2 s | p50 1 991 ms (deploy = the writer's hold) | p50 210 ms (not held) | + +So the mechanism is real: a deploy under SERIALIZABLE stalls for as long as any concurrent edit holds a lock, ~5 s per +deadlock-monitor cycle on a deadlock (two cycles ≈ 10 s), or fails outright. + +## Fix + +The compose transaction is SNAPSHOT. A snapshot read takes no shared locks: it neither waits on nor blocks an edit, and an +edit that commits after the snapshot is simply in the next deployment (the R03:3.2 contract). Composes are still serialised, +by a transaction-owned `sp_getapplock` (`OtOpcUa/DeployCompose`, 20 s) taken **before** any data access — under SNAPSHOT the +version clock starts at the first data access, so a compose queued behind another reads and advances the scope revision that +compose committed; taking the row lock first would fail the second with update conflict 3960. + +The #949 phase timer now starts at the singleton's receipt and adds `dispatch` (thread-pool hand-off) and `in-flight-check` +(both were outside the breakdown), and also logs a slow refused or failed attempt. + +## Red / green (`DeployComposeIsolationSqlServerTests`, real SQL Server) + +| Test | Red | +|---|---| +| `Deploy_is_not_held_by_an_uncommitted_edit_and_ships_the_committed_state` | isolation reverted to SERIALIZABLE: no reply within 10 s | +| `An_edit_of_an_already_read_table_does_not_wait_for_a_running_deploy` | SERIALIZABLE: the mid-read edit hits its 3 s lock timeout | +| `A_compose_queued_behind_another_advances_the_revision_that_compose_committed` | SNAPSHOT without the app lock: Rejected (3960) | + +## What is NOT established + +The specific 10.5 s stall in the #923 run is not proven to be this mechanism. In that run the only config writer was the +rig's seeder, which runs (`docker compose run --rm`) and exits **before** the deploy is triggered; the in-process writers on +CONTROL (coordinator, retention, audit, the fused node's `NodeDeploymentState` ack) write only the deploy bookkeeping tables +in sub-second `SaveChanges`; and `system_health` showed no deadlock. The run's logs were not retained. Other places the +10 s could have gone, none of which was timed then: the ask's delivery through the singleton proxy (CONTROL-1 ↔ CONTROL-2), +thread-pool queueing before the compose (now timed as `dispatch`), the in-flight check (now timed), and a stall of the SQL or +CONTROL container itself. A repeat now names the phase from receipt onwards; a long gap between the API's request and the +actor's receipt would show as a slow ask with a fast breakdown. diff --git a/docs/security.md b/docs/security.md index 4187bc67b..5a707880a 100644 --- a/docs/security.md +++ b/docs/security.md @@ -1789,7 +1789,7 @@ curl -X POST https:///api/deployments \ 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). +**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 (`dispatch`, `in-flight-check`, `snapshot-begin+compose-lock`, `snapshot-read`, `validate`, `compose`, `save+commit`), timed from the singleton's receipt of the request, for any deploy slower than 3 s. Since lmxopcua#955 the compose reads under SNAPSHOT isolation (serialised against other composes by an app lock), not SERIALIZABLE: a concurrent AdminUI edit neither waits for a running deploy nor holds it, and the two can no longer deadlock (under SERIALIZABLE a cross-table edit made the deploy wait ~5 s per deadlock-monitor cycle or fail with "StartDeployment failed on the server"). An edit that commits after the deploy's snapshot is simply in the next deployment. 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.Configuration/Validation/DraftSnapshotFactory.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftSnapshotFactory.cs index 2b8db0d19..c975740ab 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftSnapshotFactory.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftSnapshotFactory.cs @@ -30,7 +30,10 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Validation; /// validator never saw" unrepresentable. SQL Server requires ALLOW_SNAPSHOT_ISOLATION ON /// (migration EnableSnapshotIsolation); without it the first query fails with error 3952 and /// the deploy is rejected rather than silently read unisolated. A non-relational provider (the -/// InMemory test provider) and a context already inside a transaction read without one. +/// InMemory test provider) and a context already inside a transaction read without one — the +/// deploy compose opens its own SNAPSHOT transaction (it also writes the Deployment row in it). Do not +/// call this inside a SERIALIZABLE transaction: the read would range-lock every config table until +/// commit and deadlock with concurrent edits (lmxopcua#955). /// /// public static class DraftSnapshotFactory 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 b7dbde83c..5625c5b9c 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AdminOperationsActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AdminOperationsActor.cs @@ -262,10 +262,28 @@ public sealed class AdminOperationsActor : ReceiveActor // Captured here: Context/Sender are not available on the thread-pool thread. var sourceNode = Akka.Cluster.Cluster.Get(Context.System).SelfAddress.Host ?? "unknown"; var self = Self; + // #955: timed from receipt, not from the compose's first line — the thread-pool hand-off and the + // in-flight check were outside the #949 breakdown, so a stall there would have read as "fast compose". + var phases = new ComposePhaseTimer(); Task.Run(async () => { - var refusal = await CheckInFlightAsync(msg).ConfigureAwait(false); - return refusal ?? await ComposeDeploymentAsync(msg, sourceNode).ConfigureAwait(false); + phases.Mark("dispatch"); + try + { + var refusal = await CheckInFlightAsync(msg).ConfigureAwait(false); + phases.Mark("in-flight-check"); + if (refusal is not null) + { + phases.LogIfSlow(_log, msg, outcome: "refused-in-flight"); + return refusal; + } + return await ComposeDeploymentAsync(msg, sourceNode, phases).ConfigureAwait(false); + } + catch (Exception) + { + phases.LogIfSlow(_log, msg, outcome: "failed"); + throw; + } }) .PipeTo(self, success: composed => new DeployComposed(msg, replyTo, composed.Result, composed.Dispatch), @@ -391,7 +409,11 @@ 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). + /// + /// Per-phase wall-clock of one StartDeployment, from the actor's receipt to the commit; logs only when it is + /// slow (lmxopcua#949, widened by #955 to the thread-pool hand-off and the in-flight check). Used by one + /// logical flow at a time (sequential awaits), so it needs no locking. + /// private sealed class ComposePhaseTimer { /// A compose slower than this is logged with its phase breakdown (normal ones take 60-630 ms). @@ -418,6 +440,15 @@ public sealed class AdminOperationsActor : ReceiveActor } } + /// + /// Transaction-owned exclusive app lock serialising deploy composes (#955). Waits up to 20 s (inside the + /// 30 s command timeout), then fails the compose rather than composing concurrently. + /// + public const string ComposeAppLockSql = + "DECLARE @r int; " + + "EXEC @r = sp_getapplock @Resource = N'OtOpcUa/DeployCompose', @LockMode = N'Exclusive', @LockOwner = N'Transaction', @LockTimeout = 20000; " + + "IF @r < 0 THROW 51955, N'Timed out waiting for another deployment compose to release the compose lock.', 1;"; + /// 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); @@ -432,26 +463,33 @@ public sealed class AdminOperationsActor : ReceiveActor /// construction (, , — /// Akka's logging adapter is thread-safe). /// - private async Task ComposeDeploymentAsync(StartDeployment msg, string sourceNode) + private async Task ComposeDeploymentAsync(StartDeployment msg, string sourceNode, ComposePhaseTimer phases) { - // 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(); + // lmxopcua#949: phase timings, logged only when the deploy is slow (see 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. + // ONE transaction holds the snapshot read, the scope-revision advance and the Deployment row, committed + // together. It is SNAPSHOT, not SERIALIZABLE (#955): a serializable read range-locked every config table + // for the whole validate + compose + gzip, so any concurrent writer (an AdminUI save) either waited for + // the deploy, made the deploy wait for IT, or deadlocked with it — the deploy then stalled ~5 s per + // deadlock-monitor cycle or failed outright (reproduced: DeployComposeIsolationSqlServerTests). A + // snapshot read takes no shared locks, so it neither waits on nor blocks an edit; an edit that commits + // after the snapshot is simply not in this artifact (R03:3.2), and the next deploy carries it. await using var transaction = db.Database.IsRelational() - ? await db.Database.BeginTransactionAsync(System.Data.IsolationLevel.Serializable) + ? await db.Database.BeginTransactionAsync(System.Data.IsolationLevel.Snapshot) : null; DataConnectionScopeState scopeState; if (transaction is not null) { + // Composes are serialised by an app lock taken BEFORE any data is touched: under SNAPSHOT the + // version clock starts at the first data access, so a compose that queued behind another one + // reads (and advances) the scope revision that compose committed. Taking the row lock first instead + // would fail the second compose with an update conflict (3960). The singleton actor already runs + // one compose at a time; this covers two singletons overlapping across a handover. + await db.Database.ExecuteSqlRawAsync(ComposeAppLockSql); 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"); + phases.Mark("snapshot-begin+compose-lock"); } else { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/DeployComposeIsolationSqlServerTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/DeployComposeIsolationSqlServerTests.cs new file mode 100644 index 000000000..5bf10d7c2 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/DeployComposeIsolationSqlServerTests.cs @@ -0,0 +1,188 @@ +using System.IO.Compression; +using System.Text; +using Akka.Actor; +using Microsoft.Data.SqlClient; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Diagnostics; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin; +using ZB.MOM.WW.OtOpcUa.Commons.Types; +using ZB.MOM.WW.OtOpcUa.Configuration; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; +using ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations; +using ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.Harness; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; + +namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Tests; + +/// +/// #955 — the deploy compose's transaction isolation, on the real provider. The compose used to run +/// SERIALIZABLE, which range-locked every config table for the whole validate + compose + gzip: a concurrent +/// edit waited for the deploy, an uncommitted edit made the deploy wait for it, and an edit touching a table +/// the compose had already read plus one it had not yet read deadlocked with it (measured: the first +/// deadlock costs ~5 s — one lock-monitor cycle — and then either side dies; the deploy was the victim 9 of +/// 10 times and answered "StartDeployment failed on the server"). It now reads under SNAPSHOT, serialised +/// against other composes by an app lock. +/// +[Trait("Category", "SchemaCompliance")] +public sealed class DeployComposeIsolationSqlServerTests : ControlPlaneActorTestBase +{ + private static readonly TimeSpan Budget = TimeSpan.FromSeconds(10); + + /// + /// An edit holding an uncommitted row lock on a config table no longer holds the deploy: it composes + /// from the last committed state. Red under SERIALIZABLE — the snapshot read waits on the row lock until + /// the editor commits (here: never, within the budget). + /// + [Fact] + public async Task Deploy_is_not_held_by_an_uncommitted_edit_and_ships_the_committed_state() + { + using var sql = new SqlServerTestDatabase(); + await SeedAsync(sql); + + await using var editor = new SqlConnection(sql.ConnectionString); + await editor.OpenAsync(TestContext.Current.CancellationToken); + await using var edit = editor.BeginTransaction(); + await ExecAsync(editor, edit, "UPDATE Tag SET Name = N'uncommitted-name' WHERE TagId = 'tag-0001'"); + + var coordinator = CreateTestProbe("coord"); + var actor = Sys.ActorOf(AdminOperationsActor.Props(sql.Factory(), coordinator.Ref, Enumerable.Empty())); + actor.Tell(new StartDeployment("joe", CorrelationId.NewId(), DeploymentId.NewId())); + + var reply = ExpectMsg(Budget, cancellationToken: TestContext.Current.CancellationToken); + reply.Outcome.ShouldBe(StartDeploymentOutcome.Accepted, reply.Message); + + await edit.RollbackAsync(TestContext.Current.CancellationToken); + await using var verify = sql.NewContext(); + var artifact = Inflate((await verify.Deployments.SingleAsync(TestContext.Current.CancellationToken)).ArtifactBlob); + artifact.ShouldNotContain("uncommitted-name"); + artifact.ShouldContain("tag-0001"); + } + + /// + /// The other direction, which is the deadlock's precondition: while the compose is mid-read, an edit of a + /// table it has ALREADY read commits without waiting. Red under SERIALIZABLE — the read's key-range locks + /// are held to commit, so the edit hits its lock timeout (1222). + /// + [Fact] + public async Task An_edit_of_an_already_read_table_does_not_wait_for_a_running_deploy() + { + using var sql = new SqlServerTestDatabase(); + await SeedAsync(sql); + + var editOutcome = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + // Tags is read after ClusterNodes, so editing ClusterNode on the first Tag materialised edits a table the + // compose has already read, from inside the compose's read. + var factory = new InterceptingFactory(sql.ConnectionString, new EditOnFirstTag(sql.ConnectionString, editOutcome)); + var coordinator = CreateTestProbe("coord"); + var actor = Sys.ActorOf(AdminOperationsActor.Props(factory, coordinator.Ref, Enumerable.Empty())); + actor.Tell(new StartDeployment("joe", CorrelationId.NewId(), DeploymentId.NewId())); + + var reply = ExpectMsg(Budget, cancellationToken: TestContext.Current.CancellationToken); + reply.Outcome.ShouldBe(StartDeploymentOutcome.Accepted, reply.Message); + (await editOutcome.Task.WaitAsync(Budget, TestContext.Current.CancellationToken)).ShouldBe("committed"); + + await using var verify = sql.NewContext(); + (await verify.ClusterNodes.SingleAsync(TestContext.Current.CancellationToken)).Host.ShouldBe("edited-mid-deploy"); + } + + /// + /// Composes still serialise: one that queues behind another (an overlapping singleton) waits for it and + /// advances the scope revision that compose committed — it neither composes concurrently nor dies on an + /// update conflict (3960), which is what taking the row lock first under SNAPSHOT would do. + /// + [Fact] + public async Task A_compose_queued_behind_another_advances_the_revision_that_compose_committed() + { + using var sql = new SqlServerTestDatabase(); + await SeedAsync(sql); + + await using var other = new SqlConnection(sql.ConnectionString); + await other.OpenAsync(TestContext.Current.CancellationToken); + await using var otherCompose = other.BeginTransaction(); + await ExecAsync(other, otherCompose, AdminOperationsActor.ComposeAppLockSql); + await ExecAsync(other, otherCompose, "UPDATE DataConnectionScopeState SET ScopeVersion = 7, Fingerprint = 'other-compose' WHERE Id = 1"); + + var coordinator = CreateTestProbe("coord"); + var actor = Sys.ActorOf(AdminOperationsActor.Props(sql.Factory(), coordinator.Ref, Enumerable.Empty())); + actor.Tell(new StartDeployment("joe", CorrelationId.NewId(), DeploymentId.NewId())); + + // Positive control that it really queued: nothing comes back while the other compose holds the lock. + ExpectNoMsg(TimeSpan.FromSeconds(1), TestContext.Current.CancellationToken); + await otherCompose.CommitAsync(TestContext.Current.CancellationToken); + + var reply = ExpectMsg(Budget, cancellationToken: TestContext.Current.CancellationToken); + reply.Outcome.ShouldBe(StartDeploymentOutcome.Accepted, reply.Message); + await using var verify = sql.NewContext(); + var scope = await verify.DataConnectionScopeStates.AsNoTracking().SingleAsync(TestContext.Current.CancellationToken); + scope.ScopeVersion.ShouldBe(8); // 7 (the other compose's) + 1: its fingerprint differs from this snapshot's + } + + private static async Task SeedAsync(SqlServerTestDatabase sql) + { + await using var db = sql.NewContext(); + db.ServerClusters.Add(new ServerCluster + { + ClusterId = "C1", Name = "c1", Enterprise = "ent", Site = "site", NodeCount = 1, + RedundancyMode = RedundancyMode.None, CreatedBy = "t", + }); + db.ClusterNodes.Add(new ClusterNode { NodeId = "n1", ClusterId = "C1", Host = "h1", ApplicationUri = "urn:n1", CreatedBy = "t" }); + db.DriverInstances.Add(new DriverInstance { DriverInstanceId = "d", ClusterId = "C1", Name = "drv", DriverType = "Modbus", DriverConfig = "{}" }); + db.Devices.Add(new Device { DeviceId = "dev", DriverInstanceId = "d", Name = "dev", DeviceConfig = "{}" }); + for (var i = 0; i < 20; i++) + db.Tags.Add(new Tag + { + TagId = $"tag-{i:D4}", DeviceId = "dev", Name = $"t{i}", DataType = "Float", + AccessLevel = TagAccessLevel.Read, TagConfig = "{\"region\":\"HoldingRegisters\",\"address\":1}", + }); + await db.SaveChangesAsync(TestContext.Current.CancellationToken); + } + + private static async Task ExecAsync(SqlConnection conn, SqlTransaction tx, string text) + { + await using var cmd = new SqlCommand(text, conn, tx); + await cmd.ExecuteNonQueryAsync(TestContext.Current.CancellationToken); + } + + private static string Inflate(byte[] blob) + { + using var gz = new GZipStream(new MemoryStream(blob), CompressionMode.Decompress); + using var reader = new StreamReader(gz, Encoding.UTF8); + return reader.ReadToEnd(); + } + + /// On the first Tag the compose materialises, edits ClusterNode on another connection (3 s lock timeout). + private sealed class EditOnFirstTag(string connectionString, TaskCompletionSource outcome) : IMaterializationInterceptor + { + private int _fired; + + public object InitializedInstance(MaterializationInterceptionData materializationData, object entity) + { + if (entity is Tag && Interlocked.Exchange(ref _fired, 1) == 0) + { + try + { + using var conn = new SqlConnection(connectionString); + conn.Open(); + using var cmd = new SqlCommand( + "SET LOCK_TIMEOUT 3000; UPDATE ClusterNode SET Host = N'edited-mid-deploy' WHERE NodeId = 'n1';", conn); + cmd.ExecuteNonQuery(); + outcome.TrySetResult("committed"); + } + catch (SqlException ex) + { + outcome.TrySetResult($"SqlException {ex.Number}"); + } + } + return entity; + } + } + + private sealed class InterceptingFactory(string connectionString, IInterceptor interceptor) : IDbContextFactory + { + public OtOpcUaConfigDbContext CreateDbContext() => + new(new DbContextOptionsBuilder().UseSqlServer(connectionString).AddInterceptors(interceptor).Options); + } +}