diff --git a/docs/plans/sql/AuditLogChannelOccurredIndex.sql b/docs/plans/sql/AuditLogChannelOccurredIndex.sql new file mode 100644 index 00000000..836a3d44 --- /dev/null +++ b/docs/plans/sql/AuditLogChannelOccurredIndex.sql @@ -0,0 +1,39 @@ +-- AuditLogChannelOccurredIndex (2026-12-03, WP6 task 6.5 / review finding AUD-5). Run with +-- QUOTED_IDENTIFIER ON (sqlcmd -I, or keep this header): AuditLog has persisted computed +-- columns / filtered indexes and SQL Server raises error 1934 otherwise. +-- Adds IX_AuditLog_Channel_Occurred (Category, OccurredAtUtc) for the per-channel retention +-- purge. AuditLog is monthly-partitioned; the index is created ON ps_AuditLog_Month(OccurredAtUtc) +-- so it stays partition-aligned and the partition-switch purge keeps working. Building it scans +-- the whole AuditLog: on a large production table run in a quiet window, and on Enterprise +-- edition add WITH (ONLINE = ON) to the CREATE INDEX statement. +-- Ships with the binaries that bind the purge's @channel parameter as varchar(32); either order +-- is safe (the index only helps; the old binaries' nvarchar binding simply cannot seek it). +SET QUOTED_IDENTIFIER ON; +SET ANSI_NULLS ON; +GO + +BEGIN TRANSACTION; +IF NOT EXISTS ( + SELECT * FROM [__EFMigrationsHistory] + WHERE [MigrationId] = N'20261203152558_AuditLogChannelOccurredIndex' +) +BEGIN + + CREATE NONCLUSTERED INDEX IX_AuditLog_Channel_Occurred + ON dbo.AuditLog (Category, OccurredAtUtc) + ON ps_AuditLog_Month(OccurredAtUtc); +END; + +IF NOT EXISTS ( + SELECT * FROM [__EFMigrationsHistory] + WHERE [MigrationId] = N'20261203152558_AuditLogChannelOccurredIndex' +) +BEGIN + INSERT INTO [__EFMigrationsHistory] ([MigrationId], [ProductVersion]) + VALUES (N'20261203152558_AuditLogChannelOccurredIndex', N'10.0.13'); +END; + +COMMIT; +GO + + diff --git a/docs/requirements/Component-AuditLog.md b/docs/requirements/Component-AuditLog.md index 759747b7..38deca12 100644 --- a/docs/requirements/Component-AuditLog.md +++ b/docs/requirements/Component-AuditLog.md @@ -270,6 +270,17 @@ know. `SourceNode` is stamped by the writing node itself (`node-a` / `node-b`) at append time and travels with the row through telemetry and reconciliation unchanged. +**Connections and indexes (WP6, 2026-12-03).** The writer and the read-only callers use +two *private-cache* WAL connections (AUD-2 — `Cache=Shared` made them share table-level +locks, so a long backlog scan stalled the batch writer); only the in-memory test override +keeps a shared cache. The reconciliation pull reads the owed states through the partial +index `IX_fwd_owed (OccurredAtUtc, EventId) WHERE ForwardState IN ('Pending','PushAbandoned','Rejected')`, +so each page is an ordered range read that stops at the limit (AUD-3; 1 M owed rows: +3.5 s → <1 ms per 256-row page), and the retention purge seeks `IX_fwd` on +`(ForwardState, IsCachedKind, OccurredAtUtc)` instead of walking each state's whole range +(AUD-4). The cached-telemetry drain resolves a batch's tracking snapshots with one batched +read of its distinct operation ids (AUD-7). + **Site SQLite retention rule (hard invariant):** > A row is eligible for purge only when both `OccurredAtUtc < retention threshold` AND `ForwardState IN ('Forwarded', 'Reconciled')`. Pending rows — and the owed push-exit states `PushAbandoned` / `Rejected` — are never purged. @@ -774,7 +785,9 @@ MS SQL for direct-write events). Unredacted secrets never persist. aid, not a compliance record) whose value is a retention window in days that MUST be strictly shorter than the global `RetentionDays`. After the daily partition switch-out, the purge actor runs a bounded, batched row DELETE - (`PurgeChannelOlderThanAsync`) for each channel whose override is shorter than + (`PurgeChannelOlderThanAsync`, seeking the partition-aligned + `IX_AuditLog_Channel_Occurred (Category, OccurredAtUtc)` with the channel bound as + `varchar(32)` — AUD-5) for each channel whose override is shorter than the global window — expiring rows of that channel earlier than the global partition switch would. Overrides equal to or longer than the global window are silently skipped (the global switch already covers them). The DELETE runs under diff --git a/docs/requirements/Component-CentralUI.md b/docs/requirements/Component-CentralUI.md index 1a97b4c8..6be3e3ad 100644 --- a/docs/requirements/Component-CentralUI.md +++ b/docs/requirements/Component-CentralUI.md @@ -381,7 +381,7 @@ Long or concurrent page work also runs on its own scope, so it can neither colli ### Isolated Test Run workers -Test Run executes in a disposable `CentralUI.SandboxWorker` process. A process-wide admission gate permits at most four workers. Queueing, compilation, execution and gateway calls consume the requested deadline (1–10 seconds); cancellation kills the process tree and capacity is released only after confirmed exit. Console capture retains at most 32,000 characters with an explicit truncation marker; return JSON is limited to 32,000 bytes. Private IPC frames are limited to 1 MiB and stderr is drained without accumulation. Each worker has a 512 MiB managed-heap ceiling. The worker is a resource/lifetime boundary; the semantic script trust policy still gates compilation. +Test Run executes in a disposable `CentralUI.SandboxWorker` process. A process-wide admission gate permits at most four workers. The requested deadline (1–10 seconds) covers execution and gateway calls only: it starts when the worker reports it is about to run user code (UI-13, 2026-12-03). Queueing for an admission slot, worker start-up and compilation are bounded instead by a separate start-up ceiling (30 seconds plus the requested deadline), whose expiry is reported as its own timeout message; cancellation kills the process tree and capacity is released only after confirmed exit. Console capture retains at most 32,000 characters with an explicit truncation marker; return JSON is limited to 32,000 bytes. Private IPC frames are limited to 1 MiB and stderr is drained without accumulation. Each worker has a 512 MiB managed-heap ceiling. The worker is a resource/lifetime boundary; the semantic script trust policy still gates compilation. External calls, shared-script lookup and bound-instance operations use a parent broker. `Notify` is simulated, not brokered: `Notify.To(list).Send` returns a fake `NotificationId`, queues and sends nothing, and writes a `[sandbox] … not delivered` line to the console pane; `Notify.Status` reports `Unknown`. A real send needs a deployed instance (Deployment → Flow Debugger) (#151). Configured SQL connections are recreated inside the worker using credentials passed only over its private pipe, preserving the existing SQL permissions and API. Termination prevents further calls and closes worker-owned sockets; it cannot undo SQL or remote work already accepted by another server. Timeout results do not retain a terminated worker's partial console buffer. diff --git a/docs/requirements/Component-DeploymentManager.md b/docs/requirements/Component-DeploymentManager.md index 7bf9c3ed..e5f8bb03 100644 --- a/docs/requirements/Component-DeploymentManager.md +++ b/docs/requirements/Component-DeploymentManager.md @@ -181,6 +181,14 @@ site-wide push would silently restart every piece of equipment an operator had deliberately stopped; they are reported in the summary's `SkippedInstances` with the reason "Disabled — bulk deploy preserves disabled state; deploy individually to re-enable", and the single-instance deploy remains the explicit re-enable path. +The skip is re-checked once each instance's operation lock is held (DEP-6, 2026-12-03): +the candidate list is read once when the batch starts, so an instance an operator +disables while the batch is still preparing earlier instances is caught by a fresh, +untracked state read (`IDeploymentManagerRepository.GetInstanceStateAsync`) and reported +as skipped with the same reason, instead of being deployed and re-enabled. A failed +staging write detaches its pending changes so it cannot poison the staging writes of +the instances after it on the shared unit of work (DEP-5), and the supersede of a prior +`PendingDeployment` row is a set-based delete rather than tracked key stubs. **Up-to-date instances are skipped too (unless `force`), at batch cost.** The pre-filter reads the deployed-hash projection (`GetDeployedRevisionHashesAsync`) and diff --git a/docs/requirements/Component-InboundAPI.md b/docs/requirements/Component-InboundAPI.md index 82ebeb46..cda6098f 100644 --- a/docs/requirements/Component-InboundAPI.md +++ b/docs/requirements/Component-InboundAPI.md @@ -175,7 +175,7 @@ The `sbk__` design already supports zero-downtime rotation — a ## Script Compilation & Hot-Reload -API method scripts are pre-compiled in the **background after startup** by `InboundMethodWarmupService` (a hosted service registered after `AkkaHostedService`, so it never delays the cluster join or `/health/*`): it waits for `ApplicationStarted`, then — only once this node is the active central node (`IActiveNodeGate`; a standby pays nothing until a failover promotes it) — loads all method definitions and compiles them into in-memory delegates. Lazy compile + the per-request revision check guarantee correctness regardless. Compiles are **single-flight per method name + script revision**: N concurrent first callers share one compile (and one non-collectible loaded assembly). `InboundScriptExecutor.CompileAndRegister(ApiMethod, out IReadOnlyList errors)` compiles once and returns the diagnostics, so a save needs no separate validate pass; the management Create/Update path uses its sibling `CompileForPublish(method, out errors, out publish)`, which compiles once for the `compileWarning` and hands back a `publish` action queued as the post-commit registration — one compile (one pinned assembly) per save even inside a configuration transaction (review 2026-10-21 05/M1). `ApiMethodCache` prunes expired entries on a miss once large (scopes are exact method names — pinned by test — so growth is bounded). A Management API/UI create, update or delete drops that method's `ApiMethodCache` entry post-commit on the node that made the change; the peer central node converges within `ApiMethodCacheTtl` (default 5 s) — Gitea #85, audit `docs/plans/2026-11-09-central-cache-staleness-audit.md`. +API method scripts are pre-compiled in the **background after startup** by `InboundMethodWarmupService` (a hosted service registered after `AkkaHostedService`, so it never delays the cluster join or `/health/*`): it waits for `ApplicationStarted`, then — only once this node is the active central node (`IActiveNodeGate`; a standby pays nothing until a failover promotes it) — loads all method definitions and compiles them into in-memory delegates. Lazy compile + the per-request revision check guarantee correctness regardless. Compiles are **single-flight per method name + script revision**: N concurrent first callers share one compile (and one non-collectible loaded assembly). `InboundScriptExecutor.CompileAndRegister(ApiMethod, out IReadOnlyList errors)` compiles once and returns the diagnostics, so a save needs no separate validate pass; the management Create/Update path uses its sibling `CompileForPublish(method, out errors, out publish)`, which compiles once for the `compileWarning` and hands back a `publish` action queued as the post-commit registration — one compile (one pinned assembly) per save even inside a configuration transaction (review 2026-10-21 05/M1). `ApiMethodCache` prunes expired entries on a miss once large (scopes are exact method names — pinned by test — so growth is bounded). A Management API/UI create, update or delete drops that method's `ApiMethodCache` entry post-commit on the node that made the change; the peer central node converges within `ApiMethodCacheTtl` (default 5 s) — Gitea #85, audit `docs/plans/2026-11-09-central-cache-staleness-audit.md`. Runtime `$ref` resolution reads the shared-schema library from a process-wide `SharedSchemaLibraryCache` snapshot on the same `ApiMethodCacheTtl`, so a schema-library edit reaches running methods within that bound instead of costing two full library reads per request (INB-2, 2026-12-03). ### Update Workflow diff --git a/docs/requirements/Component-SiteEventLogging.md b/docs/requirements/Component-SiteEventLogging.md index 01c592e0..edcbf412 100644 --- a/docs/requirements/Component-SiteEventLogging.md +++ b/docs/requirements/Component-SiteEventLogging.md @@ -194,6 +194,13 @@ Each event entry contains: - Time range - Instance ID - Severity + + The event-type, severity and instance-ID equality filters are each backed by a composite + index with `timestamp` (`idx_events_type_timestamp`, `idx_events_severity_timestamp` — #123; + `idx_events_instance_timestamp` — SEL-1, 2026-12-03, replacing the single-column + `idx_events_instance`), so a filtered page is read in `(timestamp, id)` order and stops at the + page limit. `SiteEventLogSchema.Apply` drops the superseded single-column indexes in place on + first boot. - **Keyword search**: Free-text search on message and source fields (SQLite LIKE query). Useful for finding events by script name, alarm name, or error message across all instances. The `LIKE` is a leading-wildcard full scan, so a keyword search is **bounded to a time window**: a query with no `From` (or a range wider than `ScadaBridge:SiteEventLog:KeywordSearchMaxWindow`, default 7 days) is clamped server-side to `(To ?? now) - window`, not rejected (review 2026-10-21 02/P1). - Results are **paginated** with a configurable page size (default: 500 events). Each response includes a continuation token for fetching additional pages. This prevents broad queries from overwhelming the communication channel. - The site processes the query locally against SQLite and returns matching results to central. The query runs off the actor thread (`Task.Run` + `PipeTo`) on its own short-lived read connection — WAL readers do not block the single writer, so a slow scan can no longer hold the logger's write lock and overflow the bounded write queue (review 2026-10-21 02/P1). The storage-cap trim tracks its row count locally (re-read from the database after the first batch and every 10th batch) and runs `PRAGMA incremental_vacuum` once per tick rather than per batch (02/P4). diff --git a/docs/requirements/Component-SiteRuntime.md b/docs/requirements/Component-SiteRuntime.md index d2b12e96..4226c4d2 100644 --- a/docs/requirements/Component-SiteRuntime.md +++ b/docs/requirements/Component-SiteRuntime.md @@ -285,7 +285,7 @@ When the Instance Actor is stopped (due to disable, delete, or redeployment), Ak - **WhileTrue**: On the `false → true` edge the script fires once, then re-fires on a periodic timer while the condition stays true; on the `true → false` edge the timer stops. The re-fire cadence is the script's **minimum time between runs**; with none configured the trigger degrades to the single edge fire and logs a warning. - **Minimum time between runs**: If configured, the Script Actor tracks the last execution time and skips trigger invocations that fire before the minimum interval has elapsed. For a WhileTrue trigger it doubles as the re-fire cadence. -> **Per-attribute change routing (P2).** Rather than broadcasting every attribute change to all child Script/Alarm Actors, the Instance Actor routes each change only to the children that monitor that attribute (built from their trigger configs at spawn time); **Expression-trigger children, which read an attribute snapshot, receive all changes**. Each child still keeps its own trigger gate as defense-in-depth — the routing is an optimization, not the authority. +> **Per-attribute change routing (P2).** Rather than broadcasting every attribute change to all child Script/Alarm Actors, the Instance Actor routes each change only to the children that monitor that attribute (built from their trigger configs at spawn time); **Expression-trigger children are routed by the attribute keys their expression reads** (SRT-7, 2026-12-03): a compile-time syntax walk extracts the literal `Attributes["k"]` / `Children["c"].Attributes["k"]` reads, and the child hears only changes of those attributes. Any read the walk cannot pin down (a non-literal key, an alias or member access of the `Attributes`/`Children`/`Parent` globals, a parse error, or an expression that reads no attribute at all) falls back to **receiving all changes**, as before. Each child still keeps its own trigger gate as defense-in-depth — the routing is an optimization, not the authority. ### Concurrent Execution - Each invocation launches a **new run** on the script-execution scheduler. @@ -409,7 +409,7 @@ that owns the Instance Actor, and central reads the linkage from audit rows. - **Snapshot / SnapshotComplete (reconnect reconciliation)**: `Snapshot` updates buffer into a staging set; `SnapshotComplete` performs an **atomic swap** of the mirrored set with the staged set. Any condition that was previously mirrored but is **not present** in the new snapshot emits a return-to-normal `AlarmStateChanged` and drops out. This is how the mirror self-corrects after an outage. - **Live transitions** (`Raise` / `Ack` / `Clear` / `Retrigger` / `StateChange`): upsert the condition by `SourceReference`. Updates carrying a `TransitionTime` **older** than the currently held transition are ignored (out-of-order protection). Accepted transitions persist to SQLite and emit an enriched `AlarmStateChanged` upward to the Instance Actor. - **Retention**: a mirrored condition is dropped once it is both inactive **and** acknowledged (`!Active && Acknowledged`) — the alarm has fully run its course at the source and no longer needs mirroring. The drop emits a final state change and deletes the SQLite row. -- **Per-source cap**: at most `MirroredAlarmCapPerSource` conditions are retained per source. When the cap is exceeded the **oldest** condition is dropped and the eviction is **logged** — there is no silent truncation. If the evicted condition is still **active**, a final return-to-normal `AlarmStateChanged` is emitted before it is dropped (mirroring the retention drop above), so a capped-out active condition is never left stuck-active downstream. +- **Per-source cap**: at most `MirroredAlarmCapPerSource` conditions are retained per source. When the cap is exceeded the **oldest** condition is dropped (selected with a bounded heap, not a sort of the whole mirror — SRT-14) and the eviction is **logged** — there is no silent truncation; the Warning is rate-limited to one a minute during a sustained flood and carries the number of evictions since the previous one. If the evicted condition is still **active**, a final return-to-normal `AlarmStateChanged` is emitted before it is dropped (mirroring the retention drop above), so a capped-out active condition is never left stuck-active downstream. ### Persistence - Mirrored condition state is persisted to the site SQLite `native_alarm_state` table on every accepted transition and removed on drop-out. diff --git a/docs/requirements/Component-StoreAndForward.md b/docs/requirements/Component-StoreAndForward.md index 95d81a97..f69c95ac 100644 --- a/docs/requirements/Component-StoreAndForward.md +++ b/docs/requirements/Component-StoreAndForward.md @@ -129,7 +129,7 @@ The telemetry-emitting `ICachedCallLifecycleObserver` hook is dispatched through ### Retry Sweep Indexing -`GetMessagesForRetryAsync` orders candidates `ORDER BY created_at ASC` within the due `status`. The existing `idx_sf_messages_status_due (status, last_attempt_at_ms)` matches the status filter and due-time predicate but not this ordering, forcing a sort/scan on a large sweep. The sweep page is ranked **per `(category, target)` lane** (`ROW_NUMBER() OVER (PARTITION BY category, target ORDER BY created_at)`, ordered by lane rank then `created_at`, limited to `SweepBatchLimit`), so a dead target with hundreds of due rows contributes one row per round like every other lane instead of owning the whole page and starving healthy targets (review 2026-10-21 02/C2); per-target FIFO is preserved. **Due-ness is decided per lane, not per row (2026-12-02 review SF-1):** the window runs over every *pending* row of the lane in enqueue order (`created_at`, then `rowid` as the same-instant tie-break) and only the prefix of due rows before the first not-yet-due row is eligible, so a younger row is never delivered while an older row of the same lane is still backing off (previously the failed head's `last_attempt_at` moved forward while the rows behind it kept older stamps, and a later sweep delivered B before A). An older *parked* row does not hold a lane. A dead target is therefore probed once per head retry interval. **A storage error after the handler has answered is not a delivery failure (SF-2):** the try covers the handler only; on success the row delete is retried (3 attempts) and, if it still fails, the row stays `Pending` with `RetryCount`/`LastError` untouched (never parked), the lane stops for that sweep, and the next due sweep re-delivers it (at-least-once; downstream idempotency remains the caller's). A failed park write after a permanent failure is handled the same way. A second covering index, `idx_sf_messages_status_created (status, created_at)`, lets the sweep walk matching rows already in `created_at` order and stop at the batch limit without re-sorting or touching non-pending rows (arch-review WP1.4). Both indexes are retained — `idx_sf_messages_status_due` still backs status+due-time lookups that don't order by `created_at`. +`GetMessagesForRetryAsync` orders candidates `ORDER BY created_at ASC` within the due `status`. The existing `idx_sf_messages_status_due (status, last_attempt_at_ms)` matches the status filter and due-time predicate but not this ordering, forcing a sort/scan on a large sweep. The sweep page is ranked **per `(category, target)` lane** (`ROW_NUMBER() OVER (PARTITION BY category, target ORDER BY created_at)`, ordered by lane rank then `created_at`, limited to `SweepBatchLimit`), so a dead target with hundreds of due rows contributes one row per round like every other lane instead of owning the whole page and starving healthy targets (review 2026-10-21 02/C2); per-target FIFO is preserved. **Due-ness is decided per lane, not per row (2026-12-02 review SF-1):** the window runs over every *pending* row of the lane in enqueue order (`created_at`, then `rowid` as the same-instant tie-break) and only the prefix of due rows before the first not-yet-due row is eligible, so a younger row is never delivered while an older row of the same lane is still backing off (previously the failed head's `last_attempt_at` moved forward while the rows behind it kept older stamps, and a later sweep delivered B before A). An older *parked* row does not hold a lane. A dead target is therefore probed once per head retry interval. **A storage error after the handler has answered is not a delivery failure (SF-2):** the try covers the handler only; on success the row delete is retried (3 attempts) and, if it still fails, the row stays `Pending` with `RetryCount`/`LastError` untouched (never parked), the lane stops for that sweep, and the next due sweep re-delivers it (at-least-once; downstream idempotency remains the caller's). A failed park write after a permanent failure is handled the same way. A second covering index, `idx_sf_messages_status_created (status, created_at)`, lets the sweep walk matching rows already in `created_at` order and stop at the batch limit without re-sorting or touching non-pending rows (arch-review WP1.4). Both indexes are retained — `idx_sf_messages_status_due` still backs status+due-time lookups that don't order by `created_at`. **SF-3 (2026-12-03):** the lane ranking runs over a narrow projection (`id` + lane keys) backed by the covering `idx_sf_messages_lane (status, category, target, created_at, last_attempt_at_ms, retry_interval_ms, id)`, so the window needs no sort and never reads a payload; only the chosen page of ids is joined back for full rows (200 000 due 1 KB rows: 1.29 s → 0.15 s per sweep). The index is created in place by `StoreAndForwardSchema.Apply`. ## Parked Message Management diff --git a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/SqliteAuditWriter.cs b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/SqliteAuditWriter.cs index b1728e1e..aaa06dc1 100644 --- a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/SqliteAuditWriter.cs +++ b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/SqliteAuditWriter.cs @@ -102,8 +102,18 @@ public class SqliteAuditWriter : IAuditWriter, ISiteAuditQueue, ISiteAuditPushLi _logger = logger; _nodeIdentity = nodeIdentity; + // AUD-2: a PRIVATE cache per connection. With Cache=Shared both connections shared one + // cache and its table-level locks, so WAL snapshot isolation did not apply between them — + // a long backlog scan on the read connection stalled the batch writer (in 150 ms + // SQLITE_LOCKED retry sleeps, up to the command timeout) and vice versa. Two private WAL + // connections let reads run against a snapshot while the writer commits. The busy + // timeout stays Microsoft.Data.Sqlite's default command timeout (30 s), which only a + // second writer could ever hit — there is one write connection. (The in-memory test + // override still uses Mode=Memory;Cache=Shared, which needs the shared cache to share + // one database at all.) var connectionString = connectionStringOverride - ?? $"Data Source={_options.DatabasePath};Cache=Shared"; + ?? $"Data Source={_options.DatabasePath}"; + ConnectionString = connectionString; _connection = new SqliteConnection(connectionString); _connection.Open(); @@ -227,7 +237,7 @@ public class SqliteAuditWriter : IAuditWriter, ISiteAuditQueue, ISiteAuditPushLi } using var cmd = _connection.CreateCommand(); - cmd.CommandText = """ + cmd.CommandText = $""" -- Canonical, append-only / write-once: the 10 fields of the canonical -- ZB.MOM.WW.Audit.AuditEvent stored directly (DetailsJson carries the -- ScadaBridge domain fields). No forwarding state lives here — that is @@ -268,6 +278,17 @@ public class SqliteAuditWriter : IAuditWriter, ISiteAuditQueue, ISiteAuditPushLi CREATE INDEX IF NOT EXISTS IX_fwd ON audit_forward_state (ForwardState, IsCachedKind, OccurredAtUtc); + -- AUD-3: the reconciliation pull reads the OWED states ordered by + -- (OccurredAtUtc, EventId); IX_fwd cannot serve that across an IN of three + -- states, so every page scanned + sorted the whole owed backlog. This partial + -- index is exactly the pull's range and order, so a page is an ordered range + -- read that stops at the limit. The query names it with INDEXED BY and repeats + -- the same literal state list (a partial index is only usable when the query's + -- WHERE implies the index's). Additive and idempotent. + CREATE INDEX IF NOT EXISTS IX_fwd_owed + ON audit_forward_state (OccurredAtUtc, EventId) + WHERE ForwardState IN ({OwedStatesSql}); + -- Node-local key/value state that must survive a process restart. Holds the -- reconciliation pull's served-rows high-water mark ('max_served_rowid'), so a -- restart no longer resets the bound that lets a covering cursor retire rows the @@ -866,7 +887,8 @@ public class SqliteAuditWriter : IAuditWriter, ISiteAuditQueue, ISiteAuditPushLi ? "fs.OccurredAtUtc >= $since" // Composite keyset, lexicographic on (OccurredAtUtc, EventId) — the same // ordering the query applies, so it is a strict "everything after this row". - : "(fs.OccurredAtUtc > $since OR (fs.OccurredAtUtc = $since AND ae.EventId > $afterId))"; + // The OccurredAtUtc >= $since conjunct is implied but lets the index seek. + : "fs.OccurredAtUtc >= $since AND (fs.OccurredAtUtc > $since OR (fs.OccurredAtUtc = $since AND fs.EventId > $afterId))"; // fs.rowid rides along as an 11th column purely to maintain // _maxServedRowId — the insertion-order high-water mark that bounds @@ -876,14 +898,13 @@ public class SqliteAuditWriter : IAuditWriter, ISiteAuditQueue, ISiteAuditPushLi SELECT ae.EventId, ae.OccurredAtUtc, ae.Actor, ae.Action, ae.Outcome, ae.Category, ae.Target, ae.SourceNode, ae.CorrelationId, ae.DetailsJson, fs.rowid - FROM audit_event ae - JOIN audit_forward_state fs ON fs.EventId = ae.EventId - WHERE fs.ForwardState IN ($pending, $pushAbandoned, $rejected) + FROM audit_forward_state fs INDEXED BY IX_fwd_owed + JOIN audit_event ae ON ae.EventId = fs.EventId + WHERE fs.ForwardState IN ({OwedStatesSql}) AND {cursorPredicate} - ORDER BY fs.OccurredAtUtc ASC, ae.EventId ASC + ORDER BY fs.OccurredAtUtc ASC, fs.EventId ASC LIMIT $limit; """; - AddOwedStateParameters(cmd); // Normalise to UTC ISO-8601 round-trip format to match how OccurredAtUtc // is stored on insert ("o" format) — string comparison is monotonic for // that encoding so we can index-scan against it. @@ -931,6 +952,17 @@ public class SqliteAuditWriter : IAuditWriter, ISiteAuditQueue, ISiteAuditPushLi /// Binds the three "owed to central" states — $pending, $pushAbandoned, /// $rejected — that the reconciliation pull serves and retires. /// + /// + /// AUD-3: the owed states as SQL literals, shared by the IX_fwd_owed partial-index + /// definition and the pull query that uses it — SQLite only uses a partial index when the + /// query's WHERE implies the index's, which a bound parameter never does. + /// + internal static readonly string OwedStatesSql = + $"'{AuditForwardState.Pending}', '{SiteAuditForwardStates.PushAbandoned}', '{SiteAuditForwardStates.Rejected}'"; + + /// The connection string both connections were opened with (AUD-2 regression surface). + internal string ConnectionString { get; } + private static void AddOwedStateParameters(SqliteCommand cmd) { cmd.Parameters.AddWithValue("$pending", AuditForwardState.Pending.ToString()); @@ -1535,6 +1567,7 @@ public class SqliteAuditWriter : IAuditWriter, ISiteAuditQueue, ISiteAuditPushLi CREATE TEMP TABLE purge_ids AS SELECT EventId FROM audit_forward_state WHERE ForwardState IN ($forwarded, $reconciled) + AND IsCachedKind IN (0, 1) -- AUD-4: lets IX_fwd seek (state, kind, age) instead of walking each state's whole range AND OccurredAtUtc < $cutoff LIMIT $limit; """; diff --git a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/Telemetry/SiteAuditTelemetryActor.cs b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/Telemetry/SiteAuditTelemetryActor.cs index 4fb0253e..3790800a 100644 --- a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/Telemetry/SiteAuditTelemetryActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/Telemetry/SiteAuditTelemetryActor.cs @@ -233,6 +233,44 @@ public class SiteAuditTelemetryActor : ReceiveActor } } + /// + /// AUD-7: builds the per-drain tracking lookup. With an + /// the distinct ids are read in one batched call (a fault there surfaces per row, exactly as a + /// per-id fault did, so those rows stay Pending); otherwise each distinct id is read once and + /// memoised for the drain. + /// + private async Task>> PrefetchTrackingAsync( + IReadOnlyList pending, CancellationToken ct) + { + var store = _trackingStore!; + if (store is IOperationTrackingBatchReader batchReader) + { + var ids = pending + .Where(r => r.CorrelationId is not null) + .Select(r => new TrackedOperationId(r.CorrelationId!.Value)) + .Distinct() + .ToList(); + try + { + var found = await batchReader.GetStatusManyAsync(ids, ct).ConfigureAwait(false); + return id => Task.FromResult(found.TryGetValue(id, out var s) ? s : null); + } + catch (Exception ex) + { + return _ => Task.FromException(ex); + } + } + + var memo = new Dictionary(); + return async id => + { + if (memo.TryGetValue(id, out var cached)) return cached; + var snapshot = await store.GetStatusAsync(id, ct).ConfigureAwait(false); + memo[id] = snapshot; + return snapshot; + }; + } + /// /// Combined-telemetry drain. Reads cached-lifecycle audit /// rows, joins each with the matching @@ -287,6 +325,12 @@ public class SiteAuditTelemetryActor : ReceiveActor var graceSeconds = Math.Max(0, _options.CachedTrackingGraceSeconds); var abandonBefore = DateTime.UtcNow - TimeSpan.FromSeconds(graceSeconds); + // AUD-7: the tracking store is a single-writer queue whose every read waits behind + // all queued writes. Resolve the batch's distinct operation ids ONCE — one barrier + // for the drain when the store offers a batched read, and never the same id twice + // (several lifecycle rows of one operation share it) otherwise. + var lookup = await PrefetchTrackingAsync(pending, ct).ConfigureAwait(false); + foreach (var auditRow in pending) { if (auditRow.CorrelationId is null) @@ -302,8 +346,7 @@ public class SiteAuditTelemetryActor : ReceiveActor TrackingStatusSnapshot? snapshot; try { - snapshot = await _trackingStore - .GetStatusAsync(new TrackedOperationId(auditRow.CorrelationId.Value), ct) + snapshot = await lookup(new TrackedOperationId(auditRow.CorrelationId.Value)) .ConfigureAwait(false); } catch (Exception ex) diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Auth/SiteScopeService.cs b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Auth/SiteScopeService.cs index e100664d..7fd136b5 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Auth/SiteScopeService.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Auth/SiteScopeService.cs @@ -64,6 +64,14 @@ public sealed class SiteScopeService public async Task> PermittedSiteIdsAsync() => (await ResolveAsync()).Sites; + /// + /// UI-12: the system-wide flag AND the permitted site ids from ONE authoritative resolve — + /// for callers that need both (calling then + /// revalidates the session twice). + /// + /// Whether the user is unrestricted, and otherwise the permitted Site.Id set. + public Task<(bool IsSystemWide, IReadOnlySet Sites)> ResolveScopeAsync() => ResolveAsync(); + /// /// Returns the subset of the user is permitted to /// see. A system-wide user gets the full list back unchanged. diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Deployment/Deployments.razor b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Deployment/Deployments.razor index 04d3a50d..d5ab2f80 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Deployment/Deployments.razor +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Deployment/Deployments.razor @@ -609,10 +609,12 @@ // instance, rather than by loading every instance to build an // InstanceId → SiteId map. A system-wide user passes null (no filter); // a scoped user's EMPTY grant is a real filter that matches nothing. - var systemWide = await SiteScope.IsSystemWideAsync(); + // UI-12: one authoritative resolve per reload (reloads arrive every 500 ms during a + // bulk deploy), not one for the flag and another for the id set. + var (systemWide, permittedSites) = await SiteScope.ResolveScopeAsync(); IReadOnlyCollection? siteScope = systemWide ? null - : (await SiteScope.PermittedSiteIdsAsync()).ToArray(); + : permittedSites.ToArray(); _appliedSearch = _searchInput.Trim(); var filter = new DeploymentListFilter( diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Deployment/InstanceConfigure.razor b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Deployment/InstanceConfigure.razor index d6f8e974..c3a2c97a 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Deployment/InstanceConfigure.razor +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Deployment/InstanceConfigure.razor @@ -1422,20 +1422,43 @@ return; } - var failures = new List(); - foreach (var (attrName, value) in toSave) + // UI-6: send only the overrides that actually changed. _overrideValues is seeded + // with every existing override, so saving the whole map rewrote (and audited) all + // of them — ~260 transactions and audit rows to change one value. + var changed = OverrideSaveDiff.Changed(toSave, _existingOverrides); + if (changed.Count == 0) { - var result = await MutationServices.GetRequiredService().ExecuteInstanceAsync(Id, null, (instanceService, currentUser) => instanceService.SetAttributeOverrideAsync(Id, attrName, value, currentUser)); - if (result.IsSuccess) - _existingOverrides[attrName] = result.Value!; - else - failures.Add($"{attrName}: {result.Error}"); + _toast.ShowInfo("No override changes to save."); + _saving = false; + return; + } + + // ...and apply them in ONE configuration transaction: a failure on any row rolls + // the whole save back instead of leaving a partial apply reported only as a count. + try + { + var saved = await MutationServices.GetRequiredService().ExecuteInstanceAsync(Id, null, async (instanceService, currentUser) => + { + var rows = new List<(string Name, InstanceAttributeOverride Row)>(changed.Count); + var failed = new List(); + foreach (var (attrName, value) in changed) + { + var result = await instanceService.SetAttributeOverrideAsync(Id, attrName, value, currentUser); + if (result.IsSuccess) rows.Add((attrName, result.Value!)); + else failed.Add($"{attrName}: {result.Error}"); + } + if (failed.Count > 0) throw new OverrideSaveDiff.BatchFailedException(failed); + return rows; + }); + foreach (var (attrName, row) in saved) + _existingOverrides[attrName] = row; + _toast.ShowSuccess($"Saved {saved.Count} override(s)."); + } + catch (OverrideSaveDiff.BatchFailedException batch) + { + _toast.ShowError( + $"No overrides were saved — {batch.Failures.Count} failed: {string.Join("; ", batch.Failures)}"); } - if (failures.Count > 0) - _toast.ShowError($"Failed to save {failures.Count} override(s): {string.Join("; ", failures)}"); - var savedCount = toSave.Count - failures.Count; - if (savedCount > 0) - _toast.ShowSuccess($"Saved {savedCount} override(s)."); } catch (Exception ex) { diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Deployment/OverrideSaveDiff.cs b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Deployment/OverrideSaveDiff.cs new file mode 100644 index 00000000..38182f2d --- /dev/null +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Deployment/OverrideSaveDiff.cs @@ -0,0 +1,35 @@ +using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances; + +namespace ZB.MOM.WW.ScadaBridge.CentralUI.Components.Pages.Deployment; + +/// +/// UI-6: the Instance Configure "Save overrides" diff — which working values differ from the +/// stored override rows — and the failure that rolls a batched save back. +/// +internal static class OverrideSaveDiff +{ + /// + /// The working values that are new or differ (ordinal) from the stored override; an + /// unchanged value is not re-saved (no transaction, no audit row). + /// + /// The page's working override values, by attribute name. + /// The stored override rows, by attribute name. + /// The (attribute, value) pairs to save. + public static IReadOnlyList<(string Name, string? Value)> Changed( + IReadOnlyDictionary working, + IReadOnlyDictionary existing) => + working + .Where(kv => !existing.TryGetValue(kv.Key, out var row) + || !string.Equals(row.OverrideValue, kv.Value, StringComparison.Ordinal)) + .Select(kv => (kv.Key, kv.Value)) + .ToList(); + + /// Thrown inside the save transaction when any row fails, so nothing commits. + /// The per-attribute failure messages. + public sealed class BatchFailedException(IReadOnlyList failures) + : Exception($"{failures.Count} override(s) failed to save.") + { + /// Gets the per-attribute failure messages. + public IReadOnlyList Failures { get; } = failures; + } +} diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Monitoring/ParkedMessages.razor b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Monitoring/ParkedMessages.razor index 8f833efe..74bb6236 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Monitoring/ParkedMessages.razor +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Monitoring/ParkedMessages.razor @@ -644,15 +644,21 @@ _bulkInProgress = true; _bulkAction = "Retry"; int success = 0, failed = 0; + // UI-12: authorise ONCE per bulk action — the role check and the site-scope check each + // force an LDAP-group → role re-map against the database, and the site list is a full + // read; per message that was ~3 round trips × N before any relay was sent. + if (!await AuthorizeBulkMutationAsync()) + { + _bulkInProgress = false; + _bulkAction = null; + return; + } foreach (var id in ids) { try { var req = new ParkedMessageRetryRequest(Guid.NewGuid().ToString("N"), _selectedSiteId, id, DateTimeOffset.UtcNow); - await MutationAuth.RequireRoleAsync(ZB.MOM.WW.ScadaBridge.Security.Roles.Deployer); - var mutationSite = (await SiteRepository.GetAllSitesAsync()).FirstOrDefault(s => s.SiteIdentifier == _selectedSiteId); - if (mutationSite is null || !await SiteScope.IsSiteAllowedAsync(mutationSite.Id)) throw new UnauthorizedAccessException("Site access was revoked."); - var resp = await CommunicationService.RetryParkedMessageAsync(_selectedSiteId, req); + var resp = await CommunicationService.RetryParkedMessageAsync(_selectedSiteId, req); if (resp.Success) success++; else failed++; } catch { failed++; } @@ -680,15 +686,21 @@ _bulkInProgress = true; _bulkAction = "Discard"; int success = 0, failed = 0; + // UI-12: authorise ONCE per bulk action — the role check and the site-scope check each + // force an LDAP-group → role re-map against the database, and the site list is a full + // read; per message that was ~3 round trips × N before any relay was sent. + if (!await AuthorizeBulkMutationAsync()) + { + _bulkInProgress = false; + _bulkAction = null; + return; + } foreach (var id in ids) { try { var req = new ParkedMessageDiscardRequest(Guid.NewGuid().ToString("N"), _selectedSiteId, id, DateTimeOffset.UtcNow); - await MutationAuth.RequireRoleAsync(ZB.MOM.WW.ScadaBridge.Security.Roles.Deployer); - var mutationSite = (await SiteRepository.GetAllSitesAsync()).FirstOrDefault(s => s.SiteIdentifier == _selectedSiteId); - if (mutationSite is null || !await SiteScope.IsSiteAllowedAsync(mutationSite.Id)) throw new UnauthorizedAccessException("Site access was revoked."); - var resp = await CommunicationService.DiscardParkedMessageAsync(_selectedSiteId, req); + var resp = await CommunicationService.DiscardParkedMessageAsync(_selectedSiteId, req); if (resp.Success) success++; else failed++; } catch { failed++; } @@ -700,6 +712,27 @@ await FetchPage(); } + /// + /// UI-12: the bulk actions' one-time authorisation — Deployer role and the selected site + /// still in scope — taken once before the per-message loop instead of per message. + /// + private async Task AuthorizeBulkMutationAsync() + { + try + { + await MutationAuth.RequireRoleAsync(ZB.MOM.WW.ScadaBridge.Security.Roles.Deployer); + var mutationSite = (await SiteRepository.GetAllSitesAsync()).FirstOrDefault(s => s.SiteIdentifier == _selectedSiteId); + if (mutationSite is null || !await SiteScope.IsSiteAllowedAsync(mutationSite.Id)) + throw new UnauthorizedAccessException("Site access was revoked."); + return true; + } + catch (Exception ex) + { + _toast.ShowError($"Not permitted: {ex.Message}"); + return false; + } + } + // ── Single actions ── private async Task RetrySingle(ParkedMessageEntry msg) diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Operations/SecuredWrites.razor b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Operations/SecuredWrites.razor index f33b4a88..2bab873d 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Operations/SecuredWrites.razor +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Operations/SecuredWrites.razor @@ -332,10 +332,15 @@ try { _sites = await SiteRepository.GetAllSitesAsync(); + // UI-12: one connection read for every site, not one per site (the N+1 the Sites + // page removed under CentralUI-012). + var connectionsBySiteId = (await SiteRepository.GetAllDataConnectionsAsync()) + .GroupBy(c => c.SiteId) + .ToDictionary(g => g.Key, g => (IReadOnlyList)g.ToList()); foreach (var site in _sites) { _connectionsBySite[site.SiteIdentifier] = - await SiteRepository.GetDataConnectionsBySiteIdAsync(site.Id); + connectionsBySiteId.TryGetValue(site.Id, out var conns) ? conns : Array.Empty(); } } catch (Exception ex) diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/ScriptAnalysis/SandboxWorkerProtocol.cs b/src/ZB.MOM.WW.ScadaBridge.CentralUI/ScriptAnalysis/SandboxWorkerProtocol.cs index 04f048ab..8ed78b87 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CentralUI/ScriptAnalysis/SandboxWorkerProtocol.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/ScriptAnalysis/SandboxWorkerProtocol.cs @@ -20,6 +20,15 @@ public static class SandboxWorkerProtocol private sealed record Start(SandboxRunRequest Request, bool External, bool Database, bool Bound); private sealed record ConnectionInfo(string Provider, string ConnectionString, bool Open); + /// + /// UI-13: the generous ceiling on everything BEFORE user code runs — admission wait, worker + /// process start-up, runtime JIT and the first Roslyn compile — added on top of the + /// script's own budget. The script deadline (TimeoutSeconds) only starts when the + /// worker reports it is about to run user code, so a cold start or a queue behind other + /// Test Runs no longer eats the budget the operator set for the script. Settable for tests. + /// + internal static TimeSpan StartupCeiling { get; set; } = TimeSpan.FromSeconds(30); + /// Runs one child under a deadline; a slot remains charged until confirmed process exit. /// The sandbox run request to execute in the child process. /// The service provider supplying host services for the run. @@ -41,8 +50,14 @@ public static class SandboxWorkerProtocol ISharedScriptCatalog catalog, CancellationToken caller, Action? started = null) { var seconds = Math.Clamp(request.TimeoutSeconds ?? 5, 1, 10); - using var deadline = CancellationTokenSource.CreateLinkedTokenSource(caller); - deadline.CancelAfter(TimeSpan.FromSeconds(seconds)); + // UI-13: two deadlines. The ceiling covers start-up + compile + the script budget and is + // armed now; the script deadline is armed only when the worker sends its "running" frame. + // Every wait below uses deadline.Token, which the ceiling (and the caller) also cancel. + var ceilingSpan = StartupCeiling + TimeSpan.FromSeconds(seconds); + using var ceiling = CancellationTokenSource.CreateLinkedTokenSource(caller); + ceiling.CancelAfter(ceilingSpan); + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(ceiling.Token); + var userCodeStarted = false; var clock = Stopwatch.StartNew(); var acquired = false; Process? process = null; @@ -84,6 +99,16 @@ public static class SandboxWorkerProtocol var frame = await ReadAsync(process.StandardOutput.BaseStream, deadline.Token); if (frame.Kind == "result") return frame.Data.Deserialize(Json) ?? throw new InvalidDataException("Missing sandbox result."); + if (frame.Kind == "running") + { + // UI-13: user code is about to run — start the script's own budget now. + if (!userCodeStarted) + { + userCodeStarted = true; + deadline.CancelAfter(TimeSpan.FromSeconds(seconds)); + } + continue; + } if (frame.Kind != "call") throw new InvalidDataException("Unexpected sandbox message."); deadline.Token.ThrowIfCancellationRequested(); Frame reply; @@ -98,6 +123,8 @@ public static class SandboxWorkerProtocol await WriteAsync(process.StandardInput.BaseStream, reply, deadline.Token); } } + catch (OperationCanceledException) when (!userCodeStarted && ceiling.IsCancellationRequested && !caller.IsCancellationRequested) + { return new(false, null, null, "", $"The sandbox did not start running the script within its {ceilingSpan.TotalSeconds:0}-second start-up ceiling (Test Runs queued or the node is busy); try again.", SandboxErrorKind.Timeout, clock.ElapsedMilliseconds, null); } catch (OperationCanceledException) { return new(false, null, null, "", $"Script execution exceeded the {seconds}-second sandbox timeout or was canceled.", SandboxErrorKind.Timeout, clock.ElapsedMilliseconds, null); } catch (ScriptSandboxException ex) @@ -189,13 +216,23 @@ public static class SandboxWorkerProtocol using var provider = services.BuildServiceProvider(); using var cache = new MemoryCache(new MemoryCacheOptions()); var runner = new ScriptAnalysisService(rpc, cache, provider); - var result = await runner.RunInWorkerAsync(start.Request, CancellationToken.None); + var result = await runner.RunInWorkerAsync(start.Request, CancellationToken.None, rpc.NotifyRunningAsync); await WriteAsync(output, new Frame("result", null, Encode(result)), CancellationToken.None); } private sealed class Rpc(Stream input, Stream output) : ISharedScriptCatalog, IExternalSystemClient, IDatabaseGateway, ISandboxInstanceGateway { private readonly SemaphoreSlim _gate = new(1); + + /// UI-13: tells the host user code is about to run, so it starts the script deadline. + /// Cancellation token. + /// A task that represents the asynchronous operation. + public async Task NotifyRunningAsync(CancellationToken ct) + { + await _gate.WaitAsync(ct); + try { await WriteAsync(output, new Frame("running", null, Encode(null)), ct); } + finally { _gate.Release(); } + } private async Task Call(string method, object?[] args, CancellationToken ct) { await _gate.WaitAsync(ct); diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/ScriptAnalysis/ScriptAnalysisService.cs b/src/ZB.MOM.WW.ScadaBridge.CentralUI/ScriptAnalysis/ScriptAnalysisService.cs index 90536b56..01022ed4 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CentralUI/ScriptAnalysis/ScriptAnalysisService.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/ScriptAnalysis/ScriptAnalysisService.cs @@ -286,6 +286,18 @@ public class ScriptAnalysisService /// Cancellation token for the run. /// A describing the outcome, return value, console output, and any error. public async Task RunInWorkerAsync(SandboxRunRequest request, CancellationToken ct) + => await RunInWorkerAsync(request, ct, userCodeStarting: null); + + /// Execution core invoked only by the disposable worker executable. + /// The sandbox run request including code, kind, parameters, and optional instance binding. + /// Cancellation token for the run. + /// + /// UI-13: invoked once compile, trust check and admission are done, immediately before the + /// root script runs — the worker reports it so the host starts the script deadline then. + /// + /// A describing the outcome, return value, console output, and any error. + public async Task RunInWorkerAsync(SandboxRunRequest request, CancellationToken ct, + Func? userCodeStarting) { if (string.IsNullOrWhiteSpace(request.Code)) { @@ -513,6 +525,8 @@ public class ScriptAnalysisService // and a queued run reports Timeout rather than hanging. await SandboxRunGate.WaitAsync(linkedCts.Token).ConfigureAwait(false); gateAcquired = true; + if (userCodeStarting is not null) + await userCodeStarting(linkedCts.Token).ConfigureAwait(false); // Run on a thread-pool thread with no SynchronizationContext: a // bound script's Instance.SetAttribute / Attributes[...] block diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/IDeploymentManagerRepository.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/IDeploymentManagerRepository.cs index 6f213da2..dbb6c2ba 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/IDeploymentManagerRepository.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/IDeploymentManagerRepository.cs @@ -413,6 +413,16 @@ public interface IDeploymentManagerRepository /// A cancellation token that can be used to cancel the operation. /// The instance, or null if not found. Task GetInstanceByIdAsync(int instanceId, CancellationToken cancellationToken = default); + + /// + /// DEP-6: reads an instance's CURRENT lifecycle state straight from the database, + /// untracked — bypassing EF identity resolution, which would otherwise answer with the + /// state of an entity this unit of work loaded earlier. + /// + /// The instance id. + /// Cancellation token. + /// The state, or when the instance does not exist. + Task GetInstanceStateAsync(int instanceId, CancellationToken cancellationToken = default); /// /// Refreshes in place from the database so a caller that /// waited for the per-instance operation lock can validate the state the command ahead diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/ITemplateEngineRepository.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/ITemplateEngineRepository.cs index c78677e6..8bb7b77f 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/ITemplateEngineRepository.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/ITemplateEngineRepository.cs @@ -286,6 +286,18 @@ public interface ITemplateEngineRepository /// Cancellation token. /// A task that resolves to the matching instance, or if not found. Task GetInstanceByIdAsync(int id, CancellationToken cancellationToken = default); + + /// + /// DEP-4: loads several instances with the same child collections as + /// , untracked, in one split query per chunk of + /// ids — for read-only paths (fleet staleness) that must not fill the scoped change + /// tracker with every deployed instance's overrides and bindings. + /// + /// The instance ids; missing ids are absent from the result. + /// Cancellation token. + /// The instances found. + Task> GetInstancesByIdsUntrackedAsync( + IReadOnlyCollection ids, CancellationToken cancellationToken = default); /// Retrieves all instances. /// Cancellation token. /// A task that resolves to a read-only list of all instances. @@ -301,6 +313,38 @@ public interface ITemplateEngineRepository /// A task that resolves to a read-only list of instances for the specified site. Task> GetInstancesBySiteIdAsync(int siteId, CancellationToken cancellationToken = default); + /// + /// TPL-4: a site's instances WITHOUT their child collections, untracked — for checks + /// that only need identity, name and area (area/site delete guards), which used to load + /// and track every instance's overrides and bindings. + /// + /// The site ID. + /// Cancellation token. + /// The site's instances, shallow and untracked. + Task> GetInstancesBySiteIdShallowAsync(int siteId, CancellationToken cancellationToken = default); + + /// + /// MGT-5: every instance's (Id, UniqueName) — the name index bundle export resolves + /// --instances against, instead of loading every instance with its child collections. + /// + /// Cancellation token. + /// One (Id, UniqueName) pair per instance. + Task> GetInstanceNamesAsync(CancellationToken cancellationToken = default); + + /// + /// TPL-4: whether a template other than named + /// (case-insensitively) already sits in + /// ( = the root) — the folder-move collision check, which used to load + /// the whole template table. + /// + /// The destination folder, or null for the root. + /// The template name. + /// The template being moved. + /// Cancellation token. + /// when a sibling with that name exists. + Task TemplateNameExistsInFolderAsync( + int? folderId, string name, int excludeTemplateId, CancellationToken cancellationToken = default); + /// Reads one bounded, untracked page of topology instance rows for a site/area. /// The site ID. /// The area ID to filter by, or null for every area. diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/IOperationTrackingBatchReader.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/IOperationTrackingBatchReader.cs new file mode 100644 index 00000000..a3efb977 --- /dev/null +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/IOperationTrackingBatchReader.cs @@ -0,0 +1,28 @@ +using ZB.MOM.WW.ScadaBridge.Commons.Types; + +// Same namespace convention as IOperationTrackingStore (see the note there). +namespace ZB.MOM.WW.ScadaBridge.Commons.Interfaces; + +/// +/// Optional batched read surface of an (AUD-7). +/// +/// +/// Kept as a separate interface rather than a new member so +/// existing implementations and test doubles are untouched: a consumer probes for it and falls +/// back to per-id when it is absent. The +/// read has the same read-your-writes guarantee as GetStatusAsync, but pays the writer +/// queue barrier once for the whole set instead of once per id. +/// +public interface IOperationTrackingBatchReader +{ + /// + /// Returns the latest snapshot of each supplied id that has a tracking row. Ids with no row + /// (purged or never recorded) are absent from the result. + /// + /// The operation ids to read; duplicates are ignored. + /// Cancellation token. + /// The snapshots found, keyed by id. + Task> GetStatusManyAsync( + IReadOnlyCollection ids, + CancellationToken ct = default); +} diff --git a/src/ZB.MOM.WW.ScadaBridge.Communication/Grpc/SitePairChannelProvider.cs b/src/ZB.MOM.WW.ScadaBridge.Communication/Grpc/SitePairChannelProvider.cs index 3fdc6793..f804f208 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Communication/Grpc/SitePairChannelProvider.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Communication/Grpc/SitePairChannelProvider.cs @@ -438,31 +438,7 @@ public sealed class SitePairChannelProvider : IDisposable while (await timer.WaitForNextTickAsync(ct).ConfigureAwait(false)) { SweepGraveyard(); - var now = DateTime.UtcNow; - foreach (var kvp in _sites) - { - var pair = kvp.Value; - bool due; - lock (pair.Gate) - { - due = !pair.CurrentIsA && pair.ChannelA is not null && now >= pair.NextProbeUtc; - } - if (due) - { - try - { - await TryFailbackAsync(kvp.Key, ct).ConfigureAwait(false); - } - catch (OperationCanceledException) - { - throw; - } - catch (Exception ex) - { - _logger.LogDebug(ex, "Failback probe for site {TargetSiteId} faulted", kvp.Key); - } - } - } + await RunDueFailbackProbesAsync(DateTime.UtcNow, ct).ConfigureAwait(false); } } catch (OperationCanceledException) @@ -471,6 +447,54 @@ public sealed class SitePairChannelProvider : IDisposable } } + /// COMM-8: how many failback probes one sweep runs concurrently. + internal const int FailbackProbeParallelism = 8; + + /// + /// COMM-8: probes every site that is due for failback at , + /// concurrently up to . The probes used to run one + /// after another, each up to its 5 s deadline, so 30 black-holed NodeAs made one pass take + /// ~150 s: a site whose NodeA had recovered waited minutes past its backoff, and the + /// graveyard sweep (which runs once per pass) stalled with it. Per-site state is guarded by + /// each pair's own gate, so concurrent probes of different sites do not interact. + /// + /// The time the due check is evaluated at. + /// Cancellation token. + /// A task that completes when every due probe has finished. + internal async Task RunDueFailbackProbesAsync(DateTime nowUtc, CancellationToken ct) + { + var due = new List(); + foreach (var kvp in _sites) + { + var pair = kvp.Value; + lock (pair.Gate) + { + if (!pair.CurrentIsA && pair.ChannelA is not null && nowUtc >= pair.NextProbeUtc) + due.Add(kvp.Key); + } + } + if (due.Count == 0) + return; + + await Parallel.ForEachAsync(due, + new ParallelOptions { MaxDegreeOfParallelism = FailbackProbeParallelism, CancellationToken = ct }, + async (siteId, token) => + { + try + { + await TryFailbackAsync(siteId, token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (token.IsCancellationRequested) + { + throw; + } + catch (Exception ex) + { + _logger.LogDebug(ex, "Failback probe for site {TargetSiteId} faulted", siteId); + } + }).ConfigureAwait(false); + } + /// /// Parks a channel that is no longer reachable through instead of /// disposing it inline. diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Configurations/AuditLogEntityTypeConfiguration.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Configurations/AuditLogEntityTypeConfiguration.cs index 6a0fe5a3..df8cff37 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Configurations/AuditLogEntityTypeConfiguration.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Configurations/AuditLogEntityTypeConfiguration.cs @@ -235,6 +235,14 @@ public class AuditLogEntityTypeConfiguration : IEntityTypeConfiguration new { e.Channel, e.OccurredAtUtc }) + .HasDatabaseName("IX_AuditLog_Channel_Occurred"); + builder.HasIndex(e => new { e.Target, e.OccurredAtUtc }) .IsDescending(false, true) .HasFilter("[Target] IS NOT NULL") diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Migrations/20261203152558_AuditLogChannelOccurredIndex.Designer.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Migrations/20261203152558_AuditLogChannelOccurredIndex.Designer.cs new file mode 100644 index 00000000..525d004f --- /dev/null +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Migrations/20261203152558_AuditLogChannelOccurredIndex.Designer.cs @@ -0,0 +1,2317 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase; + +#nullable disable + +namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Migrations +{ + [DbContext(typeof(ScadaBridgeDbContext))] + [Migration("20261203152558_AuditLogChannelOccurredIndex")] + partial class AuditLogChannelOccurredIndex + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.13") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("Microsoft.AspNetCore.DataProtection.EntityFrameworkCore.DataProtectionKey", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("FriendlyName") + .HasColumnType("nvarchar(max)"); + + b.Property("Xml") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("DataProtectionKeys"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Audit.AuditLogEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("AfterStateJson") + .HasColumnType("nvarchar(max)"); + + b.Property("BundleImportId") + .HasColumnType("uniqueidentifier"); + + b.Property("EntityId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("EntityName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("EntityType") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("Timestamp") + .HasColumnType("datetimeoffset"); + + b.Property("User") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.HasKey("Id"); + + b.HasIndex("Action"); + + b.HasIndex("BundleImportId") + .HasDatabaseName("IX_AuditLogEntries_BundleImportId"); + + b.HasIndex("EntityId"); + + b.HasIndex("EntityName") + .HasDatabaseName("IX_AuditLogEntries_EntityName"); + + b.HasIndex("EntityType"); + + b.HasIndex("Timestamp"); + + b.HasIndex("User"); + + b.HasIndex("EntityType", "Timestamp") + .IsDescending(false, true) + .HasDatabaseName("IX_AuditLogEntries_EntityType_Timestamp"); + + b.HasIndex("Timestamp", "Id") + .IsDescending() + .HasDatabaseName("IX_AuditLogEntries_Timestamp_Id"); + + b.HasIndex("User", "Timestamp") + .IsDescending(false, true) + .HasDatabaseName("IX_AuditLogEntries_User_Timestamp"); + + b.ToTable("AuditLogEntries"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Audit.SiteCall", b => + { + b.Property("TrackedOperationId") + .HasMaxLength(36) + .IsUnicode(false) + .HasColumnType("varchar(36)"); + + b.Property("Channel") + .IsRequired() + .HasMaxLength(32) + .IsUnicode(false) + .HasColumnType("varchar(32)"); + + b.Property("CreatedAtUtc") + .HasColumnType("datetime2"); + + b.Property("HttpStatus") + .HasColumnType("int"); + + b.Property("IngestedAtUtc") + .HasColumnType("datetime2"); + + b.Property("LastError") + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("RetryCount") + .HasColumnType("int"); + + b.Property("SourceNode") + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)"); + + b.Property("SourceSite") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(32) + .IsUnicode(false) + .HasColumnType("varchar(32)"); + + b.Property("Target") + .IsRequired() + .HasMaxLength(256) + .IsUnicode(false) + .HasColumnType("varchar(256)"); + + b.Property("TerminalAtUtc") + .HasColumnType("datetime2"); + + b.Property("UpdatedAtUtc") + .HasColumnType("datetime2"); + + b.HasKey("TrackedOperationId"); + + b.HasIndex("CreatedAtUtc") + .HasDatabaseName("IX_SiteCalls_NonTerminal") + .HasFilter("[TerminalAtUtc] IS NULL"); + + SqlServerIndexBuilderExtensions.IncludeProperties(b.HasIndex("CreatedAtUtc"), new[] { "SourceSite", "SourceNode", "Status" }); + + b.HasIndex("TerminalAtUtc") + .HasDatabaseName("IX_SiteCalls_Terminal") + .HasFilter("[TerminalAtUtc] IS NOT NULL"); + + b.HasIndex("CreatedAtUtc", "TrackedOperationId") + .IsDescending() + .HasDatabaseName("IX_SiteCalls_Created_TrackedOperationId"); + + b.HasIndex("SourceSite", "CreatedAtUtc") + .IsDescending(false, true) + .HasDatabaseName("IX_SiteCalls_Source_Created"); + + b.HasIndex("Status", "UpdatedAtUtc") + .IsDescending(false, true) + .HasDatabaseName("IX_SiteCalls_Status_Updated"); + + b.ToTable("SiteCalls", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Deployment.DeployedConfigSnapshot", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ConfigurationJson") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("DeployedAt") + .HasColumnType("datetimeoffset"); + + b.Property("DeploymentId") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("InstanceId") + .HasColumnType("int"); + + b.Property("RevisionHash") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.HasKey("Id"); + + b.HasIndex("DeploymentId"); + + b.HasIndex("InstanceId") + .IsUnique(); + + b.HasIndex("RowVersion"); + + b.ToTable("DeployedConfigSnapshots"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Deployment.DeploymentRecord", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("CompletedAt") + .HasColumnType("datetimeoffset"); + + b.Property("DeployedAt") + .HasColumnType("datetimeoffset"); + + b.Property("DeployedBy") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("DeploymentId") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("ErrorMessage") + .HasColumnType("nvarchar(max)"); + + b.Property("InstanceId") + .HasColumnType("int"); + + b.Property("RevisionHash") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.HasKey("Id"); + + b.HasIndex("DeployedBy") + .HasDatabaseName("IX_DeploymentRecords_DeployedBy"); + + b.HasIndex("DeploymentId") + .IsUnique(); + + b.HasIndex("InstanceId"); + + b.HasIndex("RevisionHash") + .HasDatabaseName("IX_DeploymentRecords_RevisionHash"); + + b.HasIndex("DeployedAt", "Id") + .IsDescending() + .HasDatabaseName("IX_DeploymentRecords_DeployedAt_Id"); + + b.ToTable("DeploymentRecords"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Deployment.PendingDeployment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ConfigurationJson") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedAtUtc") + .HasColumnType("datetimeoffset"); + + b.Property("DeploymentId") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("ExpiresAtUtc") + .HasColumnType("datetimeoffset"); + + b.Property("InstanceId") + .HasColumnType("int"); + + b.Property("RevisionHash") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("Token") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Id"); + + b.HasIndex("DeploymentId") + .IsUnique(); + + b.HasIndex("ExpiresAtUtc"); + + b.HasIndex("InstanceId"); + + b.ToTable("PendingDeployments", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Deployment.SystemArtifactDeploymentRecord", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ArtifactType") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("DeployedAt") + .HasColumnType("datetimeoffset"); + + b.Property("DeployedBy") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("PerSiteStatus") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Id"); + + b.HasIndex("DeployedAt"); + + b.ToTable("SystemArtifactDeploymentRecords"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.ExternalSystems.DatabaseConnectionDefinition", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ConnectionString") + .IsRequired() + .HasMaxLength(8000) + .HasColumnType("nvarchar(max)"); + + b.Property("MaxRetries") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("RetryDelay") + .HasColumnType("time"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("RowVersion"); + + b.ToTable("DatabaseConnectionDefinitions"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.ExternalSystems.ExternalSystemDefinition", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AuthConfiguration") + .HasMaxLength(8000) + .HasColumnType("nvarchar(max)"); + + b.Property("AuthType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("EndpointUrl") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("nvarchar(2000)"); + + b.Property("MaxRetries") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("RetryDelay") + .HasColumnType("time"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("TimeoutSeconds") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(0); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("RowVersion"); + + b.ToTable("ExternalSystemDefinitions"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.ExternalSystems.ExternalSystemMethod", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ExternalSystemDefinitionId") + .HasColumnType("int"); + + b.Property("HttpMethod") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("nvarchar(10)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("ParameterDefinitions") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("nvarchar(2000)"); + + b.Property("ReturnDefinition") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.HasKey("Id"); + + b.HasIndex("RowVersion"); + + b.HasIndex("ExternalSystemDefinitionId", "Name") + .IsUnique(); + + b.ToTable("ExternalSystemMethods"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.InboundApi.ApiMethod", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("ParameterDefinitions") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("ReturnDefinition") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Script") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("TimeoutSeconds") + .HasColumnType("int"); + + b.Property("TraceAllCalls") + .ValueGeneratedOnAdd() + .HasColumnType("bit") + .HasDefaultValue(false); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("ApiMethods"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Area", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("ParentAreaId") + .HasColumnType("int"); + + b.Property("SiteId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ParentAreaId"); + + b.HasIndex("SiteId", "ParentAreaId", "Name") + .IsUnique() + .HasFilter("[ParentAreaId] IS NOT NULL"); + + b.ToTable("Areas"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Instance", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AreaId") + .HasColumnType("int"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SiteId") + .HasColumnType("int"); + + b.Property("State") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("TemplateId") + .HasColumnType("int"); + + b.Property("UniqueName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.HasKey("Id"); + + b.HasIndex("AreaId"); + + b.HasIndex("RowVersion"); + + b.HasIndex("SiteId"); + + b.HasIndex("TemplateId"); + + b.HasIndex("UniqueName") + .IsUnique(); + + b.ToTable("Instances"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.InstanceAlarmOverride", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AlarmCanonicalName") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("nvarchar(400)"); + + b.Property("InstanceId") + .HasColumnType("int"); + + b.Property("IsMesReportableOverride") + .HasColumnType("bit"); + + b.Property("PriorityLevelOverride") + .HasColumnType("int"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("TriggerConfigurationOverride") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Id"); + + b.HasIndex("RowVersion"); + + b.HasIndex("InstanceId", "AlarmCanonicalName") + .IsUnique(); + + b.ToTable("InstanceAlarmOverrides"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.InstanceAttributeOverride", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AttributeName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("ElementDataType") + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("InstanceId") + .HasColumnType("int"); + + b.Property("OverrideValue") + .HasColumnType("nvarchar(max)"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.HasKey("Id"); + + b.HasIndex("RowVersion"); + + b.HasIndex("InstanceId", "AttributeName") + .IsUnique(); + + b.ToTable("InstanceAttributeOverrides"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.InstanceConnectionBinding", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AttributeName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("DataConnectionId") + .HasColumnType("int"); + + b.Property("DataSourceReferenceOverride") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("InstanceId") + .HasColumnType("int"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.HasKey("Id"); + + b.HasIndex("DataConnectionId"); + + b.HasIndex("RowVersion"); + + b.HasIndex("InstanceId", "AttributeName") + .IsUnique(); + + b.ToTable("InstanceConnectionBindings"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.InstanceNativeAlarmSourceOverride", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ConditionFilterOverride") + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("ConnectionNameOverride") + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("InstanceId") + .HasColumnType("int"); + + b.Property("IsMesReportableOverride") + .HasColumnType("bit"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SourceCanonicalName") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("nvarchar(400)"); + + b.Property("SourceReferenceOverride") + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.HasKey("Id"); + + b.HasIndex("RowVersion"); + + b.HasIndex("InstanceId", "SourceCanonicalName") + .IsUnique(); + + b.ToTable("InstanceNativeAlarmSourceOverrides"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Kpi.KpiRollupHourly", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("HourStartUtc") + .HasColumnType("datetime2"); + + b.Property("MaxValue") + .HasColumnType("float"); + + b.Property("Metric") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)"); + + b.Property("MinValue") + .HasColumnType("float"); + + b.Property("SampleCount") + .HasColumnType("int"); + + b.Property("Scope") + .IsRequired() + .HasMaxLength(16) + .IsUnicode(false) + .HasColumnType("varchar(16)"); + + b.Property("ScopeKey") + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)"); + + b.Property("Source") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)"); + + b.Property("Value") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.HasIndex("HourStartUtc") + .HasDatabaseName("IX_KpiRollupHourly_Hour"); + + b.HasIndex("Source", "Metric", "Scope", "ScopeKey", "HourStartUtc") + .IsUnique() + .HasDatabaseName("IX_KpiRollupHourly_Series"); + + b.ToTable("KpiRollupHourly", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Kpi.KpiSample", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("CapturedAtUtc") + .HasColumnType("datetime2"); + + b.Property("Metric") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)"); + + b.Property("Scope") + .IsRequired() + .HasMaxLength(16) + .IsUnicode(false) + .HasColumnType("varchar(16)"); + + b.Property("ScopeKey") + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)"); + + b.Property("Source") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)"); + + b.Property("Value") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.HasIndex("CapturedAtUtc") + .HasDatabaseName("IX_KpiSample_Captured"); + + b.HasIndex("Source", "Metric", "Scope", "ScopeKey", "CapturedAtUtc") + .HasDatabaseName("IX_KpiSample_Series"); + + b.ToTable("KpiSample", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Notifications.Notification", b => + { + b.Property("NotificationId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Body") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedAt") + .HasColumnType("datetimeoffset"); + + b.Property("DeliveredAt") + .HasColumnType("datetimeoffset"); + + b.Property("LastAttemptAt") + .HasColumnType("datetimeoffset"); + + b.Property("LastError") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("ListName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("NextAttemptAt") + .HasColumnType("datetimeoffset"); + + b.Property("OriginExecutionId") + .HasColumnType("uniqueidentifier"); + + b.Property("OriginParentExecutionId") + .HasColumnType("uniqueidentifier"); + + b.Property("ResolvedTargets") + .HasColumnType("nvarchar(max)"); + + b.Property("RetryCount") + .HasColumnType("int"); + + b.Property("SiteEnqueuedAt") + .HasColumnType("datetimeoffset"); + + b.Property("SourceInstanceId") + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("SourceNode") + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)"); + + b.Property("SourceScript") + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("SourceSiteId") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Subject") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("TypeData") + .HasColumnType("nvarchar(max)"); + + b.HasKey("NotificationId"); + + b.HasIndex("DeliveredAt") + .HasDatabaseName("IX_Notifications_Delivered") + .HasFilter("[Status] = 'Delivered'"); + + b.HasIndex("CreatedAt", "NotificationId") + .IsDescending() + .HasDatabaseName("IX_Notifications_Created_NotificationId"); + + b.HasIndex("SourceSiteId", "CreatedAt"); + + b.HasIndex("Status", "NextAttemptAt"); + + b.ToTable("Notifications"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Notifications.NotificationList", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("NotificationLists"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Notifications.NotificationRecipient", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("EmailAddress") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("NotificationListId") + .HasColumnType("int"); + + b.Property("PhoneNumber") + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Id"); + + b.HasIndex("NotificationListId"); + + b.ToTable("NotificationRecipients"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Notifications.SmsConfiguration", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AccountSid") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("ApiBaseUrl") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("AuthToken") + .HasMaxLength(8000) + .HasColumnType("nvarchar(max)"); + + b.Property("ConnectionTimeoutSeconds") + .HasColumnType("int"); + + b.Property("FromNumber") + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("MaxRetries") + .HasColumnType("int"); + + b.Property("MessagingServiceSid") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("RetryDelay") + .HasColumnType("time"); + + b.HasKey("Id"); + + b.ToTable("SmsConfigurations"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Notifications.SmtpConfiguration", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AuthType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("ConnectionTimeoutSeconds") + .HasColumnType("int"); + + b.Property("Credentials") + .HasMaxLength(8000) + .HasColumnType("nvarchar(max)"); + + b.Property("FromAddress") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("Host") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("MaxConcurrentConnections") + .HasColumnType("int"); + + b.Property("MaxRetries") + .HasColumnType("int"); + + b.Property("OAuth2Authority") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("OAuth2Scope") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("Port") + .HasColumnType("int"); + + b.Property("RetryDelay") + .HasColumnType("time"); + + b.Property("TlsMode") + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("Transport") + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.HasKey("Id"); + + b.ToTable("SmtpConfigurations"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Schemas.SharedSchema", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("SchemaJson") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Scope") + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SharedSchemas"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Scripts.SharedScript", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Code") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("ParameterDefinitions") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("ReturnDefinition") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("RowVersion"); + + b.ToTable("SharedScripts"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.SecuredWrites.PendingSecuredWrite", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ConnectionName") + .IsRequired() + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("varchar(128)"); + + b.Property("DecidedAtUtc") + .HasColumnType("datetime2"); + + b.Property("ExecutedAtUtc") + .HasColumnType("datetime2"); + + b.Property("ExecutionError") + .HasMaxLength(2048) + .IsUnicode(false) + .HasColumnType("varchar(2048)"); + + b.Property("OperatorComment") + .HasMaxLength(1024) + .IsUnicode(false) + .HasColumnType("varchar(1024)"); + + b.Property("OperatorUser") + .IsRequired() + .HasMaxLength(256) + .IsUnicode(false) + .HasColumnType("varchar(256)"); + + b.Property("SiteId") + .IsRequired() + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("varchar(128)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(32) + .IsUnicode(false) + .HasColumnType("varchar(32)"); + + b.Property("SubmittedAtUtc") + .HasColumnType("datetime2"); + + b.Property("TagPath") + .IsRequired() + .HasMaxLength(512) + .IsUnicode(false) + .HasColumnType("varchar(512)"); + + b.Property("ValueJson") + .IsRequired() + .HasMaxLength(4000) + .IsUnicode(false) + .HasColumnType("varchar(4000)"); + + b.Property("ValueType") + .IsRequired() + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("varchar(128)"); + + b.Property("VerifierComment") + .HasMaxLength(1024) + .IsUnicode(false) + .HasColumnType("varchar(1024)"); + + b.Property("VerifierUser") + .HasMaxLength(256) + .IsUnicode(false) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("SiteId") + .HasDatabaseName("IX_PendingSecuredWrites_Site"); + + b.HasIndex("Status", "SubmittedAtUtc") + .HasDatabaseName("IX_PendingSecuredWrites_Status_Submitted"); + + b.ToTable("PendingSecuredWrites", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Security.LdapGroupMapping", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("LdapGroupName") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.HasKey("Id"); + + b.HasIndex("LdapGroupName") + .IsUnique(); + + b.ToTable("LdapGroupMappings"); + + b.HasData( + new + { + Id = 1, + LdapGroupName = "SCADA-Admins", + Role = "Administrator" + }, + new + { + Id = 2, + LdapGroupName = "SCADA-Designers", + Role = "Designer" + }, + new + { + Id = 3, + LdapGroupName = "SCADA-Deploy-All", + Role = "Deployer" + }, + new + { + Id = 4, + LdapGroupName = "SCADA-Deploy-SiteA", + Role = "Deployer" + }, + new + { + Id = 5, + LdapGroupName = "SCADA-Viewers", + Role = "Viewer" + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Security.SiteScopeRule", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("LdapGroupMappingId") + .HasColumnType("int"); + + b.Property("SiteId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("SiteId"); + + b.HasIndex("LdapGroupMappingId", "SiteId") + .IsUnique(); + + b.ToTable("SiteScopeRules"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites.DataConnection", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("BackupConfiguration") + .HasColumnType("nvarchar(max)"); + + b.Property("FailoverRetryCount") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(3); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("PrimaryConfiguration") + .HasColumnType("nvarchar(max)"); + + b.Property("Protocol") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SiteId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("RowVersion"); + + b.HasIndex("SiteId", "Name") + .IsUnique(); + + b.ToTable("DataConnections"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites.Site", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ArtifactRevisionHash") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("ArtifactsDeployedAt") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("nvarchar(2000)"); + + b.Property("GrpcNodeAAddress") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("GrpcNodeBAddress") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("NodeAAddress") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("NodeBAddress") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SiteIdentifier") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("RowVersion"); + + b.HasIndex("SiteIdentifier") + .IsUnique(); + + b.ToTable("Sites"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.Template", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("nvarchar(2000)"); + + b.Property("FolderId") + .HasColumnType("int"); + + b.Property("IsDerived") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("OwnerCompositionId") + .HasColumnType("int"); + + b.Property("ParentTemplateId") + .HasColumnType("int"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.HasKey("Id"); + + b.HasIndex("FolderId"); + + b.HasIndex("Name") + .IsUnique() + .HasFilter("[IsDerived] = 0"); + + b.HasIndex("ParentTemplateId"); + + b.HasIndex("RowVersion"); + + b.ToTable("Templates"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateAlarm", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("nvarchar(2000)"); + + b.Property("IsInherited") + .HasColumnType("bit"); + + b.Property("IsLocked") + .HasColumnType("bit"); + + b.Property("IsMesReportable") + .HasColumnType("bit"); + + b.Property("LockedInDerived") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("OnTriggerScriptId") + .HasColumnType("int"); + + b.Property("PriorityLevel") + .HasColumnType("int"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("TemplateId") + .HasColumnType("int"); + + b.Property("TriggerConfiguration") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("TriggerType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.HasKey("Id"); + + b.HasIndex("RowVersion"); + + b.HasIndex("TemplateId", "Name") + .IsUnique(); + + b.ToTable("TemplateAlarms"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateAttribute", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("DataSourceReference") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("DataType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("nvarchar(2000)"); + + b.Property("ElementDataType") + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("IsInherited") + .HasColumnType("bit"); + + b.Property("IsLocked") + .HasColumnType("bit"); + + b.Property("LockedInDerived") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("TemplateId") + .HasColumnType("int"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.HasIndex("RowVersion"); + + b.HasIndex("TemplateId", "Name") + .IsUnique(); + + b.ToTable("TemplateAttributes"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateComposition", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComposedTemplateId") + .HasColumnType("int"); + + b.Property("InstanceName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("TemplateId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ComposedTemplateId"); + + b.HasIndex("RowVersion"); + + b.HasIndex("TemplateId", "InstanceName") + .IsUnique(); + + b.ToTable("TemplateCompositions"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateFolder", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("ParentFolderId") + .HasColumnType("int"); + + b.Property("SortOrder") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ParentFolderId", "Name") + .IsUnique() + .HasFilter("[ParentFolderId] IS NOT NULL"); + + b.ToTable("TemplateFolders"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateNativeAlarmSource", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ConditionFilter") + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("ConnectionName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("nvarchar(2000)"); + + b.Property("IsInherited") + .HasColumnType("bit"); + + b.Property("IsLocked") + .HasColumnType("bit"); + + b.Property("IsMesReportable") + .HasColumnType("bit"); + + b.Property("LockedInDerived") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SourceReference") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("TemplateId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("RowVersion"); + + b.HasIndex("TemplateId", "Name") + .IsUnique(); + + b.ToTable("TemplateNativeAlarmSources"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateScript", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Code") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ExecutionTimeoutSeconds") + .HasColumnType("int"); + + b.Property("IsInherited") + .HasColumnType("bit"); + + b.Property("IsLocked") + .HasColumnType("bit"); + + b.Property("LockedInDerived") + .HasColumnType("bit"); + + b.Property("MinTimeBetweenRuns") + .HasColumnType("time"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("ParameterDefinitions") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("ReturnDefinition") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("TemplateId") + .HasColumnType("int"); + + b.Property("TriggerConfiguration") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("TriggerType") + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.HasKey("Id"); + + b.HasIndex("RowVersion"); + + b.HasIndex("TemplateId", "Name") + .IsUnique(); + + b.ToTable("TemplateScripts"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Transport.BundleUnlockAttempt", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AttemptedAtUtc") + .HasColumnType("datetime2"); + + b.Property("ClientKey") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)"); + + b.HasKey("Id"); + + b.HasIndex("ClientKey", "AttemptedAtUtc") + .HasDatabaseName("IX_BundleUnlockAttempt_Client_Attempted"); + + b.ToTable("BundleUnlockAttempt", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Entities.AuditLogRow", b => + { + b.Property("OccurredAtUtc") + .HasColumnType("datetime2"); + + b.Property("EventId") + .HasColumnType("uniqueidentifier"); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Channel") + .IsRequired() + .HasMaxLength(32) + .IsUnicode(false) + .HasColumnType("varchar(32)") + .HasColumnName("Category"); + + b.Property("CorrelationId") + .HasColumnType("uniqueidentifier"); + + b.Property("DetailsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("ExecutionId") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("uniqueidentifier") + .HasComputedColumnSql("CAST(JSON_VALUE(DetailsJson,'$.executionId') AS uniqueidentifier)", true); + + b.Property("IngestedAtUtc") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime2(7)") + .HasComputedColumnSql("CAST(SWITCHOFFSET(CAST(JSON_VALUE(DetailsJson,'$.ingestedAtUtc') AS datetimeoffset), 0) AS datetime2(7))", false); + + b.Property("Kind") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasMaxLength(32) + .IsUnicode(false) + .HasColumnType("varchar(32)") + .HasComputedColumnSql("JSON_VALUE(DetailsJson,'$.kind')", true); + + b.Property("Outcome") + .IsRequired() + .HasMaxLength(16) + .IsUnicode(false) + .HasColumnType("varchar(16)"); + + b.Property("ParentExecutionId") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("uniqueidentifier") + .HasComputedColumnSql("CAST(JSON_VALUE(DetailsJson,'$.parentExecutionId') AS uniqueidentifier)", true); + + b.Property("SourceNode") + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)"); + + b.Property("SourceSiteId") + .ValueGeneratedOnAddOrUpdate() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)") + .HasComputedColumnSql("JSON_VALUE(DetailsJson,'$.sourceSiteId')", true); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasMaxLength(32) + .IsUnicode(false) + .HasColumnType("varchar(32)") + .HasComputedColumnSql("JSON_VALUE(DetailsJson,'$.status')", true); + + b.Property("Target") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("OccurredAtUtc", "EventId"); + + b.HasIndex("CorrelationId") + .HasDatabaseName("IX_AuditLog_CorrelationId") + .HasFilter("[CorrelationId] IS NOT NULL"); + + b.HasIndex("ExecutionId") + .HasDatabaseName("IX_AuditLog_Execution"); + + b.HasIndex("OccurredAtUtc") + .IsDescending() + .HasDatabaseName("IX_AuditLog_OccurredAtUtc"); + + SqlServerIndexBuilderExtensions.IncludeProperties(b.HasIndex("OccurredAtUtc"), new[] { "Status" }); + + b.HasIndex("ParentExecutionId") + .HasDatabaseName("IX_AuditLog_ParentExecution"); + + b.HasIndex("Actor", "OccurredAtUtc") + .IsDescending(false, true) + .HasDatabaseName("IX_AuditLog_Actor_Occurred"); + + b.HasIndex("Channel", "OccurredAtUtc") + .HasDatabaseName("IX_AuditLog_Channel_Occurred"); + + b.HasIndex("EventId", "OccurredAtUtc") + .IsUnique() + .HasDatabaseName("UX_AuditLog_EventId_Occurred"); + + b.HasIndex("Kind", "OccurredAtUtc") + .IsDescending(false, true) + .HasDatabaseName("IX_AuditLog_Kind_Occurred"); + + b.HasIndex("SourceNode", "OccurredAtUtc") + .HasDatabaseName("IX_AuditLog_Node_Occurred"); + + b.HasIndex("SourceSiteId", "OccurredAtUtc") + .IsDescending(false, true) + .HasDatabaseName("IX_AuditLog_Site_Occurred"); + + b.HasIndex("Target", "OccurredAtUtc") + .IsDescending(false, true) + .HasDatabaseName("IX_AuditLog_Target_Occurred") + .HasFilter("[Target] IS NOT NULL"); + + b.HasIndex("Channel", "Status", "OccurredAtUtc") + .IsDescending(false, false, true) + .HasDatabaseName("IX_AuditLog_Channel_Status_Occurred"); + + b.ToTable("AuditLog", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Deployment.DeployedConfigSnapshot", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Instance", null) + .WithMany() + .HasForeignKey("InstanceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Deployment.DeploymentRecord", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Instance", null) + .WithMany() + .HasForeignKey("InstanceId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Deployment.PendingDeployment", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Instance", null) + .WithMany() + .HasForeignKey("InstanceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.ExternalSystems.ExternalSystemMethod", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.ExternalSystems.ExternalSystemDefinition", null) + .WithMany() + .HasForeignKey("ExternalSystemDefinitionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Area", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Area", null) + .WithMany("Children") + .HasForeignKey("ParentAreaId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites.Site", null) + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Instance", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Area", null) + .WithMany() + .HasForeignKey("AreaId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites.Site", null) + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.Template", null) + .WithMany() + .HasForeignKey("TemplateId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.InstanceAlarmOverride", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Instance", null) + .WithMany("AlarmOverrides") + .HasForeignKey("InstanceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.InstanceAttributeOverride", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Instance", null) + .WithMany("AttributeOverrides") + .HasForeignKey("InstanceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.InstanceConnectionBinding", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites.DataConnection", null) + .WithMany() + .HasForeignKey("DataConnectionId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Instance", null) + .WithMany("ConnectionBindings") + .HasForeignKey("InstanceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.InstanceNativeAlarmSourceOverride", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Instance", null) + .WithMany("NativeAlarmSourceOverrides") + .HasForeignKey("InstanceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Notifications.NotificationRecipient", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Notifications.NotificationList", null) + .WithMany("Recipients") + .HasForeignKey("NotificationListId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Security.SiteScopeRule", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Security.LdapGroupMapping", null) + .WithMany() + .HasForeignKey("LdapGroupMappingId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites.Site", null) + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites.DataConnection", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites.Site", null) + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.Template", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateFolder", null) + .WithMany() + .HasForeignKey("FolderId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.Template", null) + .WithMany() + .HasForeignKey("ParentTemplateId") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateAlarm", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.Template", null) + .WithMany("Alarms") + .HasForeignKey("TemplateId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateAttribute", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.Template", null) + .WithMany("Attributes") + .HasForeignKey("TemplateId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateComposition", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.Template", null) + .WithMany() + .HasForeignKey("ComposedTemplateId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.Template", null) + .WithMany("Compositions") + .HasForeignKey("TemplateId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateFolder", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateFolder", null) + .WithMany() + .HasForeignKey("ParentFolderId") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateNativeAlarmSource", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.Template", null) + .WithMany("NativeAlarmSources") + .HasForeignKey("TemplateId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateScript", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.Template", null) + .WithMany("Scripts") + .HasForeignKey("TemplateId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Area", b => + { + b.Navigation("Children"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Instance", b => + { + b.Navigation("AlarmOverrides"); + + b.Navigation("AttributeOverrides"); + + b.Navigation("ConnectionBindings"); + + b.Navigation("NativeAlarmSourceOverrides"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Notifications.NotificationList", b => + { + b.Navigation("Recipients"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.Template", b => + { + b.Navigation("Alarms"); + + b.Navigation("Attributes"); + + b.Navigation("Compositions"); + + b.Navigation("NativeAlarmSources"); + + b.Navigation("Scripts"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Migrations/20261203152558_AuditLogChannelOccurredIndex.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Migrations/20261203152558_AuditLogChannelOccurredIndex.cs new file mode 100644 index 00000000..3a970b8b --- /dev/null +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Migrations/20261203152558_AuditLogChannelOccurredIndex.cs @@ -0,0 +1,37 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Migrations +{ + /// + /// AUD-5 (WP6 task 6.5): IX_AuditLog_Channel_Occurred (Category, OccurredAtUtc) for the + /// per-channel retention purge (DELETE TOP (@batch) ... WHERE Category = @channel AND + /// OccurredAtUtc < @threshold), whose channel and age predicates were not adjacent in + /// any index. + /// + public partial class AuditLogChannelOccurredIndex : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + // AuditLog is monthly-partitioned (ps_AuditLog_Month) with a partition-switch purge, + // so the index MUST be partition-aligned. EF's CreateIndex cannot express the + // ON ps_AuditLog_Month(OccurredAtUtc) clause -> raw SQL, exactly as + // ReviewRemediationIndexes / AddAuditLogSourceNode. On a large production AuditLog + // consider WITH (ONLINE = ON) (Enterprise edition) in the generated script. + migrationBuilder.Sql(@" +CREATE NONCLUSTERED INDEX IX_AuditLog_Channel_Occurred +ON dbo.AuditLog (Category, OccurredAtUtc) +ON ps_AuditLog_Month(OccurredAtUtc);"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.Sql(@" +IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IX_AuditLog_Channel_Occurred' AND object_id = OBJECT_ID('dbo.AuditLog')) + DROP INDEX IX_AuditLog_Channel_Occurred ON dbo.AuditLog;"); + } + } +} diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Migrations/ScadaBridgeDbContextModelSnapshot.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Migrations/ScadaBridgeDbContextModelSnapshot.cs index 7283f246..10c6b121 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Migrations/ScadaBridgeDbContextModelSnapshot.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Migrations/ScadaBridgeDbContextModelSnapshot.cs @@ -2043,6 +2043,9 @@ namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Migrations .IsDescending(false, true) .HasDatabaseName("IX_AuditLog_Actor_Occurred"); + b.HasIndex("Channel", "OccurredAtUtc") + .HasDatabaseName("IX_AuditLog_Channel_Occurred"); + b.HasIndex("EventId", "OccurredAtUtc") .IsUnique() .HasDatabaseName("UX_AuditLog_EventId_Occurred"); diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/AuditLogRepository.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/AuditLogRepository.cs index c91c6939..65ef182d 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/AuditLogRepository.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/AuditLogRepository.cs @@ -769,10 +769,10 @@ VALUES pBatch.Value = (int)Math.Min(batchSize, maxRows - totalDeleted); cmd.Parameters.Add(pBatch); - var pChannel = cmd.CreateParameter(); - pChannel.ParameterName = "@channel"; - pChannel.Value = channel; - cmd.Parameters.Add(pChannel); + // AUD-5: bind as varchar(32) to match the Category column. An untyped string + // parameter goes out as nvarchar, which under a SQL collation converts the + // column side and rules out a seek on IX_AuditLog_Channel_Occurred. + AddParameter(cmd, "@channel", SqlDbType.VarChar, size: 32, channel); var pThreshold = cmd.CreateParameter(); pThreshold.ParameterName = "@threshold"; diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/DeploymentManagerRepository.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/DeploymentManagerRepository.cs index d486d90c..19448235 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/DeploymentManagerRepository.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/DeploymentManagerRepository.cs @@ -407,21 +407,20 @@ public class DeploymentManagerRepository : IDeploymentManagerRepository // Supersession: a newer deploy for the same instance replaces any prior pending // row. Safe because the per-instance operation lock serializes same-instance - // deploys. SaveChanges is deferred to the caller, matching the other Add methods. + // deploys. The new row's SaveChanges is deferred to the caller, matching the other + // Add methods. // - // Only the prior rows' KEYS are read: each row carries the whole flattened - // ConfigurationJson (tens of KB), and materialising it just to delete it was the - // dominant cost of the supersede. The delete itself stays a tracked Remove (not - // ExecuteDelete) so it still commits atomically with the new row in the caller's - // SaveChanges. - var priorIds = await _dbContext.Set() - .Where(p => p.InstanceId == pending.InstanceId) - .Select(p => p.Id) - .ToListAsync(cancellationToken); - foreach (var id in priorIds) - { - RemovePendingByKey(id); - } + // DEP-5: the prior rows are removed with a set-based ExecuteDelete keyed on the + // instance — never materialised (each carries the whole flattened ConfigurationJson) + // and never tracked. The old tracked key-only stubs made the caller's SaveChanges + // throw DbUpdateConcurrencyException whenever the TTL purge (or reconciliation) + // removed one of those rows first, and the failed stub then stayed tracked and + // poisoned every later staging save on the shared bulk-deploy context. The trade + // is that the supersede commits on its own, just before the insert: a failed + // insert leaves the instance with no pending row, which is what the superseded + // deploy was about to become anyway. + var instanceId = pending.InstanceId; + await DeletePendingWhereAsync(p => p.InstanceId == instanceId, cancellationToken); await _dbContext.Set().AddAsync(pending, cancellationToken); } @@ -505,29 +504,6 @@ public class DeploymentManagerRepository : IDeploymentManagerRepository return rows.Count; } - /// - /// Marks the pending row with primary key for deletion on the next - /// SaveChanges without loading it: an already-tracked instance is removed in place, - /// otherwise a key-only stub is attached and removed (EF deletes by key). - /// - /// Primary key of the pending row. - private void RemovePendingByKey(int id) - { - var set = _dbContext.Set(); - var tracked = set.Local.FirstOrDefault(p => p.Id == id); - if (tracked != null) - { - set.Remove(tracked); - return; - } - - var stub = new PendingDeployment( - string.Empty, 0, string.Empty, string.Empty, string.Empty, - default, default) { Id = id }; - set.Attach(stub); - set.Remove(stub); - } - /// public async Task PurgeTerminalDeploymentRecordsAsync( DateTimeOffset cutoffUtc, @@ -801,6 +777,18 @@ public class DeploymentManagerRepository : IDeploymentManagerRepository return entry.State == EntityState.Detached; } + /// + public async Task GetInstanceStateAsync(int instanceId, CancellationToken cancellationToken = default) + { + // A scalar projection is never tracked and never identity-resolved, so this sees a + // state committed by another request after this context loaded the instance. + return await _dbContext.Set() + .Where(i => i.Id == instanceId) + .Select(i => (InstanceState?)i.State) + .FirstOrDefaultAsync(cancellationToken); + } + + /// public async Task GetInstanceByIdAsync(int instanceId, CancellationToken cancellationToken = default) { return await _dbContext.Set() diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/TemplateEngineRepository.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/TemplateEngineRepository.cs index 5bef7c5a..344bfdf4 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/TemplateEngineRepository.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/TemplateEngineRepository.cs @@ -501,6 +501,29 @@ public class TemplateEngineRepository : ITemplateEngineRepository .FirstOrDefaultAsync(i => i.Id == id, cancellationToken); } + /// + public async Task> GetInstancesByIdsUntrackedAsync( + IReadOnlyCollection ids, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(ids); + var result = new List(ids.Count); + // Chunked so the IN list stays well under SQL Server's 2,100-parameter limit. + foreach (var chunk in ids.Distinct().Chunk(500)) + { + result.AddRange(await _context.Instances + .AsNoTracking() + .Where(i => chunk.Contains(i.Id)) + .Include(i => i.AttributeOverrides) + .Include(i => i.AlarmOverrides) + .Include(i => i.ConnectionBindings) + .Include(i => i.NativeAlarmSourceOverrides) + .AsSplitQuery() + .ToListAsync(cancellationToken)); + } + + return result; + } + /// public async Task> GetAllInstancesAsync(CancellationToken cancellationToken = default) { @@ -521,6 +544,40 @@ public class TemplateEngineRepository : ITemplateEngineRepository .ToListAsync(cancellationToken); } + /// + public async Task> GetInstancesBySiteIdShallowAsync(int siteId, CancellationToken cancellationToken = default) + { + return await _context.Instances + .AsNoTracking() + .Where(i => i.SiteId == siteId) + .ToListAsync(cancellationToken); + } + + /// + public async Task> GetInstanceNamesAsync(CancellationToken cancellationToken = default) + { + var rows = await _context.Instances + .AsNoTracking() + .Select(i => new { i.Id, i.UniqueName }) + .ToListAsync(cancellationToken); + return rows.Select(r => (r.Id, r.UniqueName)).ToList(); + } + + /// + public async Task TemplateNameExistsInFolderAsync( + int? folderId, string name, int excludeTemplateId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(name); + // Only the destination folder's names are read (one narrow projection), then compared + // case-insensitively in memory — independent of the database collation. + var siblingNames = await _context.Templates + .AsNoTracking() + .Where(t => t.FolderId == folderId && t.Id != excludeTemplateId) + .Select(t => t.Name) + .ToListAsync(cancellationToken); + return siblingNames.Any(n => string.Equals(n, name, StringComparison.OrdinalIgnoreCase)); + } + /// public async Task> GetInstancesBySiteIdAsync(int siteId, CancellationToken cancellationToken = default) { diff --git a/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/RealMxGatewayClient.cs b/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/RealMxGatewayClient.cs index c96e74e7..52c210ca 100644 --- a/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/RealMxGatewayClient.cs +++ b/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/RealMxGatewayClient.cs @@ -713,16 +713,36 @@ public sealed class RealMxGatewayClient : IMxGatewayClient /// Maps MXAccess quality. A failing status proxy is authoritative bad; otherwise /// the OPC-style quality byte: ≥192 Good, ≥64 Uncertain, else Bad. /// - private static QualityCode MapQuality(int quality, IEnumerable statuses) + /// + /// DCL-10: on the per-value event path (~37 500 events/s per site at target). Takes the + /// concrete repeated field and index-loops it — IEnumerable.Any boxed the + /// repeated-field enumerator on every event although the list is normally empty or one + /// entry — and maps the quality byte through a static table (no per-call work beyond a + /// bounds check and an array read). + /// + internal static QualityCode MapQuality(int quality, IReadOnlyList statuses) { - if (statuses.Any(s => !s.IsSuccess())) - return QualityCode.Bad; - return quality switch + for (var i = 0; i < statuses.Count; i++) { - >= 192 => QualityCode.Good, - >= 64 => QualityCode.Uncertain, - _ => QualityCode.Bad, - }; + if (!statuses[i].IsSuccess()) + return QualityCode.Bad; + } + if (quality < 0) return QualityCode.Bad; + return quality < QualityByByte.Length ? QualityByByte[quality] : QualityCode.Good; + } + + /// + /// DCL-10: OPC-style quality byte → quality: ≥192 Good, ≥64 Uncertain, else Bad. Values above + /// 255 map to Good and negatives to Bad, exactly as the former range switch did. + /// + private static readonly QualityCode[] QualityByByte = BuildQualityMap(); + + private static QualityCode[] BuildQualityMap() + { + var map = new QualityCode[256]; + for (var q = 0; q < map.Length; q++) + map[q] = q >= 192 ? QualityCode.Good : q >= 64 ? QualityCode.Uncertain : QualityCode.Bad; + return map; } private static MxValue ToMxValue(object? value) => value switch diff --git a/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/DeploymentService.cs b/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/DeploymentService.cs index 2f56c15a..c77e1a5d 100644 --- a/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/DeploymentService.cs +++ b/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/DeploymentService.cs @@ -63,6 +63,9 @@ public class DeploymentService /// Reason reported on every a bulk site /// deploy produces for a instance. /// + /// DEP-4: instances bulk-loaded (untracked) per chunk by the fleet staleness read. + private const int StalenessPreloadChunk = 500; + internal const string DisabledSkipReason = "Disabled — bulk deploy preserves disabled state; deploy individually to re-enable"; @@ -330,6 +333,20 @@ public class DeploymentService { var instanceId = instance.Id; + // DEP-6: a bulk deploy loaded its candidates once, up front, and EF identity + // resolution hands Prepare that same tracked entity — so a Disable committed after + // the batch started was invisible here, and the batch would deploy (and finalise + // as enabled) an instance the operator had just stopped. Disable/enable take this + // operation lock too, so a fresh, untracked read of the state taken while holding + // it is authoritative. Single-instance deploy (no reconcileGate) keeps + // deploy-and-enable as its explicit operator action. + if (reconcileGate is not null + && await _repository.GetInstanceStateAsync(instanceId, cancellationToken) == InstanceState.Disabled) + { + lockHandle.Dispose(); + return PreparedDeployment.Skipped(DisabledSkipReason); + } + // Generate unique deployment ID var deploymentId = Guid.NewGuid().ToString("N"); @@ -503,6 +520,15 @@ public class DeploymentService { command = await StagePendingDeploymentAsync(prepared, user, cancellationToken); } + catch + { + // DEP-5: a failed staging save leaves its Added row tracked on the scoped + // context; in a bulk deploy every later instance's staging save would retry + // it and fail the same way. Drop it while still holding dbGate (the only + // repository writer in phase 2), like MarkDeploymentFailedAsync does (P7-5). + _repository.DetachPendingChanges(); + throw; + } finally { dbGate?.Release(); @@ -833,8 +859,19 @@ public class DeploymentService string ConfigJson, string SiteIdentifier, IDisposable? LockHandle, - Result? EarlyResult) + Result? EarlyResult, + string? SkipReason = null) { + /// + /// DEP-6: a bulk-deploy instance found Disabled once its operation lock was held — + /// reported as a skipped row (never sent, never re-enabled), not as a failure. + /// + /// The skip reason shown in the bulk summary. + /// A prepared deployment holding no lock, with set. + public static PreparedDeployment Skipped(string reason) => + new(null!, string.Empty, null!, string.Empty, string.Empty, string.Empty, null, + Result.Failure(reason), reason); + /// Builds a prepare-phase-resolved deployment carrying the given result and holding no lock. /// The result to hand back to the caller. /// A prepared deployment whose is set. @@ -1077,6 +1114,13 @@ public class DeploymentService continue; } + if (step.SkipReason is { } skipReason) + { + skipped.Add(new SkippedInstanceResult(instance.Id, instance.UniqueName, skipReason)); + disabledCount++; + continue; + } + if (step.EarlyResult is { } early) { results.Add(ToInstanceResult(instance.Id, instance.UniqueName, early)); @@ -2092,13 +2136,25 @@ public class DeploymentService // resolved together after the loop with ONE untracked snapshot read. var mismatched = new Dictionary(); - foreach (var instanceId in instanceIds.Distinct()) + // DEP-4: load the deployed instances in untracked chunks (one split query each) + // instead of a tracked four-Include load per instance — the evaluator's scoped + // context used to end up tracking every deployed instance, override and binding. + var toEvaluate = instanceIds.Distinct().Where(deployedHashes.ContainsKey).ToList(); + foreach (var instanceId in toEvaluate) { cancellationToken.ThrowIfCancellationRequested(); if (!deployedHashes.TryGetValue(instanceId, out var deployedHash)) continue; + if ((evaluated % StalenessPreloadChunk) == 0) + { + var chunk = toEvaluate.Skip(evaluated).Take(StalenessPreloadChunk).ToList(); + session.PreloadInstances( + await _templateRepository.GetInstancesByIdsUntrackedAsync(chunk, cancellationToken) + ?? (IReadOnlyList)Array.Empty()); + } + evaluated++; // Read-only path: hash only — no validation (its result was always discarded diff --git a/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/FlattenSession.cs b/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/FlattenSession.cs index 3a7656ad..4fcc8096 100644 --- a/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/FlattenSession.cs +++ b/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/FlattenSession.cs @@ -1,3 +1,4 @@ +using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances; using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites; using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates; using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services; @@ -48,6 +49,7 @@ public sealed class FlattenSession private readonly Dictionary _chains = new(); private readonly Dictionary Compositions)> _compositions = new(); private readonly Dictionary> _dataConnections = new(); + private readonly Dictionary _preloadedInstances = new(); private IReadOnlyList? _sharedScripts; private IReadOnlyDictionary? _schemaLibrary; @@ -78,6 +80,27 @@ public sealed class FlattenSession /// Number of per-site data-connection queries that missed the memo. public int DataConnectionLoads { get; private set; } + /// + /// DEP-4: hands the session instances already loaded in bulk (untracked) so the flatten + /// does not load each one again. Only read-only callers (fleet staleness) preload; a + /// deploy's session never does, so prepare keeps its tracked load. + /// + /// The preloaded instances. + public void PreloadInstances(IEnumerable instances) + { + foreach (var instance in instances) + _preloadedInstances[instance.Id] = instance; + } + + /// + /// Takes (and forgets) a preloaded instance, so a chunked caller never holds more than + /// one chunk of the fleet in memory. + /// + /// The instance id. + /// The preloaded instance, or when none was preloaded. + public Instance? TakePreloadedInstance(int instanceId) => + _preloadedInstances.Remove(instanceId, out var instance) ? instance : null; + /// /// Every template id this session resolved — the union of all inheritance and /// composed chains it walked. The staleness fast path records the watermark diff --git a/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/FlatteningPipeline.cs b/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/FlatteningPipeline.cs index c609abc9..03049e36 100644 --- a/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/FlatteningPipeline.cs +++ b/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/FlatteningPipeline.cs @@ -190,8 +190,9 @@ public class FlatteningPipeline : IFlatteningPipeline private async Task DataConnections)>> FlattenCoreAsync(int instanceId, FlattenSession session, CancellationToken cancellationToken) { - // Load instance with full graph - var instance = await _templateRepo.GetInstanceByIdAsync(instanceId, cancellationToken); + // Load instance with full graph (DEP-4: a read-only caller may have bulk-preloaded it) + var instance = session.TakePreloadedInstance(instanceId) + ?? await _templateRepo.GetInstanceByIdAsync(instanceId, cancellationToken); if (instance == null) return Result<(FlattenedConfiguration, IReadOnlyDictionary)>.Failure( $"Instance with ID {instanceId} not found."); diff --git a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/EndpointExtensions.cs b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/EndpointExtensions.cs index 171532db..dc5fce98 100644 --- a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/EndpointExtensions.cs +++ b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/EndpointExtensions.cs @@ -260,7 +260,9 @@ public static class EndpointExtensions var sharedSchemaRepo = httpContext.RequestServices.GetService(); var resolveRef = await SchemaRefResolver.BuildAsync( - sharedSchemaRepo, [method.ParameterDefinitions], httpContext.RequestAborted); + sharedSchemaRepo, [method.ParameterDefinitions], + httpContext.RequestServices.GetService(), // INB-2 + httpContext.RequestAborted); var paramResult = ParameterValidator.Validate(body, method.ParameterDefinitions, resolveRef); if (!paramResult.IsValid) diff --git a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/InboundScriptExecutor.cs b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/InboundScriptExecutor.cs index 80c26de8..2ad08eb3 100644 --- a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/InboundScriptExecutor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/InboundScriptExecutor.cs @@ -651,7 +651,9 @@ public class InboundScriptExecutor var sharedSchemaRepo = scope?.ServiceProvider.GetService(); var resolveRef = await SchemaRefResolver.BuildAsync( - sharedSchemaRepo, [method.ReturnDefinition], cts.Token); + sharedSchemaRepo, [method.ReturnDefinition], + scope?.ServiceProvider.GetService(), // INB-2 + cts.Token); // Validate the script's return value against the // method's declared ReturnDefinition. A method whose script returns a diff --git a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/Middleware/AuditWriteMiddleware.cs b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/Middleware/AuditWriteMiddleware.cs index e1017d58..d06f66aa 100644 --- a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/Middleware/AuditWriteMiddleware.cs +++ b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/Middleware/AuditWriteMiddleware.cs @@ -528,6 +528,17 @@ public sealed class AuditWriteMiddleware /// afterwards so the framework's next reader (the endpoint handler's /// JSON parser) sees the full body. /// + /// + /// INB-3: how many body bytes the audit copy expects to read — the declared + /// Content-Length when it is under the cap, else the cap. The scratch buffer is + /// rented at this plus one byte. + /// + /// The request's declared Content-Length, if any. + /// The audit capture cap. + /// The expected capture length in bytes. + internal static int ExpectedCaptureBytes(long? contentLength, int capBytes) => + contentLength is long declared && declared >= 0 && declared < capBytes ? (int)declared : capBytes; + private static async Task<(string? body, bool truncated)> ReadBufferedRequestBodyAsync( HttpRequest request, int capBytes) @@ -543,7 +554,14 @@ public sealed class AuditWriteMiddleware // (and immediately discard) `cap + 1` bytes per request — the pool // may hand back a buffer LARGER than `limit`, so we treat `limit` // (not `buffer.Length`) as the read ceiling. - var limit = capBytes + 1; + // + // INB-3: size the rent to the declared Content-Length when it is under the cap. A + // 200-byte body used to rent cap + 1 (1 MiB + 1 → the 2 MiB pool bucket, LOH) per + // request; a burst beyond the pool's per-core retention allocated fresh LOH arrays. + // Kestrel enforces that the body matches Content-Length, and anything read past the + // declared length is still reported as truncated below. + var expected = ExpectedCaptureBytes(request.ContentLength, capBytes); + var limit = expected + 1; var buffer = ArrayPool.Shared.Rent(limit); try { @@ -567,8 +585,8 @@ public sealed class AuditWriteMiddleware return (null, false); } - var truncated = total > capBytes; - var bytesForString = truncated ? capBytes : total; + var truncated = total > expected; + var bytesForString = truncated ? expected : total; var content = DecodeUtf8Bounded(buffer, bytesForString, cutAtValidBytes: truncated); return (string.IsNullOrEmpty(content) ? null : content, truncated); } diff --git a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/RelayProvenance.cs b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/RelayProvenance.cs index ebdfe318..9dd46b5c 100644 --- a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/RelayProvenance.cs +++ b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/RelayProvenance.cs @@ -83,13 +83,39 @@ internal static class RelayProvenance context.Items[AuditWriteMiddleware.InboundExecutionIdItemKey] = proof.ExecutionId; } + /// INB-4: the full replay-cache scan runs at most once per this many seconds. + private const int ReplayPruneIntervalSeconds = 5; + + /// Unix second before which no further prune scan runs (INB-4). + private static long _nextPruneAt; + + /// Number of prune scans performed — a test hook for INB-4. + internal static int PruneScans; + private static bool TryRecordProof(Proof proof) + => TryRecordProof(proof.ExecutionId, proof.Nonce!, proof.Time); + + /// Records a proof as seen; for a replay or a full cache. + /// The proof's execution id. + /// The proof's nonce. + /// The proof's own unix-second timestamp. + /// Whether the proof was new and recorded. + internal static bool TryRecordProof(Guid executionId, string nonce, long proofTime) { var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + // INB-4: prune on a time basis. Each entry lives ~301 s past its proof time, so above + // ~14 relayed req/s the count stays over the threshold with nothing expired, and the + // old every-call scan walked up to the whole dictionary per relayed request. One + // thread per interval wins the CAS and scans; everyone else skips straight to the add. if (SeenProofs.Count >= ReplayPruneThreshold) { - foreach (var kv in SeenProofs) - if (kv.Value <= now) SeenProofs.TryRemove(kv); + var due = Interlocked.Read(ref _nextPruneAt); + if (now >= due && Interlocked.CompareExchange(ref _nextPruneAt, now + ReplayPruneIntervalSeconds, due) == due) + { + Interlocked.Increment(ref PruneScans); + foreach (var kv in SeenProofs) + if (kv.Value <= now) SeenProofs.TryRemove(kv); + } } // Still full after pruning live entries: fail closed rather than grow without bound. @@ -97,7 +123,7 @@ internal static class RelayProvenance // The proof is valid for +/- the window around its own timestamp, so keep the record // until the far edge of that window. - return SeenProofs.TryAdd(proof.ExecutionId.ToString("N") + ":" + proof.Nonce, proof.Time + ProofWindowSeconds + 1); + return SeenProofs.TryAdd(executionId.ToString("N") + ":" + nonce, proofTime + ProofWindowSeconds + 1); } /// Reads a stream fully, failing if it exceeds the given byte limit. diff --git a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/SchemaRefResolver.cs b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/SchemaRefResolver.cs index 07b9e596..a1460548 100644 --- a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/SchemaRefResolver.cs +++ b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/SchemaRefResolver.cs @@ -44,9 +44,26 @@ public static class SchemaRefResolver /// A synchronous name → schema JSON? resolver, or null when no definition /// uses a $ref (so the validators take their unchanged no-resolver path). /// + public static Task?> BuildAsync( + ISharedSchemaRepository? repository, + IEnumerable definitions, + CancellationToken ct = default) + => BuildAsync(repository, definitions, cache: null, ct); + + /// + /// As , + /// serving the library from when one is supplied (INB-2) instead of + /// reading it from the database on every call. + /// + /// The shared-schema repository, or null when none is registered. + /// The schema definition JSON strings to be validated (parameter and/or return). + /// The process-wide library snapshot cache, or null to read the repository directly. + /// Cancellation token for the library load. + /// A synchronous resolver, or null when no definition uses a $ref. public static async Task?> BuildAsync( ISharedSchemaRepository? repository, IEnumerable definitions, + SharedSchemaLibraryCache? cache, CancellationToken ct = default) { // Skip the library round-trip entirely unless some definition uses a $ref. @@ -55,8 +72,9 @@ public static class SchemaRefResolver return null; } - var library = await repository.ListAsync(ct); - var map = library.ToDictionary(s => s.Name, s => s.SchemaJson, StringComparer.Ordinal); + IReadOnlyDictionary map = cache is not null + ? await cache.GetAsync(repository, ct) + : (await repository.ListAsync(ct)).ToDictionary(s => s.Name, s => s.SchemaJson, StringComparer.Ordinal); return name => map.GetValueOrDefault(name); } } diff --git a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/ServiceCollectionExtensions.cs b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/ServiceCollectionExtensions.cs index acf0fd42..92dd675a 100644 --- a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/ServiceCollectionExtensions.cs +++ b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/ServiceCollectionExtensions.cs @@ -29,6 +29,11 @@ public static class ServiceCollectionExtensions services.AddSingleton(sp => new ApiMethodCache( sp.GetRequiredService>().Value.ApiMethodCacheTtl)); + // INB-2: the shared-schema library snapshot runtime $ref resolution reads, on the same + // TTL as the ApiMethod row it is resolved for. + services.AddSingleton(sp => new SharedSchemaLibraryCache( + sp.GetRequiredService>().Value.ApiMethodCacheTtl)); + // Routed calls go through the IInstanceRouter seam; the // production implementation delegates to CommunicationService. services.AddScoped(); diff --git a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/SharedSchemaLibraryCache.cs b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/SharedSchemaLibraryCache.cs new file mode 100644 index 00000000..02f81e6e --- /dev/null +++ b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/SharedSchemaLibraryCache.cs @@ -0,0 +1,57 @@ +using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories; + +namespace ZB.MOM.WW.ScadaBridge.InboundAPI; + +/// +/// INB-2: a short-TTL, process-wide snapshot of the shared-schema library (name → schema +/// JSON) for runtime $ref resolution. +/// +/// +/// A method whose parameter or return definition used a $ref read the whole library +/// from the database twice per request (once for parameter validation, once for return +/// validation, on different scopes). The library changes only on a designer edit, so one +/// snapshot is shared for — the same bound +/// the resolved ApiMethod row is already cached for, so a schema edit becomes visible +/// to callers on the same cadence as a method edit. Concurrent misses may both load; the +/// last write wins, which is harmless for a read-only snapshot. +/// +public sealed class SharedSchemaLibraryCache +{ + private sealed record Snapshot(IReadOnlyDictionary Library, DateTimeOffset ExpiresAtUtc); + + private readonly TimeSpan _ttl; + private readonly TimeProvider _timeProvider; + private Snapshot? _snapshot; + + /// Initializes the cache. + /// How long a loaded library snapshot is served. + /// Clock; defaults to the system clock. + public SharedSchemaLibraryCache(TimeSpan ttl, TimeProvider? timeProvider = null) + { + if (ttl <= TimeSpan.Zero) + throw new ArgumentOutOfRangeException(nameof(ttl), ttl, "SharedSchemaLibraryCache TTL must be positive."); + _ttl = ttl; + _timeProvider = timeProvider ?? TimeProvider.System; + } + + /// Returns the cached library snapshot, loading it through when stale. + /// The shared-schema repository used on a miss. + /// Cancellation token. + /// The library as name → schema JSON. + public async Task> GetAsync(ISharedSchemaRepository repository, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(repository); + var now = _timeProvider.GetUtcNow(); + var current = Volatile.Read(ref _snapshot); + if (current is not null && current.ExpiresAtUtc > now) + return current.Library; + + var library = (await repository.ListAsync(ct).ConfigureAwait(false)) + .ToDictionary(s => s.Name, s => s.SchemaJson, StringComparer.Ordinal); + Volatile.Write(ref _snapshot, new Snapshot(library, now + _ttl)); + return library; + } + + /// Drops the snapshot so the next lookup reloads the library. + public void Invalidate() => Volatile.Write(ref _snapshot, null); +} diff --git a/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs b/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs index 37c222a5..1d068cb3 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs @@ -4449,7 +4449,10 @@ public class ManagementActor : ReceiveActor var inboundRepo = sp.GetRequiredService(); var siteRepo = sp.GetRequiredService(); - var templates = await templateRepo.GetAllTemplatesAsync(); + // MGT-5: names resolve against narrow (Id, Name) projections — the exporter loads the + // selected rows itself, so the full tracked template graph and every instance with its + // child collections were materialised here only to map names to ids. + var templates = await templateRepo.GetTemplateStubsAsync(); var sharedScripts = await templateRepo.GetAllSharedScriptsAsync(); var externalSystems = await externalRepo.GetAllExternalSystemsAsync(); var dbConnections = await externalRepo.GetAllDatabaseConnectionsAsync(); @@ -4462,7 +4465,7 @@ public class ManagementActor : ReceiveActor // Site/instance-scoped selection. Sites match on SiteIdentifier // (preferred) or Name; instances match on UniqueName. var sites = await siteRepo.GetAllSitesAsync(); - var instances = await templateRepo.GetAllInstancesAsync(); + var instances = await templateRepo.GetInstanceNamesAsync(); int[] ResolveIds(IReadOnlyList all, IReadOnlyList? names, Func getName, Func getId, string entityType) diff --git a/src/ZB.MOM.WW.ScadaBridge.ScriptAnalysis/FlowShapePredictor.cs b/src/ZB.MOM.WW.ScadaBridge.ScriptAnalysis/FlowShapePredictor.cs index 8fb28308..e6f2986d 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ScriptAnalysis/FlowShapePredictor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ScriptAnalysis/FlowShapePredictor.cs @@ -185,7 +185,7 @@ public static class FlowShapePredictor _nodes.Add(new PredictedNode(id, kind, lane, title, inputDependent, mergedNote)); if (_previous != null) { - var fromLane = _nodes.First(n => n.Id == _previous).Lane; + var fromLane = _nodes[IndexOf(_previous)].Lane; _edges.Add(new PredictedEdge(_previous, id, (fromLane == FlowLane.Central) != (lane == FlowLane.Central), async)); } @@ -194,12 +194,28 @@ public static class FlowShapePredictor return id; } + /// + /// CMN-11: O(1) node lookup. Ids are minted append-only as "n" + (index + 1), so the + /// index is read from the id; the linear scan is only a fallback for a foreign id. + /// + /// The node id. + /// The node's index, or -1 when absent. + private int IndexOf(string id) + { + if (id.Length > 1 && id[0] == 'n' + && int.TryParse(id.AsSpan(1), NumberStyles.None, CultureInfo.InvariantCulture, out var ordinal) + && ordinal >= 1 && ordinal <= _nodes.Count + && _nodes[ordinal - 1].Id == id) + return ordinal - 1; + return _nodes.FindIndex(n => n.Id == id); + } + /// Appends a note to an existing node. /// The id of the node to annotate. /// The note to append. internal void Annotate(string id, string note) { - var i = _nodes.FindIndex(n => n.Id == id); + var i = IndexOf(id); if (i < 0) return; var n = _nodes[i]; _nodes[i] = n with { Note = n.Note == null ? note : $"{n.Note}; {note}" }; diff --git a/src/ZB.MOM.WW.ScadaBridge.SiteEventLogging/EventLogPurgeService.cs b/src/ZB.MOM.WW.ScadaBridge.SiteEventLogging/EventLogPurgeService.cs index a9d12d7a..45cc347e 100644 --- a/src/ZB.MOM.WW.ScadaBridge.SiteEventLogging/EventLogPurgeService.cs +++ b/src/ZB.MOM.WW.ScadaBridge.SiteEventLogging/EventLogPurgeService.cs @@ -90,9 +90,10 @@ public class EventLogPurgeService : BackgroundService private const double TablePageFillFactor = 0.78; /// - /// Number of secondary indexes on site_events: timestamp, instance_id, + /// Number of secondary indexes on site_events: timestamp, (instance_id, timestamp), /// (event_type, timestamp) and (severity, timestamp). The sampled indexed_bytes - /// charges every covered column once per index, hence 3 * octet_length(timestamp). + /// charges every covered column once per index, hence 4 * octet_length(timestamp) + /// (SEL-1 added timestamp to the instance index). /// private const int IndexedColumnCount = 4; @@ -734,7 +735,7 @@ public class EventLogPurgeService : BackgroundService + octet_length(severity) + COALESCE(octet_length(instance_id), 0) + octet_length(source) + octet_length(message) + COALESCE(octet_length(details), 0) AS payload_bytes, - (3 * octet_length(timestamp)) + octet_length(event_type) + (4 * octet_length(timestamp)) + octet_length(event_type) + octet_length(severity) + COALESCE(octet_length(instance_id), 0) AS indexed_bytes FROM site_events LIMIT {SizeSampleRows} @@ -746,7 +747,7 @@ public class EventLogPurgeService : BackgroundService + octet_length(severity) + COALESCE(octet_length(instance_id), 0) + octet_length(source) + octet_length(message) + COALESCE(octet_length(details), 0) AS payload_bytes, - (3 * octet_length(timestamp)) + octet_length(event_type) + (4 * octet_length(timestamp)) + octet_length(event_type) + octet_length(severity) + COALESCE(octet_length(instance_id), 0) AS indexed_bytes FROM site_events ORDER BY rowid DESC LIMIT {SizeSampleRows} diff --git a/src/ZB.MOM.WW.ScadaBridge.SiteEventLogging/SiteEventLogSchema.cs b/src/ZB.MOM.WW.ScadaBridge.SiteEventLogging/SiteEventLogSchema.cs index 04581b72..cd48a6b4 100644 --- a/src/ZB.MOM.WW.ScadaBridge.SiteEventLogging/SiteEventLogSchema.cs +++ b/src/ZB.MOM.WW.ScadaBridge.SiteEventLogging/SiteEventLogSchema.cs @@ -67,7 +67,8 @@ public static class SiteEventLogSchema details TEXT ); CREATE INDEX IF NOT EXISTS idx_events_timestamp ON site_events(timestamp); - CREATE INDEX IF NOT EXISTS idx_events_instance ON site_events(instance_id); + DROP INDEX IF EXISTS idx_events_instance; + CREATE INDEX IF NOT EXISTS idx_events_instance_timestamp ON site_events(instance_id, timestamp); DROP INDEX IF EXISTS idx_events_type; DROP INDEX IF EXISTS idx_events_severity; CREATE INDEX IF NOT EXISTS idx_events_type_timestamp ON site_events(event_type, timestamp); @@ -85,6 +86,11 @@ public static class SiteEventLogSchema // part of LocalDb's replicated-table digest, so a pair may upgrade one node at a // time as far as this change is concerned. // + // SEL-1 (2026-12-03): the instance_id index got the same treatment — the Instances + // page drill-in filters by instance and orders by (timestamp, id), which the old + // single-column idx_events_instance could only answer by fetching and sorting every + // row of that instance. Dropped and rebuilt in place on first boot, like #123. + // // The query service also supports keyword search via leading-wildcard // LIKE on message/source. A leading-wildcard LIKE cannot use a B-tree // index, so that path intentionally full-scans; severity/event_type/ diff --git a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/InstanceActor.cs b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/InstanceActor.cs index e5f6e24f..2185ced3 100644 --- a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/InstanceActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/InstanceActor.cs @@ -505,10 +505,13 @@ public class InstanceActor : ReceiveActor var self = Self; var instanceName = _instanceUniqueName; var storage = _storage; + // SRT-5: SQLite's async APIs run synchronously (open included), so the ungated read is + // started on the thread pool rather than inline on this actor's dispatcher thread. var load = _staticStateResetGate == null - ? storage.GetStaticOverridesAsync(instanceName) + ? Task.Run(() => storage.GetStaticOverridesAsync(instanceName)) : _staticStateResetGate - .ContinueWith(_ => storage.GetStaticOverridesAsync(instanceName)) + .ContinueWith(_ => storage.GetStaticOverridesAsync(instanceName), + TaskScheduler.Default) .Unwrap(); load.ContinueWith(t => { @@ -2158,7 +2161,20 @@ public class InstanceActor : ReceiveActor var key = kvp.Key; var logger = _logger; var instanceName = _instanceUniqueName; - _storage.SetStaticOverrideAsync(instanceName, key, native!) + var storage = _storage; + var nativeValue = native!; + // SRT-5: off the dispatcher and on the ordered persist chain, so the + // normalising write can never land after (and undo) a newer flush. + var previous = _staticOverridePersistTail; + var normalize = Task.Run(async () => + { + try { await previous.ConfigureAwait(false); } + catch { /* logged by its own continuation */ } + await storage.SetStaticOverrideAsync(instanceName, key, nativeValue) + .ConfigureAwait(false); + }); + _staticOverridePersistTail = normalize; + normalize .ContinueWith(t => logger.LogWarning(t.Exception?.GetBaseException(), "Failed to normalize static override {Instance}.{Attr} to native JSON", instanceName, key), @@ -2231,6 +2247,19 @@ public class InstanceActor : ReceiveActor } list.Add(child); break; + case TriggerRoutingKind.MonitoredAttributes: + // SRT-7: an Expression trigger whose reads are all literal keys hears only + // changes of those attributes (its snapshot is only ever read at those keys). + foreach (var attribute in decision.MonitoredAttributeSet!) + { + if (!_childrenByMonitoredAttribute.TryGetValue(attribute, out var set)) + { + set = new List(); + _childrenByMonitoredAttribute[attribute] = set; + } + set.Add(child); + } + break; case TriggerRoutingKind.AllChanges: _allChangeChildren.Add(child); break; diff --git a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/NativeAlarmActor.cs b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/NativeAlarmActor.cs index 53fbda64..d1f97baa 100644 --- a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/NativeAlarmActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/NativeAlarmActor.cs @@ -131,8 +131,17 @@ public class NativeAlarmActor : ReceiveActor // Rehydrate last-known state from SQLite (non-blocking), then subscribe. // A fresh source snapshot will reconcile/replace this once it arrives. - (_rehydrationRead ?? _storage.GetNativeAlarmsAsync(_instanceName, _source.CanonicalName)) - .PipeTo(Self, Self, rows => new RehydrationCompleted(rows)); + // SRT-5: Microsoft.Data.Sqlite's *Async methods run synchronously (connection open + // included), so the read is started on the thread pool — never on this actor's + // dispatcher thread — and the result is piped back. Persist flushes chain behind it + // (the tail starts as the read), so a flush can never commit before the read runs. + var storage = _storage; + var instanceName = _instanceName; + var canonicalName = _source.CanonicalName; + var read = _rehydrationRead + ?? Task.Run(() => storage.GetNativeAlarmsAsync(instanceName, canonicalName)); + _persistTail = read; + read.PipeTo(Self, Self, rows => new RehydrationCompleted(rows)); SendSubscribe(); @@ -158,6 +167,13 @@ public class NativeAlarmActor : ReceiveActor private readonly Task>? _rehydrationRead; + /// + /// SRT-5: the ordered persist chain (InstanceActor's static-override pattern). Each flush + /// runs on the thread pool after the previous one, so batches commit in order without the + /// SQLite open/transaction/commit ever running on the actor's dispatcher thread. + /// + private Task _persistTail = Task.CompletedTask; + private string? _subscribeCorrelation; private DateTimeOffset _subscribeDeadline; private int _subscribeDelayMs; @@ -427,10 +443,7 @@ public class NativeAlarmActor : ReceiveActor return; } - var overflow = _alarms.Values - .OrderBy(a => a.TransitionTime) - .Take(_alarms.Count - cap) - .ToList(); + var overflow = SelectOldest(_alarms.Values, _alarms.Count - cap); foreach (var evicted in overflow) { @@ -455,12 +468,68 @@ public class NativeAlarmActor : ReceiveActor // This condition is gone for good — evict the parent's // _latestAlarmEvents key so it does not retain a stale entry. NotifyParentDropped(sourceRef); - _logger.LogWarning( - "Native alarm cap {Cap} exceeded for {Source} on {Instance}; dropped oldest mirrored alarm {Ref}", - cap, _source.CanonicalName, _instanceName, sourceRef); + LogCapEviction(cap, sourceRef); } } + /// + /// SRT-14: the oldest mirrored conditions (by transition time), + /// oldest first, chosen with a bounded max-heap — O(n log k) with k almost always 1 — instead + /// of sorting the whole mirror on every transition at the cap. + /// + /// The mirrored conditions. + /// How many to select. + /// The selected conditions, oldest first. + internal static List SelectOldest( + IEnumerable alarms, int count) + { + var result = new List(Math.Max(0, count)); + if (count <= 0) return result; + + // Max-heap on transition time holding the k oldest seen so far. + var heap = new PriorityQueue( + count + 1, Comparer.Create((a, b) => b.CompareTo(a))); + foreach (var alarm in alarms) + { + if (heap.Count < count) + { + heap.Enqueue(alarm, alarm.TransitionTime); + } + else if (heap.TryPeek(out _, out var newestKept) && alarm.TransitionTime < newestKept) + { + heap.EnqueueDequeue(alarm, alarm.TransitionTime); + } + } + + while (heap.TryDequeue(out var alarm, out _)) + result.Add(alarm); + result.Reverse(); // the max-heap drains newest first + return result; + } + + private DateTimeOffset _lastCapWarningAt = DateTimeOffset.MinValue; + private int _capEvictionsSinceWarning; + + /// + /// SRT-14: the cap eviction Warning is rate-limited (once a minute, carrying the count of + /// evictions since the last one) so a sustained flood at the cap does not log a Warning per + /// transition. Evictions are never silent — the first one after a quiet minute logs at once. + /// + private void LogCapEviction(int cap, string sourceRef) + { + _capEvictionsSinceWarning++; + var now = DateTimeOffset.UtcNow; + if (now - _lastCapWarningAt < CapWarningInterval) return; + + _logger.LogWarning( + "Native alarm cap {Cap} exceeded for {Source} on {Instance}; dropped oldest mirrored alarm {Ref} ({Evicted} eviction(s) since the last warning)", + cap, _source.CanonicalName, _instanceName, sourceRef, _capEvictionsSinceWarning); + _lastCapWarningAt = now; + _capEvictionsSinceWarning = 0; + } + + private static readonly TimeSpan CapWarningInterval = TimeSpan.FromMinutes(1); + /// /// Signals the parent Instance Actor that a native condition has /// left the mirror for good so it can evict the matching _latestAlarmEvents @@ -641,11 +710,27 @@ public class NativeAlarmActor : ReceiveActor var deletes = _dirtyUpserts.Where(kv => kv.Value is null).Select(kv => kv.Key).ToList(); _dirtyUpserts.Clear(); - _storage.ApplyNativeAlarmChangesAsync(_instanceName, _source.CanonicalName, batch, deletes) - .ContinueWith( - task => _logger.LogWarning(task.Exception, + // SRT-5: run the batched transaction on the thread pool, chained behind the previous + // flush (and the rehydration read) so batches stay ordered. SQLite's async APIs block + // synchronously; a write waiting on the shared LocalDb write lock must not park a + // default-dispatcher thread. + var storage = _storage; + var instanceName = _instanceName; + var canonicalName = _source.CanonicalName; + var logger = _logger; + var previous = _persistTail; + var persist = Task.Run(async () => + { + try { await previous.ConfigureAwait(false); } + catch { /* The prior batch/read was logged; a transient failure must not poison future writes. */ } + await storage.ApplyNativeAlarmChangesAsync(instanceName, canonicalName, batch, deletes) + .ConfigureAwait(false); + }); + _persistTail = persist; + persist.ContinueWith( + task => logger.LogWarning(task.Exception, "Failed to persist {Count} native alarm changes on {Instance}", - batch.Count + deletes.Count, _instanceName), + batch.Count + deletes.Count, instanceName), TaskContinuationOptions.OnlyOnFaulted); } diff --git a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Scripts/TriggerExpressionKeys.cs b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Scripts/TriggerExpressionKeys.cs new file mode 100644 index 00000000..9056cbf4 --- /dev/null +++ b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Scripts/TriggerExpressionKeys.cs @@ -0,0 +1,140 @@ +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Scripts; + +/// +/// SRT-7: extracts the canonical attribute keys a trigger expression reads, so an +/// Expression-triggered script/alarm can be routed only the changes it depends on instead +/// of every attribute change on the instance. +/// +/// +/// +/// The walk is deliberately conservative. It recognises exactly the two literal read forms +/// exposes — Attributes["k"] (key k) and +/// Children["c"].Attributes["k"] (key c.k) — and gives up (returns +/// , which routes the child to every change exactly as before) on +/// anything it cannot pin down: a non-literal index, any other use of the +/// Attributes/Children/Parent globals (an alias, a member access, a +/// method-group pass), a parse error, or an expression that reads no attribute at all (it may +/// depend on something other than attribute values, e.g. the clock, and has always been +/// re-evaluated on every change). +/// +/// +/// Routing remains an optimisation: the child's own snapshot/evaluation is unchanged. A child +/// routed by keys simply stops receiving changes for attributes its expression never reads. +/// +/// +internal static class TriggerExpressionKeys +{ + private static readonly CSharpParseOptions ScriptParse = + CSharpParseOptions.Default.WithKind(SourceCodeKind.Script); + + /// + /// Tries to extract the literal attribute keys an expression reads. + /// + /// The trigger expression source. + /// The distinct canonical keys read, when the method returns . + /// when every attribute read is a recognised literal form and at least one exists. + public static bool TryExtract(string? expression, out IReadOnlyList keys) + { + keys = Array.Empty(); + if (string.IsNullOrWhiteSpace(expression)) return false; + + SyntaxTree tree; + try + { + tree = CSharpSyntaxTree.ParseText(expression, ScriptParse); + } + catch + { + return false; + } + + var root = tree.GetRoot(); + if (root.ContainsDiagnostics) return false; + + var found = new List(); + var seen = new HashSet(StringComparer.Ordinal); + + foreach (var id in root.DescendantNodes().OfType()) + { + switch (id.Identifier.ValueText) + { + case "Parent": + return false; + + case "Attributes": + { + // Children["c"].Attributes["k"]: the identifier is the Name of a member access + // whose receiver is a literal Children index. + if (id.Parent is MemberAccessExpressionSyntax member && member.Name == id) + { + if (!TryChildPrefix(member.Expression, out var childPrefix)) return false; + if (!TryLiteralIndex(member, out var key)) return false; + Add(childPrefix + "." + key); + break; + } + + // Attributes["k"] + if (!TryLiteralIndex(id, out var rootKey)) return false; + Add(rootKey); + break; + } + + case "Children": + // Valid only as the receiver of Children["c"].Attributes[...]; that whole + // form is validated from the Attributes identifier above. + if (!IsChildrenReceiver(id)) return false; + break; + } + } + + if (found.Count == 0) return false; + keys = found; + return true; + + void Add(string key) + { + if (seen.Add(key)) found.Add(key); + } + } + + /// True when is directly indexed by one string literal. + private static bool TryLiteralIndex(ExpressionSyntax node, out string key) + { + key = ""; + if (node.Parent is not ElementAccessExpressionSyntax access || access.Expression != node) + return false; + return TrySingleStringLiteral(access.ArgumentList, out key); + } + + /// Matches Children["c"] and returns c. + private static bool TryChildPrefix(ExpressionSyntax receiver, out string prefix) + { + prefix = ""; + return receiver is ElementAccessExpressionSyntax access + && access.Expression is IdentifierNameSyntax { Identifier.ValueText: "Children" } + && TrySingleStringLiteral(access.ArgumentList, out prefix); + } + + private static bool IsChildrenReceiver(IdentifierNameSyntax id) => + id.Parent is ElementAccessExpressionSyntax access + && access.Expression == id + && access.Parent is MemberAccessExpressionSyntax member + && member.Expression == access + && member.Name.Identifier.ValueText == "Attributes" + && TrySingleStringLiteral(access.ArgumentList, out _); + + private static bool TrySingleStringLiteral(BracketedArgumentListSyntax args, out string value) + { + value = ""; + if (args.Arguments.Count != 1) return false; + if (args.Arguments[0].Expression is not LiteralExpressionSyntax literal + || !literal.IsKind(SyntaxKind.StringLiteralExpression)) + return false; + value = literal.Token.ValueText; + return value.Length > 0; + } +} diff --git a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Scripts/TriggerRouting.cs b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Scripts/TriggerRouting.cs index f9bd6044..4b47a6b7 100644 --- a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Scripts/TriggerRouting.cs +++ b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Scripts/TriggerRouting.cs @@ -14,13 +14,18 @@ internal enum TriggerRoutingKind AllChanges, /// Never reacts to attribute changes (interval / call-only scripts). - None + None, + + /// SRT-7: reacts to changes of any of a set of named attributes — an Expression + /// trigger whose attribute reads are all literal keys (see ). + MonitoredAttributes } /// /// Result of classifying a child's trigger for attribute-change routing. /// -internal readonly record struct TriggerRoutingDecision(TriggerRoutingKind Kind, string? MonitoredAttribute) +internal readonly record struct TriggerRoutingDecision( + TriggerRoutingKind Kind, string? MonitoredAttribute, IReadOnlyList? MonitoredAttributeSet = null) { public static readonly TriggerRoutingDecision AllChanges = new(TriggerRoutingKind.AllChanges, null); public static readonly TriggerRoutingDecision None = new(TriggerRoutingKind.None, null); @@ -29,6 +34,23 @@ internal readonly record struct TriggerRoutingDecision(TriggerRoutingKind Kind, /// The name of the attribute to monitor. /// A of kind . public static TriggerRoutingDecision Monitored(string attribute) => new(TriggerRoutingKind.MonitoredAttribute, attribute); + + /// Creates a decision routing on changes to any of several named attributes (SRT-7). + /// The attribute names to monitor. + /// A of kind . + public static TriggerRoutingDecision MonitoredSet(IReadOnlyList attributes) => + new(TriggerRoutingKind.MonitoredAttributes, null, attributes); + + /// + /// SRT-7: routes an Expression trigger by the literal attribute keys it reads, falling back + /// to all-changes whenever the keys cannot be pinned down. + /// + /// The Expression trigger config JSON. + /// The routing decision. + public static TriggerRoutingDecision ForExpression(string? triggerConfigJson) => + TriggerExpressionKeys.TryExtract(TriggerExpressionGlobals.ExtractExpression(triggerConfigJson), out var keys) + ? MonitoredSet(keys) + : AllChanges; } /// @@ -79,7 +101,8 @@ internal static class TriggerRouting /// /// Classifies a script trigger. valuechange/conditional → the named attribute (fail open to - /// all-changes if unparseable); expression → all-changes; interval/call → none; anything + /// all-changes if unparseable); expression → its literal attribute keys (SRT-7; all-changes + /// when they cannot be extracted); interval/call → none; anything /// unknown → all-changes (fail open — a misconfigured script still reacts, its own gate /// remains the correctness check). /// @@ -96,7 +119,7 @@ internal static class TriggerRouting ? TriggerRoutingDecision.Monitored(attr) : TriggerRoutingDecision.AllChanges; case "expression": - return TriggerRoutingDecision.AllChanges; + return TriggerRoutingDecision.ForExpression(triggerConfigJson); case "interval": case "call": return TriggerRoutingDecision.None; @@ -106,7 +129,8 @@ internal static class TriggerRouting } /// - /// Classifies an alarm trigger. Expression → all-changes; HiLo/ValueMatch/RangeViolation/ + /// Classifies an alarm trigger. Expression → its literal attribute keys (SRT-7; all-changes + /// when they cannot be extracted); HiLo/ValueMatch/RangeViolation/ /// RateOfChange → the named attribute (fail open to all-changes if unparseable); an /// unknown/unparseable trigger type → all-changes (fail open). /// @@ -120,7 +144,7 @@ internal static class TriggerRouting switch (tt) { case AlarmTriggerType.Expression: - return TriggerRoutingDecision.AllChanges; + return TriggerRoutingDecision.ForExpression(triggerConfigJson); case AlarmTriggerType.HiLo: case AlarmTriggerType.ValueMatch: case AlarmTriggerType.RangeViolation: diff --git a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Tracking/OperationTrackingStore.cs b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Tracking/OperationTrackingStore.cs index fe44ddf8..aca8da8d 100644 --- a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Tracking/OperationTrackingStore.cs +++ b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Tracking/OperationTrackingStore.cs @@ -51,7 +51,7 @@ namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Tracking; /// path. /// /// -public class OperationTrackingStore : IOperationTrackingStore, IAsyncDisposable, IDisposable +public class OperationTrackingStore : IOperationTrackingStore, IOperationTrackingBatchReader, IAsyncDisposable, IDisposable { /// Queue bound; past it Record*Async waits (never drops). internal const int MaxQueuedWrites = 8192; @@ -595,7 +595,61 @@ public class OperationTrackingStore : IOperationTrackingStore, IAsyncDisposable, return null; } - return new TrackingStatusSnapshot( + return ReadSnapshot(reader); + } + + /// Most ids bound into one IN (…) read (well under SQLite's parameter limit). + private const int MaxIdsPerStatusRead = 500; + + /// + /// + /// AUD-7: one writer-queue barrier for the whole set, then chunked IN (…) reads on one + /// connection — instead of a barrier + connection + query per id. + /// + public async Task> GetStatusManyAsync( + IReadOnlyCollection ids, + CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(ids); + var result = new Dictionary(); + if (ids.Count == 0) + { + return result; + } + + await WaitForQueuedWritesAsync(ct).ConfigureAwait(false); + ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposeState) != 0, this); + + await using var readConnection = _localDb.CreateConnection(); + foreach (var chunk in ids.Select(i => i.ToString()).Distinct(StringComparer.Ordinal).Chunk(MaxIdsPerStatusRead)) + { + await using var cmd = readConnection.CreateCommand(); + var names = new string[chunk.Length]; + for (var i = 0; i < chunk.Length; i++) + { + names[i] = "$id" + i.ToString(CultureInfo.InvariantCulture); + cmd.Parameters.AddWithValue(names[i], chunk[i]); + } + + cmd.CommandText = + "SELECT TrackedOperationId, Kind, TargetSummary, Status, " + + "RetryCount, LastError, HttpStatus, CreatedAtUtc, UpdatedAtUtc, TerminalAtUtc, " + + "SourceInstanceId, SourceScript, SourceNode " + + "FROM OperationTracking WHERE TrackedOperationId IN (" + string.Join(", ", names) + ");"; + + await using var reader = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false); + while (await reader.ReadAsync(ct).ConfigureAwait(false)) + { + var snapshot = ReadSnapshot(reader); + result[snapshot.Id] = snapshot; + } + } + + return result; + } + + private static TrackingStatusSnapshot ReadSnapshot(SqliteDataReader reader) => + new TrackingStatusSnapshot( Id: TrackedOperationId.Parse(reader.GetString(0)), Kind: reader.GetString(1), TargetSummary: reader.IsDBNull(2) ? null : reader.GetString(2), @@ -609,7 +663,6 @@ public class OperationTrackingStore : IOperationTrackingStore, IAsyncDisposable, SourceInstanceId: reader.IsDBNull(10) ? null : reader.GetString(10), SourceScript: reader.IsDBNull(11) ? null : reader.GetString(11), SourceNode: reader.IsDBNull(12) ? null : reader.GetString(12)); - } /// public async Task PurgeTerminalAsync( diff --git a/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardSchema.cs b/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardSchema.cs index 8f9ab17b..0a2b47e9 100644 --- a/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardSchema.cs +++ b/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardSchema.cs @@ -111,6 +111,19 @@ public static class StoreAndForwardSchema "CREATE INDEX IF NOT EXISTS idx_sf_messages_status_created ON sf_messages(status, created_at)"; orderIndex.ExecuteNonQuery(); } + + // SF-3: covering index for the sweep's fair lane ranking. Leading (status, category, + // target, created_at) matches ROW_NUMBER() OVER (PARTITION BY category, target ORDER BY + // created_at) so the window reads rows already in lane order with no sort, and the + // trailing due-predicate columns + id make it covering, so the ranking never reads a + // payload. Applied in place on every boot (idempotent); local only — indexes are not + // part of LocalDb's CDC capture. + using (var laneIndex = connection.CreateCommand()) + { + laneIndex.CommandText = + "CREATE INDEX IF NOT EXISTS idx_sf_messages_lane ON sf_messages(status, category, target, created_at, last_attempt_at_ms, retry_interval_ms, id)"; + laneIndex.ExecuteNonQuery(); + } } /// diff --git a/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardStorage.cs b/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardStorage.cs index bbb000f3..d208298f 100644 --- a/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardStorage.cs +++ b/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardStorage.cs @@ -199,9 +199,6 @@ public class StoreAndForwardStorage await using var connection = OpenConnection(); await using var cmd = connection.CreateCommand(); - const string cols = @"id, category, target, payload_json, retry_count, max_retries, - retry_interval_ms, created_at, last_attempt_at, status, last_error, origin_instance, - execution_id, source_script, parent_execution_id"; const string dueExpr = @"(last_attempt_at_ms IS NULL OR retry_interval_ms = 0 OR (@nowMs - last_attempt_at_ms) >= retry_interval_ms)"; @@ -211,30 +208,35 @@ public class StoreAndForwardStorage // (created_at, rowid as the same-instant tie-break), and `blocked_by` counts the // not-yet-due rows at or before each row. Only the lane prefix with // blocked_by = 0 is eligible, so a younger row can never be handed out while an - // older row of the same lane is still pending but backing off — previously the - // head's failure pushed ITS last_attempt_at forward while the rows behind it - // kept their older stamps, so a later sweep delivered B before A. It also means - // a dead target is probed once per head retry interval rather than by whichever - // staggered row happened to come due on each sweep. + // older row of the same lane is still pending but backing off. // // The page is then taken FAIRLY across lanes by lane rank (review 2026-10-21 // 02/C2): one dead target holding hundreds of rows contributes one row per - // "round" like every other lane instead of owning the whole page. Within a lane - // rank order == enqueue order, preserved by the service's stable GroupBy. + // "round" like every other lane. Within a lane rank order == enqueue order. + // + // SF-3: the ranking runs over a NARROW projection (id + lane keys + due columns) + // that idx_sf_messages_lane covers, so the window never touches a payload; only + // the chosen page of ids is joined back for the full rows. cmd.CommandText = $@" - SELECT {cols} - FROM ( - SELECT {cols}, - ROW_NUMBER() OVER lane AS lane_rank, - SUM(CASE WHEN {dueExpr} THEN 0 ELSE 1 END) OVER lane AS blocked_by - FROM sf_messages - WHERE status = @pending - WINDOW lane AS (PARTITION BY category, target ORDER BY created_at ASC, rowid ASC - ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) + WITH page AS ( + SELECT id, lane_rank, created_at, rid + FROM ( + SELECT id, created_at, rowid AS rid, + ROW_NUMBER() OVER lane AS lane_rank, + SUM(CASE WHEN {dueExpr} THEN 0 ELSE 1 END) OVER lane AS blocked_by + FROM sf_messages + WHERE status = @pending + WINDOW lane AS (PARTITION BY category, target ORDER BY created_at ASC, rowid ASC + ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) + ) + WHERE blocked_by = 0 + ORDER BY lane_rank ASC, created_at ASC, rid ASC" + + (limit > 0 ? "\n LIMIT @limit" : string.Empty) + $@" ) - WHERE blocked_by = 0 - ORDER BY lane_rank ASC, created_at ASC" - + (limit > 0 ? "\n LIMIT @limit" : string.Empty); + SELECT {SweepColumnsM} + FROM page p + JOIN sf_messages m ON m.id = p.id + ORDER BY p.lane_rank ASC, p.created_at ASC, p.rid ASC"; if (limit > 0) cmd.Parameters.AddWithValue("@limit", limit); @@ -244,6 +246,15 @@ public class StoreAndForwardStorage return await ReadMessagesAsync(cmd); } + /// The sweep's column list qualified with the m alias (SF-3 join-back). + private static readonly string SweepColumnsM = + string.Join(", ", new[] + { + "id", "category", "target", "payload_json", "retry_count", "max_retries", + "retry_interval_ms", "created_at", "last_attempt_at", "status", "last_error", "origin_instance", + "execution_id", "source_script", "parent_execution_id", + }.Select(c => "m." + c)); + /// /// Updates a message after a delivery attempt. /// diff --git a/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/AreaService.cs b/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/AreaService.cs index 9dfcee7a..50b0fc2c 100644 --- a/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/AreaService.cs +++ b/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/AreaService.cs @@ -188,7 +188,8 @@ public class AreaService return Result.Failure($"Area with ID {areaId} not found."); // Check for instances assigned to this area - var allInstances = await _repository.GetInstancesBySiteIdAsync(area.SiteId, cancellationToken); + // TPL-4: shallow + untracked — only AreaId/UniqueName are read. + var allInstances = await _repository.GetInstancesBySiteIdShallowAsync(area.SiteId, cancellationToken); var allAreas = await _repository.GetAreasBySiteIdAsync(area.SiteId, cancellationToken); // Collect this area and all descendant area IDs diff --git a/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/InstanceService.cs b/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/InstanceService.cs index 76d8ec35..1a22bf07 100644 --- a/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/InstanceService.cs +++ b/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/InstanceService.cs @@ -183,6 +183,15 @@ public class InstanceService var overrides = await _repository.GetOverridesByInstanceIdAsync(instanceId, cancellationToken); var existingOverride = overrides.FirstOrDefault(o => o.AttributeName == attributeName); + // UI-6: an unchanged value is not rewritten — no save and no UpdateOverride audit row + // burying the one real edit of a bulk save. + if (existingOverride != null + && string.Equals(existingOverride.OverrideValue, overrideValue, StringComparison.Ordinal) + && existingOverride.ElementDataType == templateAttr.ElementDataType) + { + return Result.Success(existingOverride); + } + if (existingOverride != null) { existingOverride.OverrideValue = overrideValue; @@ -250,7 +259,9 @@ public class InstanceService // rule for a composed alarm. Mirrors SetAttributeOverrideAsync. // The resolver reads member names and lock flags only, so the no-tracking, // script-body-free analysis projection suffices (review 2026-10-21 04/P6, 08/P1). - var allTemplates = await _repository.GetAllTemplatesForAnalysisAsync(cancellationToken); + // TPL-4: the template's analysis closure (chain + compositions) is all the resolver + // walks — not the whole template table. + var allTemplates = await _repository.GetTemplateAnalysisClosureAsync(instance.TemplateId, cancellationToken); var resolvedAlarm = TemplateResolver .ResolveAllMembers(instance.TemplateId, allTemplates) .FirstOrDefault(m => m.MemberType == "Alarm" && m.CanonicalName == alarmCanonicalName); diff --git a/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/TemplateService.cs b/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/TemplateService.cs index ac79c963..d37946fb 100644 --- a/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/TemplateService.cs +++ b/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/TemplateService.cs @@ -228,12 +228,9 @@ public class TemplateService // only invariant the move can break is two templates sharing a // (FolderId, Name) at the destination, which the design's // naming-collisions-are-design-time-errors rule forbids. - var allTemplates = await _repository.GetAllTemplatesForAnalysisAsync(cancellationToken); - var collision = allTemplates.FirstOrDefault(t => - t.Id != templateId && - t.FolderId == newFolderId && - string.Equals(t.Name, template.Name, StringComparison.OrdinalIgnoreCase)); - if (collision != null) + // TPL-4: a (FolderId, Name) existence query, not a load of every template. + if (await _repository.TemplateNameExistsInFolderAsync( + newFolderId, template.Name, templateId, cancellationToken)) { var location = newFolderId.HasValue ? "the target folder" : "the root"; return Result