Merge branch 'review/wp6' into review/integration
# Conflicts: # docs/requirements/Component-StoreAndForward.md # src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/DeploymentManagerRepository.cs # src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardStorage.cs # src/ZB.MOM.WW.ScadaBridge.Transport/Import/BundleImporter.cs # tests/ZB.MOM.WW.ScadaBridge.StoreAndForward.Tests/StoreAndForwardStorageTests.cs
This commit is contained in:
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -175,7 +175,7 @@ The `sbk_<keyId>_<secret>` 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<string> 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<string> 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
|
||||
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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 — <c>$pending</c>, <c>$pushAbandoned</c>,
|
||||
/// <c>$rejected</c> — that the reconciliation pull serves and retires.
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// AUD-3: the owed states as SQL literals, shared by the <c>IX_fwd_owed</c> 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.
|
||||
/// </summary>
|
||||
internal static readonly string OwedStatesSql =
|
||||
$"'{AuditForwardState.Pending}', '{SiteAuditForwardStates.PushAbandoned}', '{SiteAuditForwardStates.Rejected}'";
|
||||
|
||||
/// <summary>The connection string both connections were opened with (AUD-2 regression surface).</summary>
|
||||
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;
|
||||
""";
|
||||
|
||||
@@ -233,6 +233,44 @@ public class SiteAuditTelemetryActor : ReceiveActor
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// AUD-7: builds the per-drain tracking lookup. With an <see cref="IOperationTrackingBatchReader"/>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private async Task<Func<TrackedOperationId, Task<TrackingStatusSnapshot?>>> PrefetchTrackingAsync(
|
||||
IReadOnlyList<AuditEvent> 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<TrackingStatusSnapshot?>(ex);
|
||||
}
|
||||
}
|
||||
|
||||
var memo = new Dictionary<TrackedOperationId, TrackingStatusSnapshot?>();
|
||||
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;
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Combined-telemetry drain. Reads cached-lifecycle audit
|
||||
/// rows, joins each with the matching <see cref="IOperationTrackingStore"/>
|
||||
@@ -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)
|
||||
|
||||
@@ -64,6 +64,14 @@ public sealed class SiteScopeService
|
||||
public async Task<IReadOnlySet<int>> PermittedSiteIdsAsync()
|
||||
=> (await ResolveAsync()).Sites;
|
||||
|
||||
/// <summary>
|
||||
/// UI-12: the system-wide flag AND the permitted site ids from ONE authoritative resolve —
|
||||
/// for callers that need both (calling <see cref="IsSystemWideAsync"/> then
|
||||
/// <see cref="PermittedSiteIdsAsync"/> revalidates the session twice).
|
||||
/// </summary>
|
||||
/// <returns>Whether the user is unrestricted, and otherwise the permitted <c>Site.Id</c> set.</returns>
|
||||
public Task<(bool IsSystemWide, IReadOnlySet<int> Sites)> ResolveScopeAsync() => ResolveAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Returns the subset of <paramref name="sites"/> the user is permitted to
|
||||
/// see. A system-wide user gets the full list back unchanged.
|
||||
|
||||
@@ -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<int>? siteScope = systemWide
|
||||
? null
|
||||
: (await SiteScope.PermittedSiteIdsAsync()).ToArray();
|
||||
: permittedSites.ToArray();
|
||||
|
||||
_appliedSearch = _searchInput.Trim();
|
||||
var filter = new DeploymentListFilter(
|
||||
|
||||
+35
-12
@@ -1422,20 +1422,43 @@
|
||||
return;
|
||||
}
|
||||
|
||||
var failures = new List<string>();
|
||||
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<ConfigurationCommandService>().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<ConfigurationCommandService>().ExecuteInstanceAsync(Id, null, async (instanceService, currentUser) =>
|
||||
{
|
||||
var rows = new List<(string Name, InstanceAttributeOverride Row)>(changed.Count);
|
||||
var failed = new List<string>();
|
||||
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)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.CentralUI.Components.Pages.Deployment;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal static class OverrideSaveDiff
|
||||
{
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
/// <param name="working">The page's working override values, by attribute name.</param>
|
||||
/// <param name="existing">The stored override rows, by attribute name.</param>
|
||||
/// <returns>The (attribute, value) pairs to save.</returns>
|
||||
public static IReadOnlyList<(string Name, string? Value)> Changed(
|
||||
IReadOnlyDictionary<string, string?> working,
|
||||
IReadOnlyDictionary<string, InstanceAttributeOverride> 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();
|
||||
|
||||
/// <summary>Thrown inside the save transaction when any row fails, so nothing commits.</summary>
|
||||
/// <param name="failures">The per-attribute failure messages.</param>
|
||||
public sealed class BatchFailedException(IReadOnlyList<string> failures)
|
||||
: Exception($"{failures.Count} override(s) failed to save.")
|
||||
{
|
||||
/// <summary>Gets the per-attribute failure messages.</summary>
|
||||
public IReadOnlyList<string> Failures { get; } = failures;
|
||||
}
|
||||
}
|
||||
+41
-8
@@ -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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private async Task<bool> 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)
|
||||
|
||||
@@ -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<DataConnection>)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<DataConnection>();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
@@ -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);
|
||||
|
||||
/// <summary>
|
||||
/// 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 (<c>TimeoutSeconds</c>) 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.
|
||||
/// </summary>
|
||||
internal static TimeSpan StartupCeiling { get; set; } = TimeSpan.FromSeconds(30);
|
||||
|
||||
/// <summary>Runs one child under a deadline; a slot remains charged until confirmed process exit.</summary>
|
||||
/// <param name="request">The sandbox run request to execute in the child process.</param>
|
||||
/// <param name="services">The service provider supplying host services for the run.</param>
|
||||
@@ -41,8 +50,14 @@ public static class SandboxWorkerProtocol
|
||||
ISharedScriptCatalog catalog, CancellationToken caller, Action<int>? 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<SandboxRunResult>(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);
|
||||
|
||||
/// <summary>UI-13: tells the host user code is about to run, so it starts the script deadline.</summary>
|
||||
/// <param name="ct">Cancellation token.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
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<JsonElement> Call(string method, object?[] args, CancellationToken ct)
|
||||
{
|
||||
await _gate.WaitAsync(ct);
|
||||
|
||||
@@ -286,6 +286,18 @@ public class ScriptAnalysisService
|
||||
/// <param name="ct">Cancellation token for the run.</param>
|
||||
/// <returns>A <see cref="SandboxRunResult"/> describing the outcome, return value, console output, and any error.</returns>
|
||||
public async Task<SandboxRunResult> RunInWorkerAsync(SandboxRunRequest request, CancellationToken ct)
|
||||
=> await RunInWorkerAsync(request, ct, userCodeStarting: null);
|
||||
|
||||
/// <summary>Execution core invoked only by the disposable worker executable.</summary>
|
||||
/// <param name="request">The sandbox run request including code, kind, parameters, and optional instance binding.</param>
|
||||
/// <param name="ct">Cancellation token for the run.</param>
|
||||
/// <param name="userCodeStarting">
|
||||
/// 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.
|
||||
/// </param>
|
||||
/// <returns>A <see cref="SandboxRunResult"/> describing the outcome, return value, console output, and any error.</returns>
|
||||
public async Task<SandboxRunResult> RunInWorkerAsync(SandboxRunRequest request, CancellationToken ct,
|
||||
Func<CancellationToken, Task>? 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
|
||||
|
||||
+10
@@ -413,6 +413,16 @@ public interface IDeploymentManagerRepository
|
||||
/// <param name="cancellationToken">A cancellation token that can be used to cancel the operation.</param>
|
||||
/// <returns>The instance, or null if not found.</returns>
|
||||
Task<Instance?> GetInstanceByIdAsync(int instanceId, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="instanceId">The instance id.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>The state, or <see langword="null"/> when the instance does not exist.</returns>
|
||||
Task<InstanceState?> GetInstanceStateAsync(int instanceId, CancellationToken cancellationToken = default);
|
||||
/// <summary>
|
||||
/// Refreshes <paramref name="instance"/> in place from the database so a caller that
|
||||
/// waited for the per-instance operation lock can validate the state the command ahead
|
||||
|
||||
+44
@@ -286,6 +286,18 @@ public interface ITemplateEngineRepository
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>A task that resolves to the matching instance, or <see langword="null"/> if not found.</returns>
|
||||
Task<Instance?> GetInstanceByIdAsync(int id, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// DEP-4: loads several instances with the same child collections as
|
||||
/// <see cref="GetInstanceByIdAsync"/>, <b>untracked</b>, 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.
|
||||
/// </summary>
|
||||
/// <param name="ids">The instance ids; missing ids are absent from the result.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>The instances found.</returns>
|
||||
Task<IReadOnlyList<Instance>> GetInstancesByIdsUntrackedAsync(
|
||||
IReadOnlyCollection<int> ids, CancellationToken cancellationToken = default);
|
||||
/// <summary>Retrieves all instances.</summary>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>A task that resolves to a read-only list of all instances.</returns>
|
||||
@@ -301,6 +313,38 @@ public interface ITemplateEngineRepository
|
||||
/// <returns>A task that resolves to a read-only list of instances for the specified site.</returns>
|
||||
Task<IReadOnlyList<Instance>> GetInstancesBySiteIdAsync(int siteId, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="siteId">The site ID.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>The site's instances, shallow and untracked.</returns>
|
||||
Task<IReadOnlyList<Instance>> GetInstancesBySiteIdShallowAsync(int siteId, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// MGT-5: every instance's (Id, UniqueName) — the name index bundle export resolves
|
||||
/// <c>--instances</c> against, instead of loading every instance with its child collections.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>One (Id, UniqueName) pair per instance.</returns>
|
||||
Task<IReadOnlyList<(int Id, string UniqueName)>> GetInstanceNamesAsync(CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// TPL-4: whether a template other than <paramref name="excludeTemplateId"/> named
|
||||
/// <paramref name="name"/> (case-insensitively) already sits in <paramref name="folderId"/>
|
||||
/// (<see langword="null"/> = the root) — the folder-move collision check, which used to load
|
||||
/// the whole template table.
|
||||
/// </summary>
|
||||
/// <param name="folderId">The destination folder, or null for the root.</param>
|
||||
/// <param name="name">The template name.</param>
|
||||
/// <param name="excludeTemplateId">The template being moved.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns><see langword="true"/> when a sibling with that name exists.</returns>
|
||||
Task<bool> TemplateNameExistsInFolderAsync(
|
||||
int? folderId, string name, int excludeTemplateId, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>Reads one bounded, untracked page of topology instance rows for a site/area.</summary>
|
||||
/// <param name="siteId">The site ID.</param>
|
||||
/// <param name="areaId">The area ID to filter by, or null for every area.</param>
|
||||
|
||||
+28
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Optional batched read surface of an <see cref="IOperationTrackingStore"/> (AUD-7).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Kept as a separate interface rather than a new <see cref="IOperationTrackingStore"/> member so
|
||||
/// existing implementations and test doubles are untouched: a consumer probes for it and falls
|
||||
/// back to per-id <see cref="IOperationTrackingStore.GetStatusAsync"/> when it is absent. The
|
||||
/// read has the same read-your-writes guarantee as <c>GetStatusAsync</c>, but pays the writer
|
||||
/// queue barrier once for the whole set instead of once per id.
|
||||
/// </remarks>
|
||||
public interface IOperationTrackingBatchReader
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="ids">The operation ids to read; duplicates are ignored.</param>
|
||||
/// <param name="ct">Cancellation token.</param>
|
||||
/// <returns>The snapshots found, keyed by id.</returns>
|
||||
Task<IReadOnlyDictionary<TrackedOperationId, TrackingStatusSnapshot>> GetStatusManyAsync(
|
||||
IReadOnlyCollection<TrackedOperationId> ids,
|
||||
CancellationToken ct = default);
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>COMM-8: how many failback probes one sweep runs concurrently.</summary>
|
||||
internal const int FailbackProbeParallelism = 8;
|
||||
|
||||
/// <summary>
|
||||
/// COMM-8: probes every site that is due for failback at <paramref name="nowUtc"/>,
|
||||
/// concurrently up to <see cref="FailbackProbeParallelism"/>. 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.
|
||||
/// </summary>
|
||||
/// <param name="nowUtc">The time the due check is evaluated at.</param>
|
||||
/// <param name="ct">Cancellation token.</param>
|
||||
/// <returns>A task that completes when every due probe has finished.</returns>
|
||||
internal async Task RunDueFailbackProbesAsync(DateTime nowUtc, CancellationToken ct)
|
||||
{
|
||||
var due = new List<string>();
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parks a channel that is no longer reachable through <see cref="_sites"/> instead of
|
||||
/// disposing it inline.
|
||||
|
||||
+8
@@ -235,6 +235,14 @@ public class AuditLogEntityTypeConfiguration : IEntityTypeConfiguration<AuditLog
|
||||
.IsDescending(false, false, true)
|
||||
.HasDatabaseName("IX_AuditLog_Channel_Status_Occurred");
|
||||
|
||||
// AUD-5: the per-channel retention purge (DELETE TOP (@batch) ... WHERE Category =
|
||||
// @channel AND OccurredAtUtc < @threshold) had no index with the two predicates
|
||||
// adjacent — Status sits between them in IX_AuditLog_Channel_Status_Occurred — so each
|
||||
// batch scanned most of the table. Created via raw SQL ON ps_AuditLog_Month so it stays
|
||||
// partition-aligned for the partition-switch purge (AuditLogChannelOccurredIndex).
|
||||
builder.HasIndex(e => 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")
|
||||
|
||||
+2317
File diff suppressed because it is too large
Load Diff
+37
@@ -0,0 +1,37 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Migrations
|
||||
{
|
||||
/// <summary>
|
||||
/// AUD-5 (WP6 task 6.5): <c>IX_AuditLog_Channel_Occurred (Category, OccurredAtUtc)</c> for the
|
||||
/// per-channel retention purge (<c>DELETE TOP (@batch) ... WHERE Category = @channel AND
|
||||
/// OccurredAtUtc < @threshold</c>), whose channel and age predicates were not adjacent in
|
||||
/// any index.
|
||||
/// </summary>
|
||||
public partial class AuditLogChannelOccurredIndex : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
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);");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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;");
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
@@ -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");
|
||||
|
||||
@@ -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";
|
||||
|
||||
+25
-37
@@ -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<PendingDeployment>()
|
||||
.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<PendingDeployment>().AddAsync(pending, cancellationToken);
|
||||
}
|
||||
|
||||
@@ -505,29 +504,6 @@ public class DeploymentManagerRepository : IDeploymentManagerRepository
|
||||
return rows.Count;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Marks the pending row with primary key <paramref name="id"/> for deletion on the next
|
||||
/// <c>SaveChanges</c> without loading it: an already-tracked instance is removed in place,
|
||||
/// otherwise a key-only stub is attached and removed (EF deletes by key).
|
||||
/// </summary>
|
||||
/// <param name="id">Primary key of the pending row.</param>
|
||||
private void RemovePendingByKey(int id)
|
||||
{
|
||||
var set = _dbContext.Set<PendingDeployment>();
|
||||
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);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<int> PurgeTerminalDeploymentRecordsAsync(
|
||||
DateTimeOffset cutoffUtc,
|
||||
@@ -801,6 +777,18 @@ public class DeploymentManagerRepository : IDeploymentManagerRepository
|
||||
return entry.State == EntityState.Detached;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<InstanceState?> 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<Instance>()
|
||||
.Where(i => i.Id == instanceId)
|
||||
.Select(i => (InstanceState?)i.State)
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<Instance?> GetInstanceByIdAsync(int instanceId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return await _dbContext.Set<Instance>()
|
||||
|
||||
+57
@@ -501,6 +501,29 @@ public class TemplateEngineRepository : ITemplateEngineRepository
|
||||
.FirstOrDefaultAsync(i => i.Id == id, cancellationToken);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<Instance>> GetInstancesByIdsUntrackedAsync(
|
||||
IReadOnlyCollection<int> ids, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(ids);
|
||||
var result = new List<Instance>(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;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<Instance>> GetAllInstancesAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
@@ -521,6 +544,40 @@ public class TemplateEngineRepository : ITemplateEngineRepository
|
||||
.ToListAsync(cancellationToken);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<Instance>> GetInstancesBySiteIdShallowAsync(int siteId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return await _context.Instances
|
||||
.AsNoTracking()
|
||||
.Where(i => i.SiteId == siteId)
|
||||
.ToListAsync(cancellationToken);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<(int Id, string UniqueName)>> 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();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<bool> 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));
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<Instance>> GetInstancesBySiteIdAsync(int siteId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
|
||||
@@ -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.
|
||||
/// </summary>
|
||||
private static QualityCode MapQuality(int quality, IEnumerable<MxStatusProxy> statuses)
|
||||
/// <remarks>
|
||||
/// 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 — <c>IEnumerable.Any</c> 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).
|
||||
/// </remarks>
|
||||
internal static QualityCode MapQuality(int quality, IReadOnlyList<MxStatusProxy> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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
|
||||
|
||||
@@ -63,6 +63,9 @@ public class DeploymentService
|
||||
/// Reason reported on every <see cref="SkippedInstanceResult"/> a bulk site
|
||||
/// deploy produces for a <see cref="InstanceState.Disabled"/> instance.
|
||||
/// </summary>
|
||||
/// <summary>DEP-4: instances bulk-loaded (untracked) per chunk by the fleet staleness read.</summary>
|
||||
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<DeploymentRecord>? EarlyResult)
|
||||
Result<DeploymentRecord>? EarlyResult,
|
||||
string? SkipReason = null)
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="reason">The skip reason shown in the bulk summary.</param>
|
||||
/// <returns>A prepared deployment holding no lock, with <see cref="SkipReason"/> set.</returns>
|
||||
public static PreparedDeployment Skipped(string reason) =>
|
||||
new(null!, string.Empty, null!, string.Empty, string.Empty, string.Empty, null,
|
||||
Result<DeploymentRecord>.Failure(reason), reason);
|
||||
|
||||
/// <summary>Builds a prepare-phase-resolved deployment carrying the given result and holding no lock.</summary>
|
||||
/// <param name="result">The result to hand back to the caller.</param>
|
||||
/// <returns>A prepared deployment whose <see cref="EarlyResult"/> is set.</returns>
|
||||
@@ -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<int, string>();
|
||||
|
||||
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<Instance>)Array.Empty<Instance>());
|
||||
}
|
||||
|
||||
evaluated++;
|
||||
|
||||
// Read-only path: hash only — no validation (its result was always discarded
|
||||
|
||||
@@ -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<int, CachedChain> _chains = new();
|
||||
private readonly Dictionary<int, (long Version, IReadOnlyList<TemplateComposition> Compositions)> _compositions = new();
|
||||
private readonly Dictionary<int, IReadOnlyDictionary<int, DataConnection>> _dataConnections = new();
|
||||
private readonly Dictionary<int, Instance> _preloadedInstances = new();
|
||||
|
||||
private IReadOnlyList<ResolvedScript>? _sharedScripts;
|
||||
private IReadOnlyDictionary<string, string>? _schemaLibrary;
|
||||
@@ -78,6 +80,27 @@ public sealed class FlattenSession
|
||||
/// <summary>Number of per-site data-connection queries that missed the memo.</summary>
|
||||
public int DataConnectionLoads { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="instances">The preloaded instances.</param>
|
||||
public void PreloadInstances(IEnumerable<Instance> instances)
|
||||
{
|
||||
foreach (var instance in instances)
|
||||
_preloadedInstances[instance.Id] = instance;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Takes (and forgets) a preloaded instance, so a chunked caller never holds more than
|
||||
/// one chunk of the fleet in memory.
|
||||
/// </summary>
|
||||
/// <param name="instanceId">The instance id.</param>
|
||||
/// <returns>The preloaded instance, or <see langword="null"/> when none was preloaded.</returns>
|
||||
public Instance? TakePreloadedInstance(int instanceId) =>
|
||||
_preloadedInstances.Remove(instanceId, out var instance) ? instance : null;
|
||||
|
||||
/// <summary>
|
||||
/// Every template id this session resolved — the union of all inheritance and
|
||||
/// composed chains it walked. The staleness fast path records the watermark
|
||||
|
||||
@@ -190,8 +190,9 @@ public class FlatteningPipeline : IFlatteningPipeline
|
||||
private async Task<Result<(FlattenedConfiguration Config, IReadOnlyDictionary<int, DataConnection> 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<int, DataConnection>)>.Failure(
|
||||
$"Instance with ID {instanceId} not found.");
|
||||
|
||||
@@ -260,7 +260,9 @@ public static class EndpointExtensions
|
||||
var sharedSchemaRepo =
|
||||
httpContext.RequestServices.GetService<ISharedSchemaRepository>();
|
||||
var resolveRef = await SchemaRefResolver.BuildAsync(
|
||||
sharedSchemaRepo, [method.ParameterDefinitions], httpContext.RequestAborted);
|
||||
sharedSchemaRepo, [method.ParameterDefinitions],
|
||||
httpContext.RequestServices.GetService<SharedSchemaLibraryCache>(), // INB-2
|
||||
httpContext.RequestAborted);
|
||||
|
||||
var paramResult = ParameterValidator.Validate(body, method.ParameterDefinitions, resolveRef);
|
||||
if (!paramResult.IsValid)
|
||||
|
||||
@@ -651,7 +651,9 @@ public class InboundScriptExecutor
|
||||
var sharedSchemaRepo =
|
||||
scope?.ServiceProvider.GetService<ISharedSchemaRepository>();
|
||||
var resolveRef = await SchemaRefResolver.BuildAsync(
|
||||
sharedSchemaRepo, [method.ReturnDefinition], cts.Token);
|
||||
sharedSchemaRepo, [method.ReturnDefinition],
|
||||
scope?.ServiceProvider.GetService<SharedSchemaLibraryCache>(), // INB-2
|
||||
cts.Token);
|
||||
|
||||
// Validate the script's return value against the
|
||||
// method's declared ReturnDefinition. A method whose script returns a
|
||||
|
||||
@@ -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.
|
||||
/// </remarks>
|
||||
/// <summary>
|
||||
/// INB-3: how many body bytes the audit copy expects to read — the declared
|
||||
/// <c>Content-Length</c> when it is under the cap, else the cap. The scratch buffer is
|
||||
/// rented at this plus one byte.
|
||||
/// </summary>
|
||||
/// <param name="contentLength">The request's declared Content-Length, if any.</param>
|
||||
/// <param name="capBytes">The audit capture cap.</param>
|
||||
/// <returns>The expected capture length in bytes.</returns>
|
||||
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<byte>.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);
|
||||
}
|
||||
|
||||
@@ -83,13 +83,39 @@ internal static class RelayProvenance
|
||||
context.Items[AuditWriteMiddleware.InboundExecutionIdItemKey] = proof.ExecutionId;
|
||||
}
|
||||
|
||||
/// <summary>INB-4: the full replay-cache scan runs at most once per this many seconds.</summary>
|
||||
private const int ReplayPruneIntervalSeconds = 5;
|
||||
|
||||
/// <summary>Unix second before which no further prune scan runs (INB-4).</summary>
|
||||
private static long _nextPruneAt;
|
||||
|
||||
/// <summary>Number of prune scans performed — a test hook for INB-4.</summary>
|
||||
internal static int PruneScans;
|
||||
|
||||
private static bool TryRecordProof(Proof proof)
|
||||
=> TryRecordProof(proof.ExecutionId, proof.Nonce!, proof.Time);
|
||||
|
||||
/// <summary>Records a proof as seen; <see langword="false"/> for a replay or a full cache.</summary>
|
||||
/// <param name="executionId">The proof's execution id.</param>
|
||||
/// <param name="nonce">The proof's nonce.</param>
|
||||
/// <param name="proofTime">The proof's own unix-second timestamp.</param>
|
||||
/// <returns>Whether the proof was new and recorded.</returns>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Reads a stream fully, failing if it exceeds the given byte limit.</summary>
|
||||
|
||||
@@ -44,9 +44,26 @@ public static class SchemaRefResolver
|
||||
/// A synchronous <c>name → schema JSON?</c> resolver, or <c>null</c> when no definition
|
||||
/// uses a <c>$ref</c> (so the validators take their unchanged no-resolver path).
|
||||
/// </returns>
|
||||
public static Task<Func<string, string?>?> BuildAsync(
|
||||
ISharedSchemaRepository? repository,
|
||||
IEnumerable<string?> definitions,
|
||||
CancellationToken ct = default)
|
||||
=> BuildAsync(repository, definitions, cache: null, ct);
|
||||
|
||||
/// <summary>
|
||||
/// As <see cref="BuildAsync(ISharedSchemaRepository?, IEnumerable{string?}, CancellationToken)"/>,
|
||||
/// serving the library from <paramref name="cache"/> when one is supplied (INB-2) instead of
|
||||
/// reading it from the database on every call.
|
||||
/// </summary>
|
||||
/// <param name="repository">The shared-schema repository, or <c>null</c> when none is registered.</param>
|
||||
/// <param name="definitions">The schema definition JSON strings to be validated (parameter and/or return).</param>
|
||||
/// <param name="cache">The process-wide library snapshot cache, or <c>null</c> to read the repository directly.</param>
|
||||
/// <param name="ct">Cancellation token for the library load.</param>
|
||||
/// <returns>A synchronous resolver, or <c>null</c> when no definition uses a <c>$ref</c>.</returns>
|
||||
public static async Task<Func<string, string?>?> BuildAsync(
|
||||
ISharedSchemaRepository? repository,
|
||||
IEnumerable<string?> 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<string, string> 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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,6 +29,11 @@ public static class ServiceCollectionExtensions
|
||||
services.AddSingleton(sp => new ApiMethodCache(
|
||||
sp.GetRequiredService<IOptions<InboundApiOptions>>().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<IOptions<InboundApiOptions>>().Value.ApiMethodCacheTtl));
|
||||
|
||||
// Routed calls go through the IInstanceRouter seam; the
|
||||
// production implementation delegates to CommunicationService.
|
||||
services.AddScoped<IInstanceRouter, CommunicationServiceInstanceRouter>();
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.InboundAPI;
|
||||
|
||||
/// <summary>
|
||||
/// INB-2: a short-TTL, process-wide snapshot of the shared-schema library (name → schema
|
||||
/// JSON) for runtime <c>$ref</c> resolution.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A method whose parameter or return definition used a <c>$ref</c> 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 <see cref="InboundApiOptions.ApiMethodCacheTtl"/> — the same bound
|
||||
/// the resolved <c>ApiMethod</c> 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.
|
||||
/// </remarks>
|
||||
public sealed class SharedSchemaLibraryCache
|
||||
{
|
||||
private sealed record Snapshot(IReadOnlyDictionary<string, string> Library, DateTimeOffset ExpiresAtUtc);
|
||||
|
||||
private readonly TimeSpan _ttl;
|
||||
private readonly TimeProvider _timeProvider;
|
||||
private Snapshot? _snapshot;
|
||||
|
||||
/// <summary>Initializes the cache.</summary>
|
||||
/// <param name="ttl">How long a loaded library snapshot is served.</param>
|
||||
/// <param name="timeProvider">Clock; defaults to the system clock.</param>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Returns the cached library snapshot, loading it through <paramref name="repository"/> when stale.</summary>
|
||||
/// <param name="repository">The shared-schema repository used on a miss.</param>
|
||||
/// <param name="ct">Cancellation token.</param>
|
||||
/// <returns>The library as name → schema JSON.</returns>
|
||||
public async Task<IReadOnlyDictionary<string, string>> 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;
|
||||
}
|
||||
|
||||
/// <summary>Drops the snapshot so the next lookup reloads the library.</summary>
|
||||
public void Invalidate() => Volatile.Write(ref _snapshot, null);
|
||||
}
|
||||
@@ -4449,7 +4449,10 @@ public class ManagementActor : ReceiveActor
|
||||
var inboundRepo = sp.GetRequiredService<IInboundApiRepository>();
|
||||
var siteRepo = sp.GetRequiredService<ISiteRepository>();
|
||||
|
||||
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<T>(IReadOnlyList<T> all, IReadOnlyList<string>? names,
|
||||
Func<T, string> getName, Func<T, int> getId, string entityType)
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// CMN-11: O(1) node lookup. Ids are minted append-only as <c>"n" + (index + 1)</c>, so the
|
||||
/// index is read from the id; the linear scan is only a fallback for a foreign id.
|
||||
/// </summary>
|
||||
/// <param name="id">The node id.</param>
|
||||
/// <returns>The node's index, or -1 when absent.</returns>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Appends a note to an existing node.</summary>
|
||||
/// <param name="id">The id of the node to annotate.</param>
|
||||
/// <param name="note">The note to append.</param>
|
||||
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}" };
|
||||
|
||||
@@ -90,9 +90,10 @@ public class EventLogPurgeService : BackgroundService
|
||||
private const double TablePageFillFactor = 0.78;
|
||||
|
||||
/// <summary>
|
||||
/// Number of secondary indexes on <c>site_events</c>: timestamp, instance_id,
|
||||
/// Number of secondary indexes on <c>site_events</c>: timestamp, (instance_id, timestamp),
|
||||
/// (event_type, timestamp) and (severity, timestamp). The sampled <c>indexed_bytes</c>
|
||||
/// charges every covered column once per index, hence <c>3 * octet_length(timestamp)</c>.
|
||||
/// charges every covered column once per index, hence <c>4 * octet_length(timestamp)</c>
|
||||
/// (SEL-1 added timestamp to the instance index).
|
||||
/// </summary>
|
||||
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}
|
||||
|
||||
@@ -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/
|
||||
|
||||
@@ -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<IActorRef>();
|
||||
_childrenByMonitoredAttribute[attribute] = set;
|
||||
}
|
||||
set.Add(child);
|
||||
}
|
||||
break;
|
||||
case TriggerRoutingKind.AllChanges:
|
||||
_allChangeChildren.Add(child);
|
||||
break;
|
||||
|
||||
@@ -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<IReadOnlyList<NativeAlarmRow>>? _rehydrationRead;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SRT-14: the <paramref name="count"/> 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.
|
||||
/// </summary>
|
||||
/// <param name="alarms">The mirrored conditions.</param>
|
||||
/// <param name="count">How many to select.</param>
|
||||
/// <returns>The selected conditions, oldest first.</returns>
|
||||
internal static List<NativeAlarmTransition> SelectOldest(
|
||||
IEnumerable<NativeAlarmTransition> alarms, int count)
|
||||
{
|
||||
var result = new List<NativeAlarmTransition>(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<NativeAlarmTransition, DateTimeOffset>(
|
||||
count + 1, Comparer<DateTimeOffset>.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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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);
|
||||
|
||||
/// <summary>
|
||||
/// Signals the parent Instance Actor that a native condition has
|
||||
/// left the mirror for good so it can evict the matching <c>_latestAlarmEvents</c>
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Scripts;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// The walk is deliberately conservative. It recognises exactly the two literal read forms
|
||||
/// <see cref="TriggerExpressionGlobals"/> exposes — <c>Attributes["k"]</c> (key <c>k</c>) and
|
||||
/// <c>Children["c"].Attributes["k"]</c> (key <c>c.k</c>) — and gives up (returns
|
||||
/// <see langword="false"/>, 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
|
||||
/// <c>Attributes</c>/<c>Children</c>/<c>Parent</c> 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).
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// 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.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
internal static class TriggerExpressionKeys
|
||||
{
|
||||
private static readonly CSharpParseOptions ScriptParse =
|
||||
CSharpParseOptions.Default.WithKind(SourceCodeKind.Script);
|
||||
|
||||
/// <summary>
|
||||
/// Tries to extract the literal attribute keys an expression reads.
|
||||
/// </summary>
|
||||
/// <param name="expression">The trigger expression source.</param>
|
||||
/// <param name="keys">The distinct canonical keys read, when the method returns <see langword="true"/>.</param>
|
||||
/// <returns><see langword="true"/> when every attribute read is a recognised literal form and at least one exists.</returns>
|
||||
public static bool TryExtract(string? expression, out IReadOnlyList<string> keys)
|
||||
{
|
||||
keys = Array.Empty<string>();
|
||||
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<string>();
|
||||
var seen = new HashSet<string>(StringComparer.Ordinal);
|
||||
|
||||
foreach (var id in root.DescendantNodes().OfType<IdentifierNameSyntax>())
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True when <paramref name="node"/> is directly indexed by one string literal.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Matches <c>Children["c"]</c> and returns <c>c</c>.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -14,13 +14,18 @@ internal enum TriggerRoutingKind
|
||||
AllChanges,
|
||||
|
||||
/// <summary>Never reacts to attribute changes (interval / call-only scripts).</summary>
|
||||
None
|
||||
None,
|
||||
|
||||
/// <summary>SRT-7: reacts to changes of any of a set of named attributes — an Expression
|
||||
/// trigger whose attribute reads are all literal keys (see <see cref="TriggerExpressionKeys"/>).</summary>
|
||||
MonitoredAttributes
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Result of classifying a child's trigger for attribute-change routing.
|
||||
/// </summary>
|
||||
internal readonly record struct TriggerRoutingDecision(TriggerRoutingKind Kind, string? MonitoredAttribute)
|
||||
internal readonly record struct TriggerRoutingDecision(
|
||||
TriggerRoutingKind Kind, string? MonitoredAttribute, IReadOnlyList<string>? 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,
|
||||
/// <param name="attribute">The name of the attribute to monitor.</param>
|
||||
/// <returns>A <see cref="TriggerRoutingDecision"/> of kind <see cref="TriggerRoutingKind.MonitoredAttribute"/>.</returns>
|
||||
public static TriggerRoutingDecision Monitored(string attribute) => new(TriggerRoutingKind.MonitoredAttribute, attribute);
|
||||
|
||||
/// <summary>Creates a decision routing on changes to any of several named attributes (SRT-7).</summary>
|
||||
/// <param name="attributes">The attribute names to monitor.</param>
|
||||
/// <returns>A <see cref="TriggerRoutingDecision"/> of kind <see cref="TriggerRoutingKind.MonitoredAttributes"/>.</returns>
|
||||
public static TriggerRoutingDecision MonitoredSet(IReadOnlyList<string> attributes) =>
|
||||
new(TriggerRoutingKind.MonitoredAttributes, null, attributes);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="triggerConfigJson">The Expression trigger config JSON.</param>
|
||||
/// <returns>The routing decision.</returns>
|
||||
public static TriggerRoutingDecision ForExpression(string? triggerConfigJson) =>
|
||||
TriggerExpressionKeys.TryExtract(TriggerExpressionGlobals.ExtractExpression(triggerConfigJson), out var keys)
|
||||
? MonitoredSet(keys)
|
||||
: AllChanges;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -79,7 +101,8 @@ internal static class TriggerRouting
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
@@ -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
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
@@ -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:
|
||||
|
||||
@@ -51,7 +51,7 @@ namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Tracking;
|
||||
/// path.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public class OperationTrackingStore : IOperationTrackingStore, IAsyncDisposable, IDisposable
|
||||
public class OperationTrackingStore : IOperationTrackingStore, IOperationTrackingBatchReader, IAsyncDisposable, IDisposable
|
||||
{
|
||||
/// <summary>Queue bound; past it <c>Record*Async</c> waits (never drops).</summary>
|
||||
internal const int MaxQueuedWrites = 8192;
|
||||
@@ -595,7 +595,61 @@ public class OperationTrackingStore : IOperationTrackingStore, IAsyncDisposable,
|
||||
return null;
|
||||
}
|
||||
|
||||
return new TrackingStatusSnapshot(
|
||||
return ReadSnapshot(reader);
|
||||
}
|
||||
|
||||
/// <summary>Most ids bound into one <c>IN (…)</c> read (well under SQLite's parameter limit).</summary>
|
||||
private const int MaxIdsPerStatusRead = 500;
|
||||
|
||||
/// <inheritdoc/>
|
||||
/// <remarks>
|
||||
/// AUD-7: one writer-queue barrier for the whole set, then chunked <c>IN (…)</c> reads on one
|
||||
/// connection — instead of a barrier + connection + query per id.
|
||||
/// </remarks>
|
||||
public async Task<IReadOnlyDictionary<TrackedOperationId, TrackingStatusSnapshot>> GetStatusManyAsync(
|
||||
IReadOnlyCollection<TrackedOperationId> ids,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(ids);
|
||||
var result = new Dictionary<TrackedOperationId, TrackingStatusSnapshot>();
|
||||
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));
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public async Task PurgeTerminalAsync(
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
/// <summary>The sweep's column list qualified with the <c>m</c> alias (SF-3 join-back).</summary>
|
||||
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));
|
||||
|
||||
/// <summary>
|
||||
/// Updates a message after a delivery attempt.
|
||||
/// </summary>
|
||||
|
||||
@@ -188,7 +188,8 @@ public class AreaService
|
||||
return Result<bool>.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
|
||||
|
||||
@@ -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<InstanceAttributeOverride>.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);
|
||||
|
||||
@@ -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<Template>.Failure(
|
||||
@@ -449,7 +446,9 @@ public class TemplateService
|
||||
var template = await _repository.GetTemplateByIdAsync(attribute.TemplateId, cancellationToken);
|
||||
if (template?.ParentTemplateId != null)
|
||||
{
|
||||
var allTemplates = await _repository.GetAllTemplatesForAnalysisAsync(cancellationToken);
|
||||
// TPL-4: the parent's analysis closure is all FindMemberByCanonicalName walks.
|
||||
var allTemplates = await _repository.GetTemplateAnalysisClosureAsync(
|
||||
template.ParentTemplateId.Value, cancellationToken);
|
||||
var parentMember = TemplateResolver.FindMemberByCanonicalName(
|
||||
attribute.Name, template.ParentTemplateId.Value, allTemplates);
|
||||
if (parentMember != null)
|
||||
@@ -676,7 +675,9 @@ public class TemplateService
|
||||
var template = await _repository.GetTemplateByIdAsync(alarm.TemplateId, cancellationToken);
|
||||
if (template?.ParentTemplateId != null)
|
||||
{
|
||||
var allTemplates = await _repository.GetAllTemplatesForAnalysisAsync(cancellationToken);
|
||||
// TPL-4: the parent's analysis closure is all FindMemberByCanonicalName walks.
|
||||
var allTemplates = await _repository.GetTemplateAnalysisClosureAsync(
|
||||
template.ParentTemplateId.Value, cancellationToken);
|
||||
var parentMember = TemplateResolver.FindMemberByCanonicalName(
|
||||
alarm.Name, template.ParentTemplateId.Value, allTemplates);
|
||||
if (parentMember != null)
|
||||
@@ -853,7 +854,9 @@ public class TemplateService
|
||||
var template = await _repository.GetTemplateByIdAsync(script.TemplateId, cancellationToken);
|
||||
if (template?.ParentTemplateId != null)
|
||||
{
|
||||
var allTemplates = await _repository.GetAllTemplatesForAnalysisAsync(cancellationToken);
|
||||
// TPL-4: the parent's analysis closure is all FindMemberByCanonicalName walks.
|
||||
var allTemplates = await _repository.GetTemplateAnalysisClosureAsync(
|
||||
template.ParentTemplateId.Value, cancellationToken);
|
||||
var parentMember = TemplateResolver.FindMemberByCanonicalName(
|
||||
script.Name, template.ParentTemplateId.Value, allTemplates);
|
||||
if (parentMember != null)
|
||||
|
||||
@@ -207,8 +207,28 @@ public sealed partial class BundleImporter
|
||||
await _dbContext.SaveChangesAsync(ct).ConfigureAwait(false);
|
||||
var service = new TemplateService(_templateRepo, _auditService);
|
||||
|
||||
// TRN-11: every owner/base root name was looked up with its own
|
||||
// `t.Name.ToLower() == lower` query (unindexable) — twice per derived template. The
|
||||
// (Id, Name, IsDerived) projection of the whole table is loaded ONCE into a
|
||||
// case-insensitive index instead (narrow: no members, no script bodies). This loop
|
||||
// only ever creates or deletes DERIVED templates, so a hit on a base row is always
|
||||
// current; a name with no base row in the index falls back to the live query, so the
|
||||
// derived-only / not-found diagnostics still see what earlier rows wrote.
|
||||
Dictionary<string, List<TemplateRow>>? templateRowsByName = null;
|
||||
async Task<IReadOnlyList<TemplateRow>> Named(string name)
|
||||
{
|
||||
if (templateRowsByName is null)
|
||||
{
|
||||
var all = await _dbContext.Templates.AsNoTracking()
|
||||
.Select(t => new TemplateRow(t.Id, t.Name, t.IsDerived))
|
||||
.ToListAsync(ct).ConfigureAwait(false);
|
||||
templateRowsByName = all
|
||||
.GroupBy(r => r.Name, StringComparer.OrdinalIgnoreCase)
|
||||
.ToDictionary(g => g.Key, g => g.ToList(), StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
if (templateRowsByName.TryGetValue(name, out var cached) && cached.Any(r => !r.IsDerived))
|
||||
return cached;
|
||||
|
||||
var lower = name.ToLower();
|
||||
return await _dbContext.Templates.AsNoTracking()
|
||||
.Where(t => t.Name.ToLower() == lower)
|
||||
|
||||
@@ -5653,6 +5653,8 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
}
|
||||
}
|
||||
|
||||
// TRN-11: one connection read per target site, not one per referencing row.
|
||||
var targetConnNamesBySiteId = new Dictionary<int, HashSet<string>>();
|
||||
foreach (var (site, name) in referencedConnections)
|
||||
{
|
||||
if (bundleConnectionRefs.Contains((site, name))) continue; // carried → creatable
|
||||
@@ -5663,8 +5665,13 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
&& mapping.TargetConnectionName is { Length: > 0 } tn
|
||||
? tn
|
||||
: name;
|
||||
var conns = await _siteRepo.GetDataConnectionsBySiteIdAsync(targetSite.Id, ct).ConfigureAwait(false);
|
||||
if (FindByName(conns, c => c.Name, targetName) is null)
|
||||
if (!targetConnNamesBySiteId.TryGetValue(targetSite.Id, out var connNames))
|
||||
{
|
||||
var conns = await _siteRepo.GetDataConnectionsBySiteIdAsync(targetSite.Id, ct).ConfigureAwait(false);
|
||||
connNames = new HashSet<string>(conns.Select(c => c.Name), StringComparer.OrdinalIgnoreCase);
|
||||
targetConnNamesBySiteId[targetSite.Id] = connNames;
|
||||
}
|
||||
if (!connNames.Contains(targetName))
|
||||
{
|
||||
errors.Add(
|
||||
$"Connection '{site}/{name}' is referenced by the bundle but is neither carried in "
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using ZB.MOM.WW.Audit;
|
||||
using ZB.MOM.WW.ScadaBridge.AuditLog.Site;
|
||||
using ZB.MOM.WW.ScadaBridge.AuditLog.Tests.TestSupport;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Audit;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.AuditLog.Tests.Site;
|
||||
|
||||
/// <summary>
|
||||
/// WP6 task 6.4: connection isolation (AUD-2) and the index shapes behind the reconciliation
|
||||
/// pull (AUD-3) and the retention purge (AUD-4).
|
||||
/// </summary>
|
||||
public class SqliteAuditWriterIndexingTests : IDisposable
|
||||
{
|
||||
private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"audit-idx-{Guid.NewGuid():N}.db");
|
||||
|
||||
/// <summary>Deletes the temp database files.</summary>
|
||||
public void Dispose()
|
||||
{
|
||||
SqliteConnection.ClearAllPools();
|
||||
foreach (var suffix in new[] { "", "-wal", "-shm" })
|
||||
{
|
||||
try { File.Delete(_dbPath + suffix); } catch { /* best-effort */ }
|
||||
}
|
||||
}
|
||||
|
||||
private SqliteAuditWriter CreateWriter() => new(
|
||||
Options.Create(new SqliteAuditWriterOptions { DatabasePath = _dbPath }),
|
||||
NullLogger<SqliteAuditWriter>.Instance,
|
||||
new FakeNodeIdentityProvider());
|
||||
|
||||
private static AuditEvent NewEvent(DateTime occurredAtUtc) => ScadaBridgeAuditEventFactory.Create(
|
||||
eventId: Guid.NewGuid(),
|
||||
occurredAtUtc: occurredAtUtc,
|
||||
channel: AuditChannel.ApiOutbound,
|
||||
kind: AuditKind.ApiCall,
|
||||
status: AuditStatus.Delivered);
|
||||
|
||||
/// <summary>
|
||||
/// AUD-2: an open read transaction on a connection opened like the writer's read connection
|
||||
/// must not stall the batch writer (it did under Cache=Shared: table-level shared-cache locks).
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task OpenReadTransaction_DoesNotStallTheWriter()
|
||||
{
|
||||
await using var writer = CreateWriter();
|
||||
Assert.DoesNotContain("Cache=Shared", writer.ConnectionString, StringComparison.OrdinalIgnoreCase);
|
||||
await writer.WriteAsync(NewEvent(DateTime.UtcNow));
|
||||
|
||||
await using var reader = new SqliteConnection(writer.ConnectionString);
|
||||
await reader.OpenAsync();
|
||||
await using var tx = reader.BeginTransaction(deferred: true);
|
||||
await using (var select = reader.CreateCommand())
|
||||
{
|
||||
select.Transaction = tx;
|
||||
select.CommandText = "SELECT COUNT(*) FROM audit_event";
|
||||
Assert.Equal(1L, (long)(await select.ExecuteScalarAsync())!);
|
||||
}
|
||||
|
||||
var sw = System.Diagnostics.Stopwatch.StartNew();
|
||||
await writer.WriteAsync(NewEvent(DateTime.UtcNow)).WaitAsync(TimeSpan.FromSeconds(5));
|
||||
sw.Stop();
|
||||
Assert.True(sw.ElapsedMilliseconds < 1000, $"writer stalled {sw.ElapsedMilliseconds} ms behind an open read");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// AUD-3: the pull pages the owed backlog as an ordered range of IX_fwd_owed (no temp sort),
|
||||
/// and the keyset cursor still yields every owed row exactly once, in order.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task ReconciliationPull_IsAnOrderedRangeRead_AndPagesCorrectly()
|
||||
{
|
||||
await using var writer = CreateWriter();
|
||||
var t0 = new DateTime(2026, 11, 1, 0, 0, 0, DateTimeKind.Utc);
|
||||
var ids = new List<Guid>();
|
||||
for (var i = 0; i < 25; i++)
|
||||
{
|
||||
// pairs share an instant so the EventId tiebreak is exercised
|
||||
var e = NewEvent(t0.AddSeconds(i / 2));
|
||||
ids.Add(e.EventId);
|
||||
await writer.WriteAsync(e);
|
||||
}
|
||||
|
||||
var served = new List<Guid>();
|
||||
var since = DateTime.MinValue.ToUniversalTime();
|
||||
string? afterId = null;
|
||||
while (true)
|
||||
{
|
||||
var page = await writer.ReadPendingSinceAsync(since, 4, afterId);
|
||||
if (page.Count == 0) break;
|
||||
served.AddRange(page.Select(p => p.EventId));
|
||||
since = page[^1].OccurredAtUtc.UtcDateTime;
|
||||
afterId = page[^1].EventId.ToString();
|
||||
}
|
||||
Assert.Equal(ids.Count, served.Count);
|
||||
Assert.Equal(served.Count, served.Distinct().Count());
|
||||
|
||||
var plan = await PlanAsync($"""
|
||||
SELECT fs.EventId FROM audit_forward_state fs INDEXED BY IX_fwd_owed
|
||||
JOIN audit_event ae ON ae.EventId = fs.EventId
|
||||
WHERE fs.ForwardState IN ({SqliteAuditWriter.OwedStatesSql}) AND fs.OccurredAtUtc >= '2026'
|
||||
ORDER BY fs.OccurredAtUtc ASC, fs.EventId ASC LIMIT 256
|
||||
""");
|
||||
Assert.Contains(plan, p => p.Contains("IX_fwd_owed"));
|
||||
Assert.DoesNotContain(plan, p => p.Contains("TEMP B-TREE"));
|
||||
}
|
||||
|
||||
/// <summary>AUD-4: the purge page seeks IX_fwd on (state, kind, age) rather than state alone.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task PurgePage_SeeksOnAge()
|
||||
{
|
||||
await using (CreateWriter()) { }
|
||||
var plan = await PlanAsync("""
|
||||
SELECT EventId FROM audit_forward_state
|
||||
WHERE ForwardState IN ('Forwarded', 'Reconciled') AND IsCachedKind IN (0, 1)
|
||||
AND OccurredAtUtc < '2026' LIMIT 5000
|
||||
""");
|
||||
Assert.Contains(plan, p => p.Contains("IX_fwd") && p.Contains("OccurredAtUtc<?"));
|
||||
}
|
||||
|
||||
private async Task<List<string>> PlanAsync(string sql)
|
||||
{
|
||||
await using var connection = new SqliteConnection($"Data Source={_dbPath}");
|
||||
await connection.OpenAsync();
|
||||
await using var cmd = connection.CreateCommand();
|
||||
cmd.CommandText = "EXPLAIN QUERY PLAN " + sql;
|
||||
var plan = new List<string>();
|
||||
await using var r = await cmd.ExecuteReaderAsync();
|
||||
while (await r.ReadAsync()) plan.Add(r.GetString(3));
|
||||
return plan;
|
||||
}
|
||||
}
|
||||
+49
@@ -416,6 +416,55 @@ public class SiteAuditTelemetryActorTests : TestKit
|
||||
Assert.Equal(expectedIds, emittedEventIds);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// AUD-7 (WP6 6.4): a drain resolves its rows' tracking snapshots with ONE batched read of
|
||||
/// the distinct ids when the store offers it, instead of one writer-queue barrier per row.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task CachedDrain_ResolvesTrackingWithOneBatchedRead()
|
||||
{
|
||||
var store = Substitute.For<IOperationTrackingStore, IOperationTrackingBatchReader>();
|
||||
var op = Guid.NewGuid();
|
||||
var other = Guid.NewGuid();
|
||||
var cachedRows = new[]
|
||||
{
|
||||
NewCachedEvent(AuditKind.CachedSubmit, correlationId: op),
|
||||
NewCachedEvent(AuditKind.ApiCallCached, correlationId: op),
|
||||
NewCachedEvent(AuditKind.CachedResolve, correlationId: other),
|
||||
};
|
||||
_queue.ReadPendingAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromResult<IReadOnlyList<AuditEvent>>(Array.Empty<AuditEvent>()));
|
||||
_queue.ReadPendingCachedTelemetryAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(
|
||||
Task.FromResult<IReadOnlyList<AuditEvent>>(cachedRows),
|
||||
Task.FromResult<IReadOnlyList<AuditEvent>>(Array.Empty<AuditEvent>()));
|
||||
((IOperationTrackingBatchReader)store)
|
||||
.GetStatusManyAsync(Arg.Any<IReadOnlyCollection<TrackedOperationId>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(c => Task.FromResult<IReadOnlyDictionary<TrackedOperationId, TrackingStatusSnapshot>>(
|
||||
c.Arg<IReadOnlyCollection<TrackedOperationId>>().ToDictionary(id => id, id => NewSnapshot(id))));
|
||||
_client.IngestCachedTelemetryAsync(Arg.Any<CachedTelemetryBatch>(), Arg.Any<CancellationToken>())
|
||||
.Returns(call =>
|
||||
{
|
||||
var ack = new IngestAck();
|
||||
foreach (var packet in call.Arg<CachedTelemetryBatch>().Packets)
|
||||
ack.AcceptedEventIds.Add(packet.AuditEvent.EventId);
|
||||
return Task.FromResult(ack);
|
||||
});
|
||||
|
||||
Sys.ActorOf(Props.Create(() => new SiteAuditTelemetryActor(
|
||||
_queue, _client, Opts(), NullLogger<SiteAuditTelemetryActor>.Instance,
|
||||
(IOperationTrackingStore?)store)));
|
||||
|
||||
await AwaitAssertAsync(async () =>
|
||||
await _queue.Received(1).MarkForwardedAsync(
|
||||
Arg.Is<IReadOnlyList<Guid>>(g => g.Count == 3), Arg.Any<CancellationToken>()),
|
||||
TimeSpan.FromSeconds(5));
|
||||
await ((IOperationTrackingBatchReader)store).Received(1).GetStatusManyAsync(
|
||||
Arg.Is<IReadOnlyCollection<TrackedOperationId>>(ids => ids.Count == 2), Arg.Any<CancellationToken>());
|
||||
await store.DidNotReceiveWithAnyArgs().GetStatusAsync(default, default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that the tracking-row versions central ACCEPTED are recorded as central acks
|
||||
/// in the tracking store — and only those — so the SiteCalls reconciliation pull stops
|
||||
|
||||
+44
-3
@@ -70,6 +70,46 @@ public class ParkedMessagesMutationRegressionTests : BunitContext
|
||||
await system.Terminate();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// UI-12 (WP6 6.8): a bulk retry authorises once — one site-list read for the whole batch,
|
||||
/// not one per message — and still relays every selected message.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task BulkRetry_AuthorisesOncePerAction_NotPerMessage()
|
||||
{
|
||||
using var system = ActorSystem.Create("parked-bulk-" + Guid.NewGuid().ToString("N"));
|
||||
var dispatched = new ConcurrentQueue<SiteEnvelope>();
|
||||
var comms = new CommunicationService(Options.Create(new CommunicationOptions()), NullLogger<CommunicationService>.Instance);
|
||||
comms.SetCommunicationActor(system.ActorOf(Props.Create(() => new ReplyActor(dispatched, 5))));
|
||||
Services.AddSingleton(comms);
|
||||
var sites = Substitute.For<ISiteRepository>();
|
||||
sites.GetAllSitesAsync(Arg.Any<CancellationToken>()).Returns(new List<Site> { new("Plant A", "plant-a") { Id = 42 } });
|
||||
Services.AddSingleton(sites);
|
||||
Services.AddSingleton<AuthenticationStateProvider>(new MutableAuth("42"));
|
||||
Services.AddScoped<SiteScopeService>();
|
||||
Services.AddAuthorizationCore();
|
||||
Services.AddLogging();
|
||||
var dialog = Substitute.For<IDialogService>();
|
||||
dialog.ConfirmAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<string?>()).Returns(true);
|
||||
Services.AddSingleton(dialog);
|
||||
JSInterop.Mode = JSRuntimeMode.Loose;
|
||||
|
||||
var page = Render<ParkedMessages>();
|
||||
await page.Find("select").ChangeAsync(new() { Value = "plant-a" });
|
||||
page.WaitForAssertion(() => Assert.Equal(5, page.FindAll("tr.parked-row").Count));
|
||||
await page.Find("input[aria-label='Select all']").ChangeAsync(new() { Value = true });
|
||||
page.WaitForAssertion(() => Assert.Contains("Retry selected", page.Markup));
|
||||
sites.ClearReceivedCalls();
|
||||
|
||||
await page.FindAll("button").Single(b => b.TextContent.Trim() == "Retry selected").ClickAsync(new());
|
||||
|
||||
page.WaitForAssertion(() => Assert.Equal(5, dispatched.Count(e => e.Message is ParkedMessageRetryRequest)));
|
||||
// One read for the bulk authorisation (the page refresh afterwards adds none of its own here).
|
||||
await sites.Received(1).GetAllSitesAsync(Arg.Any<CancellationToken>());
|
||||
await system.Terminate();
|
||||
}
|
||||
|
||||
private sealed class MutableAuth(string siteId) : AuthenticationStateProvider
|
||||
{
|
||||
/// <summary>Gets or sets the site identifier carried in the user's site-scope claim.</summary>
|
||||
@@ -87,14 +127,15 @@ public class ParkedMessagesMutationRegressionTests : BunitContext
|
||||
{
|
||||
/// <summary>Initializes the actor with the queue that records relayed retry requests.</summary>
|
||||
/// <param name="dispatched">The queue that receives each relayed retry envelope.</param>
|
||||
public ReplyActor(ConcurrentQueue<SiteEnvelope> dispatched)
|
||||
/// <param name="rows">How many parked rows the query reply carries.</param>
|
||||
public ReplyActor(ConcurrentQueue<SiteEnvelope> dispatched, int rows = 1)
|
||||
{
|
||||
Receive<SiteEnvelope>(envelope =>
|
||||
{
|
||||
if (envelope.Message is ParkedMessageQueryRequest query)
|
||||
Sender.Tell(new ParkedMessageQueryResponse(query.CorrelationId, envelope.SiteId,
|
||||
new[] { new ParkedMessageEntry("parked-message-1", "ERP", "Send", "Offline", 2, DateTimeOffset.UtcNow, DateTimeOffset.UtcNow) },
|
||||
1, 1, 25, true, null, DateTimeOffset.UtcNow));
|
||||
Enumerable.Range(1, rows).Select(i => new ParkedMessageEntry($"parked-message-{i}", "ERP", "Send", "Offline", 2, DateTimeOffset.UtcNow, DateTimeOffset.UtcNow)).ToArray(),
|
||||
rows, 1, 25, true, null, DateTimeOffset.UtcNow));
|
||||
else if (envelope.Message is ParkedMessageRetryRequest retry)
|
||||
{
|
||||
dispatched.Enqueue(envelope);
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
using ZB.MOM.WW.ScadaBridge.CentralUI.Components.Pages.Deployment;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.CentralUI.Tests.Deployment;
|
||||
|
||||
/// <summary>UI-6 (WP6 6.8): Save overrides sends only the values that changed.</summary>
|
||||
public class OverrideSaveDiffTests
|
||||
{
|
||||
/// <summary>Only new or changed values are saved; an unchanged override (of ~260) is not.</summary>
|
||||
[Fact]
|
||||
public void Changed_ReturnsOnlyNewOrDifferentValues()
|
||||
{
|
||||
var existing = Enumerable.Range(0, 260).ToDictionary(
|
||||
i => $"A{i}", i => new InstanceAttributeOverride($"A{i}") { OverrideValue = i.ToString() });
|
||||
var working = existing.ToDictionary(kv => kv.Key, kv => kv.Value.OverrideValue);
|
||||
working["A7"] = "changed";
|
||||
working["New"] = "1";
|
||||
|
||||
var changed = OverrideSaveDiff.Changed(working, existing);
|
||||
|
||||
Assert.Equal(new[] { ("A7", (string?)"changed"), ("New", (string?)"1") },
|
||||
changed.OrderBy(c => c.Name).ToArray());
|
||||
}
|
||||
}
|
||||
+40
-1
@@ -29,15 +29,54 @@ public class SandboxWorkerIsolationTests
|
||||
{
|
||||
await allEntered.Task.WaitAsync(TimeSpan.FromSeconds(8));
|
||||
var fifthStarted = false;
|
||||
// UI-13: the queue wait is charged to the start-up ceiling; shrink it so the
|
||||
// queued fifth run still gives up quickly here.
|
||||
SandboxWorkerProtocol.StartupCeiling = TimeSpan.Zero;
|
||||
var fifth = await SandboxWorkerProtocol.RunCoreAsync(new SandboxRunRequest("return 1;", null, 1),
|
||||
services, catalog, CancellationToken.None, _ => fifthStarted = true);
|
||||
Assert.Equal(SandboxErrorKind.Timeout, fifth.ErrorKind);
|
||||
Assert.False(fifthStarted);
|
||||
}
|
||||
finally { release.TrySetResult(new ExternalCallResult(true, "null", null)); }
|
||||
finally
|
||||
{
|
||||
SandboxWorkerProtocol.StartupCeiling = TimeSpan.FromSeconds(30);
|
||||
release.TrySetResult(new ExternalCallResult(true, "null", null));
|
||||
}
|
||||
foreach (var result in await Task.WhenAll(workers)) Assert.True(result.Success, result.Error);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// UI-13 (WP6 6.8): the script deadline starts when the worker reports user code is about to
|
||||
/// run. A 1-second run queued behind four busy Test Runs for ~2 s (plus a cold worker start)
|
||||
/// used to report "exceeded the 1-second sandbox timeout"; it now succeeds.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task QueuedAndColdStartTime_IsNotChargedToTheScriptBudget()
|
||||
{
|
||||
var allEntered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var release = new TaskCompletionSource<ExternalCallResult>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var count = 0;
|
||||
var external = Substitute.For<IExternalSystemClient>();
|
||||
external.CallAsync("probe", "blocked", Arg.Any<IReadOnlyDictionary<string, object?>?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_ => { if (Interlocked.Increment(ref count) == 4) allEntered.TrySetResult(); return release.Task; });
|
||||
using var services = new ServiceCollection().AddSingleton(external).BuildServiceProvider();
|
||||
var catalog = Substitute.For<ISharedScriptCatalog>();
|
||||
var busy = Enumerable.Range(0, 4).Select(_ => SandboxWorkerProtocol.RunAsync(new SandboxRunRequest(
|
||||
"await ExternalSystem.Call(\"probe\", \"blocked\"); return 42;", null, 10), services, catalog, CancellationToken.None)).ToArray();
|
||||
await allEntered.Task.WaitAsync(TimeSpan.FromSeconds(10));
|
||||
|
||||
var queued = SandboxWorkerProtocol.RunAsync(new SandboxRunRequest("return 7;", null, 1),
|
||||
services, catalog, CancellationToken.None);
|
||||
await Task.Delay(TimeSpan.FromSeconds(2)); // queued longer than its whole 1 s script budget
|
||||
release.TrySetResult(new ExternalCallResult(true, "null", null));
|
||||
|
||||
var result = await queued.WaitAsync(TimeSpan.FromSeconds(30));
|
||||
Assert.True(result.Success, result.Error);
|
||||
Assert.Equal("7", result.ReturnValueJson);
|
||||
foreach (var r in await Task.WhenAll(busy)) Assert.True(r.Success, r.Error);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that an uncooperative broker still has its child killed at the deadline and keeps the lifetime until the broker completes.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
|
||||
+43
@@ -65,6 +65,49 @@ public class SitePairChannelProviderFailbackTests
|
||||
Assert.Equal(TimeSpan.FromSeconds(4), provider.GetFailbackBackoff(Site));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// COMM-8 (WP6 6.10): due failback probes run concurrently (bounded), so one slow NodeA per
|
||||
/// site no longer serialises the pass — 16 sites with a 400 ms probe each finish in well
|
||||
/// under the 6.4 s a serial pass takes, and never more than the bound run at once.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task DueProbes_RunConcurrently_UpToTheBound()
|
||||
{
|
||||
var inFlight = 0;
|
||||
var maxInFlight = 0;
|
||||
using var provider = Build(async (_, ct) =>
|
||||
{
|
||||
var now = Interlocked.Increment(ref inFlight);
|
||||
int seen;
|
||||
while ((seen = Volatile.Read(ref maxInFlight)) < now && Interlocked.CompareExchange(ref maxInFlight, now, seen) != seen) { }
|
||||
await Task.Delay(400, ct);
|
||||
Interlocked.Decrement(ref inFlight);
|
||||
return false;
|
||||
});
|
||||
const int sites = 16;
|
||||
for (var i = 0; i < sites; i++)
|
||||
{
|
||||
var site = $"site-{i}";
|
||||
provider.UpdateSite(site, $"http://localhost:{16000 + i}", $"http://localhost:{17000 + i}");
|
||||
GrpcChannel? first = null;
|
||||
await provider.ExecuteAsync(site, (channel, _) =>
|
||||
{
|
||||
if (first is null) { first = channel; throw GrpcRetrySafety.NotDispatched("not ready"); }
|
||||
return Task.FromResult(1);
|
||||
}, CancellationToken.None);
|
||||
Assert.False(provider.IsOnPreferredNode(site));
|
||||
}
|
||||
|
||||
var sw = System.Diagnostics.Stopwatch.StartNew();
|
||||
await provider.RunDueFailbackProbesAsync(DateTime.UtcNow.AddMinutes(1), CancellationToken.None);
|
||||
sw.Stop();
|
||||
|
||||
Assert.True(sw.Elapsed < TimeSpan.FromSeconds(3), $"probe pass took {sw.ElapsedMilliseconds} ms");
|
||||
Assert.True(maxInFlight > 1, "probes did not run concurrently");
|
||||
Assert.True(maxInFlight <= SitePairChannelProvider.FailbackProbeParallelism);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that a successful real call on the preferred node after failback resets the backoff.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
|
||||
+1
@@ -186,6 +186,7 @@ public class AuditLogEntityTypeConfigurationTests : IDisposable
|
||||
var expected = new[]
|
||||
{
|
||||
"IX_AuditLog_Actor_Occurred",
|
||||
"IX_AuditLog_Channel_Occurred", // AuditLogChannelOccurredIndex (AUD-5)
|
||||
"IX_AuditLog_Channel_Status_Occurred",
|
||||
"IX_AuditLog_CorrelationId",
|
||||
"IX_AuditLog_Execution",
|
||||
|
||||
+5
-1
@@ -70,7 +70,11 @@ public sealed class FlipAuditLogClusteredKeyMigrationTests : IClassFixture<MsSql
|
||||
Assert.True(indexes["PK_AuditLog"].Clustered);
|
||||
Assert.Equal("EventId, OccurredAtUtc", indexes["UX_AuditLog_EventId_Occurred"].Keys);
|
||||
Assert.True(indexes["UX_AuditLog_EventId_Occurred"].Unique);
|
||||
Assert.Equal(NonClusteredIndexes.Length + 2, indexes.Count);
|
||||
// + PK + UX + IX_AuditLog_Channel_Occurred (AuditLogChannelOccurredIndex, AUD-5 — added
|
||||
// after the flip, so the pre-flip round-trip shape below does not carry it).
|
||||
Assert.Equal(NonClusteredIndexes.Length + 3, indexes.Count);
|
||||
Assert.Equal("Category, OccurredAtUtc", indexes["IX_AuditLog_Channel_Occurred"].Keys);
|
||||
Assert.False(indexes["IX_AuditLog_Channel_Occurred"].Clustered);
|
||||
Assert.All(indexes.Values, i => Assert.Equal("ps_AuditLog_Month", i.DataSpace));
|
||||
AssertNonClusteredIndexes(indexes, withChainIndexes: false);
|
||||
Assert.Equal(ExpectedGrants, await ReadGrantsAsync());
|
||||
|
||||
+22
@@ -84,6 +84,28 @@ public class PendingDeploymentRepositoryTests : IDisposable
|
||||
Assert.Equal(instanceId, current.InstanceId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DEP-5 (WP6 6.6): a prior pending row that the TTL purge (or reconciliation) deleted
|
||||
/// after this context loaded it must not fail the superseding stage with a concurrency
|
||||
/// error — the supersede is a set-based delete, not tracked key stubs.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task AddPendingDeployment_PriorRowDeletedConcurrently_DoesNotThrow()
|
||||
{
|
||||
var instanceId = await SeedInstanceAsync("Inst-race");
|
||||
await _repository.AddPendingDeploymentAsync(NewPending("depA", instanceId, "{}"));
|
||||
await _repository.SaveChangesAsync(); // depA is now tracked by this context
|
||||
|
||||
await _repository.AddPendingDeploymentAsync(NewPending("depB", instanceId, "{}"));
|
||||
// Between the supersede and the save, the purge actor removes depA on its own
|
||||
// connection/context (ExecuteDelete of expired rows).
|
||||
await _context.Database.ExecuteSqlRawAsync("DELETE FROM PendingDeployments WHERE DeploymentId = 'depA'");
|
||||
await _repository.SaveChangesAsync();
|
||||
|
||||
Assert.NotNull(await _repository.GetPendingDeploymentByIdAsync("depB"));
|
||||
}
|
||||
|
||||
/// <summary>Verifies that pending deployments for different instances coexist.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
|
||||
+23
@@ -24,10 +24,31 @@ public class AuditPurgeBudgetTests
|
||||
Assert.Equal(ConnectionState.Closed, connection.State);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// AUD-5 (WP6 6.5): the channel is bound as varchar(32) to match the Category column — an
|
||||
/// nvarchar parameter makes SQL Server convert the column under a SQL collation and rules
|
||||
/// out a seek on IX_AuditLog_Channel_Occurred.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task ChannelParameter_IsBoundAsVarchar32()
|
||||
{
|
||||
using var connection = new BackloggedConnection();
|
||||
await using var context = new ScadaBridgeDbContext(new DbContextOptionsBuilder<ScadaBridgeDbContext>()
|
||||
.UseSqlServer(connection).Options);
|
||||
await new AuditLogRepository(context).PurgeChannelOlderThanAsync(
|
||||
"ScriptTrace", DateTime.UtcNow, batchSize: 3, maxRows: 3);
|
||||
var channel = Assert.Single(connection.ChannelParameters);
|
||||
Assert.Equal(SqlDbType.VarChar, channel.Type);
|
||||
Assert.Equal(32, channel.Size);
|
||||
}
|
||||
|
||||
private sealed class BackloggedConnection : DbConnection
|
||||
{
|
||||
/// <summary>Gets the batch sizes requested by the purge, in order.</summary>
|
||||
public List<int> RequestedBatches { get; } = new();
|
||||
/// <summary>Gets the SQL type and size of each bound <c>@channel</c> parameter, in order.</summary>
|
||||
public List<(SqlDbType Type, int Size)> ChannelParameters { get; } = new();
|
||||
private ConnectionState _state;
|
||||
/// <inheritdoc />
|
||||
[AllowNull] public override string ConnectionString { get; set; } = "Server=localhost;Database=test";
|
||||
@@ -81,6 +102,8 @@ public class AuditPurgeBudgetTests
|
||||
throw new InvalidOperationException("Purge did not yield despite exhausting its row budget.");
|
||||
var requested = (int)_parameters.Parameters["@batch"].Value;
|
||||
owner.RequestedBatches.Add(requested);
|
||||
var channel = _parameters.Parameters["@channel"];
|
||||
owner.ChannelParameters.Add((channel.SqlDbType, channel.Size));
|
||||
return requested;
|
||||
}
|
||||
/// <inheritdoc />
|
||||
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
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.Types.Enums;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Templates;
|
||||
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Repositories;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests.Repositories;
|
||||
|
||||
/// <summary>
|
||||
/// WP6 task 6.6 (DEP-4, DEP-6, TPL-4): the targeted, untracked repository reads that replace
|
||||
/// whole-graph or per-row tracked loads, asserted against real SQL on SQLite.
|
||||
/// </summary>
|
||||
public class TargetedLoadRepositoryTests : IDisposable
|
||||
{
|
||||
private readonly ScadaBridgeDbContext _context;
|
||||
private readonly TemplateEngineRepository _templates;
|
||||
private readonly DeploymentManagerRepository _deployments;
|
||||
|
||||
/// <summary>Initializes the test class with an in-memory context and the repositories.</summary>
|
||||
public TargetedLoadRepositoryTests()
|
||||
{
|
||||
_context = SqliteTestHelper.CreateInMemoryContext();
|
||||
_templates = new TemplateEngineRepository(_context, new TemplateGraphWatermark());
|
||||
_deployments = new DeploymentManagerRepository(_context);
|
||||
}
|
||||
|
||||
/// <summary>Releases the resources held by this test class.</summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_context.Database.CloseConnection();
|
||||
_context.Dispose();
|
||||
}
|
||||
|
||||
private async Task<(int SiteId, int TemplateId, List<int> InstanceIds)> SeedAsync(int instances)
|
||||
{
|
||||
var site = new Site("Site", "S1");
|
||||
var template = new Template("T");
|
||||
_context.Sites.Add(site);
|
||||
_context.Templates.Add(template);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
var ids = new List<int>();
|
||||
for (var i = 0; i < instances; i++)
|
||||
{
|
||||
var instance = new Instance($"I{i:0000}") { SiteId = site.Id, TemplateId = template.Id };
|
||||
instance.AttributeOverrides.Add(new InstanceAttributeOverride("A") { OverrideValue = i.ToString() });
|
||||
_context.Instances.Add(instance);
|
||||
}
|
||||
await _context.SaveChangesAsync();
|
||||
ids.AddRange(await _context.Instances.Select(i => i.Id).ToListAsync());
|
||||
_context.ChangeTracker.Clear();
|
||||
return (site.Id, template.Id, ids);
|
||||
}
|
||||
|
||||
/// <summary>DEP-4: the batched loader returns every requested instance with its children, untracked, across chunks.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task GetInstancesByIdsUntracked_LoadsChildren_AcrossChunks_WithoutTracking()
|
||||
{
|
||||
var (_, _, ids) = await SeedAsync(620);
|
||||
|
||||
var loaded = await _templates.GetInstancesByIdsUntrackedAsync(ids.Append(ids[0]).Append(-1).ToList());
|
||||
|
||||
Assert.Equal(ids.Count, loaded.Count);
|
||||
Assert.All(loaded, i => Assert.Single(i.AttributeOverrides));
|
||||
Assert.Empty(_context.ChangeTracker.Entries());
|
||||
}
|
||||
|
||||
/// <summary>TPL-4: the shallow site read carries no child collections and tracks nothing.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task GetInstancesBySiteIdShallow_IsUntracked_AndCarriesNoChildren()
|
||||
{
|
||||
var (siteId, _, ids) = await SeedAsync(3);
|
||||
|
||||
var shallow = await _templates.GetInstancesBySiteIdShallowAsync(siteId);
|
||||
|
||||
Assert.Equal(ids.Count, shallow.Count);
|
||||
Assert.All(shallow, i => Assert.Empty(i.AttributeOverrides));
|
||||
Assert.Empty(_context.ChangeTracker.Entries());
|
||||
}
|
||||
|
||||
/// <summary>TPL-4: the folder-move collision check is a case-insensitive sibling-name query that excludes the moved template.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task TemplateNameExistsInFolder_IsCaseInsensitive_AndExcludesSelf()
|
||||
{
|
||||
var folder = new TemplateFolder("F");
|
||||
_context.TemplateFolders.Add(folder);
|
||||
await _context.SaveChangesAsync();
|
||||
var inFolder = new Template("Pump") { FolderId = folder.Id };
|
||||
var atRoot = new Template("Valve");
|
||||
_context.Templates.AddRange(inFolder, atRoot);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
Assert.True(await _templates.TemplateNameExistsInFolderAsync(folder.Id, "PUMP", atRoot.Id));
|
||||
Assert.False(await _templates.TemplateNameExistsInFolderAsync(folder.Id, "Pump", inFolder.Id));
|
||||
Assert.False(await _templates.TemplateNameExistsInFolderAsync(null, "Pump", atRoot.Id));
|
||||
Assert.True(await _templates.TemplateNameExistsInFolderAsync(null, "valve", inFolder.Id));
|
||||
}
|
||||
|
||||
/// <summary>DEP-6: the state read sees a state committed after this context loaded (and tracks) the instance.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task GetInstanceState_BypassesIdentityResolution()
|
||||
{
|
||||
var (_, _, ids) = await SeedAsync(1);
|
||||
var tracked = await _context.Instances.SingleAsync(i => i.Id == ids[0]);
|
||||
Assert.Equal(InstanceState.NotDeployed, tracked.State);
|
||||
|
||||
await _context.Database.ExecuteSqlRawAsync(
|
||||
"UPDATE Instances SET State = {0} WHERE Id = {1}", InstanceState.Disabled.ToString(), ids[0]);
|
||||
|
||||
Assert.Equal(InstanceState.NotDeployed, (await _context.Instances.SingleAsync(i => i.Id == ids[0])).State);
|
||||
Assert.Equal(InstanceState.Disabled, await _deployments.GetInstanceStateAsync(ids[0]));
|
||||
Assert.Null(await _deployments.GetInstanceStateAsync(-1));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using Google.Protobuf.Collections;
|
||||
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Protocol;
|
||||
using ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Adapters;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests;
|
||||
|
||||
/// <summary>DCL-10 (WP6 6.10): MxGateway quality mapping is table-driven and allocation-free.</summary>
|
||||
public class MxGatewayQualityMapTests
|
||||
{
|
||||
/// <summary>The quality byte maps exactly as the former range switch did.</summary>
|
||||
[Theory]
|
||||
[InlineData(-5, QualityCode.Bad)]
|
||||
[InlineData(0, QualityCode.Bad)]
|
||||
[InlineData(63, QualityCode.Bad)]
|
||||
[InlineData(64, QualityCode.Uncertain)]
|
||||
[InlineData(191, QualityCode.Uncertain)]
|
||||
[InlineData(192, QualityCode.Good)]
|
||||
[InlineData(255, QualityCode.Good)]
|
||||
[InlineData(1000, QualityCode.Good)]
|
||||
public void QualityByte_Maps(int quality, QualityCode expected)
|
||||
=> Assert.Equal(expected, RealMxGatewayClient.MapQuality(quality, new RepeatedField<MxStatusProxy>()));
|
||||
|
||||
/// <summary>A failing status is authoritative Bad; a success status defers to the byte.</summary>
|
||||
[Fact]
|
||||
public void FailingStatus_IsBad()
|
||||
{
|
||||
var ok = new RepeatedField<MxStatusProxy> { new MxStatusProxy { Category = MxStatusCategory.Ok } };
|
||||
var failing = new RepeatedField<MxStatusProxy> { new MxStatusProxy { Category = MxStatusCategory.Ok }, new MxStatusProxy() };
|
||||
Assert.Equal(QualityCode.Good, RealMxGatewayClient.MapQuality(192, ok));
|
||||
Assert.Equal(QualityCode.Bad, RealMxGatewayClient.MapQuality(192, failing));
|
||||
}
|
||||
|
||||
/// <summary>The per-event path allocates nothing (the old Any() boxed the enumerator per call).</summary>
|
||||
[Fact]
|
||||
public void MapQuality_DoesNotAllocate()
|
||||
{
|
||||
var statuses = new RepeatedField<MxStatusProxy> { new MxStatusProxy { Category = MxStatusCategory.Ok } };
|
||||
RealMxGatewayClient.MapQuality(192, statuses); // warm
|
||||
var before = GC.GetAllocatedBytesForCurrentThread();
|
||||
for (var i = 0; i < 10_000; i++)
|
||||
RealMxGatewayClient.MapQuality(192, statuses);
|
||||
Assert.Equal(0, GC.GetAllocatedBytesForCurrentThread() - before);
|
||||
}
|
||||
}
|
||||
@@ -397,6 +397,62 @@ public class DeploySiteAsyncTests : TestKit
|
||||
Arg.Is<DeploymentRecord>(r => r.InstanceId == 2 || r.InstanceId == 4), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DEP-6 (WP6 6.6): an instance Disabled by another request AFTER the batch loaded its
|
||||
/// candidates is caught by the fresh, lock-held state read — skipped, never flattened,
|
||||
/// sent or finalised as enabled.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task DeploySiteAsync_InstanceDisabledAfterTheBatchStarted_IsSkippedNotReEnabled()
|
||||
{
|
||||
ArrangeInstances(3);
|
||||
// The candidate list (and the tracked entity Prepare re-reads) still says NotDeployed,
|
||||
// but the database already holds the operator's Disable.
|
||||
_repo.GetInstanceStateAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ci => ci.ArgAt<int>(0) == 2 ? InstanceState.Disabled : InstanceState.NotDeployed);
|
||||
|
||||
var commActor = Sys.ActorOf(Props.Create(() =>
|
||||
new ThrottledSiteActor(new ConcurrencyTracker(), slowInstanceName: null, slowDelay: TimeSpan.Zero)));
|
||||
|
||||
var result = await CreateService(commActor, maxParallelism: 2).DeploySiteAsync(SiteId, "admin");
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal(2, result.Value.SuccessCount);
|
||||
Assert.DoesNotContain(result.Value.InstanceResults, r => r.UniqueName == "Inst-02");
|
||||
var skipped = Assert.Single(result.Value.SkippedInstances!);
|
||||
Assert.Equal("Inst-02", skipped.UniqueName);
|
||||
await _pipeline.DidNotReceive().FlattenAndValidateAsync(
|
||||
2, Arg.Any<CancellationToken>(), Arg.Any<bool>(), Arg.Any<FlattenSession?>());
|
||||
await _repo.DidNotReceive().AddDeploymentRecordAsync(
|
||||
Arg.Is<DeploymentRecord>(r => r.InstanceId == 2), Arg.Any<CancellationToken>());
|
||||
Assert.False(_lockManager.IsLocked("Inst-02"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DEP-5 (WP6 6.6): a failed staging save drops its pending changes from the shared
|
||||
/// context, so the instances staged after it are not poisoned by the same failure.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task DeploySiteAsync_FailedStagingWrite_DetachesItsPendingChanges()
|
||||
{
|
||||
ArrangeInstances(3);
|
||||
_repo.AddPendingDeploymentAsync(
|
||||
Arg.Is<PendingDeployment>(p => p.InstanceId == 1), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromException(new InvalidOperationException("staging save lost a race")));
|
||||
|
||||
var commActor = Sys.ActorOf(Props.Create(() =>
|
||||
new ThrottledSiteActor(new ConcurrencyTracker(), slowInstanceName: null, slowDelay: TimeSpan.Zero)));
|
||||
|
||||
var result = await CreateService(commActor, maxParallelism: 1).DeploySiteAsync(SiteId, "admin");
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal(2, result.Value.SuccessCount);
|
||||
Assert.Equal("Inst-01", Assert.Single(result.Value.InstanceResults, r => !r.Success).UniqueName);
|
||||
_repo.Received().DetachPendingChanges();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Phase 1 is serial, so an unreachable site used to cost the batch one
|
||||
/// full 30-second <c>QueryTimeout</c> PER INSTANCE before a single deploy was
|
||||
|
||||
+30
-1
@@ -1,3 +1,4 @@
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
|
||||
using System.Text.Json;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
@@ -35,6 +36,9 @@ public class DeploymentServiceStalenessTests
|
||||
private readonly RevisionHashService _hasher = new();
|
||||
private readonly DeploymentService _service;
|
||||
|
||||
/// <summary>DEP-4: the batched untracked instance loader the staleness read preloads from.</summary>
|
||||
private readonly ITemplateEngineRepository _templateRepo = Substitute.For<ITemplateEngineRepository>();
|
||||
|
||||
/// <summary>The single session every flatten in a batch must share.</summary>
|
||||
private readonly FlattenSession _session = new(new TemplateGraphWatermark());
|
||||
|
||||
@@ -61,7 +65,7 @@ public class DeploymentServiceStalenessTests
|
||||
_service = new DeploymentService(
|
||||
_repo,
|
||||
siteRepo,
|
||||
Substitute.For<ITemplateEngineRepository>(),
|
||||
_templateRepo,
|
||||
_pipeline,
|
||||
new CommunicationService(
|
||||
Options.Create(new CommunicationOptions()),
|
||||
@@ -182,6 +186,31 @@ public class DeploymentServiceStalenessTests
|
||||
await _pipeline.Received(1).ComputeRevisionHashAsync(3, _session, Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DEP-4 (WP6 6.6): the deployed instances are bulk-loaded untracked (one call for the
|
||||
/// batch) and handed to the shared session, instead of one tracked load per flatten.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task GetInstanceStalenessAsync_BulkPreloadsDeployedInstancesUntracked()
|
||||
{
|
||||
var config = ScalarConfig("5");
|
||||
var hash = _hasher.ComputeHash(config);
|
||||
ArrangeDeployedHashes((1, hash), (2, hash));
|
||||
ArrangeFlatten(1, config, hash);
|
||||
ArrangeFlatten(2, config, hash);
|
||||
_templateRepo.GetInstancesByIdsUntrackedAsync(Arg.Any<IReadOnlyCollection<int>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ci => (IReadOnlyList<Instance>)ci.ArgAt<IReadOnlyCollection<int>>(0)
|
||||
.Select(id => new Instance($"I{id}") { Id = id }).ToList());
|
||||
|
||||
await _service.GetInstanceStalenessAsync([1, 2, 3]); // 3 is not deployed: never loaded
|
||||
|
||||
await _templateRepo.Received(1).GetInstancesByIdsUntrackedAsync(
|
||||
Arg.Is<IReadOnlyCollection<int>>(ids => ids.Order().SequenceEqual(new[] { 1, 2 })),
|
||||
Arg.Any<CancellationToken>());
|
||||
Assert.NotNull(_session.TakePreloadedInstance(1));
|
||||
}
|
||||
|
||||
/// <summary>Verifies that a matching hash is reported as not stale and no snapshot is read.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
|
||||
@@ -97,6 +97,30 @@ public class FlattenSessionCacheTests
|
||||
await _siteRepo.Received(1).GetDataConnectionsBySiteIdAsync(SiteId, Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DEP-4 (WP6 6.6): an instance bulk-preloaded into the session is flattened from the
|
||||
/// session — no per-instance tracked repository load — and is consumed once taken.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task PreloadedInstances_AreFlattenedWithoutPerInstanceLoads()
|
||||
{
|
||||
const int instanceCount = 5;
|
||||
ArrangeSharedChain(instanceCount);
|
||||
|
||||
var session = _sut.CreateSession();
|
||||
session.PreloadInstances(Enumerable.Range(1, instanceCount)
|
||||
.Select(i => new Instance($"Tank-{i:00}") { Id = i, TemplateId = TemplateId, SiteId = SiteId }));
|
||||
for (var i = 1; i <= instanceCount; i++)
|
||||
{
|
||||
var result = await _sut.ComputeRevisionHashAsync(i, session, CancellationToken.None);
|
||||
Assert.True(result.IsSuccess);
|
||||
}
|
||||
|
||||
await _templateRepo.DidNotReceive().GetInstanceByIdAsync(Arg.Any<int>(), Arg.Any<CancellationToken>());
|
||||
Assert.Null(session.TakePreloadedInstance(1));
|
||||
}
|
||||
|
||||
/// <summary>Verifies that no shared session, every instance reloads the chain.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
using NSubstitute;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Schemas;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
|
||||
using ZB.MOM.WW.ScadaBridge.InboundAPI.Middleware;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.InboundAPI.Tests;
|
||||
|
||||
/// <summary>WP6 task 6.9: INB-2 (library snapshot), INB-3 (scratch sizing), INB-4 (time-based replay prune).</summary>
|
||||
public class Wp6InboundPerfTests
|
||||
{
|
||||
private const string RefDefinition = """[{"name":"p","type":"Object","$ref":"lib:Shape"}]""";
|
||||
|
||||
/// <summary>INB-2: repeated $ref resolution within the TTL reads the library once; after the TTL it reloads.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task SchemaLibrary_IsReadOncePerTtl_NotPerResolution()
|
||||
{
|
||||
var repo = Substitute.For<ISharedSchemaRepository>();
|
||||
repo.ListAsync(Arg.Any<CancellationToken>()).Returns(new List<SharedSchema> { new() { Name = "Shape", SchemaJson = "{\"type\":\"object\"}" } });
|
||||
var clock = new ManualClock(DateTimeOffset.UtcNow);
|
||||
var cache = new SharedSchemaLibraryCache(TimeSpan.FromSeconds(5), clock);
|
||||
|
||||
for (var i = 0; i < 100; i++)
|
||||
{
|
||||
var resolve = await SchemaRefResolver.BuildAsync(repo, [RefDefinition], cache);
|
||||
Assert.NotNull(resolve!("Shape"));
|
||||
}
|
||||
await repo.Received(1).ListAsync(Arg.Any<CancellationToken>());
|
||||
|
||||
clock.Advance(TimeSpan.FromSeconds(6));
|
||||
await SchemaRefResolver.BuildAsync(repo, [RefDefinition], cache);
|
||||
await repo.Received(2).ListAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>INB-3: the audit scratch buffer is sized to the declared body, not the 1 MiB cap.</summary>
|
||||
[Theory]
|
||||
[InlineData(200L, 1_048_576, 200)]
|
||||
[InlineData(null, 1_048_576, 1_048_576)]
|
||||
[InlineData(5_000_000L, 1_048_576, 1_048_576)]
|
||||
[InlineData(-1L, 1_048_576, 1_048_576)]
|
||||
public void AuditScratch_IsSizedToContentLength(long? contentLength, int cap, int expected)
|
||||
=> Assert.Equal(expected, AuditWriteMiddleware.ExpectedCaptureBytes(contentLength, cap));
|
||||
|
||||
/// <summary>INB-4: past the prune threshold, a burst of relayed proofs triggers at most one full scan per interval.</summary>
|
||||
[Fact]
|
||||
public void ReplayCache_PrunesOnATimeBasis_NotPerRequest()
|
||||
{
|
||||
var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
|
||||
for (var i = 0; i < 5000; i++)
|
||||
Assert.True(RelayProvenance.TryRecordProof(Guid.NewGuid(), "n", now));
|
||||
|
||||
var before = Volatile.Read(ref RelayProvenance.PruneScans);
|
||||
for (var i = 0; i < 2000; i++)
|
||||
Assert.True(RelayProvenance.TryRecordProof(Guid.NewGuid(), "n", now));
|
||||
|
||||
Assert.True(Volatile.Read(ref RelayProvenance.PruneScans) - before <= 1,
|
||||
"the replay cache was scanned more than once inside one prune interval");
|
||||
// ...and a replay is still refused.
|
||||
var id = Guid.NewGuid();
|
||||
Assert.True(RelayProvenance.TryRecordProof(id, "x", now));
|
||||
Assert.False(RelayProvenance.TryRecordProof(id, "x", now));
|
||||
}
|
||||
|
||||
private sealed class ManualClock(DateTimeOffset start) : TimeProvider
|
||||
{
|
||||
private DateTimeOffset _now = start;
|
||||
/// <summary>Advances the clock.</summary>
|
||||
/// <param name="by">The amount to advance.</param>
|
||||
public void Advance(TimeSpan by) => _now += by;
|
||||
/// <inheritdoc />
|
||||
public override DateTimeOffset GetUtcNow() => _now;
|
||||
}
|
||||
}
|
||||
@@ -1192,6 +1192,9 @@ public class ManagementActorTests : TestKit, IDisposable
|
||||
// (review 2026-10-21 04/P6, 08/P1).
|
||||
_templateRepo.GetAllTemplatesForAnalysisAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<Template> { template });
|
||||
// TPL-4: SetAlarmOverride reads the template's analysis closure, not the whole table.
|
||||
_templateRepo.GetTemplateAnalysisClosureAsync(template.Id, Arg.Any<CancellationToken>())
|
||||
.Returns(new List<Template> { template });
|
||||
_templateRepo.GetAlarmOverrideAsync(10, "HighTemp", Arg.Any<CancellationToken>())
|
||||
.Returns((InstanceAlarmOverride?)null);
|
||||
|
||||
@@ -4071,14 +4074,15 @@ public class ManagementActorTests : TestKit, IDisposable
|
||||
|
||||
// The repository fan-out HandleExportBundle does at the top of its body.
|
||||
// Tests that only exercise role gating still need these resolved.
|
||||
_templateRepo.GetAllTemplatesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<Template>());
|
||||
// MGT-5: template and instance names resolve against narrow projections.
|
||||
_templateRepo.GetTemplateStubsAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<Commons.Types.Templates.TemplateStub>());
|
||||
_templateRepo.GetAllSharedScriptsAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<Commons.Entities.Scripts.SharedScript>());
|
||||
// Export now also fans out to instances (template repo) and sites
|
||||
// (site repo) for the site/instance-scoped selection.
|
||||
_templateRepo.GetAllInstancesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<Instance>());
|
||||
_templateRepo.GetInstanceNamesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<(int, string)>());
|
||||
|
||||
var siteRepo = Substitute.For<ISiteRepository>();
|
||||
siteRepo.GetAllSitesAsync(Arg.Any<CancellationToken>())
|
||||
@@ -4234,8 +4238,8 @@ public class ManagementActorTests : TestKit, IDisposable
|
||||
// curated message must surface verbatim to the caller.
|
||||
AddBundleSubstitutes();
|
||||
// No templates in the repo; the export selection names one anyway.
|
||||
_templateRepo.GetAllTemplatesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<Template>());
|
||||
_templateRepo.GetTemplateStubsAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<Commons.Types.Templates.TemplateStub>());
|
||||
|
||||
var cmd = new ExportBundleCommand(
|
||||
All: false,
|
||||
@@ -4260,6 +4264,36 @@ public class ManagementActorTests : TestKit, IDisposable
|
||||
Assert.Contains("DoesNotExist", response.Error);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// MGT-5 (WP6 6.7): export resolves names against the (Id, Name) projections and never
|
||||
/// materialises the full template graph or every instance with its child collections.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void ExportBundleCommand_ResolvesNamesFromProjections_NotFullGraphs()
|
||||
{
|
||||
var (exporter, _) = AddBundleSubstitutes();
|
||||
_templateRepo.GetTemplateStubsAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<Commons.Types.Templates.TemplateStub> { new(7, "PumpBase", null, null, false, null) });
|
||||
Commons.Types.Transport.ExportSelection? captured = null;
|
||||
exporter.ExportAsync(
|
||||
Arg.Do<Commons.Types.Transport.ExportSelection>(s => captured = s),
|
||||
Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string?>(),
|
||||
Arg.Any<CancellationToken>())
|
||||
.Returns(_ => Task.FromResult<Stream>(new MemoryStream(new byte[] { 1 })));
|
||||
|
||||
var cmd = new ExportBundleCommand(
|
||||
All: false, TemplateNames: new[] { "PumpBase" }, SharedScriptNames: null,
|
||||
ExternalSystemNames: null, DatabaseConnectionNames: null,
|
||||
NotificationListNames: null, SmtpConfigurationNames: null, ApiMethodNames: null,
|
||||
IncludeDependencies: false, Passphrase: null, SourceEnvironment: "test-env");
|
||||
CreateActor().Tell(Envelope(cmd, "Designer"));
|
||||
|
||||
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
|
||||
Assert.Equal(new[] { 7 }, captured!.TemplateIds);
|
||||
_templateRepo.DidNotReceive().GetAllTemplatesAsync(Arg.Any<CancellationToken>());
|
||||
_templateRepo.DidNotReceive().GetAllInstancesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>Verifies that export bundle command, when with site and instance names, resolves to ids.</summary>
|
||||
[Fact]
|
||||
public void ExportBundleCommand_WithSiteAndInstanceNames_ResolvesToIds()
|
||||
@@ -4277,12 +4311,8 @@ public class ManagementActorTests : TestKit, IDisposable
|
||||
new("North Plant", "NORTH-01") { Id = 11 },
|
||||
new("East Plant", "EAST-02") { Id = 22 },
|
||||
});
|
||||
_templateRepo.GetAllInstancesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<Instance>
|
||||
{
|
||||
new("NORTH-01.Pump1") { Id = 101, SiteId = 11, TemplateId = 1 },
|
||||
new("NORTH-01.Pump2") { Id = 102, SiteId = 11, TemplateId = 1 },
|
||||
});
|
||||
_templateRepo.GetInstanceNamesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<(int, string)> { (101, "NORTH-01.Pump1"), (102, "NORTH-01.Pump2") });
|
||||
|
||||
Commons.Types.Transport.ExportSelection? captured = null;
|
||||
exporter.ExportAsync(
|
||||
@@ -4328,12 +4358,8 @@ public class ManagementActorTests : TestKit, IDisposable
|
||||
new("North Plant", "NORTH-01") { Id = 11 },
|
||||
new("East Plant", "EAST-02") { Id = 22 },
|
||||
});
|
||||
_templateRepo.GetAllInstancesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<Instance>
|
||||
{
|
||||
new("NORTH-01.Pump1") { Id = 101, SiteId = 11, TemplateId = 1 },
|
||||
new("EAST-02.Pump9") { Id = 909, SiteId = 22, TemplateId = 1 },
|
||||
});
|
||||
_templateRepo.GetInstanceNamesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<(int, string)> { (101, "NORTH-01.Pump1"), (909, "EAST-02.Pump9") });
|
||||
|
||||
Commons.Types.Transport.ExportSelection? captured = null;
|
||||
exporter.ExportAsync(
|
||||
|
||||
@@ -84,6 +84,7 @@ public class SchemaIndexTests : IDisposable
|
||||
[Theory]
|
||||
[InlineData("severity", "idx_events_severity_timestamp")]
|
||||
[InlineData("event_type", "idx_events_type_timestamp")]
|
||||
[InlineData("instance_id", "idx_events_instance_timestamp")] // SEL-1 (WP6 6.5)
|
||||
public void EqualityFilteredPage_ReadsInTimestampOrder_WithoutSortingEveryMatch(string column, string expectedIndex)
|
||||
{
|
||||
foreach (var window in new[] { "", "AND timestamp >= '2026-01-01' " })
|
||||
@@ -135,7 +136,7 @@ public class SchemaIndexTests : IDisposable
|
||||
while (reader.Read()) indexes.Add(reader.GetString(0));
|
||||
|
||||
Assert.Equal(
|
||||
["idx_events_instance", "idx_events_severity_timestamp", "idx_events_timestamp", "idx_events_type_timestamp"],
|
||||
["idx_events_instance_timestamp", "idx_events_severity_timestamp", "idx_events_timestamp", "idx_events_type_timestamp"],
|
||||
indexes);
|
||||
using var count = connection.CreateCommand();
|
||||
count.CommandText = "SELECT COUNT(*) FROM site_events INDEXED BY idx_events_severity_timestamp WHERE severity = 'Info'";
|
||||
|
||||
@@ -121,7 +121,7 @@ public class SiteEventLogSchemaTests
|
||||
while (reader.Read()) indexes.Add(reader.GetString(0));
|
||||
|
||||
Assert.Equal(
|
||||
["idx_events_instance", "idx_events_severity_timestamp", "idx_events_timestamp", "idx_events_type_timestamp"],
|
||||
["idx_events_instance_timestamp", "idx_events_severity_timestamp", "idx_events_timestamp", "idx_events_type_timestamp"],
|
||||
indexes);
|
||||
}
|
||||
|
||||
|
||||
+4
-4
@@ -75,7 +75,7 @@ public class SiteEventsSchemaCalibrationTests
|
||||
Assert.True(
|
||||
indexes.SequenceEqual(
|
||||
[
|
||||
"idx_events_instance",
|
||||
"idx_events_instance_timestamp",
|
||||
"idx_events_severity_timestamp",
|
||||
"idx_events_timestamp",
|
||||
"idx_events_type_timestamp",
|
||||
@@ -89,14 +89,14 @@ public class SiteEventsSchemaCalibrationTests
|
||||
/// <param name="expectedColumns">The columns the index is expected to cover, comma-separated, in key order.</param>
|
||||
[Theory]
|
||||
[InlineData("idx_events_timestamp", "timestamp")]
|
||||
[InlineData("idx_events_instance", "instance_id")]
|
||||
[InlineData("idx_events_instance_timestamp", "instance_id,timestamp")]
|
||||
[InlineData("idx_events_type_timestamp", "event_type,timestamp")]
|
||||
[InlineData("idx_events_severity_timestamp", "severity,timestamp")]
|
||||
public void EachIndex_CoversExactlyTheColumnsTheSamplerSums(string indexName, string expectedColumns)
|
||||
{
|
||||
// The sampler's indexed_bytes expression sums 3 * octet_length(timestamp) +
|
||||
// The sampler's indexed_bytes expression sums 4 * octet_length(timestamp) +
|
||||
// octet_length(event_type) + octet_length(severity) + octet_length(instance_id):
|
||||
// timestamp once for its own index and once for each of the two composites (#123).
|
||||
// timestamp once for its own index and once for each of the three composites (#123, SEL-1).
|
||||
// Widening or re-pointing an index changes the real entry width without changing
|
||||
// what is sampled.
|
||||
using var connection = OpenWithSchema();
|
||||
|
||||
+45
@@ -116,6 +116,51 @@ public class InstanceActorChildRoutingTests : TestKit, IDisposable
|
||||
Assert.Single(actor.AllChangeChildren);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SRT-7 (WP6 6.2): an Expression script/alarm whose reads are literal keys is routed only to
|
||||
/// those attributes, so a change to any other attribute no longer reaches it.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void LiteralKeyExpression_RoutesOnlyToTheAttributesItReads()
|
||||
{
|
||||
var config = new FlattenedConfiguration
|
||||
{
|
||||
InstanceUniqueName = "ExprKeyPump",
|
||||
Attributes =
|
||||
[
|
||||
new ResolvedAttribute { CanonicalName = "A", Value = "1", DataType = "Double" },
|
||||
new ResolvedAttribute { CanonicalName = "B", Value = "2", DataType = "Double" },
|
||||
new ResolvedAttribute { CanonicalName = "C", Value = "3", DataType = "Double" }
|
||||
],
|
||||
Scripts =
|
||||
[
|
||||
new ResolvedScript
|
||||
{
|
||||
CanonicalName = "S_expr", Code = "return 3;",
|
||||
TriggerType = "Expression",
|
||||
TriggerConfiguration = "{\"expression\":\"(double)Attributes[\\\"A\\\"] > (double)Attributes[\\\"B\\\"]\"}"
|
||||
}
|
||||
],
|
||||
Alarms =
|
||||
[
|
||||
new ResolvedAlarm
|
||||
{
|
||||
CanonicalName = "ExprAlarm",
|
||||
TriggerType = "Expression",
|
||||
TriggerConfiguration = "{\"expression\":\"(double)Attributes[\\\"B\\\"] > 1\"}",
|
||||
PriorityLevel = 1
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
var actor = BuildInstance(config);
|
||||
|
||||
Assert.Empty(actor.AllChangeChildren);
|
||||
Assert.Single(actor.ChildrenByMonitoredAttribute["A"]); // the script
|
||||
Assert.Equal(2, actor.ChildrenByMonitoredAttribute["B"].Count); // script + alarm
|
||||
Assert.False(actor.ChildrenByMonitoredAttribute.ContainsKey("C"));
|
||||
}
|
||||
|
||||
/// <summary>Verifies that a monitored-attribute alarm routes only to its attribute while an expression alarm routes to all changes.</summary>
|
||||
[Fact]
|
||||
public void MonitoredAttributeAlarm_RoutesToItsAttribute_ExpressionAlarm_RoutesToAllChanges()
|
||||
|
||||
@@ -265,6 +265,75 @@ public class NativeAlarmActorTests : TestKit, IDisposable
|
||||
Assert.Contains(rows, r => r.ConditionJson.Contains("49"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SRT-5 (WP6 6.1): a persist flush that is waiting on the shared LocalDb write lock must not
|
||||
/// park the actor's dispatcher thread. While another connection holds the write lock the
|
||||
/// actor keeps processing transitions, and the blocked batch still commits (in order) once
|
||||
/// the lock is released.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task Flush_BlockedOnWriteLock_DoesNotBlockTheActorThread()
|
||||
{
|
||||
var instance = CreateTestProbe();
|
||||
var dcl = CreateTestProbe();
|
||||
var actor = SpawnWithFlush(instance.Ref, dcl.Ref, TimeSpan.FromMilliseconds(50));
|
||||
dcl.ExpectMsg<SubscribeAlarmsRequest>();
|
||||
|
||||
await using var locker = _localDb.Db.CreateConnection();
|
||||
await using (var begin = locker.CreateCommand())
|
||||
{
|
||||
begin.CommandText = "BEGIN IMMEDIATE;";
|
||||
await begin.ExecuteNonQueryAsync();
|
||||
}
|
||||
|
||||
var t0 = DateTimeOffset.UtcNow;
|
||||
DeliverLiveTransition(actor, "ref-a", severity: 800, t0);
|
||||
instance.ExpectMsg<AlarmStateChanged>();
|
||||
await Task.Delay(300); // the 50 ms flush has started and is waiting on the lock
|
||||
|
||||
var sw = System.Diagnostics.Stopwatch.StartNew();
|
||||
DeliverLiveTransition(actor, "ref-b", severity: 801, t0.AddMilliseconds(1));
|
||||
instance.ExpectMsg<AlarmStateChanged>(TimeSpan.FromMilliseconds(500));
|
||||
sw.Stop();
|
||||
|
||||
await using (var rollback = locker.CreateCommand())
|
||||
{
|
||||
rollback.CommandText = "ROLLBACK;";
|
||||
await rollback.ExecuteNonQueryAsync();
|
||||
}
|
||||
|
||||
Assert.True(sw.ElapsedMilliseconds < 500, $"actor stalled {sw.ElapsedMilliseconds} ms behind a blocked flush");
|
||||
await AwaitAssertAsync(async () =>
|
||||
Assert.Equal(2, (await _storage.GetNativeAlarmsAsync("inst", Source().CanonicalName)).Count),
|
||||
TimeSpan.FromSeconds(5));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SRT-14 (WP6 6.2): cap eviction picks the oldest conditions with a bounded heap; the
|
||||
/// selection (and its oldest-first order) matches the full sort it replaced.
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData(1)]
|
||||
[InlineData(3)]
|
||||
[InlineData(10)]
|
||||
public void SelectOldest_MatchesAFullSort(int count)
|
||||
{
|
||||
var rng = new Random(42);
|
||||
var t0 = DateTimeOffset.UtcNow;
|
||||
var alarms = Enumerable.Range(0, 1001)
|
||||
.Select(i => Transition($"ref-{i}", AlarmTransitionKind.Raise,
|
||||
new AlarmConditionState(true, false, null, AlarmShelveState.Unshelved, false, 800),
|
||||
t0.AddMilliseconds(rng.Next(0, 1_000_000))))
|
||||
.ToList();
|
||||
|
||||
var expected = alarms.OrderBy(a => a.TransitionTime).Take(count).Select(a => a.TransitionTime).ToList();
|
||||
var actual = NativeAlarmActor.SelectOldest(alarms, count).Select(a => a.TransitionTime).ToList();
|
||||
|
||||
Assert.Equal(expected, actual);
|
||||
Assert.Empty(NativeAlarmActor.SelectOldest(alarms, 0));
|
||||
}
|
||||
|
||||
/// <summary>A snapshot swap that drops several conditions deletes their rows via the batched flush, and a delete cancels a pending upsert (review 2026-10-21 01/SR-P2).</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
using ZB.MOM.WW.ScadaBridge.SiteRuntime.Scripts;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests.Scripts;
|
||||
|
||||
/// <summary>
|
||||
/// SRT-7 (WP6 6.2): an Expression trigger is routed by the literal attribute keys it reads,
|
||||
/// and falls back to all-changes whenever those keys cannot be pinned down.
|
||||
/// </summary>
|
||||
public class TriggerExpressionKeysTests
|
||||
{
|
||||
/// <summary>Literal root and child reads are extracted as canonical keys.</summary>
|
||||
[Theory]
|
||||
[InlineData("(double)Attributes[\"Temp\"] > 50", new[] { "Temp" })]
|
||||
[InlineData("(double)Attributes[\"A\"] > (double)Attributes[\"B\"] && Attributes[\"A\"] != null", new[] { "A", "B" })]
|
||||
[InlineData("(double)Children[\"Pump1\"].Attributes[\"Speed\"] > 10", new[] { "Pump1.Speed" })]
|
||||
[InlineData("Attributes[\"Mode\"] as string == \"Auto\" || (bool)Children[\"V\"].Attributes[\"Open\"]", new[] { "Mode", "V.Open" })]
|
||||
public void LiteralReads_AreExtracted(string expression, string[] expected)
|
||||
{
|
||||
Assert.True(TriggerExpressionKeys.TryExtract(expression, out var keys));
|
||||
Assert.Equal(expected, keys);
|
||||
}
|
||||
|
||||
/// <summary>Anything that is not a recognised literal read falls back to all-changes.</summary>
|
||||
[Theory]
|
||||
[InlineData("true")] // no attribute read (may depend on the clock)
|
||||
[InlineData("DateTime.UtcNow.Second == 0")]
|
||||
[InlineData("Attributes[\"A\" + \"B\"] != null")] // non-literal key
|
||||
[InlineData("Attributes[name] != null")]
|
||||
[InlineData("Parent != null")]
|
||||
[InlineData("Children[\"P\"].Attributes[k] != null")] // non-literal child key
|
||||
[InlineData("Children[c].Attributes[\"S\"] != null")] // non-literal child name
|
||||
[InlineData("((Func<object>)(() => Attributes))() != null")] // alias of the global
|
||||
[InlineData("(double)Attributes[\"A\"] > 1 && this.Attributes[\"B\"] != null")]
|
||||
[InlineData("(double)Attributes[\"A\" > 1")] // parse error
|
||||
[InlineData("")]
|
||||
public void UnpinnableReads_FallBack(string expression)
|
||||
{
|
||||
Assert.False(TriggerExpressionKeys.TryExtract(expression, out _));
|
||||
}
|
||||
|
||||
/// <summary>Routing decisions for Expression scripts and alarms use the extracted keys.</summary>
|
||||
[Fact]
|
||||
public void ExpressionRouting_UsesKeysOrFallsBack()
|
||||
{
|
||||
var keyed = TriggerRouting.ForScript("Expression", "{\"expression\":\"(double)Attributes[\\\"A\\\"] > 1\"}");
|
||||
Assert.Equal(TriggerRoutingKind.MonitoredAttributes, keyed.Kind);
|
||||
Assert.Equal(new[] { "A" }, keyed.MonitoredAttributeSet);
|
||||
|
||||
var alarm = TriggerRouting.ForAlarm("Expression", "{\"expression\":\"Children[\\\"P\\\"].Attributes[\\\"X\\\"] != null\"}");
|
||||
Assert.Equal(TriggerRoutingKind.MonitoredAttributes, alarm.Kind);
|
||||
Assert.Equal(new[] { "P.X" }, alarm.MonitoredAttributeSet);
|
||||
|
||||
Assert.Equal(TriggerRoutingKind.AllChanges, TriggerRouting.ForScript("Expression", "{\"expression\":\"true\"}").Kind);
|
||||
Assert.Equal(TriggerRoutingKind.AllChanges, TriggerRouting.ForAlarm("Expression", "not json").Kind);
|
||||
}
|
||||
}
|
||||
@@ -282,6 +282,33 @@ public class OperationTrackingStoreTests : IDisposable
|
||||
Assert.Equal("node-a", snapshot!.SourceNode);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// AUD-7 (WP6 6.4): the batched read returns every recorded id (read-your-writes, across
|
||||
/// more ids than one IN-chunk) and omits ids with no row.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task GetStatusManyAsync_ReturnsRecordedIds_AndOmitsMissing()
|
||||
{
|
||||
var (store, _) = CreateStore(nameof(GetStatusManyAsync_ReturnsRecordedIds_AndOmitsMissing));
|
||||
await using var _store = store;
|
||||
|
||||
var recorded = Enumerable.Range(0, 1203).Select(_ => TrackedOperationId.New()).ToList();
|
||||
foreach (var id in recorded)
|
||||
{
|
||||
await store.RecordEnqueueAsync(id, kind: nameof(AuditKind.ApiCallCached), targetSummary: "ERP.GetOrder",
|
||||
sourceInstanceId: null, sourceScript: null, sourceNode: "node-a");
|
||||
}
|
||||
var missing = TrackedOperationId.New();
|
||||
|
||||
var found = await store.GetStatusManyAsync(recorded.Append(missing).Append(recorded[0]).ToList());
|
||||
|
||||
Assert.Equal(recorded.Count, found.Count);
|
||||
Assert.All(recorded, id => Assert.Equal(id, found[id].Id));
|
||||
Assert.False(found.ContainsKey(missing));
|
||||
Assert.Empty(await store.GetStatusManyAsync(Array.Empty<TrackedOperationId>()));
|
||||
}
|
||||
|
||||
/// <summary>Verifies that recording an enqueue persists a null source node.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
|
||||
@@ -912,6 +912,36 @@ public class StoreAndForwardStorageTests : IAsyncLifetime, IDisposable
|
||||
Assert.Equal(new[] { "a", "b" }, ids);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SF-3 (WP6 6.3): the sweep ranks lanes over the covering lane index (no payload read, no
|
||||
/// sort for the window) and joins back only the chosen page by primary key.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task GetMessagesForRetry_RanksOverTheCoveringLaneIndex()
|
||||
{
|
||||
await using var connection = _localDb.Db.CreateConnection();
|
||||
await using var cmd = connection.CreateCommand();
|
||||
cmd.CommandText = @"EXPLAIN QUERY PLAN
|
||||
SELECT id, created_at, rowid,
|
||||
ROW_NUMBER() OVER lane AS lane_rank,
|
||||
SUM(CASE WHEN (last_attempt_at_ms IS NULL OR retry_interval_ms = 0
|
||||
OR (1 - last_attempt_at_ms) >= retry_interval_ms) THEN 0 ELSE 1 END) OVER lane AS blocked_by
|
||||
FROM sf_messages
|
||||
WHERE status = 0
|
||||
WINDOW lane AS (PARTITION BY category, target ORDER BY created_at ASC, rowid ASC
|
||||
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)";
|
||||
var plan = new List<string>();
|
||||
await using (var reader = await cmd.ExecuteReaderAsync())
|
||||
while (await reader.ReadAsync())
|
||||
plan.Add(reader.GetString(3));
|
||||
|
||||
Assert.Contains(plan, p => p.Contains("COVERING INDEX idx_sf_messages_lane"));
|
||||
// The SF-1 rowid tie-break is the one key past the index order: SQLite may sort only
|
||||
// rows tied on (category, target, created_at) — "FOR LAST TERM" — never the backlog.
|
||||
Assert.DoesNotContain(plan, p => p.Contains("TEMP B-TREE") && !p.Contains("LAST TERM"));
|
||||
}
|
||||
|
||||
// ReplaceAll_SwapsTheEntireBuffer_Atomically was DELETED with ReplaceAllAsync in
|
||||
// LocalDb Phase 2, and deliberately not replaced. It asserted a destructive
|
||||
// delete-all-then-insert-all, which was the standby's anti-entropy apply: a resync
|
||||
|
||||
@@ -36,6 +36,16 @@ internal static class AnalysisClosureMock
|
||||
},
|
||||
ct);
|
||||
});
|
||||
|
||||
// TPL-4: the folder-move collision check is a (FolderId, Name) existence query now;
|
||||
// answer it from the same seeded graph.
|
||||
repoMock
|
||||
.Setup(r => r.TemplateNameExistsInFolderAsync(
|
||||
It.IsAny<int?>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<CancellationToken>()))
|
||||
.Returns(async (int? folderId, string name, int excludeId, CancellationToken ct) =>
|
||||
((await repoMock.Object.GetAllTemplatesForAnalysisAsync(ct)) ?? Array.Empty<Template>())
|
||||
.Any(t => t.Id != excludeId && t.FolderId == folderId
|
||||
&& string.Equals(t.Name, name, StringComparison.OrdinalIgnoreCase)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -73,7 +73,7 @@ public class AreaServiceTests
|
||||
{
|
||||
_repoMock.Setup(r => r.GetAreaByIdAsync(1, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new Area("Building A") { Id = 1, SiteId = 1 });
|
||||
_repoMock.Setup(r => r.GetInstancesBySiteIdAsync(1, It.IsAny<CancellationToken>()))
|
||||
_repoMock.Setup(r => r.GetInstancesBySiteIdShallowAsync(1, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new List<Instance>
|
||||
{
|
||||
new("Inst1") { Id = 1, AreaId = 1, SiteId = 1 }
|
||||
@@ -94,7 +94,7 @@ public class AreaServiceTests
|
||||
{
|
||||
_repoMock.Setup(r => r.GetAreaByIdAsync(1, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new Area("Parent") { Id = 1, SiteId = 1 });
|
||||
_repoMock.Setup(r => r.GetInstancesBySiteIdAsync(1, It.IsAny<CancellationToken>()))
|
||||
_repoMock.Setup(r => r.GetInstancesBySiteIdShallowAsync(1, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new List<Instance>());
|
||||
_repoMock.Setup(r => r.GetAreasBySiteIdAsync(1, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new List<Area>
|
||||
@@ -116,7 +116,7 @@ public class AreaServiceTests
|
||||
{
|
||||
_repoMock.Setup(r => r.GetAreaByIdAsync(1, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new Area("Empty") { Id = 1, SiteId = 1 });
|
||||
_repoMock.Setup(r => r.GetInstancesBySiteIdAsync(1, It.IsAny<CancellationToken>()))
|
||||
_repoMock.Setup(r => r.GetInstancesBySiteIdShallowAsync(1, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new List<Instance>());
|
||||
_repoMock.Setup(r => r.GetAreasBySiteIdAsync(1, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new List<Area> { new("Empty") { Id = 1, SiteId = 1 } });
|
||||
@@ -312,7 +312,7 @@ public class AreaServiceTests
|
||||
new("Mid") { Id = 2, SiteId = 1, ParentAreaId = 1 },
|
||||
new("Leaf") { Id = 3, SiteId = 1, ParentAreaId = 2 }
|
||||
});
|
||||
_repoMock.Setup(r => r.GetInstancesBySiteIdAsync(1, It.IsAny<CancellationToken>()))
|
||||
_repoMock.Setup(r => r.GetInstancesBySiteIdShallowAsync(1, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new List<Instance>
|
||||
{
|
||||
new("DeepInstance") { Id = 10, AreaId = 3, SiteId = 1 }
|
||||
|
||||
@@ -18,6 +18,7 @@ public class InstanceServiceTests
|
||||
/// <summary>Initializes the test with a mocked repository and audit service and the service under test.</summary>
|
||||
public InstanceServiceTests()
|
||||
{
|
||||
_repoMock.ServeClosureFromFullGraph(); // TPL-4: SetAlarmOverride reads the analysis closure
|
||||
_sut = new InstanceService(_repoMock.Object, _auditMock.Object);
|
||||
}
|
||||
|
||||
@@ -108,6 +109,32 @@ public class InstanceServiceTests
|
||||
Assert.Contains("does not exist", result.Error);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// UI-6 (WP6 6.8): re-saving an override with its current value writes nothing and adds no
|
||||
/// UpdateOverride audit row.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task SetAttributeOverride_UnchangedValue_SkipsTheWriteAndTheAuditRow()
|
||||
{
|
||||
var instance = new Instance("Inst1") { Id = 1, TemplateId = 1 };
|
||||
var existing = new InstanceAttributeOverride("Threshold") { Id = 5, InstanceId = 1, OverrideValue = "99" };
|
||||
_repoMock.Setup(r => r.GetInstanceByIdAsync(1, It.IsAny<CancellationToken>())).ReturnsAsync(instance);
|
||||
_repoMock.Setup(r => r.GetAttributesByTemplateIdAsync(1, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new List<TemplateAttribute> { new("Threshold") { IsLocked = false } });
|
||||
_repoMock.Setup(r => r.GetOverridesByInstanceIdAsync(1, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new List<InstanceAttributeOverride> { existing });
|
||||
|
||||
var result = await _sut.SetAttributeOverrideAsync(1, "Threshold", "99", "admin");
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Same(existing, result.Value);
|
||||
_repoMock.Verify(r => r.UpdateInstanceAttributeOverrideAsync(It.IsAny<InstanceAttributeOverride>(), It.IsAny<CancellationToken>()), Times.Never);
|
||||
_repoMock.Verify(r => r.SaveChangesAsync(It.IsAny<CancellationToken>()), Times.Never);
|
||||
_auditMock.Verify(a => a.LogAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(),
|
||||
It.IsAny<string>(), It.IsAny<string>(), It.IsAny<object?>(), It.IsAny<CancellationToken>()), Times.Never);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that overriding an unlocked attribute returns success.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
|
||||
Reference in New Issue
Block a user