diff --git a/.claude/rules/historian.md b/.claude/rules/historian.md index 348c7c302..ee6563617 100644 --- a/.claude/rules/historian.md +++ b/.claude/rules/historian.md @@ -36,6 +36,7 @@ historian tagname, which is the tag's driver `FullName`. - **QuestDB** (`Driver.Historian.QuestDb`, `ServerHistorian:QuestDb:*`, Npgsql over PG wire; docker-dev overlay `docker-compose.questdb.yml`): same kinds/status/aggregates/HistoryUpdate as SqlServer, soft delete by tombstone (INSERT only — never `UPDATE`/`DELETE`; every read filters `NOT deleted`). ⚠️ **Timestamps are µs** (`QuestDbConnection.Round`/`BindTimestamp`; `IHistorianDataSource.TimestampResolutionTicks` = 10 steps HistoryRead paging), **pre-1970 cannot be stored** (writer drops, HistoryUpdate `BadOutOfRange`), every write waits for WAL visibility, TTL is enforced on write commits only, set Npgsql `Maximum Pool Size` < QuestDB's 64. `docs/Historian.md` §"QuestDB backend". - ⚠️ **Reverse processed reads are Part 13/SDK-anchored (#677, client-visible):** every aggregate on SqlServer/QuestDB now anchors a reverse read at its later time — window `(end, start]`, partial interval earliest, each stamped with its later edge (was: earlier-anchored, stamped earlier edge); on forward reads Partial also marks the interval the data starts inside (not Average — the SDK's rule, forward-only); a non-default client `AggregateConfiguration` ⇒ `BadAggregateConfigurationRejected`; Gateway provisioning sends `IntegralDivisor = 1`. SDK-parity tests: `SdkAggregateParityTests`. `docs/Historian.md` §Aggregates. - ⚠️ **Reverse / end-only RAW reads work on Gateway (#686, client-visible):** `IHistorianDataSource.SupportsReverseRaw` (SqlServer/QuestDB/Null `true`, Gateway `false`, interface default `false`, guard-tested) — the node manager sends `start > end` only to a backend that declares it; otherwise `ReverseRawReader` serves it from FORWARD reads: uncapped ⇒ ONE forward read reversed in memory; capped ⇒ a bounded walk back in segments (ms-aligned request bounds, width aimed from observed density at ≈ N + 8 rows and carried page to page in the continuation point — #689: it used to aim at half `MaxTieClusterOverfetch`, ~32k rows per page on a dense tag; a read asks for `2N + 18` rows (a discovery segment ≤ 1,026), `MaxTieClusterOverfetch` is only the tie-cluster ceiling — a full read is re-read, never answered truncated; only more than max(1, `MaxTieClusterOverfetch`) samples within ONE MILLISECOND ⇒ `BadTooManyOperations` (per ms, not per timestamp — requests are ms-rounded, and letting a segment narrow below 1 ms stepped a page through one ms a tick per read, ~10k reads); walks no later than now + 1 day and never before the Unix epoch; #691: after two empty segments it asks once for the whole remainder, and the stretch a page proved empty rides the continuation point — the last pages of a deep page-through no longer each walk ~14 reads to 1970). The raw/events tie-path oversized-cluster refusal is now `BadTooManyOperations` too (was `BadHistoryOperationUnsupported`). Uncapped Gateway raw reads (forward too) used to send `max_values = 0`, which the client/gateway reject — now unbounded (`int.MaxValue`; a ceiling refusal ⇒ `BadTooManyOperations`), and a cancelled read is no longer a backend failure. Since #669 such reads failed the node on Gateway and counted as a backend fault (the gateway rejects start > end — `GatewayHistorianDataSource.ReadRawAsync` now refuses one unsent); before #669 an end-only Gateway read returned the OLDEST N ascending — now the latest N at/before EndTime, newest first. Events follow since #691.4: a reverse/end-only capped events read on Gateway (`SupportsReverseEvents` false; Null now reports `true` and answers empty) is walked back the same way (ties sorted by EventId — the gateway orders by time only; one extra event found ⇒ continuation point) — it used to be refused `BadHistoryOperationUnsupported` (explicit reverse) or answered with the OLDEST N ascending (end-only); needs the gateway's `RuntimeDb:EventReadMaxRows` 0/unlimited (it truncates silently). Uncapped Gateway events reads (forward too) used to throw "Array dimensions exceeded" (result list pre-sized to `int.MaxValue`) — fixed. Above a truncated read the walk gallops up from the newest row seen, then bisects (never below 1 ms): a burst that ended 100 days ago ≈ 18 reads, a dense tag that stopped days ago ≈ 26. `docs/Historian.md` §"Open-ended and reverse raw reads". +- **HistoryRead-Events page cap (#996 / U-6, client-visible):** `ServerHistorian:MaxEventsPerRead` (default 10 000, `<= 0` opts out; node-manager `MaxEventsPerRead`, advertised as `HistoryServerCapabilities/MaxReturnEventValues`). `NumValuesPerNode = 0` and any N above the cap are paged at the cap with a continuation point instead of reading a whole window (backend list + multi-source merge + per-event field lists + encoder) into memory; applied AFTER the end-only/reverse normalisation so an end-only 0-count read keeps its forward meaning, and before the cursor is built (the cursor carries the capped page size). The old `Events_unbounded_request_passes_int_max_to_backend` pin now runs with the cap opted out. - **Advertised aggregates (#682):** `IHistorianDataSource.SupportedAggregates` (Gateway 4 via `GatewayHistorianDataSource.ServedAggregates`, SqlServer/QuestDB 19 via `AggregateFamilies.Served` — DurationGood/DurationBad added by #820, the PercentGood/PercentBad region times in ms, Null **none**; a null set ⇒ all) is the one authority for `HistoryServerCapabilities/AggregateFunctions` (i=11201 — only its folder references are trimmed) and the up-front `BadAggregateNotSupported` in HistoryRead-Processed. ⚠️ `ServerCapabilities/AggregateFunctions` (i=2997) is deliberately NOT trimmed: it keeps the SDK's 37 because live `AggregateFilter` subscriptions still compute them all. ⚠️ Historian disabled ⇒ Processed is now `BadAggregateNotSupported`, not `GoodNoData`. `docs/Historian.md` §Advertised aggregates. ⚠️ **#897 (client-visible): per-node DataType check before any backend call** ⇒ `BadAggregateNotSupported` (Part 11 §6.5.4), unsent, no backend failure: shared Part 13 Table 50 rule `HistoryAggregateDataTypes` (numeric-only aggregates on a String/DateTime node, every backend — SQL used to answer `BadAggregateInvalidInputs` per interval), then `IHistorianDataSource.SupportsAggregateFor(aggregate, TypeCode?)` (every production backend declares it, guard-tested; only Gateway narrows: native TimeAverage/Total on a Boolean node — AVEVA refuses them on a discrete tag, which the gateway reports only as `Internal`/`HistorianServerOperationException`). Boolean stays served as 0/1 on SQL and by Gateway's raw-evaluated aggregates. `docs/Historian.md` §Aggregates by node DataType. - **Raw `ReturnBounds` is honoured on every backend (#691, client-visible):** Part 11 bounding values (§4.6 Table 1 is the test oracle) are composed in the server by `HistoryBounds` from each backend's raw reads — "at or before" = capped reverse read (native on SQL backends, the #686 `ReverseRawReader` walk-back on Gateway, never AVEVA's synthetic boundary row), "at or after" = capped forward read. Bounds are stored samples of any quality, count toward `NumValuesPerNode`, start bound on the first page / end bound on the last (pending end bound rides the continuation point); missing ⇒ `Bad_BoundNotFound` (null, at the bound time; a one-sided read's open side ±1 s from the previous value). ⚠️ **Breaking for SDK-default clients:** the .NET SDK's `new ReadRawModifiedDetails()` defaults BOTH `ReturnBounds = true` AND `IsReadModified = true` — a client that cleared only `IsReadModified` now gets bounds, and one that set neither is a modified read with bounds ⇒ `Bad_InvalidArgument` (§6.5.3.3); set both explicitly (Client.Shared does; tests building details must too). No data AND no bound found ⇒ `GoodNoData`, no values (the pre-bounds answer). On Gateway the at-or-after lookup ends at now + 1 day (never a year-9999 end to AVEVA). Kill switch `ServerHistorian:HonorReturnBounds` (default `true`; `false` = pre-#691). `docs/Historian.md` §Bounding values. - ⚠️ **Raw pages are full (#692, client-visible, every backend):** each raw page asks the backend for `N + skip + 1` rows (the boundary ties it will trim + one lookahead row) — a resumed page used to ask only N, trim the ties and come back short; at N=1 that was an EMPTY page + continuation point that then fell into the `MaxTieClusterOverfetch + 1` over-fetch (live: 8 values = 17 pages / 25 reads / 524k rows ⇒ now 8/8/≤24). No lookahead row ⇒ last page, no CP (an exact multiple no longer ends on an empty page). Exception: an oversized tie cluster — its last slice is `min(N, remaining)` with a CP, and stepping past one at the end of data can give one empty final page. The over-fetch fires only when every row past the trimmed ties sits on the boundary timestamp; a cursor inside such a cluster is marked `WithinTieCluster` (next page goes straight to the over-fetch). `SliceTieCluster` resumes only strictly before EndTime (truncated to the backend resolution) — it used to resume AT the exclusive EndTime and return samples there. Bound placeholders carry an explicit marker (`HistoryBounds.IsPlaceholder` no longer matches a stored `Bad_BoundNotFound`/null row); the N=1 bounds probe carries its walk hint + resolved end bound into the cursor. Reviewer fuzz harnesses (paged vs unpaged over random tie series) are the right test for any paging change — repo tests passed while master mismatched 1-in-160. diff --git a/docs/DataConnections.md b/docs/DataConnections.md index 3aa3ef51e..8cf9ba484 100644 --- a/docs/DataConnections.md +++ b/docs/DataConnections.md @@ -24,6 +24,14 @@ validator remains authoritative: consumers must belong to the owning cluster, ma must be a subset of the connection's consumers, local parents must be valid containers, and branch collisions, invalid self-routes and unsupported type expectations are rejected. +**Authoring reads are narrow (#996, review C-11 / A-5).** The `/clusters/{id}/data-connections` page and its save/delete use +`DraftSnapshotFactory.FromConfigDbForDataConnectionsAsync`, not the whole-DB deploy snapshot: it skips Scripts, PollGroups, +NodeAcls, ApiKeys and reservations (nothing in `DataConnectionValidator` reads them) and projects each Tag to id/device/group/name, +selecting `TagConfig` only for rows that could carry an `alarm` intent (the alarm-bearing-export-root rule, #942). Never feed that +snapshot to `DraftValidator` or the artifact composer. `LoadAppliedAsync` fetches and inflates each distinct applied artifact once +(`DeploymentArtifact.ParseDataConnections(blob, nodeIds)`), however many nodes share it. Tag-level picker lists are capped at 500 +entries; type the root as `Kind|EntityId` for anything beyond. + New connections default to a 30-second call timeout. Existing explicitly configured shorter timeouts remain in force. This limit never extends a caller's original deadline; a write without enough remaining time for the driver budget is rejected before dispatch. diff --git a/docs/DriverLifecycle.md b/docs/DriverLifecycle.md index 4504e752a..473fba611 100644 --- a/docs/DriverLifecycle.md +++ b/docs/DriverLifecycle.md @@ -195,6 +195,11 @@ routes it to `Unsubscribe`, dropping a stale handle.) Things to know before touching any of this: +- **Restart/Reconnect reply = the dispatch (#996, review H-3).** `AdminOperationsActor` handles `RestartDriver` / + `ReconnectDriver` as synchronous receives: dispatch to the nodes, reply success, then write the `ConfigEdit` audit row on a pool + thread. An audit-write failure is logged (with op, driver, user, correlation) and never changes the reply — it used to answer + "failed" for a command already on its way (the operator retried ⇒ a second restart) and suspended the admin mailbox for a connect timeout. + - ⚠️ **The supervision route is the invisible one, and it was the worst.** There is **no** `SupervisorStrategy` anywhere under `src/Server`, so a child that throws gets Akka's default `Restart`. A restart recreates the actor object around the **same** `IDriver` — the Props closure captured it — diff --git a/docs/Historian.md b/docs/Historian.md index fe6257ed6..bc8cd6908 100644 --- a/docs/Historian.md +++ b/docs/Historian.md @@ -200,6 +200,7 @@ Processed read is `BadAggregateNotSupported` and no history aggregate functions | `HistoryReadBatchParallelism` | int | `4` | Max historized nodes served **concurrently** within one HistoryRead batch (arch-review 03/S3). The SDK's `HistoryRead*` override surface is synchronous, so each arm bridges once at its boundary; this turns per-node serving from sequential (`N × CallTimeout` worst case) into `⌈N / P⌉ × CallTimeout`. Also caps the gateway-load multiplication a single client can command. `≤ 1` serves sequentially. | | `MaxConcurrentHistoryReadBatches` | int | `16` | Process-wide limit on HistoryRead (and HistoryUpdate) batches served **concurrently** (arch-review 03/S3). A flood of history clients degrades to `BadTooManyOperations` rather than exhausting the SDK request-thread pool. With `HistoryReadBatchParallelism` this caps total in-flight gateway reads at `MaxConcurrentHistoryReadBatches × HistoryReadBatchParallelism` (default 16 × 4 = 64). A batch that cannot get a slot within `min(HistoryReadDeadline, 5 s)` fails every handle `BadTooManyOperations`. | | `MaxTimeWeightedRawRows` | int | `1000000` | `SqlServer` / `QuestDb` (#671), and the `Gateway` per-sample aggregates (#681 — every per-sample read there streams raw samples, so the cap applies to the window's raw rows; see [Aggregate set](#aggregate-set-and-badaggregatenotsupported-285)). The most raw in-window samples one [time-weighted aggregate](#time-weighted-aggregates-part-13-671) read (TimeAverage, TimeAverage2, **Total**, Total2, Interpolative, and — since #680 — **PercentGood/PercentBad**, since #820 **DurationGood/DurationBad**) may stream into the server-side evaluator — that family is **not** pushed down to SQL. The window query is capped at this + 1 rows; one row past the cap fails **that node** with `BadTooManyOperations` (not counted as a backend fault) instead of holding a pooled connection until `HistoryReadDeadline` and returning `BadTimeout`. Bound rows outside the window do not count; per-sample aggregates are not capped on the SQL backends (pushed down). 1 000 000 ≈ 11.5 days of a 1 Hz tag. Non-positive = unbounded (a `Validate()` warning). `Gateway` (#688): the row budget it asks the gateway for (`cap + 18`) is clamped at the gateway's default `MaxValuesCeiling` (1,000,000) while the cap is at or under it, so the default works against a gateway with `AllowStreamingBeyondCeiling=false`; against a gateway with a *lower* ceiling the refused budget is retried once at the ceiling the gateway names (#691.3), so no change is needed (`ceiling − 18` only saves that round-trip). | +| `MaxEventsPerRead` | int | `10000` | Every backend (#996, review U-6): the most events one HistoryRead-Events page returns for a node and the most a backend is asked for in one read — the events twin of `MaxRawValuesPerRead`. `NumValuesPerNode = 0` ("all") or any larger N is served as pages of at most this many events, each with a continuation point; advertised as `HistoryServerCapabilities/MaxReturnEventValues`. Non-positive = unbounded (the pre-#996 behaviour; a `Validate` warning). | | `HistoryReadDeadline` | TimeSpan | `00:01:00` | Per-request wall-clock deadline for a HistoryRead (and HistoryUpdate) batch (arch-review 03/S3). A node still in flight at the deadline surfaces `BadTimeout`, so one request can never hold an SDK request thread longer than this regardless of node count. Non-positive = unbounded (a `Validate()` warning). | | `ProvisionTags` | string | `CreateOrUpdate` | What [tag auto-provisioning](#tag-auto-provisioning-ensuretags) may do (#899). `CreateOrUpdate` = the `EnsureTags` / `MERGE` upsert: create a missing tag, re-type and re-describe an existing one (the behaviour before #899). `CreateOnly` (**Gateway backend only** — any other backend fails host start) = look each tag up first (`GetTagMetadata`, a read) and send only the ones the historian reports **absent**; an existing tag is left exactly as it is (counted `skipped`), and a failed lookup is counted `failed` and **not** sent. `Off` = no provisioning at all; HistoryRead and continuous historization are unaffected. Case-insensitive; an unknown value fails host start. A tag's own `historianReadOnly: true` opts it out under every policy. | | `HistoryUpdateMaxFutureSkew` | TimeSpan | `1.00:00:00` | #674. How far past the server clock a HistoryUpdate (Insert / Replace / Update) item's `SourceTimestamp` may lie; an item beyond `now + skew` is refused **`BadOutOfRange`** by the node manager before any backend sees it (every backend). Guards against a far-future typo (a 2062 timestamp). The live recorder is not bounded. Non-positive disables the bound (no warning — a deliberate choice). See [HistoryUpdate](#historyupdate). | diff --git a/docs/Redundancy.md b/docs/Redundancy.md index d1bf5bc8c..b8e750216 100644 --- a/docs/Redundancy.md +++ b/docs/Redundancy.md @@ -809,6 +809,12 @@ deployment green fleet-wide. Now: `Degraded = false, DegradedReason = null` (an old node's DPS JSON decodes clean); `ApplyAckMessage` gained `bool degraded = 6; optional string degraded_reason = 7;` (an old node's gRPC ack decodes clean). The outcome stays `APPLIED` — a degraded node *did* apply the revision. +- **Ack rows are written off the coordinator thread (#996, review H-6).** `ConfigPublishCoordinator` persists each node's ack on a pool + thread (`AckPersisted` is piped back; one write per node at a time, a newer ack for the same node waits behind it) and decides + count/seal on the actor thread. With the ConfigDb slow or unreachable (no EF retry strategy ⇒ a connect timeout per call) the + timeouts now overlap instead of serialising N × timeout of unresponsive mailbox; the deadline kicks its whole unpersisted backlog off at + once and decides as soon as the last write lands. The dispatch guard/seed and the terminal seal/fail/timeout writes are still + synchronous single calls (see the follow-up issue). - **Central records it without a status-model change.** `ConfigPublishCoordinator.PersistNodeAck` keeps the node's `NodeDeploymentState.Status = Applied` and writes `FailureReason = "Applied degraded: "` (`ConfigPublishCoordinator.IsDegraded` = Applied **and** a reason). The deployment still **seals** — diff --git a/docs/Reservations.md b/docs/Reservations.md index 0b48980b0..74720d755 100644 --- a/docs/Reservations.md +++ b/docs/Reservations.md @@ -122,10 +122,13 @@ permanent for the life of the asset. (`[Authorize]`) but is not restricted to a specific Admin UI role — any signed-in user can view it. -The page is a **read-only flat list** of all `ExternalIdReservation` rows, -ordered by Kind then Value. It shows Kind, Value, owning `EquipmentUuid`, and -Cluster. There is no Active/Released split, no Release action, and no Release -dialog on this page. +The page is a **read-only list** of `ExternalIdReservation` rows, ordered by Kind +then Value. It shows Kind, Value, owning `EquipmentUuid`, and Cluster. Since +#996 (review A-8) it lists **active** rows by default (a "Show released" toggle +adds the released ones and a Released column), reads only the displayed columns +(`ReservationListQuery`) and shows at most 200 rows with a "Showing N of M" +header — released rows accumulate for the life of the database. There is no +Release action and no Release dialog on this page. You cannot *create* a reservation from this page — reservations only ever come into existence as a side-effect of publishing a generation. The release flow diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Queries/DeploymentQueries.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Queries/DeploymentQueries.cs new file mode 100644 index 000000000..7afb55694 --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Queries/DeploymentQueries.cs @@ -0,0 +1,56 @@ +using Microsoft.EntityFrameworkCore; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; + +namespace ZB.MOM.WW.OtOpcUa.Configuration.Queries; + +/// +/// A row WITHOUT its ArtifactBlob (lmxopcua#996, review C-6). The blob is the +/// gzip of the whole fleet config (hundreds of KB to MBs); every reader that only needs the row's metadata +/// must project to this shape instead of materialising the entity. +/// +/// Deployment id. +/// Artifact revision hash. +/// Deployment status. +/// Creator. +/// Creation time. +/// Seal time, when sealed. +/// Failure text, when failed. +public sealed record DeploymentSummary( + Guid DeploymentId, + string RevisionHash, + DeploymentStatus Status, + string CreatedBy, + DateTime CreatedAtUtc, + DateTime? SealedAtUtc, + string? FailureReason); + +/// +/// Blob-free Deployment queries shared by the DB health probe, the readiness check, the cluster overview +/// and the driver-host boot read. A plain db.Deployments…ToList() drags ArtifactBlob over the wire; +/// these projections cannot. +/// +public static class DeploymentQueries +{ + /// + /// Liveness probe query: selects one DeploymentId (never the artifact blob). Used by the 5 s + /// DbHealthProbeActor tick and the configdb readiness check. + /// + /// The config database context. + /// A query yielding at most one deployment id. + public static IQueryable ProbeQuery(OtOpcUaConfigDbContext db) => + db.Deployments.AsNoTracking().Select(d => d.DeploymentId).Take(1); + + /// Projects a deployment query to (no blob). + /// The source query. + /// The blob-free projection. + public static IQueryable ToSummary(this IQueryable deployments) => + deployments.Select(d => new DeploymentSummary( + d.DeploymentId, d.RevisionHash, d.Status, d.CreatedBy, d.CreatedAtUtc, d.SealedAtUtc, d.FailureReason)); + + /// The newest deployment (by CreatedAtUtc) as a blob-free summary. + /// The config database context. + /// A query yielding at most one summary. + public static IQueryable LatestSummary(OtOpcUaConfigDbContext db) => + db.Deployments.AsNoTracking().OrderByDescending(d => d.CreatedAtUtc).ToSummary().Take(1); +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Queries/ReservationListQuery.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Queries/ReservationListQuery.cs new file mode 100644 index 000000000..fe32277ea --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Queries/ReservationListQuery.cs @@ -0,0 +1,54 @@ +using Microsoft.EntityFrameworkCore; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; + +namespace ZB.MOM.WW.OtOpcUa.Configuration.Queries; + +/// One displayed ExternalIdReservation row (only the columns the /reservations page shows). +/// ZTag or SAPID. +/// The reserved external id. +/// Owning equipment. +/// Cluster it was published in. +/// When it was released, or null while active. +public sealed record ReservationRow(ReservationKind Kind, string Value, Guid EquipmentUuid, string ClusterId, DateTime? ReleasedAt); + +/// A bounded page of reservations plus the total matching the filter. +/// At most pageSize rows, ordered by kind then value. +/// All rows matching the filter (so the page can say "showing N of M"). +public sealed record ReservationPage(IReadOnlyList Rows, int Total); + +/// +/// The /reservations page's read (lmxopcua#996, review A-8): active rows by default, projected to the displayed columns and +/// capped — the page used to render every row, released ones included, which accumulate for the life of the database. +/// +public static class ReservationListQuery +{ + /// Rows shown per page (the cluster-audit page's size). + public const int DefaultPageSize = 200; + + /// The filtered, ordered, projected query (exposed so a test can pin its SQL shape). + /// The config DB context. + /// True to include released rows. + /// The unbounded ordered projection. + public static IQueryable Query(OtOpcUaConfigDbContext db, bool includeReleased) + { + var rows = db.ExternalIdReservations.AsNoTracking().AsQueryable(); + if (!includeReleased) rows = rows.Where(r => r.ReleasedAt == null); + return rows.OrderBy(r => r.Kind).ThenBy(r => r.Value) + .Select(r => new ReservationRow(r.Kind, r.Value, r.EquipmentUuid, r.ClusterId, r.ReleasedAt)); + } + + /// Loads one capped page and the total count for the filter. + /// The config DB context. + /// True to include released rows. + /// Maximum rows returned. + /// Cancellation token. + /// The page and the total. + public static async Task LoadAsync( + OtOpcUaConfigDbContext db, bool includeReleased, int pageSize = DefaultPageSize, CancellationToken ct = default) + { + var query = Query(db, includeReleased); + var total = await query.CountAsync(ct); + var rows = await query.Take(pageSize).ToListAsync(ct); + return new ReservationPage(rows, total); + } +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftSnapshotFactory.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftSnapshotFactory.cs index c975740ab..6aeeeff71 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftSnapshotFactory.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftSnapshotFactory.cs @@ -42,7 +42,45 @@ public static class DraftSnapshotFactory /// The config DB context to read from. /// Cancellation token. /// A snapshot populated from the live DB, ready for . - public static async Task FromConfigDbAsync(OtOpcUaConfigDbContext db, CancellationToken ct = default) + public static Task FromConfigDbAsync(OtOpcUaConfigDbContext db, CancellationToken ct = default) + => ReadInSnapshotAsync(db, ReadAsync, ct); + + /// + /// Builds a NARROW for and the data-connections + /// authoring page (lmxopcua#996, review C-11 / A-5). It skips every table that validator never reads (Scripts, + /// PollGroups, NodeAcls, ApiKeys, reservations) and projects to id/device/group/name + /// with TagConfig kept ONLY for rows that could carry an alarm intent. It must NOT be fed to + /// or the artifact composer — those need the whole snapshot + /// (). + /// + /// The config DB context to read from. + /// Cancellation token. + /// A snapshot sufficient for . + public static Task FromConfigDbForDataConnectionsAsync(OtOpcUaConfigDbContext db, CancellationToken ct = default) + => ReadInSnapshotAsync(db, ReadForDataConnectionsAsync, ct); + + /// + /// The narrow tag projection used by : TagConfig is + /// selected only when it could contain an alarm intent (case-insensitive substring, or any JSON + /// \u escape that could spell it), else NULL. Exposed so a test can pin the generated SQL. + /// + /// The config DB context. + /// The projection query. + public static IQueryable NarrowTags(OtOpcUaConfigDbContext db) => + db.Tags.AsNoTracking().OrderBy(x => x.TagId).Select(x => new NarrowTag( + x.TagId, x.DeviceId, x.TagGroupId, x.Name, + x.TagConfig.Contains("alarm") || x.TagConfig.Contains("\\u") ? x.TagConfig : null)); + + /// A reduced to what the data-connection rules read. + /// Tag id. + /// Owning device. + /// Owning group, if any. + /// Tag name. + /// Config JSON, only when it may carry an alarm intent. + public sealed record NarrowTag(string TagId, string DeviceId, string? TagGroupId, string Name, string? TagConfig); + + private static async Task ReadInSnapshotAsync( + OtOpcUaConfigDbContext db, Func> read, CancellationToken ct) { ArgumentNullException.ThrowIfNull(db); @@ -52,13 +90,45 @@ public static class DraftSnapshotFactory : null; await using (tx) { - var snapshot = await ReadAsync(db, ct).ConfigureAwait(false); + var snapshot = await read(db, ct).ConfigureAwait(false); // Read-only: committing releases the snapshot's version-store reservation; nothing was written. if (tx is not null) await tx.CommitAsync(ct).ConfigureAwait(false); return snapshot; } } + private static async Task ReadForDataConnectionsAsync(OtOpcUaConfigDbContext db, CancellationToken ct) + { + var tags = await NarrowTags(db).ToListAsync(ct); + return new DraftSnapshot + { + GenerationId = 0, + ClusterId = string.Empty, + ServerClusters = await db.ServerClusters.AsNoTracking().OrderBy(x => x.ClusterId).ToListAsync(ct), + ClusterNodes = await db.ClusterNodes.AsNoTracking().OrderBy(x => x.NodeId).ToListAsync(ct), + DataConnectionScopeVersion = await db.DataConnectionScopeStates.AsNoTracking().Where(x => x.Id == 1).Select(x => x.ScopeVersion).SingleOrDefaultAsync(ct), + DataConnections = await db.DataConnections.AsNoTracking().OrderBy(x => x.DataConnectionId).ToListAsync(ct), + DataExports = await db.DataExports.AsNoTracking().OrderBy(x => x.DataExportId).ToListAsync(ct), + RemoteNamespaceMappings = await db.RemoteNamespaceMappings.AsNoTracking().OrderBy(x => x.RemoteNamespaceMappingId).ToListAsync(ct), + RawFolders = await db.RawFolders.AsNoTracking().OrderBy(x => x.RawFolderId).ToListAsync(ct), + DriverInstances = await db.DriverInstances.AsNoTracking().OrderBy(x => x.DriverInstanceId).ToListAsync(ct), + Devices = await db.Devices.AsNoTracking().OrderBy(x => x.DeviceId).ToListAsync(ct), + TagGroups = await db.TagGroups.AsNoTracking().OrderBy(x => x.TagGroupId).ToListAsync(ct), + UnsAreas = await db.UnsAreas.AsNoTracking().OrderBy(x => x.UnsAreaId).ToListAsync(ct), + UnsLines = await db.UnsLines.AsNoTracking().OrderBy(x => x.UnsLineId).ToListAsync(ct), + Equipment = await db.Equipment.AsNoTracking().OrderBy(x => x.EquipmentId).ToListAsync(ct), + Tags = tags.ConvertAll(t => new Entities.Tag + { + TagId = t.TagId, DeviceId = t.DeviceId, TagGroupId = t.TagGroupId, Name = t.Name, + DataType = string.Empty, AccessLevel = default, TagConfig = t.TagConfig ?? "{}", + }), + UnsTagReferences = await db.UnsTagReferences.AsNoTracking().OrderBy(x => x.UnsTagReferenceId).ToListAsync(ct), + VirtualTags = await db.VirtualTags.AsNoTracking().OrderBy(x => x.VirtualTagId).ToListAsync(ct), + ScriptedAlarms = await db.ScriptedAlarms.AsNoTracking().OrderBy(x => x.ScriptedAlarmId).ToListAsync(ct), + PriorEquipment = [], + }; + } + // Every composed table is read ORDERED BY ITS NATURAL KEY, server-side. That order IS the deployment // artifact's order (ConfigComposer.Compose serialises the snapshot as given): it is exactly the order the // pre-R03:3.2 composer's own queries produced — the database collation's, case-insensitive on SQL Server — diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor index 442a9cfb3..3215f569f 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor @@ -114,7 +114,7 @@ else - +
Tag-level choices are limited to the first @MaxPickerTags; for others type the root below as Kind|EntityId (e.g. RawTag|tag-id).
@Operations(e.AllowedOperations, v => e.AllowedOperations = v) @@ -152,6 +152,8 @@ else @code { [Parameter] public string ClusterId { get; set; } = ""; + /// Per-list cap on tag-level picker options (lmxopcua#996 / A-5): a 50k-tag cluster used to push 50k option elements per render. Larger sets use the typed-id fields. + private const int MaxPickerTags = 500; private DraftSnapshot? _snapshot; private DataConnectionEditorModel? _connection; private DataExport? _export; @@ -226,15 +228,15 @@ else { var drivers = _snapshot!.DriverInstances.Where(x => Same(x.ClusterId, ClusterId)).Select(x => x.DriverInstanceId).ToHashSet(StringComparer.OrdinalIgnoreCase); var devices = _snapshot.Devices.Where(x => drivers.Contains(x.DriverInstanceId)).Select(x => x.DeviceId).ToHashSet(StringComparer.OrdinalIgnoreCase); - foreach (var tag in _snapshot.Tags.Where(x => devices.Contains(x.DeviceId))) yield return ($"RawTag|{tag.TagId}", $"Tag: {tag.Name} ({tag.TagId})"); + foreach (var tag in _snapshot.Tags.Where(x => devices.Contains(x.DeviceId)).Take(MaxPickerTags)) yield return ($"RawTag|{tag.TagId}", $"Tag: {tag.Name} ({tag.TagId})"); } else if (realm == DataRealm.Uns) { var areas = _snapshot!.UnsAreas.Where(x => Same(x.ClusterId, ClusterId)).Select(x => x.UnsAreaId).ToHashSet(StringComparer.OrdinalIgnoreCase); var lines = _snapshot.UnsLines.Where(x => areas.Contains(x.UnsAreaId)).Select(x => x.UnsLineId).ToHashSet(StringComparer.OrdinalIgnoreCase); var equipment = _snapshot.Equipment.Where(x => lines.Contains(x.UnsLineId)).Select(x => x.EquipmentId).ToHashSet(StringComparer.OrdinalIgnoreCase); - foreach (var tag in _snapshot.VirtualTags.Where(x => equipment.Contains(x.EquipmentId))) yield return ($"VirtualTag|{tag.VirtualTagId}", $"Virtual tag: {tag.Name} ({tag.VirtualTagId})"); - foreach (var tag in _snapshot.UnsTagReferences.Where(x => equipment.Contains(x.EquipmentId))) yield return ($"UnsTagReference|{tag.UnsTagReferenceId}", $"Tag reference: {tag.UnsTagReferenceId}"); + foreach (var tag in _snapshot.VirtualTags.Where(x => equipment.Contains(x.EquipmentId)).Take(MaxPickerTags)) yield return ($"VirtualTag|{tag.VirtualTagId}", $"Virtual tag: {tag.Name} ({tag.VirtualTagId})"); + foreach (var tag in _snapshot.UnsTagReferences.Where(x => equipment.Contains(x.EquipmentId)).Take(MaxPickerTags)) yield return ($"UnsTagReference|{tag.UnsTagReferenceId}", $"Tag reference: {tag.UnsTagReferenceId}"); } } private IEnumerable<(string Id, string Label)> RemoteRoots(RemoteNamespaceMapping mapping) @@ -252,7 +254,7 @@ else foreach (var x in devices) yield return (x.DeviceId, $"Device: {x.Name} ({x.DeviceId})"); var deviceIds = devices.Select(x => x.DeviceId).ToHashSet(StringComparer.OrdinalIgnoreCase); foreach (var x in _snapshot.TagGroups.Where(x => deviceIds.Contains(x.DeviceId))) yield return (x.TagGroupId, $"Tag group: {x.Name} ({x.TagGroupId})"); - foreach (var x in _snapshot.Tags.Where(x => deviceIds.Contains(x.DeviceId))) yield return (x.TagId, $"Tag: {x.Name} ({x.TagId})"); + foreach (var x in _snapshot.Tags.Where(x => deviceIds.Contains(x.DeviceId)).Take(MaxPickerTags)) yield return (x.TagId, $"Tag: {x.Name} ({x.TagId})"); } else { diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterOverview.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterOverview.razor index 4364141d4..30ec858e4 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterOverview.razor +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterOverview.razor @@ -4,6 +4,7 @@ @using Microsoft.EntityFrameworkCore @using ZB.MOM.WW.OtOpcUa.Configuration @using ZB.MOM.WW.OtOpcUa.Configuration.Entities +@using ZB.MOM.WW.OtOpcUa.Configuration.Queries @inject IDbContextFactory DbFactory @inject NavigationManager Nav @@ -131,7 +132,7 @@ else private bool _loaded; private ServerCluster? _cluster; private List? _nodes; - private Deployment? _lastDeployment; + private DeploymentSummary? _lastDeployment; protected override async Task OnInitializedAsync() { @@ -144,9 +145,7 @@ else .Where(n => n.ClusterId == ClusterId) .OrderBy(n => n.NodeId) .ToListAsync(); - _lastDeployment = await db.Deployments.AsNoTracking() - .OrderByDescending(d => d.CreatedAtUtc) - .FirstOrDefaultAsync(); + _lastDeployment = await DeploymentQueries.LatestSummary(db).FirstOrDefaultAsync(); } _loaded = true; } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Reservations.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Reservations.razor index aae435988..df6bc23a8 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Reservations.razor +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Reservations.razor @@ -3,7 +3,7 @@ @rendermode RenderMode.InteractiveServer @using Microsoft.EntityFrameworkCore @using ZB.MOM.WW.OtOpcUa.Configuration -@using ZB.MOM.WW.OtOpcUa.Configuration.Entities +@using ZB.MOM.WW.OtOpcUa.Configuration.Queries @inject IDbContextFactory DbFactory @@ -11,6 +11,7 @@

External ID reservations

+
@if (_rows is null) @@ -20,7 +21,7 @@ else {
-

@_rows.Count reservation@(_rows.Count == 1 ? "" : "s")

+

@(_total > _rows.Count ? $"Showing {_rows.Count} of {_total}" : _total.ToString()) @(_includeReleased ? "" : "active ")reservation@(_total == 1 ? "" : "s")

@if (_rows.Count == 0) {
No reservations yet.
@@ -35,6 +36,7 @@ else Value Equipment UUID Cluster + @if (_includeReleased) { Released } @@ -45,6 +47,7 @@ else @r.Value @r.EquipmentUuid @r.ClusterId + @if (_includeReleased) { @(r.ReleasedAt?.ToString("u") ?? "active") } } @@ -56,13 +59,24 @@ else @code { - private List? _rows; + private IReadOnlyList? _rows; + private int _total; + private bool _includeReleased; - protected override async Task OnInitializedAsync() + protected override async Task OnInitializedAsync() => await LoadAsync(); + + private async Task ToggleReleased(ChangeEventArgs e) { + _includeReleased = e.Value is true; + await LoadAsync(); + } + + private async Task LoadAsync() + { + // Active rows only by default, projected to the shown columns and capped (#996 / A-8). await using var db = await DbFactory.CreateDbContextAsync(); - _rows = await db.ExternalIdReservations.AsNoTracking() - .OrderBy(r => r.Kind).ThenBy(r => r.Value) - .ToListAsync(); + var page = await ReservationListQuery.LoadAsync(db, _includeReleased); + _rows = page.Rows; + _total = page.Total; } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/DataConnections/DataConnectionAdminService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/DataConnections/DataConnectionAdminService.cs index 761499d91..0489fc1dd 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/DataConnections/DataConnectionAdminService.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/DataConnections/DataConnectionAdminService.cs @@ -17,7 +17,7 @@ public sealed class DataConnectionAdminService(IDbContextFactory LoadAsync(CancellationToken ct = default) { await using var db = await factory.CreateDbContextAsync(ct); - return await DraftSnapshotFactory.FromConfigDbAsync(db, ct); + return await DraftSnapshotFactory.FromConfigDbForDataConnectionsAsync(db, ct); } /// Returns the last successfully applied artifact's connection revision per node, when available. @@ -25,18 +25,27 @@ public sealed class DataConnectionAdminService(IDbContextFactory n.ClusterId == clusterId).Select(n => n.NodeId).ToListAsync(ct); - var result = new List(); + // lmxopcua#996 (A-5): resolve each node's applied deployment id first, then fetch + inflate + parse each DISTINCT + // artifact once. Two nodes on the same deployment used to download and inflate the same blob twice, on every + // page open and after every save. + var nodeDeployment = new List<(string Node, Guid Deployment)>(); foreach (var node in nodes) { var deployment = await db.NodeDeploymentStates.AsNoTracking().Where(s => s.NodeId == node && s.Status == NodeDeploymentStatus.Applied) .OrderByDescending(s => s.StartedAtUtc).Select(s => (Guid?)s.DeploymentId).FirstOrDefaultAsync(ct); - if (deployment is null) continue; - var blob = await db.Deployments.AsNoTracking().Where(d => d.DeploymentId == deployment).Select(d => d.ArtifactBlob).FirstOrDefaultAsync(ct); + if (deployment is not null) nodeDeployment.Add((node, deployment.Value)); + } + var result = new List(); + foreach (var group in nodeDeployment.GroupBy(x => x.Deployment)) + { + var deploymentId = group.Key; + var blob = await db.Deployments.AsNoTracking().Where(d => d.DeploymentId == deploymentId).Select(d => d.ArtifactBlob).FirstOrDefaultAsync(ct); if (blob is not { Length: > 0 }) continue; try { - result.AddRange(DeploymentArtifact.ParseDataConnections(blob, node) - .Select(c => new AppliedConnection(node, c.DataConnectionId, c.Revision, c.Enabled))); + var perNode = DeploymentArtifact.ParseDataConnections(blob, group.Select(x => x.Node)); + foreach (var (node, _) in group) + result.AddRange(perNode[node].Select(c => new AppliedConnection(node, c.DataConnectionId, c.Revision, c.Enabled))); } catch (Exception ex) when (ex is InvalidDataException or InvalidOperationException or System.Text.Json.JsonException) { @@ -50,7 +59,7 @@ public sealed class DataConnectionAdminService(IDbContextFactory(HandleDeployComposed); Receive(HandleDeployComposeFailed); Receive(HandleTestDriverConnect); - ReceiveAsync(HandleRestartDriverAsync); - ReceiveAsync(HandleReconnectDriverAsync); + Receive(HandleRestartDriver); + Receive(HandleReconnectDriver); + Receive(HandleDriverOperationAuditFailed); Receive(HandleAcknowledgeAlarm); Receive(HandleShelveAlarm); } @@ -773,64 +774,71 @@ public sealed class AdminOperationsActor : ReceiveActor } } - private async Task HandleRestartDriverAsync(RestartDriver msg) + /// + /// #996 (review H-3): a Restart/Reconnect REPORTS THE DISPATCH, which is what it does. It used to dispatch, then + /// write the ConfigEdit audit row inside the same try — so a ConfigDb failure answered "failed" for a + /// command that was already on its way to every node (the operator retried ⇒ a second restart, a second data gap), + /// and, as a ReceiveAsync, the audit write suspended the whole mailbox (one connect timeout per click + /// against an unreachable server; alarm acks and deploys queued behind it). Now both are synchronous receives: + /// dispatch, reply, and write the audit row off-thread; an audit failure is logged (with the full record) and + /// never changes the operator-visible result. + /// + private void HandleRestartDriver(RestartDriver msg) => + DispatchDriverOperation(msg, "restart", msg.DriverInstanceId, msg.ActorByUserName, msg.CorrelationId, + new RestartDriverResult(true, null, msg.CorrelationId), + _ => new RestartDriverResult(false, ServerFault("RestartDriver", msg.CorrelationId), msg.CorrelationId)); + + private void HandleReconnectDriver(ReconnectDriver msg) => + DispatchDriverOperation(msg, "reconnect", msg.DriverInstanceId, msg.ActorByUserName, msg.CorrelationId, + new ReconnectDriverResult(true, null, msg.CorrelationId), + _ => new ReconnectDriverResult(false, ServerFault("ReconnectDriver", msg.CorrelationId), msg.CorrelationId)); + + private void DispatchDriverOperation( + object command, string op, string driverInstanceId, string actor, object correlationId, + object success, Func failure) { var replyTo = Sender; try { - // Broadcast to every DriverHostActor on every node via the driver-control DPS topic. - // Only the host that owns the instance will act; others ignore it (id not found in _children). - Dispatch(DriverControlTopic.Name, msg); - - await using var db = await _dbFactory.CreateDbContextAsync(); - db.ConfigEdits.Add(new ConfigEdit - { - EntityType = "DriverInstance", - EntityId = Guid.TryParse(msg.DriverInstanceId, out var guid) ? guid : Guid.Empty, - FieldsJson = $"{{\"op\":\"restart\",\"driverInstanceId\":{System.Text.Json.JsonSerializer.Serialize(msg.DriverInstanceId)}}}", - EditedBy = msg.ActorByUserName, - SourceNode = Akka.Cluster.Cluster.Get(Context.System).SelfAddress.Host ?? "unknown", - }); - await db.SaveChangesAsync(); - - _log.Info("AdminOps: RestartDriver dispatched for {DriverInstanceId} by {User}", - msg.DriverInstanceId, msg.ActorByUserName); - replyTo.Tell(new RestartDriverResult(true, null, msg.CorrelationId)); + // Broadcast to every DriverHostActor on every node via the driver-control topic. Only the host that owns the + // instance acts; others ignore it (id not found in _children). + Dispatch(DriverControlTopic.Name, command); } catch (Exception ex) { - _log.Error(ex, "AdminOps: RestartDriver failed for {DriverInstanceId} (correlation {CorrelationId})", msg.DriverInstanceId, msg.CorrelationId); - replyTo.Tell(new RestartDriverResult(false, ServerFault("RestartDriver", msg.CorrelationId), msg.CorrelationId)); + // The ONLY genuine failure: nothing was dispatched. + _log.Error(ex, "AdminOps: {Op} dispatch failed for {DriverInstanceId} (correlation {CorrelationId})", op, driverInstanceId, correlationId); + replyTo.Tell(failure(ex)); + return; } - } - private async Task HandleReconnectDriverAsync(ReconnectDriver msg) - { - var replyTo = Sender; - try + _log.Info("AdminOps: {Op} dispatched for {DriverInstanceId} by {User}", op, driverInstanceId, actor); + replyTo.Tell(success); + + // Audit off the mailbox. Cluster state is read HERE (actor thread); the DB work is a pool-thread task. + var sourceNode = Akka.Cluster.Cluster.Get(Context.System).SelfAddress.Host ?? "unknown"; + var factory = _dbFactory; + Task.Run(async () => { - // Broadcast to every DriverHostActor; only the one owning the instance reacts. - Dispatch(DriverControlTopic.Name, msg); - - await using var db = await _dbFactory.CreateDbContextAsync(); + await using var db = await factory.CreateDbContextAsync().ConfigureAwait(false); db.ConfigEdits.Add(new ConfigEdit { EntityType = "DriverInstance", - EntityId = Guid.TryParse(msg.DriverInstanceId, out var guid) ? guid : Guid.Empty, - FieldsJson = $"{{\"op\":\"reconnect\",\"driverInstanceId\":{System.Text.Json.JsonSerializer.Serialize(msg.DriverInstanceId)}}}", - EditedBy = msg.ActorByUserName, - SourceNode = Akka.Cluster.Cluster.Get(Context.System).SelfAddress.Host ?? "unknown", + EntityId = Guid.TryParse(driverInstanceId, out var guid) ? guid : Guid.Empty, + FieldsJson = $"{{\"op\":\"{op}\",\"driverInstanceId\":{System.Text.Json.JsonSerializer.Serialize(driverInstanceId)}}}", + EditedBy = actor, + SourceNode = sourceNode, }); - await db.SaveChangesAsync(); - - _log.Info("AdminOps: ReconnectDriver dispatched for {DriverInstanceId} by {User}", - msg.DriverInstanceId, msg.ActorByUserName); - replyTo.Tell(new ReconnectDriverResult(true, null, msg.CorrelationId)); - } - catch (Exception ex) - { - _log.Error(ex, "AdminOps: ReconnectDriver failed for {DriverInstanceId} (correlation {CorrelationId})", msg.DriverInstanceId, msg.CorrelationId); - replyTo.Tell(new ReconnectDriverResult(false, ServerFault("ReconnectDriver", msg.CorrelationId), msg.CorrelationId)); - } + await db.SaveChangesAsync().ConfigureAwait(false); + }).PipeTo(Self, failure: ex => new DriverOperationAuditFailed(op, driverInstanceId, actor, correlationId, ex)); } + + private void HandleDriverOperationAuditFailed(DriverOperationAuditFailed m) => + _log.Warning(m.Error, + "AdminOps: the audit row for {Op} of {DriverInstanceId} by {User} could NOT be written (correlation {CorrelationId}); " + + "the command WAS dispatched and the operator was told so", + m.Op, m.DriverInstanceId, m.Actor, m.CorrelationId); + + /// The off-thread ConfigEdit audit write for a dispatched driver operation failed (#996 / H-3). + private sealed record DriverOperationAuditFailed(string Op, string DriverInstanceId, string Actor, object CorrelationId, Exception Error); } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Coordinators/ConfigPublishCoordinator.cs b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Coordinators/ConfigPublishCoordinator.cs index b508feb84..38509907f 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Coordinators/ConfigPublishCoordinator.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Coordinators/ConfigPublishCoordinator.cs @@ -109,6 +109,12 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU private readonly Dictionary _unpersisted = new(NodeIdComparer); private string? _lastPersistError; + /// Acks whose ConfigDb write is in flight on a pool thread (#996 / H-6), one per node. + private readonly Dictionary _persisting = new(NodeIdComparer); + + /// A newer ack for a node that already has a write in flight; started when that write returns (newest wins). + private readonly Dictionary _pendingBehind = new(NodeIdComparer); + /// /// Acks counted without a persisted row (a rejected write, or the deferral cap) — re-sent across a restart, since /// no row records them (fourth review M1). Dropped once a later persist of that node succeeds. @@ -250,6 +256,7 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU { Receive(HandleDispatch); Receive(HandleAck); + Receive(HandleAckPersisted); Receive(HandleRetryAckPersist); Receive(HandleDeadline); Receive(_ => { /* DPS subscribe confirmation */ }); @@ -278,6 +285,9 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU // Timers die with this incarnation; the mailbox survives. Re-send every ack that is still unpersisted so the // next incarnation (which stashes while Loading) persists and counts it — its node will not resend (M2). foreach (var pending in _unpersisted.Values) Self.Tell(pending.Ack); + // ...and acks whose write was in flight: its outcome is unknown to the next incarnation (#996). + foreach (var inflight in _persisting.Values) Self.Tell(inflight); + foreach (var behind in _pendingBehind.Values) Self.Tell(behind); // Fourth review M1: so are acks counted only FROM MEMORY (rejected writes, the deferral cap) — the outcome they // fed has not been written yet, and without this the next incarnation would wait on their nodes forever. foreach (var ack in _memoryOnlyAcks.Values) Self.Tell(ack); @@ -623,28 +633,81 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU // Persist FIRST: the row is the system of record (driver-only nodes never write their own, and nodes do not // resend). A throw here used to restart the actor and drop the ack; it is re-queued instead. - if (!TryPersistAck(msg)) return; - if (_acks.Count < _expectedAcks.Count) return; - CompleteFromAcks(); + StartAckPersist(msg); } /// - /// Persists an ack and, only on success, counts it (and drops any older unpersisted ack of that node, with its - /// retry timer — review L3). On failure the ack is held in and retried on a backoff. + /// lmxopcua#996 (review H-6): the ack write runs OFF the actor thread and its outcome comes back as + /// . The write used to be a blocking SaveChanges in the handler, so with the + /// ConfigDb unreachable (no retry strategy ⇒ a full connect timeout per call) N acks, N retry ticks and the + /// deadline's backlog re-try serialised N × timeout on the one coordinator thread, delaying every other message + /// (a new dispatch, the deadline decision) by minutes. Now the timeouts overlap and the mailbox stays live. + /// One write per node at a time; a newer ack for a node with a write in flight is held in + /// and started when that write returns. /// - /// when the ack is persisted and counted. - private bool TryPersistAck(ApplyAck msg) + private void StartAckPersist(ApplyAck msg) { - try + if (_persisting.ContainsKey(msg.NodeId)) { - PersistNodeAck(msg); + _pendingBehind[msg.NodeId] = msg; + return; } - catch (Exception ex) when (IsPoison(ex)) + _persisting[msg.NodeId] = msg; + var factory = _dbFactory; + // Task.Run: a factory/provider that throws synchronously still faults the TASK, never this thread. + Task.Run(() => PersistNodeAck(factory, msg)).PipeTo( + Self, + success: () => new AckPersisted(msg, null), + failure: ex => new AckPersisted(msg, ex is AggregateException { InnerException: { } inner } ? inner : ex)); + } + + /// The outcome of an off-thread ack write: counts the ack on success, queues its retry on failure. + private void HandleAckPersisted(AckPersisted result) + { + var node = result.Ack.NodeId; + _persisting.Remove(node); + + if (_current is null || result.Ack.DeploymentId != _current.Value) + { + // The deployment closed (or was superseded) while the write ran: nothing to count or retry. + _pendingBehind.Remove(node); + return; + } + + var counted = ApplyPersistOutcome(result.Ack, result.Error); + + if (_pendingBehind.Remove(node, out var next) && _current is not null && next.DeploymentId == _current.Value) + StartAckPersist(next); + + if (_current is null) return; + if (counted && _acks.Count >= _expectedAcks.Count && _expectedAcks.Count > 0) + { + CompleteFromAcks(); + return; + } + + // A deadline that was deferred on unpersisted acks decides as soon as the last write lands, rather than + // waiting out its re-armed delay. + if (_deadlineDeferredSinceUtc is not null && _unpersisted.Count == 0 && _persisting.Count == 0) + { + Timers.Cancel(DeadlineTimerKey); + Self.Tell(new DeadlineElapsed(_current.Value)); + } + } + + /// + /// Counts a persisted ack (and drops any older unpersisted ack of that node, with its retry timer — review L3). + /// On failure the ack is held in and retried on a backoff. + /// + /// when the ack is now counted. + private bool ApplyPersistOutcome(ApplyAck msg, Exception? error) + { + if (error is not null && IsPoison(error)) { // Third review #1: a write the DB REJECTS (constraint, truncation, …) fails identically on every retry; // retrying it forever wedged the deployment (the deadline deferred on it) and every later deploy. The // node DID ack, so count it from memory and say loudly that its row is not recorded. - _log.Error(ex, + _log.Error(error, "The ApplyAck from {Node} for {Id} ({Outcome}) was REJECTED by the ConfigDb and will not be retried; " + "counting it from memory. Its NodeDeploymentState row stays unrecorded", msg.NodeId, msg.DeploymentId, msg.Outcome); @@ -653,8 +716,10 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU CountAck(msg); return true; } - catch (Exception ex) + + if (error is not null) { + var ex = error; var attempts = _unpersisted.TryGetValue(msg.NodeId, out var prior) ? prior.Attempts + 1 : 1; _unpersisted[msg.NodeId] = new PendingPersist(msg, attempts); _lastPersistError = ex.Message; @@ -728,6 +793,8 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU private void HandleRetryAckPersist(RetryAckPersist msg) { if (!_unpersisted.TryGetValue(msg.Ack.NodeId, out var pending) || !ReferenceEquals(pending.Ack, msg.Ack)) return; + // A write for this node is already in flight (e.g. kicked by the deadline): its outcome re-arms the retry itself. + if (_persisting.ContainsKey(msg.Ack.NodeId)) return; HandleAck(msg.Ack); } @@ -751,9 +818,10 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU private static string AckRetryTimerKey(NodeId node) => $"ack-retry:{node.Value.ToUpperInvariant()}"; - private void PersistNodeAck(ApplyAck msg) + /// Writes one node's ack row. Static and touching no actor state: it runs on a pool thread (#996 / H-6). + private static void PersistNodeAck(IDbContextFactory dbFactory, ApplyAck msg) { - using var db = _dbFactory.CreateDbContext(); + using var db = dbFactory.CreateDbContext(); var row = db.NodeDeploymentStates .FirstOrDefault(x => x.NodeId == msg.NodeId.Value && x.DeploymentId == msg.DeploymentId.Value); if (row is null) return; @@ -830,11 +898,14 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU } // Review M2: an ack that ARRIVED but is not yet persisted must never be timed out as "no ack from" its node. // Persist the backlog now; if the DB still refuses, defer the decision (the terminal write needs it too). - if (_unpersisted.Count > 0) + if (_unpersisted.Count > 0 || _persisting.Count > 0) { - foreach (var pending in _unpersisted.Values.ToList()) TryPersistAck(pending.Ack); + // #996 / H-6: kick the whole backlog off-thread at once (the connect timeouts overlap, they no longer + // serialise on this thread); the deadline is re-armed below and also fires early once the last write lands. + foreach (var pending in _unpersisted.Values.ToList()) StartAckPersist(pending.Ack); _deadlineDeferredSinceUtc ??= DateTime.UtcNow; - if (_unpersisted.Count > 0 && DateTime.UtcNow - _deadlineDeferredSinceUtc.Value >= MaxDeadlineDeferral) + var capped = DateTime.UtcNow - _deadlineDeferredSinceUtc.Value >= MaxDeadlineDeferral; + if (capped) { // Third review #1: bounded. Past the cap the outcome is decided from what was RECEIVED — the nodes did // ack — rather than waiting on rows that may never be writable. @@ -848,13 +919,15 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU _memoryOnlyAcks[pending.Ack.NodeId] = pending.Ack; CountAck(pending.Ack); } + // A write still in flight at the cap is decided from memory too (its late outcome is discarded). + foreach (var inflight in _persisting.Values) CountAck(inflight); } - if (_unpersisted.Count > 0) + else if (_unpersisted.Count > 0 || _persisting.Count > 0) { - var delay = Backoff(_unpersisted.Values.Min(p => p.Attempts)); + var delay = _unpersisted.Count > 0 ? Backoff(_unpersisted.Values.Min(p => p.Attempts)) : Backoff(1); _log.Warning( "Deployment {Id} reached its apply deadline with {Count} received ack(s) not yet persisted; deferring " + - "the outcome {Delay} until they are", _current.Value, _unpersisted.Count, delay); + "the outcome {Delay} until they are", _current.Value, _unpersisted.Count + _persisting.Count, delay); Timers.StartSingleTimer(DeadlineTimerKey, msg, delay); return; } @@ -936,6 +1009,7 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU ReportPersistBacklog(); } _memoryOnlyAcks.Clear(); + _pendingBehind.Clear(); _current = null; _expectedAcks.Clear(); _acks.Clear(); @@ -945,6 +1019,9 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU private const string DeadlineTimerKey = "apply-deadline"; private const string LoadRetryTimerKey = "recovery-load-retry"; + /// The outcome of an off-thread ack write (#996 / H-6): error = persisted. + private sealed record AckPersisted(ApplyAck Ack, Exception? Error); + /// An ack whose persist failed, re-delivered by its retry timer. private sealed record RetryAckPersist(ApplyAck Ack); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Health/HealthEndpoints.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Health/HealthEndpoints.cs index 24fec2e01..9e3995ec9 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Health/HealthEndpoints.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Health/HealthEndpoints.cs @@ -10,6 +10,7 @@ using ZB.MOM.WW.Health.EntityFrameworkCore; using ZB.MOM.WW.LocalDb.Replication; using ZB.MOM.WW.OtOpcUa.Cluster; using ZB.MOM.WW.OtOpcUa.Configuration; +using ZB.MOM.WW.OtOpcUa.Configuration.Queries; using ZB.MOM.WW.OtOpcUa.Host.Configuration; using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; @@ -85,7 +86,7 @@ public static class HealthEndpoints tags: new[] { ZbHealthTags.Ready, ZbHealthTags.Active }, args: new DatabaseHealthCheckOptions { - ProbeQuery = static (db, ct) => db.Deployments.AsNoTracking().Take(1).ToListAsync(ct), + ProbeQuery = static (db, ct) => DeploymentQueries.ProbeQuery(db).ToListAsync(ct), }); // lmxopcua#868: Degraded (still 200) while the deploy coordinator singleton on this node is retrying diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs index 922af0a3d..590312480 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs @@ -452,6 +452,7 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl _server.NodeManager.HistoryReadBatchParallelism = _serverHistorianOptions.HistoryReadBatchParallelism; _server.NodeManager.MaxConcurrentHistoryReadBatches = _serverHistorianOptions.MaxConcurrentHistoryReadBatches; _server.NodeManager.HistoryReadDeadline = _serverHistorianOptions.HistoryReadDeadline; + _server.NodeManager.MaxEventsPerRead = _serverHistorianOptions.MaxEventsPerRead; // HistoryUpdate is Primary-only (BadInvalidState elsewhere, and closed until this node's first // redundancy snapshot) and refuses a SourceTimestamp beyond now + HistoryUpdateMaxFutureSkew (BadOutOfRange), diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/HistoryPaging.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/HistoryPaging.cs index 18a682592..83ff194f3 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/HistoryPaging.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/HistoryPaging.cs @@ -175,6 +175,30 @@ internal static class HistoryPaging } } + /// + /// Advertise the server events cap as HistoryServerCapabilities/MaxReturnEventValues (Part 11 §5.4.2; 0 = no + /// limit), the events twin of . Idempotent, never throws, advisory only. + /// + /// The running server (null before start). + /// The cap (<= 0 advertises 0 = no limit). + /// true when the property was written. + public static bool AdvertiseMaxReturnEventValues(IServerInternal? server, int maxEventsPerRead) + { + if (server?.DiagnosticsNodeManager is not DiagnosticsNodeManager diagnostics) return false; + try + { + var capabilities = diagnostics.GetDefaultHistoryCapabilitiesAsync().AsTask().GetAwaiter().GetResult(); + if (capabilities?.MaxReturnEventValues is not { } property) return false; + property.Value = (uint)Math.Max(0, maxEventsPerRead); + property.ClearChangeMasks(diagnostics.SystemContext, false); + return true; + } + catch (Exception) + { + return false; + } + } + /// /// Decide whether a just-returned read is "full" and therefore MAY be followed by more data — /// the signal to emit a continuation point. A read is full when it was issued with a finite request diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs index a6c2eb2db..467c63ef1 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs @@ -650,6 +650,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage // #736: HistoryServerCapabilities/MaxReturnDataValues (i=11273) carries the source's raw-page cap // (0 = unlimited), re-synced on every source assignment like the aggregate set above. + HistoryPaging.AdvertiseMaxReturnEventValues(Server, MaxEventsPerRead); if (!HistoryPaging.AdvertiseMaxReturnDataValues(Server, source.MaxRawValuesPerRead)) { _logger.LogWarning( @@ -918,6 +919,30 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage /// public int MaxConcurrentHistoryReadBatches { get; set; } = DefaultMaxConcurrentHistoryReadBatches; + /// The default of : 10 000 events per HistoryReadEvents page. + public const int DefaultMaxEventsPerRead = 10_000; + + private int _maxEventsPerRead = DefaultMaxEventsPerRead; + + /// + /// The most events ONE HistoryReadEvents page returns for a node, and the most the backend is asked for in one read + /// (lmxopcua#996, review U-6) — the events twin of the raw cap ServerHistorian:MaxRawValuesPerRead. A request's + /// NumValuesPerNode = 0 ("all values") no longer materialises a whole window in memory (backend list, multi-source + /// merge, per-event field lists, encoder): it is served as pages of at most this many events, each with a continuation + /// point (Part 11 allows fewer than requested with one); a larger NumValuesPerNode is paged at it too. Advertised as + /// HistoryServerCapabilities/MaxReturnEventValues. Mirrors ServerHistorianOptions.MaxEventsPerRead; the + /// Host sets it at StartAsync. Non-positive = unbounded (the pre-#996 behaviour). + /// + public int MaxEventsPerRead + { + get => Volatile.Read(ref _maxEventsPerRead); + set + { + Volatile.Write(ref _maxEventsPerRead, value); + HistoryPaging.AdvertiseMaxReturnEventValues(Server, value); + } + } + /// The CPU-scaled default of : clamp(2 × ProcessorCount, 4, 16). public static int DefaultMaxConcurrentHistoryReadBatches { get; } = Math.Clamp(Environment.ProcessorCount * 2, 4, 16); @@ -9453,6 +9478,13 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage } } + // #996 (U-6): the server's own per-page event ceiling. Applied AFTER the request/cursor normalisation above (an + // end-only 0-count read keeps its forward meaning) and before the cursor is built, so the capped size is the + // page size the cursor carries: 0 ("all") and any larger N become pages of the cap, each with a continuation point. + var eventCap = MaxEventsPerRead; + if (eventCap > 0 && (numValuesPerNode == 0 || numValuesPerNode > (uint)eventCap)) + numValuesPerNode = (uint)eventCap; + // A reverse read on a backend that cannot read newest-first (the Gateway) is never sent there (it is refused // here); instead it is walked back from bounded forward reads — the raw walk, with ties ordered by // EventId because the gateway orders by event time only. Decided by the capability, not by catching an diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DeploymentArtifact.DataConnections.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DeploymentArtifact.DataConnections.cs index 0ae0ce274..48d863f37 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DeploymentArtifact.DataConnections.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DeploymentArtifact.DataConnections.cs @@ -22,6 +22,26 @@ public static partial class DeploymentArtifact return parsed.ParseDataConnections(nodeId); } + /// + /// Read the node-effective data connections of SEVERAL nodes from one artifact, inflating and opening the blob + /// once (lmxopcua#996 / A-5: two nodes on one deployment used to inflate the same blob twice). + /// + /// The artifact blob. + /// The nodes to project for. + /// One entry per distinct node id (case-insensitive). + public static IReadOnlyDictionary> ParseDataConnections( + ReadOnlySpan blob, + IEnumerable nodeIds + ) + { + using var parsed = Open(blob.ToArray()); + var result = new Dictionary>(StringComparer.OrdinalIgnoreCase); + foreach (var node in nodeIds) + if (!result.ContainsKey(node)) + result[node] = parsed.ParseDataConnections(node); + return result; + } + /// Read the node-effective data exports from an artifact. public static IReadOnlyList ParseDataExports(ReadOnlySpan blob, string nodeId) { diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs index 43aa0623c..27d915f6a 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs @@ -1477,12 +1477,15 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn return; } - var deployment = db.Deployments + // Hash only: the whole row drags the multi-MB ArtifactBlob (#996 / C-6). + var revisionHash = db.Deployments .AsNoTracking() - .FirstOrDefault(d => d.DeploymentId == latest.DeploymentId); - var revision = deployment is null + .Where(d => d.DeploymentId == latest.DeploymentId) + .Select(d => d.RevisionHash) + .FirstOrDefault(); + var revision = revisionHash is null ? (RevisionHash?)null - : RevisionHash.Parse(deployment.RevisionHash); + : RevisionHash.Parse(revisionHash); switch (latest.Status) { diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Health/DbHealthProbeActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Health/DbHealthProbeActor.cs index 8134c9142..b8991de97 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Health/DbHealthProbeActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Health/DbHealthProbeActor.cs @@ -2,6 +2,7 @@ using Akka.Actor; using Akka.Event; using Microsoft.EntityFrameworkCore; using ZB.MOM.WW.OtOpcUa.Configuration; +using ZB.MOM.WW.OtOpcUa.Configuration.Queries; namespace ZB.MOM.WW.OtOpcUa.Runtime.Health; @@ -96,7 +97,8 @@ public sealed class DbHealthProbeActor : ReceiveActor, IWithTimers // Local to this lease — the pool resets it on return (see DriverHostActor.LoadArtifactBlob). if (db.Database.IsRelational()) db.Database.SetCommandTimeout(CommandTimeout); - _ = db.Deployments.AsNoTracking().Take(1).ToList(); + // Id-only projection: a whole Deployment row drags ArtifactBlob (#996 / C-6). + _ = DeploymentQueries.ProbeQuery(db).ToList(); return new DbHealthStatus(true, DateTime.UtcNow, null); } catch (Exception ex) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Historian/ServerHistorianOptions.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Historian/ServerHistorianOptions.cs index 1e474916f..be6d4565a 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Historian/ServerHistorianOptions.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Historian/ServerHistorianOptions.cs @@ -225,6 +225,20 @@ public sealed class ServerHistorianOptions /// public int MaxRawValuesPerRead { get; init; } = DefaultMaxRawValuesPerRead; + /// The default of : 10 000 events per HistoryReadEvents page. + public const int DefaultMaxEventsPerRead = 10_000; + + /// + /// Every backend: the most events the server returns on ONE HistoryReadEvents page and asks a backend for in one read + /// (lmxopcua#996, review U-6) — the events twin of . A client's + /// NumValuesPerNode = 0 ("all values") or any larger N is served as pages of at most this many events, each with + /// a continuation point (Part 11 allows fewer values than requested with one), so a whole-history read of an + /// alarm-owning folder can no longer buffer millions of events (several times over) and fail at encode time. Advertised as + /// HistoryServerCapabilities/MaxReturnEventValues. Default 10 000. Non-positive = unbounded, the pre-#996 + /// behaviour (a warning). + /// + public int MaxEventsPerRead { get; init; } = DefaultMaxEventsPerRead; + /// /// as the backends and the node manager apply it: 0 (unbounded) when /// non-positive, otherwise at least . The one place the rule lives. @@ -285,6 +299,8 @@ public sealed class ServerHistorianOptions warnings.Add($"ServerHistorian:MaxConcurrentHistoryReadBatches is {MaxConcurrentHistoryReadBatches} — must be > 0; the process-wide HistoryRead batch limiter is disabled."); if (MaxTimeWeightedRawRows <= 0) warnings.Add($"ServerHistorian:MaxTimeWeightedRawRows is {MaxTimeWeightedRawRows} — must be > 0; time-weighted aggregate reads on the SqlServer/QuestDb backends stream an unbounded number of raw samples."); + if (MaxEventsPerRead <= 0) + warnings.Add($"ServerHistorian:MaxEventsPerRead is {MaxEventsPerRead} — must be > 0; HistoryRead-Events pages are unbounded, so a client asking for a whole window (NumValuesPerNode = 0) materialises every event in memory."); if (MaxRawValuesPerRead <= 0) warnings.Add($"ServerHistorian:MaxRawValuesPerRead is {MaxRawValuesPerRead} — must be > 0; HistoryRead-Raw pages and backend raw reads are unbounded, so a client asking for a whole window (NumValuesPerNode = 0) materialises every sample in memory."); else if (MaxRawValuesPerRead < MinMaxRawValuesPerRead) diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DeploymentQueriesTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DeploymentQueriesTests.cs new file mode 100644 index 000000000..4287b21ba --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DeploymentQueriesTests.cs @@ -0,0 +1,68 @@ +using Microsoft.EntityFrameworkCore; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; +using ZB.MOM.WW.OtOpcUa.Configuration.Queries; + +namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests; + +/// +/// lmxopcua#996 / review C-6: the blob-free Deployment queries must never put ArtifactBlob in the SQL +/// SELECT list. The query shape is asserted against the SQL Server provider's generated text +/// (ToQueryString — no connection is opened), with a positive control proving the assertion can fail. +/// +[Trait("Category", "Unit")] +public sealed class DeploymentQueriesTests +{ + private static OtOpcUaConfigDbContext SqlServerContext() => + new(new DbContextOptionsBuilder() + .UseSqlServer("Server=127.0.0.1,1;Database=never;Connect Timeout=1") + .Options); + + /// Positive control: the naive whole-entity read DOES select the blob. + [Fact] + public void WholeEntityQuery_SelectsArtifactBlob() + { + using var db = SqlServerContext(); + db.Deployments.AsNoTracking().Take(1).ToQueryString().ShouldContain("ArtifactBlob"); + } + + /// The health-probe / readiness query selects only the id. + [Fact] + public void ProbeQuery_DoesNotSelectArtifactBlob() + { + using var db = SqlServerContext(); + var sql = DeploymentQueries.ProbeQuery(db).ToQueryString(); + sql.ShouldNotContain("ArtifactBlob"); + sql.ShouldContain("DeploymentId"); + } + + /// The cluster-overview latest-deployment query carries the metadata but not the blob. + [Fact] + public void LatestSummary_DoesNotSelectArtifactBlob() + { + using var db = SqlServerContext(); + var sql = DeploymentQueries.LatestSummary(db).ToQueryString(); + sql.ShouldNotContain("ArtifactBlob"); + sql.ShouldContain("RevisionHash"); + sql.ShouldContain("SealedAtUtc"); + } + + /// The summary projection returns the right newest row. + [Fact] + public async Task LatestSummary_ReturnsNewestRow() + { + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase($"dep-q-{Guid.NewGuid():N}").Options; + await using var db = new OtOpcUaConfigDbContext(options); + db.Deployments.Add(new Deployment { RevisionHash = "old", CreatedBy = "t", CreatedAtUtc = DateTime.UtcNow.AddHours(-1), ArtifactBlob = new byte[8] }); + db.Deployments.Add(new Deployment { RevisionHash = "new", CreatedBy = "t", Status = DeploymentStatus.Sealed, ArtifactBlob = new byte[8] }); + await db.SaveChangesAsync(TestContext.Current.CancellationToken); + + var latest = await DeploymentQueries.LatestSummary(db).SingleAsync(TestContext.Current.CancellationToken); + latest.RevisionHash.ShouldBe("new"); + latest.Status.ShouldBe(DeploymentStatus.Sealed); + (await DeploymentQueries.ProbeQuery(db).ToListAsync(TestContext.Current.CancellationToken)).Count.ShouldBe(1); + } +} diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/ReservationListQueryTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/ReservationListQueryTests.cs new file mode 100644 index 000000000..aa8aadc02 --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/ReservationListQueryTests.cs @@ -0,0 +1,63 @@ +using Microsoft.EntityFrameworkCore; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; +using ZB.MOM.WW.OtOpcUa.Configuration.Queries; + +namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests; + +/// lmxopcua#996 / review A-8: the /reservations page read is active-only by default, projected and capped. +[Trait("Category", "Unit")] +public sealed class ReservationListQueryTests +{ + private static OtOpcUaConfigDbContext InMemory() => + new(new DbContextOptionsBuilder().UseInMemoryDatabase($"resv-{Guid.NewGuid():N}").Options); + + private static void Seed(OtOpcUaConfigDbContext db, int active, int released) + { + for (var i = 0; i < active + released; i++) + db.ExternalIdReservations.Add(new ExternalIdReservation + { + ReservationId = Guid.NewGuid(), Kind = i % 2 == 0 ? ReservationKind.ZTag : ReservationKind.SAPID, + Value = $"v{i:0000}", EquipmentUuid = Guid.NewGuid(), ClusterId = "MAIN", FirstPublishedBy = "t", + ReleasedAt = i < active ? null : DateTime.UtcNow, ReleasedBy = i < active ? null : "t", + }); + db.SaveChanges(); + } + + /// 1,000 rows render at most the page size and the total is reported; released rows are hidden by default. + [Fact] + public async Task Page_is_capped_and_defaults_to_active_rows() + { + using var db = InMemory(); + Seed(db, active: 700, released: 300); + + var page = await ReservationListQuery.LoadAsync(db, includeReleased: false, ct: TestContext.Current.CancellationToken); + page.Rows.Count.ShouldBe(ReservationListQuery.DefaultPageSize); + page.Total.ShouldBe(700); + page.Rows.ShouldAllBe(r => r.ReleasedAt == null); + + // Positive control: asking for released rows too changes the total (so the filter was what hid them). + var all = await ReservationListQuery.LoadAsync(db, includeReleased: true, pageSize: 50, ct: TestContext.Current.CancellationToken); + all.Total.ShouldBe(1000); + all.Rows.Count.ShouldBe(50); + } + + /// The SQL selects only the displayed columns (no audit columns) and filters released rows server-side. + [Fact] + public void Query_projects_displayed_columns_and_filters_released_rows_in_sql() + { + using var db = new OtOpcUaConfigDbContext(new DbContextOptionsBuilder() + .UseSqlServer("Server=127.0.0.1,1;Database=never;Connect Timeout=1").Options); + + var sql = ReservationListQuery.Query(db, includeReleased: false).ToQueryString(); + sql.ShouldContain("[ReleasedAt] IS NULL"); + sql.ShouldNotContain("FirstPublishedBy"); + sql.ShouldNotContain("LastPublishedAt"); + + ReservationListQuery.Query(db, includeReleased: true).ToQueryString().ShouldNotContain("IS NULL"); + // Positive control: the whole-entity read does select the audit columns. + db.ExternalIdReservations.AsNoTracking().ToQueryString().ShouldContain("FirstPublishedBy"); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/DataConnections/DataConnectionsAppliedReadSqlServerTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/DataConnections/DataConnectionsAppliedReadSqlServerTests.cs new file mode 100644 index 000000000..90c7c790d --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/DataConnections/DataConnectionsAppliedReadSqlServerTests.cs @@ -0,0 +1,110 @@ +using System.Data.Common; +using System.Security.Claims; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Components.Authorization; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Diagnostics; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.AdminUI.DataConnections; +using ZB.MOM.WW.OtOpcUa.Configuration; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; +using ZB.MOM.WW.OtOpcUa.Configuration.Validation; +using ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.DataConnections; + +/// +/// lmxopcua#996 (review A-5): LoadAppliedAsync fetches and inflates each DISTINCT applied artifact once, however +/// many nodes share it. Counted on a real SQL Server (EF InMemory has no command stream to observe). +/// +[Collection(nameof(AdminUiSqlServerCollection))] +public sealed class DataConnectionsAppliedReadSqlServerTests(AdminUiSqlServerFixture sql) +{ + [SqlServerFact] + public async Task Two_nodes_on_one_deployment_read_the_artifact_blob_once() + { + var ct = TestContext.Current.CancellationToken; + var suffix = Guid.NewGuid().ToString("N")[..8]; + var cluster = $"c996-{suffix}"; + string[] nodes = [$"n1-{suffix}:4840", $"n2-{suffix}:4840"]; + var deploymentId = Guid.NewGuid(); + var at = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc); + + var draft = new DraftSnapshot + { + GenerationId = 0, ClusterId = cluster, + ServerClusters = [new ServerCluster { ClusterId = cluster, Name = "c", Enterprise = "e", Site = "s", NodeCount = 2, RedundancyMode = RedundancyMode.Warm, CreatedBy = "t", CreatedAt = at }], + ClusterNodes = nodes.Select(n => new ClusterNode { NodeId = n, ClusterId = cluster, Host = n.Split(':')[0], ApplicationUri = "urn:" + n, CreatedAt = at, CreatedBy = "t" }).ToList(), + DataConnections = [new DataConnection + { + DataConnectionId = $"peer-{suffix}", ClusterId = cluster, Enabled = true, ConsumerNodeIds = [.. nodes], + TargetMode = DataTargetMode.Cluster, ExpectedClusterId = "remote", EligibleTargetNodeIds = ["r1"], + Endpoints = ["https://peer:7443"], SecretReference = "secret:data/up", SecretScopeClusterId = cluster, + AllowedOperations = DataOperations.Browse | DataOperations.Read, + }], + }; + var blob = ConfigComposer.Compose(draft).Blob; + + await using (var db = await sql.Factory.CreateDbContextAsync(ct)) + { + db.ServerClusters.AddRange(draft.ServerClusters); + db.ClusterNodes.AddRange(draft.ClusterNodes); + db.Deployments.Add(new Deployment { DeploymentId = deploymentId, RevisionHash = $"r-{suffix}", CreatedBy = "t", Status = DeploymentStatus.Sealed, ArtifactBlob = blob }); + await db.SaveChangesAsync(ct); + db.NodeDeploymentStates.AddRange(nodes.Select(n => new NodeDeploymentState { NodeId = n, DeploymentId = deploymentId, Status = NodeDeploymentStatus.Applied })); + await db.SaveChangesAsync(ct); + } + + try + { + var counter = new BlobReadCounter(); + var factory = new CountingFactory(sql.ConnectionString!, counter); + var service = new DataConnectionAdminService(factory, new Auth(), new User()); + + var applied = await service.LoadAppliedAsync(cluster, ct); + + applied.Select(a => a.NodeId).OrderBy(x => x).ShouldBe(nodes.OrderBy(x => x)); + applied.ShouldAllBe(a => a.ConnectionId == $"peer-{suffix}"); + counter.BlobReads.ShouldBe(1); + } + finally + { + await using var db = await sql.Factory.CreateDbContextAsync(CancellationToken.None); + await db.NodeDeploymentStates.Where(s => s.DeploymentId == deploymentId).ExecuteDeleteAsync(CancellationToken.None); + await db.Deployments.Where(d => d.DeploymentId == deploymentId).ExecuteDeleteAsync(CancellationToken.None); + await db.ClusterNodes.Where(n => n.ClusterId == cluster).ExecuteDeleteAsync(CancellationToken.None); + await db.ServerClusters.Where(c => c.ClusterId == cluster).ExecuteDeleteAsync(CancellationToken.None); + } + } + + private sealed class BlobReadCounter : DbCommandInterceptor + { + public int BlobReads; + public override ValueTask> ReaderExecutingAsync(DbCommand command, CommandEventData data, InterceptionResult result, CancellationToken ct = default) + { + if (command.CommandText.Contains("ArtifactBlob", StringComparison.Ordinal)) Interlocked.Increment(ref BlobReads); + return ValueTask.FromResult(result); + } + } + + private sealed class CountingFactory(string connectionString, BlobReadCounter counter) : IDbContextFactory + { + public OtOpcUaConfigDbContext CreateDbContext() => + new(new DbContextOptionsBuilder().UseSqlServer(connectionString).AddInterceptors(counter).Options); + public Task CreateDbContextAsync(CancellationToken cancellationToken = default) => Task.FromResult(CreateDbContext()); + } + + private sealed class User : AuthenticationStateProvider + { + public override Task GetAuthenticationStateAsync() => Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity("test")))); + } + + private sealed class Auth : IAuthorizationService + { + public Task AuthorizeAsync(ClaimsPrincipal user, object? resource, IEnumerable requirements) => Task.FromResult(AuthorizationResult.Success()); + public Task AuthorizeAsync(ClaimsPrincipal user, object? resource, string policyName) => Task.FromResult(AuthorizationResult.Success()); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/DataConnections/DataConnectionsNarrowLoadTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/DataConnections/DataConnectionsNarrowLoadTests.cs new file mode 100644 index 000000000..0dea721ef --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/DataConnections/DataConnectionsNarrowLoadTests.cs @@ -0,0 +1,129 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Components.Authorization; +using Microsoft.EntityFrameworkCore; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.AdminUI.DataConnections; +using ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Acls; +using ZB.MOM.WW.OtOpcUa.Configuration; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; +using ZB.MOM.WW.OtOpcUa.Configuration.Validation; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.DataConnections; + +/// +/// lmxopcua#996 (review C-11 / A-5): the data-connections page and its save/delete no longer read the whole ConfigDb. +/// The narrow loader must (a) skip the tables the validator never reads, (b) keep exactly the tag data the rules do read +/// (the alarm bit), and (c) leave the authoring rules unchanged. +/// +[Trait("Category", "Unit"), Trait("Feature", "GrpcData")] +public sealed class DataConnectionsNarrowLoadTests +{ + private const string AlarmConfig = "{\"alarm\":{\"alarmType\":\"AlarmCondition\",\"severity\":700}}"; + + private static async Task> SeedAsync() + { + var name = $"dc-narrow-{Guid.NewGuid():N}"; + await using (var db = AclScopeTestDb.CreateNamed(name)) + { + AclScopeTestDb.Seed(db); // MAIN cluster, DEV-1, TAG-speed ("{}") and four ApiKeys + db.Tags.Add(new Tag + { + TagId = "TAG-alarm", DeviceId = AclScopeTestDb.DeviceId, TagGroupId = null, Name = "overtemp", + DataType = "Boolean", AccessLevel = TagAccessLevel.Read, TagConfig = AlarmConfig, + }); + db.Tags.Add(new Tag + { + TagId = "TAG-bulky", DeviceId = AclScopeTestDb.DeviceId, TagGroupId = null, Name = "bulky", + DataType = "Float", AccessLevel = TagAccessLevel.Read, TagConfig = "{\"address\":\"" + new string('x', 4000) + "\"}", + }); + db.Scripts.Add(new Script { ScriptId = "S1", Name = "s", SourceCode = "return 1;", SourceHash = "h" }); + await db.SaveChangesAsync(TestContext.Current.CancellationToken); + } + return AclScopeTestDb.Factory(name); + } + + [Fact] + public async Task Narrow_snapshot_skips_tables_the_validator_never_reads_and_strips_tag_config() + { + var ct = TestContext.Current.CancellationToken; + var factory = await SeedAsync(); + await using var db = await factory.CreateDbContextAsync(ct); + + var narrow = await DraftSnapshotFactory.FromConfigDbForDataConnectionsAsync(db, ct); + var full = await DraftSnapshotFactory.FromConfigDbAsync(db, ct); + + // Positive control: the full snapshot DOES carry them, so the absence below is a real difference. + full.ApiKeys.Count.ShouldBeGreaterThan(0); + full.Scripts.Count.ShouldBe(1); + full.Tags.Single(t => t.TagId == "TAG-bulky").TagConfig.Length.ShouldBeGreaterThan(4000); + + narrow.ApiKeys.ShouldBeEmpty(); + narrow.Scripts.ShouldBeEmpty(); + narrow.NodeAcls.ShouldBeEmpty(); + narrow.PollGroups.ShouldBeEmpty(); + narrow.ActiveReservations.ShouldBeEmpty(); + + narrow.Tags.Select(t => t.TagId).ShouldBe(full.Tags.Select(t => t.TagId)); + narrow.Tags.Single(t => t.TagId == "TAG-bulky").TagConfig.ShouldBe("{}"); + narrow.Tags.Single(t => t.TagId == AclScopeTestDb.TagId).TagConfig.ShouldBe("{}"); + narrow.Tags.Single(t => t.TagId == "TAG-alarm").TagConfig.ShouldBe(AlarmConfig); + + // Same rows for everything the validator reads. + narrow.DataConnections.Count.ShouldBe(full.DataConnections.Count); + narrow.ClusterNodes.Count.ShouldBe(full.ClusterNodes.Count); + narrow.Devices.Count.ShouldBe(full.Devices.Count); + DataConnectionValidator.Validate(narrow).ShouldBe(DataConnectionValidator.Validate(full)); + } + + [Fact] + public void Narrow_tag_query_selects_tag_config_only_behind_an_alarm_guard() + { + using var db = new OtOpcUaConfigDbContext(new DbContextOptionsBuilder() + .UseSqlServer("Server=127.0.0.1,1;Database=never;Connect Timeout=1").Options); + + var sql = DraftSnapshotFactory.NarrowTags(db).ToQueryString(); + sql.ShouldContain("CASE"); + sql.ShouldContain("alarm"); + sql.ShouldNotContain("[t].[DataType]"); + sql.ShouldNotContain("[t].[AccessLevel]"); + sql.ShouldNotContain("[t].[PollGroupId]"); + + // Positive control: the whole-entity read selects them. + var whole = db.Tags.AsNoTracking().ToQueryString(); + whole.ShouldContain("[t].[DataType]"); + } + + [Fact] + public async Task An_export_rooted_at_an_alarm_bearing_tag_is_still_refused_through_the_narrow_load() + { + var ct = TestContext.Current.CancellationToken; + var factory = await SeedAsync(); + var service = new DataConnectionAdminService(factory, new Auth(), new User()); + + DataExport Export(string id, string tag) => new() + { + ClusterId = "MAIN", DataExportId = id, Enabled = true, Realm = DataRealm.Raw, + RootKind = "RawTag", RootEntityId = tag, PrincipalId = "peer", + AllowedOperations = DataOperations.Browse | DataOperations.Read, + }; + + await service.SaveAsync("MAIN", Export("exp-value", AclScopeTestDb.TagId), ct); + await Should.ThrowAsync(() => service.SaveAsync("MAIN", Export("exp-alarm", "TAG-alarm"), ct)); + (await service.LoadAsync(ct)).DataExports.Select(e => e.DataExportId).ShouldBe(["exp-value"]); + } + + private sealed class User : AuthenticationStateProvider + { + public override Task GetAuthenticationStateAsync() => Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity("test")))); + } + + private sealed class Auth : IAuthorizationService + { + public Task AuthorizeAsync(ClaimsPrincipal user, object? resource, IEnumerable requirements) => Task.FromResult(AuthorizationResult.Success()); + public Task AuthorizeAsync(ClaimsPrincipal user, object? resource, string policyName) => Task.FromResult(AuthorizationResult.Success()); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorDriverOperationTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorDriverOperationTests.cs new file mode 100644 index 000000000..538a95ed1 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorDriverOperationTests.cs @@ -0,0 +1,114 @@ +using Akka.Actor; +using Microsoft.EntityFrameworkCore; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin; +using ZB.MOM.WW.OtOpcUa.Commons.Messages.Mesh; +using ZB.MOM.WW.OtOpcUa.Commons.Types; +using ZB.MOM.WW.OtOpcUa.Configuration; +using ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations; +using ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.Harness; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; + +namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Tests; + +/// +/// lmxopcua#996 (review H-3): Restart/Reconnect report the DISPATCH. A ConfigDb failure while writing the audit row +/// must not turn an already-dispatched command into a "failed" reply (the operator retries ⇒ a second restart), and the +/// audit write must not suspend the admin mailbox. +/// +public sealed class AdminOperationsActorDriverOperationTests : ControlPlaneActorTestBase +{ + private static readonly TimeSpan AckBudget = TimeSpan.FromSeconds(1); + + private (IActorRef Actor, Akka.TestKit.TestProbe Router) Create(IDbContextFactory factory) + { + var router = CreateTestProbe("router"); + var coordinator = CreateTestProbe("coord"); + var actor = Sys.ActorOf(AdminOperationsActor.Props(factory, coordinator.Ref, Enumerable.Empty(), meshRouter: router.Ref)); + return (actor, router); + } + + /// The audit write throws: the command still went out and the reply says so (success). + [Theory] + [InlineData(true)] + [InlineData(false)] + public void Audit_failure_does_not_turn_a_dispatched_command_into_a_failure(bool restart) + { + var (actor, router) = Create(new ThrowingAsyncFactory(NewInMemoryDbFactory())); + var correlation = Guid.NewGuid(); + + if (restart) actor.Tell(new RestartDriver("MAIN", "drv-1", "joe", correlation)); + else actor.Tell(new ReconnectDriver("MAIN", "drv-1", "joe", correlation)); + + var command = router.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + if (restart) command.Message.ShouldBeOfType(); + else command.Message.ShouldBeOfType(); + + if (restart) + { + var reply = ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + reply.Ok.ShouldBeTrue(); + reply.CorrelationId.ShouldBe(correlation); + } + else + { + var reply = ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + reply.Ok.ShouldBeTrue(); + reply.CorrelationId.ShouldBe(correlation); + } + } + + /// + /// While the audit write is parked on a gated DB, the reply is already out and an alarm ack is answered; releasing the + /// gate writes the row (positive control: the audit is not skipped, only moved off the mailbox). + /// + [Fact] + public void Audit_write_does_not_hold_the_mailbox_and_is_still_recorded() + { + var inner = NewInMemoryDbFactory(); + var gated = new GatedAsyncFactory(inner); + var (actor, router) = Create(gated); + gated.Hold(); + + actor.Tell(new RestartDriver("MAIN", "drv-2", "joe", Guid.NewGuid())); + ExpectMsg(AckBudget, cancellationToken: TestContext.Current.CancellationToken).Ok.ShouldBeTrue(); + gated.Entered.Wait(PresenceBudget, TestContext.Current.CancellationToken).ShouldBeTrue("the audit write must be parked"); + + // The mailbox is free: a second operation is dispatched and answered while the first audit is still parked. + actor.Tell(new ReconnectDriver("MAIN", "drv-3", "kim", Guid.NewGuid())); + ExpectMsg(AckBudget, cancellationToken: TestContext.Current.CancellationToken).Ok.ShouldBeTrue(); + using (var db = inner.CreateDbContext()) db.ConfigEdits.ShouldBeEmpty(); + + gated.Release(); + AwaitAssert(() => + { + using var db = inner.CreateDbContext(); + db.ConfigEdits.Count().ShouldBe(2); + db.ConfigEdits.Select(e => e.EditedBy).OrderBy(x => x).ToList().ShouldBe(["joe", "kim"]); + }, duration: PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + router.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + } + + private sealed class ThrowingAsyncFactory(IDbContextFactory inner) : IDbContextFactory + { + public OtOpcUaConfigDbContext CreateDbContext() => inner.CreateDbContext(); + public Task CreateDbContextAsync(CancellationToken cancellationToken = default) => + throw new InvalidOperationException("ConfigDb unreachable (simulated)"); + } + + private sealed class GatedAsyncFactory(IDbContextFactory inner) : IDbContextFactory + { + private volatile TaskCompletionSource? _gate; + public ManualResetEventSlim Entered { get; } = new(); + public void Hold() => _gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + public void Release() => _gate?.TrySetResult(); + public OtOpcUaConfigDbContext CreateDbContext() => inner.CreateDbContext(); + public async Task CreateDbContextAsync(CancellationToken cancellationToken = default) + { + Entered.Set(); + if (_gate is { } gate) await gate.Task.WaitAsync(cancellationToken); + return inner.CreateDbContext(); + } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/ConfigPublishCoordinatorOffThreadAckTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/ConfigPublishCoordinatorOffThreadAckTests.cs new file mode 100644 index 000000000..63f34c9f4 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/ConfigPublishCoordinatorOffThreadAckTests.cs @@ -0,0 +1,107 @@ +using System.Diagnostics; +using Akka.Actor; +using Microsoft.EntityFrameworkCore; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy; +using ZB.MOM.WW.OtOpcUa.Commons.Types; +using ZB.MOM.WW.OtOpcUa.Configuration; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; +using ZB.MOM.WW.OtOpcUa.ControlPlane.Coordinators; +using ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.Harness; + +namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Tests; + +/// +/// lmxopcua#996 (review H-6): the per-node ack write used to be a blocking SaveChanges on the coordinator's +/// thread, so with a slow or unreachable ConfigDb N acks cost N x the connect timeout of unresponsive mailbox. The +/// write now runs on a pool thread and reports back as a message. +/// +public sealed class ConfigPublishCoordinatorOffThreadAckTests : ControlPlaneActorTestBase +{ + private static readonly RevisionHash Revision = RevisionHash.Parse(new string('e', 64)); + private static readonly TimeSpan NoTimeout = TimeSpan.FromMinutes(5); + private static readonly TimeSpan PerCall = TimeSpan.FromMilliseconds(500); + private const int NodeCount = 6; + + /// + /// Six acks arrive while every ConfigDb call takes 500 ms (a slow link or a connect timeout). The mailbox stays live + /// (an Identify round-trip answers in well under the 3 s the serialised writes would take), and every ack still lands + /// and seals the deployment (positive control: the writes DID happen, off-thread). + /// + [Fact] + public async Task Slow_ConfigDb_acks_do_not_block_the_coordinator_mailbox_and_still_seal() + { + var ct = TestContext.Current.CancellationToken; + var dbName = Guid.NewGuid().ToString("N"); + var direct = NewInMemoryDbFactory(dbName); + var slow = new SlowDbFactory(NewInMemoryDbFactory(dbName)); + var nodes = Enumerable.Range(1, NodeCount).Select(i => $"site-a-{i}:4053").ToArray(); + Seed(direct, nodes, out var deploymentId); + + var coordinator = Sys.ActorOf(ConfigPublishCoordinator.Props( + slow, NoTimeout, loadRetryMin: TimeSpan.FromMilliseconds(50), loadRetryMax: TimeSpan.FromMilliseconds(200))); + coordinator.Tell(new DispatchDeployment(deploymentId, Revision, CorrelationId.NewId())); + AwaitAssert(() => + { + using var db = direct.CreateDbContext(); + db.Deployments.Single().Status.ShouldBe(DeploymentStatus.AwaitingApplyAcks); + }, duration: PresenceBudget, cancellationToken: ct); + + slow.Delay = PerCall; + foreach (var node in nodes) + coordinator.Tell(new ApplyAck(deploymentId, NodeId.Parse(node), ApplyAckOutcome.Applied, null, CorrelationId.NewId())); + + var sw = Stopwatch.StartNew(); + var identity = await coordinator.Ask(new Identify("probe"), TimeSpan.FromSeconds(10), ct); + sw.Stop(); + identity.Subject.ShouldBe(coordinator); + // Serialised on the actor thread this is >= 6 x 500 ms = 3 s; off-thread it is one scheduling hop. + sw.Elapsed.ShouldBeLessThan(TimeSpan.FromMilliseconds(1500), + "the coordinator mailbox must not wait on the ConfigDb writes of the acks"); + + AwaitAssert(() => + { + using var db = direct.CreateDbContext(); + db.Deployments.Single().Status.ShouldBe(DeploymentStatus.Sealed); + db.NodeDeploymentStates.Count(s => s.Status == NodeDeploymentStatus.Applied).ShouldBe(NodeCount); + }, duration: PresenceBudget, cancellationToken: ct); + } + + private static void Seed(IDbContextFactory factory, string[] nodeIds, out DeploymentId id) + { + id = DeploymentId.NewId(); + using var db = factory.CreateDbContext(); + db.ServerClusters.Add(new ServerCluster + { + ClusterId = "SITE-A", Name = "Site A", Enterprise = "zb", Site = "site-a", + NodeCount = (byte)nodeIds.Length, RedundancyMode = RedundancyMode.None, CreatedBy = "test", + }); + foreach (var nodeId in nodeIds) + db.ClusterNodes.Add(new ClusterNode + { + NodeId = nodeId, ClusterId = "SITE-A", Host = nodeId.Split(':')[0], + ApplicationUri = $"urn:OtOpcUa:{nodeId}", Enabled = true, CreatedBy = "test", + }); + db.Deployments.Add(new Deployment + { + DeploymentId = id.Value, RevisionHash = Revision.Value, Status = DeploymentStatus.Dispatching, CreatedBy = "test", + }); + db.SaveChanges(); + } + + /// A factory whose synchronous context creation takes (a slow connect). + private sealed class SlowDbFactory(IDbContextFactory inner) : IDbContextFactory + { + public TimeSpan Delay { get => _delay; set => _delay = value; } + private TimeSpan _delay; + + public OtOpcUaConfigDbContext CreateDbContext() + { + var delay = Delay; + if (delay > TimeSpan.Zero) Thread.Sleep(delay); + return inner.CreateDbContext(); + } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/NodeManagerHistoryReadEventsPagingTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/NodeManagerHistoryReadEventsPagingTests.cs index c49448a8c..963cb1e5f 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/NodeManagerHistoryReadEventsPagingTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/NodeManagerHistoryReadEventsPagingTests.cs @@ -348,6 +348,47 @@ public sealed class NodeManagerHistoryReadEventsPagingTests : IDisposable await host.DisposeAsync(); } + // --- #996 (U-6): the server's own per-page event cap (ServerHistorian:MaxEventsPerRead) ------------------------ + + [Theory] + [InlineData(0u)] // "all values" is paged, never one shot + [InlineData(50u)] // a request above the cap is paged at the cap + public async Task Server_event_cap_pages_an_uncapped_or_oversized_request_and_bounds_the_backend_read(uint requested) + { + var (host, nm, node, src) = await SetupAsync(Distinct(25)); + nm.MaxEventsPerRead = 10; + + var first = ReadEvents(nm, node, requested, inboundCp: null); + first.Error.StatusCode.Code.ShouldBe(StatusCodes.Good.Code); + first.Ids.Count.ShouldBe(10, "a page never exceeds the server cap"); + first.Cp.ShouldNotBeNull("the truncated page carries a continuation point"); + src.MaxRequested.ShouldBeLessThanOrEqualTo(10, "the backend is never asked for more than the cap (no boundary skip on page 1)"); + + // Paging yields every event exactly once, in order. + var sizes = new List(); + DrainAsync(nm, node, requested, pageSizes: sizes).ShouldBe(src.All.Select(e => e.EventId)); + sizes.ShouldAllBe(n => n <= 10); + sizes.Count.ShouldBe(3); + await host.DisposeAsync(); + } + + [Fact] + public async Task Server_event_cap_applies_to_reverse_reads_and_opting_out_restores_the_one_shot_answer() + { + var (host, nm, node, src) = await SetupAsync(Distinct(25)); + nm.MaxEventsPerRead = 10; + DrainAsync(nm, node, max: 0, start: Epoch.AddSeconds(30), end: Epoch.AddSeconds(-1)) + .ShouldBe(src.All.Select(e => e.EventId).Reverse()); + ReadEvents(nm, node, 0, null, end: Epoch.AddSeconds(-1), start: Epoch.AddSeconds(30)).Ids.Count.ShouldBe(10); + + // Positive control: the cap is what paged it. Opt out (<= 0) and the same read is one complete page. + nm.MaxEventsPerRead = 0; + var all = ReadEvents(nm, node, 0, null); + all.Ids.Count.ShouldBe(25); + all.Cp.ShouldBeNull(); + await host.DisposeAsync(); + } + private static readonly DateTime Early = Epoch.AddDays(-1); private static readonly DateTime Late = Epoch.AddDays(1); @@ -725,10 +766,14 @@ public sealed class NodeManagerHistoryReadEventsPagingTests : IDisposable events.OrderBy(e => e.EventTimeUtc).ThenBy(e => e.EventId, StringComparer.Ordinal).ToList(); public int Calls { get; private set; } + /// The largest maxEvents any read asked this source for (#996: the server's cap must bound it). + public int MaxRequested { get; private set; } + public Task ReadEventsAsync( string? sourceName, DateTime startUtc, DateTime endUtc, int maxEvents, CancellationToken ct) { Calls++; + MaxRequested = Math.Max(MaxRequested, maxEvents); // Like the SQL backends: a reversed window is swapped, inputs truncate to the storage resolution. if (startUtc > endUtc) (startUtc, endUtc) = (endUtc, startUtc); startUtc = Trunc(startUtc); @@ -746,6 +791,7 @@ public sealed class NodeManagerHistoryReadEventsPagingTests : IDisposable { if (!reverse) return ReadEventsAsync(sourceName, startUtc, endUtc, maxEvents, ct); Calls++; + MaxRequested = Math.Max(MaxRequested, maxEvents); var (lo, hi) = startUtc <= endUtc ? (startUtc, endUtc) : (endUtc, startUtc); lo = Trunc(lo); hi = Trunc(hi); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/NodeManagerHistoryReadEventsTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/NodeManagerHistoryReadEventsTests.cs index bf9322590..b16916316 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/NodeManagerHistoryReadEventsTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/NodeManagerHistoryReadEventsTests.cs @@ -98,7 +98,8 @@ public sealed class NodeManagerHistoryReadEventsTests : IDisposable /// OpcUaServer-002: a HistoryReadEvents with NumValuesPerNode == 0 means "no limit — /// return ALL values" per OPC UA Part 4/11, so the backend must receive an UNBOUNDED cap /// (), NOT the maxEvents <= 0 "use the default cap" sentinel that - /// would silently truncate a whole-window read. + /// would silently truncate a whole-window read. Since #996 that holds only with the server cap opted out + /// (MaxEventsPerRead = 0); by default the backend receives the cap (). [Fact] public async Task Events_unbounded_request_passes_int_max_to_backend() { @@ -106,6 +107,7 @@ public sealed class NodeManagerHistoryReadEventsTests : IDisposable var nm = server.NodeManager!; var fake = new RecordingHistorianDataSource(); nm.HistorianDataSource = fake; + nm.MaxEventsPerRead = 0; // opt out of the #996 server cap: the pre-#996 unbounded semantics const string equipmentId = "eq-unbounded"; nm.EnsureFolder(equipmentId, parentNodeId: null, displayName: "Equipment", realm: AddressSpaceRealm.Uns); @@ -133,6 +135,35 @@ public sealed class NodeManagerHistoryReadEventsTests : IDisposable await host.DisposeAsync(); } + /// #996 (U-6): with the cap at its default, a NumValuesPerNode == 0 read asks the backend for at most the + /// server cap — never — and the advertised property is not required for that. + [Fact] + public async Task Events_zero_count_request_is_bounded_by_the_server_cap_by_default() + { + var (host, server) = await BootAsync(); + var nm = server.NodeManager!; + var fake = new RecordingHistorianDataSource(); + nm.HistorianDataSource = fake; + nm.MaxEventsPerRead.ShouldBe(OtOpcUaNodeManager.DefaultMaxEventsPerRead); + + const string equipmentId = "eq-capped"; + nm.EnsureFolder(equipmentId, parentNodeId: null, displayName: "Equipment", realm: AddressSpaceRealm.Uns); + nm.MaterialiseAlarmCondition("alarm-c", equipmentId, "Cond", "OffNormalAlarm", severity: 600, realm: AddressSpaceRealm.Uns); + var notifierNodeId = nm.TryGetFolder(equipmentId)!.NodeId; + fake.EventsResult = new HistoricalEventsResult( + new[] { new HistoricalEvent("evt-x", "Src", DateTime.UtcNow, DateTime.UtcNow, "msg", 600) }, null); + + var details = new ReadEventDetails + { + StartTime = DateTime.UtcNow.AddHours(-1), EndTime = DateTime.UtcNow, NumValuesPerNode = 0, Filter = SelectFilter("EventId"), + }; + var (_, errors) = InvokeHistoryRead(server, nm, details, notifierNodeId); + + errors[0].StatusCode.Code.ShouldBe(StatusCodes.Good.Code); + fake.LastMaxEvents.ShouldBe(OtOpcUaNodeManager.DefaultMaxEventsPerRead); + await host.DisposeAsync(); + } + /// An unsupported select operand (BrowsePath ["LocalTime"]) projects to Variant.Null — a field /// the server can't supply is null (spec-conformant) — while supported siblings still project. (EventType used to /// be such a field; it is projected now — see NodeManagerHistoryReadEventsProjectionTests.)