diff --git a/docs/components/DelmiaNotifier.md b/docs/components/DelmiaNotifier.md index 8ad3c5c7..7e706aab 100644 --- a/docs/components/DelmiaNotifier.md +++ b/docs/components/DelmiaNotifier.md @@ -28,7 +28,7 @@ The spec for this component is the project `README.md` plus `docs/plans/2026-06- | Kind | Raised when | Loop behaviour | |---|---|---| -| `ConnectFailed` | `HttpRequestException` with `HttpRequestError.NameResolutionError`, or an inner `SocketException` with `ConnectionRefused` | Try the next URL | +| `ConnectFailed` | Any failure while opening the TCP connection — refusal, name resolution, unreachable/powered-off host, or the connect timeout (`min(5 s, TimeoutSeconds / 2)`) firing — recognised by the `ConnectPhaseException` marker the client's `ConnectCallback` puts in the exception chain (DLM-1); also the legacy `NameResolutionError` / `ConnectionRefused` shapes | Try the next URL | | `StandbyRejected` | HTTP 503 whose `X-ScadaBridge-Standby` header is exactly `1` | Try the next URL | | `OutcomeUnknown` | Any other `HttpRequestException`, or a timeout (`OperationCanceledException` not caused by the caller's token) | Stop; return `NO` with `OUTCOME_UNKNOWN: the request may have been applied; verify before retrying.` | | `Connected` | Any HTTP response not matched above | Stop; the node's answer is final | diff --git a/docs/plans/sql/AddKpiRollupBackfillState.sql b/docs/plans/sql/AddKpiRollupBackfillState.sql new file mode 100644 index 00000000..c39f0ea7 --- /dev/null +++ b/docs/plans/sql/AddKpiRollupBackfillState.sql @@ -0,0 +1,35 @@ +-- AddKpiRollupBackfillState (2026-12-03, code review KPI-1 / WP4 task 4.10). +-- Creates the single-row KpiRollupBackfillState table: the KPI rollup backfill's own +-- persisted progress marker. Small, no data migration. After it is applied the first +-- KPI recorder start folds the whole raw-retention window once (the marker starts empty). +SET QUOTED_IDENTIFIER ON; +SET ANSI_NULLS ON; +GO + +BEGIN TRANSACTION; +IF NOT EXISTS ( + SELECT * FROM [__EFMigrationsHistory] + WHERE [MigrationId] = N'20261203152501_AddKpiRollupBackfillState' +) +BEGIN + CREATE TABLE [KpiRollupBackfillState] ( + [Id] int NOT NULL, + [BackfilledThroughUtc] datetime2 NOT NULL, + [UpdatedAtUtc] datetime2 NOT NULL, + CONSTRAINT [PK_KpiRollupBackfillState] PRIMARY KEY ([Id]) + ); +END; + +IF NOT EXISTS ( + SELECT * FROM [__EFMigrationsHistory] + WHERE [MigrationId] = N'20261203152501_AddKpiRollupBackfillState' +) +BEGIN + INSERT INTO [__EFMigrationsHistory] ([MigrationId], [ProductVersion]) + VALUES (N'20261203152501_AddKpiRollupBackfillState', N'10.0.13'); +END; + +COMMIT; +GO + + diff --git a/docs/requirements/Component-AuditLog.md b/docs/requirements/Component-AuditLog.md index f0af2960..759747b7 100644 --- a/docs/requirements/Component-AuditLog.md +++ b/docs/requirements/Component-AuditLog.md @@ -396,6 +396,21 @@ issues `PullAuditEvents(sinceUtc, batchSize[, afterId])` against each site and inserts-if-not-exists. Same self-healing pattern as Site Call Audit's reconciliation of `SiteCalls`. +**Both nodes, one cursor each (AUD-1, 2026-12).** The site audit store is a +per-node, unreplicated SQLite file, so each node owes its own rows. Every tick +pulls **every configured node** of the site (`GrpcNodeAAddress` and a distinct +`GrpcNodeBAddress`) through `IPullAuditEventsClient.PullFromEndpointAsync` — +one node, no NodeA→NodeB failover — and keeps a composite cursor per +**(site, node endpoint)**. Before, the pull went to NodeA whenever NodeA +answered: after any NodeA restart (NodeB active, NodeA a healthy standby with an +empty store) every pull reported "drained" and NodeB's `PushAbandoned`/`Rejected` +rows never reached central; and the single per-site cursor, fed by NodeA's rows, +could be sent to NodeB, skipping NodeB's owed rows and letting +`MarkReconciledUpToAsync` retire rows central never received. One node failing +does not skip the other; the stalled latch stays per site (non-draining when any +node is). An edited address drops that node's cursor and starts the new one from +the beginning of what it owes. + **The pull serves only rows central has not acknowledged (review 2026-10-21 06/PERF-1).** `ReadPendingSinceAsync` returns `Pending`, `PushAbandoned` and `Rejected` rows — never `Forwarded`. It used to serve `Forwarded` rows too, so @@ -715,6 +730,15 @@ MS SQL for direct-write events). Unredacted secrets never persist. and emits an `AuditLogPurgedEvent` (partition range, rowcount, duration) per switched partition. A partition-maintenance step rolls forward each month, creating the next month's partition ahead of time. +- **Partition 1 is purged and archived too (AUD-6, 2026-12).** Rows stamped before + the first boundary (a site whose clock was reset, a back-dated row) land in + partition 1, which has no lower boundary, so the per-boundary enumeration never + offered it and those rows outlived retention and the cold archive indefinitely. + `GetPartitionBoundariesOlderThanAsync` now also returns partition 1 — once its + newest row is older than the window — as the **month start of its newest row**, a + value inside partition 1: the switch-out and the archive resolve the partition + with `$partition.pf_AuditLog_Month(value)`, so they handle it like any month, and + the archive is labelled (and its `RetentionDays` counted) by the age of that data. - **Purge failure is a health metric, not just a log line:** every purge step that throws — a partition switch-out, a per-channel override DELETE, or the pre-purge boundary enumeration — publishes an `AuditLogPurgeFailedEvent` (month boundary, diff --git a/docs/requirements/Component-Communication.md b/docs/requirements/Component-Communication.md index 87077a2d..aba1b467 100644 --- a/docs/requirements/Component-Communication.md +++ b/docs/requirements/Component-Communication.md @@ -271,11 +271,17 @@ Three layers of dead-client detection prevent orphan streams on site nodes: Keepalive settings are configurable via `CommunicationOptions`: - `GrpcKeepAlivePingDelay`: 15 seconds (default) - `GrpcKeepAlivePingTimeout`: 10 seconds (default) +- `GrpcConnectTimeout`: 5 seconds (default, validated positive) — `SocketsHttpHandler.ConnectTimeout` on every cross-cluster channel (central→site command pair, site→central control pair, site stream clients). See *Black-holed peers* below. - `GrpcMaxStreamLifetime`: 4 hours (default) - `GrpcMaxConcurrentStreams`: 100 (default) - `GrpcStreamBatchMaxEvents`: 100 (default) — see Event Batching above - `GrpcStreamBatchWindow`: 25 ms (default) — see Event Batching above +**Black-holed peers (COMM-5, 2026-12).** A peer whose host silently drops SYNs (powered off behind a router, firewall drop, WAN black hole) used to hold every connect for the OS TCP timeout (~21 s on Windows, ~2 min on Linux), so calls with shorter deadlines ended `DeadlineExceeded` — which neither channel pair failed over on — and a dead node kept every command. Three changes close it: +- `GrpcConnectTimeout` (5 s) makes the connect fail as `Unavailable` ("Error connecting to subchannel.", `TimeoutException` cause) well inside every call deadline. That shape is also recognised by `GrpcRetrySafety.WasNeverSent`, so even a mutation fails over within the call — the request provably never left the client. +- A `DeadlineExceeded` that expires while the channel is still `Connecting`/`TransientFailure` (`GrpcRetrySafety.IsConnectPhaseDeadline`) moves the pair: `SitePairChannelProvider` flips NodeA↔NodeB, `GrpcCentralTransport` flips central-a↔central-b (heartbeat included, so a quiet site leaves a dead central). The deadline is spent, so the call itself is not retried; a deadline on a connected (`Ready`) channel is a slow peer and moves nothing. +- The Alarm Summary aggregator's stream **open deadline** is now a stream error (flip node, spend a retry) rather than only a release of the in-flight guard; before, the next reconcile tick reopened on the same black-holed node indefinitely. + ### 6a. Debug Snapshot (Central → Site) - **Pattern**: Request/Response (one-shot, no subscription). - Central sends a `DebugSnapshotRequest` (identified by instance unique name) to the site. @@ -441,6 +447,8 @@ Disconnect is detected at the **transport layer**, never via an application-leve - **In-flight command/control messages (gRPC call + deadline)**: When a connection drops while a request is in flight (e.g., a deployment sent but no response received), the gRPC call fails or hits its deadline and the caller receives a failure. There is **no automatic retry or buffering at central** — the engineer sees the failure in the UI and re-initiates the action. This is consistent with the design principle that central does not buffer messages. An in-progress deployment whose round-trip exceeds the timeout (default 120 s at `CommunicationService.DeployInstanceAsync`) surfaces as `DeploymentStatus.Failed` to the caller. - **Debug streams (gRPC)**: Any gRPC stream interruption is detected by the HTTP/2 keepalive PING (~25 s) and triggers reconnection logic in the `DebugStreamBridgeActor`. The bridge actor attempts to reconnect to the other site node endpoint (NodeB if NodeA failed, or vice versa), with up to 3 retries and 5-second backoff. If all retries fail, the consumer is notified via `OnStreamTerminated` and the bridge actor is stopped. Events during the reconnection gap are lost (acceptable for real-time debug view). On successful reconnection, the consumer can request a fresh snapshot to re-sync state. +- **Debug View snapshot hand-over (COMM-3/COMM-7, 2026-12).** The bridge actor buffers stream events until the snapshot arrives and flushes that gap-window buffer right after it; `DebugStreamService.StartStreamAsync` now **holds** every event that follows the snapshot until it hands the snapshot back, folds them into it (newer-or-equal timestamp per entity wins, unseen entities appended) and only then passes later events through to `onEvent`. Before this the gap-window events reached the consumer before the caller had applied the snapshot, so the SignalR hub sent `OnAttributeChanged` ahead of `OnSnapshot` and a client that replaces its state from the snapshot regressed to the older value. A fail-fast `Status.Failure` from the command transport for the snapshot request (no gRPC channel for the site, an immediate RPC error) now fails the start at once with that cause and tears the session down, instead of waiting out the 30 s snapshot timeout. +- **Only the active site node serves streams (COMM-2, 2026-12).** The site stream hub is node-local — Instance Actors, and therefore every attribute/alarm event, exist only on the active node (oldest Up member of the `site-{SiteId}` role, `ActiveNodeEvaluator.SelfIsOldestUp`). `SiteStreamGrpcServer` therefore refuses `SubscribeInstance`/`SubscribeSite` with **`Unavailable`** on a node that is not active, and a watchdog (2 s) ends every open stream with **`Unavailable`** once the node loses the active role. Both consumers treat `Unavailable` as a stream error and flip NodeA↔NodeB, so after a failover — and in the steady state after any NodeA restart, where NodeA rejoins as standby — the Alarm Summary aggregator and Debug View land on the node that produces events. Before this a subscription to a healthy standby succeeded (headers flushed, keepalives passed) and never delivered an event; nothing errored, so the consumer never flipped and `IsLive` stayed true. The ending deliberately uses an error status, not OK: a graceful completion does not flip the node (below). The reconciliation/trace pulls on the same service are not gated — they read node-local stores and must answer on either node. - **Graceful end of stream is NOT a fault, but it IS a reconnect trigger.** When the site's `GrpcMaxStreamLifetime` (4 h) elapses — and on a graceful site shutdown — the server ends the RPC with status **OK**, so the client's read loop simply finishes with no exception. `SiteStreamGrpcClient` reports that through a dedicated `onCompleted` callback, distinct from `onError`, and both consuming actors treat it as a reconnect trigger that **does not spend (or refund) the error-retry budget** and does **not** flip the node — the peer that closed cleanly is healthy. `SiteAlarmAggregatorActor` marks the stream down and lets the periodic reconcile tick reopen it (which also re-seeds); `DebugStreamBridgeActor` reopens on the same endpoint after `ReconnectDelay`. Both stamp the stream generation on the callback so a completion racing out of an already-replaced stream is ignored, and both observe the subscription `Task` itself so a fault escaping the subscribe call can never go unobserved. Without the `onCompleted` leg an OK completion was invisible to the reconnect logic and the stream stayed silently dead until the central process restarted. ## Failover Behavior diff --git a/docs/requirements/Component-ExternalSystemGateway.md b/docs/requirements/Component-ExternalSystemGateway.md index d316fa93..f0e85574 100644 --- a/docs/requirements/Component-ExternalSystemGateway.md +++ b/docs/requirements/Component-ExternalSystemGateway.md @@ -107,6 +107,7 @@ Scripts choose between two call modes per invocation, mirroring the dual-mode da - Each external system definition specifies a **timeout** (`TimeoutSeconds`) that applies to all method calls on that system. `0` means unset — the gateway's configured `DefaultHttpTimeout` applies instead. Editable via the Central UI External System form ("Timeout (seconds)", helper text "0 = use gateway default") and deployed to sites in the artifact alongside the rest of the definition. - Error classification by HTTP response: - **Transient failures** (connection refused, timeout, HTTP 408, 429, 5xx): Behavior depends on call mode — `CachedCall` buffers for retry; `Call` returns error to script. + - **A connection lost while reading the response body** (headers received, then a reset or truncation — `IOException`/`HttpIOException`/`HttpRequestException` from the body read) is **transient** when the status was a success or a transient code, exactly like a timeout at the same point (ESG-1, 2026-12; before, the raw `IOException` escaped into the script and `CachedCall` buffered nothing). With a permanent status the call stays permanent — losing the error body does not make it retryable. - **Permanent failures** (HTTP 4xx except 408/429): Always returned to the calling script regardless of call mode. Logged to Site Event Logging. For `CachedCall`, the failure is additionally recorded as a terminal `Failed` tracking record — so even a never-buffered cached call has an authoritative status record. - This classification ensures the S&F buffer is not polluted with requests that will never succeed. - **Idempotency note**: `CachedCall` retries may result in duplicate delivery if the external system received the original request but the response was lost. Callers should use `CachedCall` only for operations that are idempotent or where duplicate delivery is acceptable. diff --git a/docs/requirements/Component-HealthMonitoring.md b/docs/requirements/Component-HealthMonitoring.md index 03c728b7..8b28680f 100644 --- a/docs/requirements/Component-HealthMonitoring.md +++ b/docs/requirements/Component-HealthMonitoring.md @@ -48,8 +48,10 @@ Site clusters (metric collection and reporting). Central cluster (aggregation an - Sites send a **health report message** to central at a configurable interval (default: **30 seconds**). - Each report is a **flat snapshot** containing the current values of all monitored metrics, a **monotonic sequence number**, and the **report timestamp** from the site. Central replaces the previous state for that site only if the incoming sequence number is higher than the last received — this prevents stale reports (e.g., delayed in transit or from a pre-failover node) from overwriting newer state. + - **The sequence number is wall-clock anchored on every report** (COMM-1, 2026-12): each report takes `max(previous + 1, now as Unix-ms)`, so after a failover the newly active node's first report sorts above anything the old active node sent, however long either process has run. (The earlier scheme seeded Unix-ms once at process start and added 1 per report; for a pair started `g` ms apart it broke once the active node had sent more than `g` reports — ~42 h for a 5 s gap — after which every report from the new active node was rejected for days.) The same rule drives the central self-report (`$central`). + - **A rejected report is nacked, never silently dropped**: `ICentralHealthAggregator.ProcessReport` returns whether it applied the report, and the central communication actor acks the site with `Accepted=false` + an error on a stale rejection. The site's transport then throws, the per-interval counters are restored into the next report, and the drop is logged at the site. - Central tracks two **distinct** signals per site — do not conflate them: - - **Liveness (online/offline)**: driven by the **last signal of any kind** (a full report *or* a transport heartbeat, the latter arriving every ~5s from any reachable site node). If central receives no signal within `OfflineTimeout` (default: **60 seconds**), the site is marked **offline**. Because heartbeats are frequent, this only fires on genuine total loss of contact — not during a single-node failover, when the surviving node keeps heartbeating. The synthetic *central* self-report site has no heartbeat source and uses the longer `CentralOfflineTimeout` (default: **3 minutes**) so a single missed self-report does not flap it offline. + - **Liveness (online/offline)**: driven by the **last signal of any kind** (a full report *or* a transport heartbeat, the latter arriving every ~5s from any reachable site node). Both are stamped with **central's receive time** — never the site-stamped heartbeat timestamp (COMM-4): the offline check compares against central's clock, so a site clock running X fast used to stretch the timeout to 60 s + X. `MarkHeartbeat` also clamps any future-dated value to central's now. If central receives no signal within `OfflineTimeout` (default: **60 seconds**), the site is marked **offline**. Because heartbeats are frequent, this only fires on genuine total loss of contact — not during a single-node failover, when the surviving node keeps heartbeating. The synthetic *central* self-report site has no heartbeat source and uses the longer `CentralOfflineTimeout` (default: **3 minutes**) so a single missed self-report does not flap it offline. - **Metrics staleness**: an **online** site (heartbeats still arriving) that has produced no full **report** within `MetricsStaleTimeout` (default: **2 minutes**) is flagged **metrics stale**. This surfaces the failure mode where a site's report pipeline (`HealthReportSender`) has died but the node is otherwise reachable — previously such a site showed "online with frozen metrics forever". A site that has **never** delivered a report is anchored on its first-contact time (`FirstSeenAt`), so a report pipeline dead from first boot is also flagged after `MetricsStaleTimeout` (previously such a site showed online-with-no-metrics indefinitely). `MetricsStaleTimeout` must be positive and no shorter than the report interval. - **Online recovery**: when central receives a health report from a site that was marked offline, the site is automatically marked **online** and the metrics-stale flag cleared (a fresh report proves the pipeline is alive); a heartbeat alone also restores **online** but leaves the metrics-stale flag untouched. No manual acknowledgment required. - **Status-transition timestamp**: each online↔offline flip stamps `LastStatusChangeAt`, so the UI can answer "since when has this site been offline/online" rather than only "is it offline now". Report/heartbeat traffic that leaves the status unchanged does not move it. @@ -60,6 +62,7 @@ Script error rates and alarm evaluation error rates are calculated as **raw coun - The site maintains a counter for each metric that increments on every failure. - Each health report includes the count since the last report. The counter resets after each report is sent. +- A **standby** node does not send reports but still **drains** its interval counters on every report tick (COMM-6), so the first report after it becomes active covers one interval rather than its whole standby life (a node standby for weeks used to report every dead letter of that period as one 30 s spike). - Central displays these as "X errors in the last 30 seconds" (or whatever the configured interval is). - **Script errors** include all failures that prevent a script from completing successfully: unhandled exceptions, timeouts, recursion limit violations, and any other error condition. - **Alarm evaluation errors** include all failures during alarm condition evaluation. diff --git a/docs/requirements/Component-InboundAPI.md b/docs/requirements/Component-InboundAPI.md index a8f76882..82ebeb46 100644 --- a/docs/requirements/Component-InboundAPI.md +++ b/docs/requirements/Component-InboundAPI.md @@ -148,7 +148,7 @@ The `sbk__` design already supports zero-downtime rotation — a | `VALIDATION_FAILED` | 400 | Parameter validation failed (missing required field, wrong type, undeclared field). | | `BODY_TOO_LARGE` | 413 | Request body exceeded `MaxRequestBodyBytes`. | | `STANDBY_NODE` | 503 | Request hit a standby central node that could not relay it: no `StandbyForwardPeerEndpoints` configured, or the request was already relayed once (loop guard — neither node is active, e.g. mid-failover). Carries the `X-ScadaBridge-Standby: 1` response header. | -| `ACTIVE_NODE_UNREACHABLE` | 503 | Every configured peer refused before execution or failed with proven name-resolution/connection-refusal errors. | +| `ACTIVE_NODE_UNREACHABLE` | 503 | Every configured peer refused before execution or failed while opening the connection (refusal, name resolution, unreachable host, 5 s connect timeout). | | `OUTCOME_UNKNOWN` | 502 | A relay timed out or lost its response after possible execution; it does not replay the request. Verify the operation before retrying. | | `TIMEOUT` | 500 | The method script exceeded its execution timeout. | | `SITE_UNREACHABLE` | 500 | The target site did not respond to the routed request within the routing timeout (no contact / down / partitioned) — typed from the routed Ask expiring (`AskTimeoutException`), never inferred from an error-message substring. A `Success=false` response means the site answered and is classified `SCRIPT_ERROR`. | @@ -374,7 +374,7 @@ A standby now **relays** the request to the active peer instead (`InboundApiEndp - **Configuration.** `ScadaBridge:InboundApi:StandbyForwardPeerEndpoints` — the HTTP base URL(s) of the *other* central node(s), e.g. `["http://scadabridge-central-b:5000"]` on central-a. Empty (default) keeps the old 503 behaviour. `StandbyForwardTimeout` (default 60 s) is the total relay budget and should exceed the longest method timeout plus network overhead. Validated at startup (absolute http/https URLs, positive timeout). Note the standby discovers the active peer from **appsettings**, not from cluster state — the Akka member address carries the remoting port, not the HTTP port — the options snapshot is read per relay. - **Pure relay.** Method, path, query string, body and credentials travel unchanged; hop-by-hop/Host/forwarding-provenance headers are excluded and authenticated provenance is rebuilt, so the **active node** authenticates the caller's own `Authorization`/`X-API-Key` credential, applies its own body cap and method timeout, and writes the audit row. The peer's status, `Content-Type` and body are replayed unchanged. The serving node owns its `ApiInbound` row; the originating standby retains a failure row when no peer serves or the outcome is uncertain. Verified internal standby refusals are not duplicated. - **Order of checks.** The body-size cap (HTTP 413) runs before audit reads and the active-node check, so a standby never buffers or relays a body the active node would refuse. A relaying standby skips the audit middleware's request/response capture entirely; the body is read once, by the forwarder (bounded by `MaxRequestBodyBytes`), so it can be re-sent to a second peer. On the node that executes, request bodies up to the 1 MiB cap are buffered in memory (`EnableBuffering` with the cap as threshold), not spilled to a temp file. The relay proof (`X-ScadaBridge-Relay`) carries a random nonce, is signed fresh per peer attempt, and is **single-use** within its 300 s window: the receiver keeps a bounded `(ExecutionId, nonce)` set and treats a repeat (or a nonce-less proof from an older peer) as unverified — the request still runs, but a captured proof cannot re-stamp ExecutionId/IP. -- **Peer selection.** The standby knows only that it is *not* active. It tries the peers in order and accepts the first response that is not a standby refusal; a peer answering 503 with `X-ScadaBridge-Standby: 1`, proven name-resolution failure, or connection refusal permits trying the next peer. Timeout or ambiguous response loss returns 502 `OUTCOME_UNKNOWN` without replay. A 503 *without* the marker is the active node's own answer and is replayed, not retried. All peers failing → 503 `ACTIVE_NODE_UNREACHABLE`. +- **Peer selection.** The standby knows only that it is *not* active. It tries the peers in order and accepts the first response that is not a standby refusal; a peer answering 503 with `X-ScadaBridge-Standby: 1`, or any failure while opening the TCP connection (refusal, name resolution, unreachable/powered-off host, the relay client's 5 s connect timeout — DLM-1, 2026-12; recognised by a marker the relay handler's `ConnectCallback` puts in the exception chain), permits trying the next peer. Before DLM-1 a powered-off peer held the relay for the whole 60 s `StandbyForwardTimeout` and ended in 502 `OUTCOME_UNKNOWN`. Timeout or ambiguous response loss returns 502 `OUTCOME_UNKNOWN` without replay. A 503 *without* the marker is the active node's own answer and is replayed, not retried. All peers failing → 503 `ACTIVE_NODE_UNREACHABLE`. - **One-hop loop guard.** Every relayed request carries `X-ScadaBridge-Forwarded: `. A standby never relays a request that already carries it — it answers 503 `STANDBY_NODE` with the marker header — so a pair in which neither node is active (a transient during failover) bounces at most one hop and never ping-pongs. The active node ignores the header and serves the request normally. - **Still not a retry layer.** The relay makes one HTTP attempt per peer and does not retry a peer that answered; at-least-once callers keep their own retry loop and the idempotent-method authoring note above still applies. @@ -412,6 +412,6 @@ A serving peer owns the inbound audit for its success or method failure. The ori Relays overwrite caller-supplied provenance with an HMAC signed envelope using a domain-separated key derived from `ApiKeyPepper`. Both centrals must share that server secret. The envelope binds the original verified remote address, execution ID, timestamp, method, path/query, content type, caller credentials, and bounded body digest. The receiver accepts it for at most five minutes and only when the request binding matches. Unsigned loop markers and forwarded-address headers confer no identity trust; missing or invalid proof uses the receiver's verified remote address. Forwarding remains one hop. Use TLS between peers when network confidentiality is required. -`StandbyForwardTimeout` is one budget across permitted attempts and response consumption. Only explicit pre-execution standby rejection, name-resolution failure, or connection refusal permits another peer. Timeout or response loss returns HTTP 502 `OUTCOME_UNKNOWN`: verify the operation before manually retrying because it may already have applied. This avoids blindly replaying non-idempotent methods. +`StandbyForwardTimeout` is one budget across permitted attempts and response consumption. Only explicit pre-execution standby rejection or a connect-phase failure (refusal, name resolution, unreachable host, connect timeout) permits another peer. Timeout or response loss returns HTTP 502 `OUTCOME_UNKNOWN`: verify the operation before manually retrying because it may already have applied. This avoids blindly replaying non-idempotent methods. `SkipBodyCapture` suppresses request/response summaries and all exception message/detail text, including stashed script exceptions; retain status/category and request metadata for diagnosis. Error text can quote payload values and is subject to the same privacy boundary as the body. diff --git a/docs/requirements/Component-KpiHistory.md b/docs/requirements/Component-KpiHistory.md index 3f6251e8..3acc7999 100644 --- a/docs/requirements/Component-KpiHistory.md +++ b/docs/requirements/Component-KpiHistory.md @@ -92,7 +92,7 @@ Each source has a `SourceTimeout` (default 10 seconds) bounding the actual wait **Hourly rollup tick.** A third timer (`kpi-rollup`) fires every `RollupInterval` (default 1h). On each tick the recorder opens a per-tick DI scope and calls `IKpiHistoryRepository.FoldHourlyRollupsAsync` over the window `[TruncateToHour(now) − RollupLookbackHours, TruncateToHour(now))` — an **exclusive** upper bound at the current hour start, so the in-progress hour is never folded. The fold groups raw `KpiSample` rows by `(series, hour)`, applies the per-metric aggregation intent (sum for rate metrics, last-value for gauges — see Query), and **idempotently upserts** each `(Source, Metric, Scope, ScopeKey, HourStartUtc)` row. Re-folding the trailing lookback window (default 3h) rather than only the last hour is the self-heal for a **singleton-failover-missed tick**: because the upsert overwrites the aggregate in place, re-running the same window produces identical values (no double-count), so any complete hour a missed tick skipped is refilled on the next fold. A `_rollupInFlight` guard (mirroring `_sampleInFlight`) skips a tick while a prior fold is still running so two idempotent upserts never race on overlapping rows. During a **failover overlap** — the old singleton incarnation's in-flight fold and the new node's first fold both `Add`-ing the same `(series, hour)` row — the loser of the unique `IX_KpiRollupHourly_Series` upsert race discards its **whole fold pass** (a single `SaveChanges`), logged at Information and repaired by the next idempotent fold; when reading fold logs after a failover, the failure grain is the **pass, not the row** (arch-review 04 round 2, R5). Only a unique-key violation (SQL Server 2601/2627; the SQLite `UNIQUE constraint failed` fault on the test provider) is classified as that benign race — any other save failure propagates and the recorder logs it at Error, so a fold that faults for a real reason is no longer invisible. -**One-shot backfill.** So the 30 d / 90 d charts are not blank until enough wall-clock passes, the recorder runs a backfill on start (`kpi-rollup-backfill` timer) that folds the retention window, reusing the same `FoldHourlyRollupsAsync` path. The `FoldHourlyRollupsAsync` repository call reads raw samples **one hour at a time** (an untracked projection of a single hour, grouped in memory by series), so resident memory is bounded by one hour of samples regardless of the window; the backfill still folds the window in **≤24 h slices, oldest-first** — one bounded slice per fold — rather than handing the fold the full 90-day window at once (which at fleet volume is tens of millions of rows in one tracked pass). Between slices it lowers its in-flight guard so periodic folds **interleave** instead of stalling behind the historical pass; a periodic fold and a backfill slice strictly alternate through the single `_rollupInFlight`/`_backfillInFlight` gate pair, so the two idempotent upserts never race on overlapping rows. On a **failover restart** the plan first consults the `IKpiHistoryRepository.GetLatestRollupHourAsync` watermark: if the newest folded hour is already within `RollupLookbackHours` of now (the common case) the whole historical pass is **skipped** — the periodic fold's lookback covers the tail — otherwise the window is **shrunk to the un-rolled tail** `[watermark, TruncateToHour(now))` (re-folding the watermark hour itself as an idempotent safety margin) instead of the full `RetentionDays` floor. A `_backfillDone` latch makes the whole pass at-most-once per actor lifetime, and it defers (re-arms) while a periodic fold is in flight. Being an idempotent upsert, it is safe (idempotent) to re-run on a later failover restart; the watermark fast-path makes the failover re-run cheap as well. +**One-shot backfill.** So the 30 d / 90 d charts are not blank until enough wall-clock passes, the recorder runs a backfill on start (`kpi-rollup-backfill` timer) that folds the retention window, reusing the same `FoldHourlyRollupsAsync` path. The `FoldHourlyRollupsAsync` repository call reads raw samples **one hour at a time** (an untracked projection of a single hour, grouped in memory by series), so resident memory is bounded by one hour of samples regardless of the window; the backfill still folds the window in **≤24 h slices, oldest-first** — one bounded slice per fold — rather than handing the fold the full 90-day window at once (which at fleet volume is tens of millions of rows in one tracked pass). Between slices it lowers its in-flight guard so periodic folds **interleave** instead of stalling behind the historical pass; a periodic fold and a backfill slice strictly alternate through the single `_rollupInFlight`/`_backfillInFlight` gate pair, so the two idempotent upserts never race on overlapping rows. The plan reads the backfill's **own persisted watermark** — the single-row `KpiRollupBackfillState` table (`IKpiHistoryRepository.GetRollupBackfillWatermarkAsync`; migration `AddKpiRollupBackfillState`), the exclusive hour boundary its completed slices have folded through — never the periodic fold's `MAX(KpiRollupHourly.HourStartUtc)` (KPI-1, 2026-12: the periodic fold writes the last `RollupLookbackHours` seconds before the plan ran, so whenever samples existed in that window the backfill latched itself "current" and folded nothing — an upgrade onto 90 days of raw samples never got its 30 d/90 d history, and an interrupted backfill was never resumed). If the watermark is already within `RollupLookbackHours` of now the historical pass is **skipped**; otherwise the window is `[max(watermark, retention floor), TruncateToHour(now))` — the full retention window on a fresh install or after the upgrade. Each slice advances the watermark only after it folds; a failed slice drops the remaining queue and re-plans from the watermark after 5 min (three consecutive failures give up until the next singleton start), so the marker never jumps a gap. Once the backfill has completed, each periodic fold advances the marker too, but only when it already reaches that fold's lower bound (`onlyIfReachedUtc`) — contiguous, never created by the periodic fold — so a later restart plans only the short tail. A `_backfillDone` latch makes the whole pass at-most-once per actor lifetime, and it defers (re-arms) while a periodic fold is in flight. Being an idempotent upsert, it is safe (idempotent) to re-run on a later failover restart; the watermark fast-path makes the failover re-run cheap as well. **Retention.** A daily purge timer (`PurgeInterval`, default 24h) now runs **both** purges: raw `KpiSample` rows older than `RetentionDays` (default 90) via `IKpiHistoryRepository.PurgeOlderThanAsync`, **and** hourly rollup rows older than `RollupRetentionDays` (default 365) via `IKpiHistoryRepository.PurgeRollupsOlderThanAsync` (a one-hour-sliced batched DELETE mirroring the raw purge). Rollups deliberately **outlive** raw samples so long-range trend charts have data after the raw rows are purged; the options validator enforces `RollupRetentionDays >= RetentionDays` so a window never falls into a hole where raw is purged but no rollup exists. diff --git a/docs/requirements/Component-NotificationOutbox.md b/docs/requirements/Component-NotificationOutbox.md index 72fdb4c7..b07e68ba 100644 --- a/docs/requirements/Component-NotificationOutbox.md +++ b/docs/requirements/Component-NotificationOutbox.md @@ -111,6 +111,8 @@ The site→central handoff is **at-least-once**. Central ingests an inbound noti Delivery has no row-level claim or lease: dispatchers read due rows and persist delivery status after sending. An interrupted delivery can therefore be sent again after failover. During a dual-active partition permitted by the auto-down policy, both central singletons can repeatedly select overlapping batches and deliver duplicate notifications across multiple sweeps; exposure is not limited to one notification or one handover. The `NotificationId` deduplication above protects ingestion, not external Email/SMS delivery. This remains an accepted at-least-once delivery limitation; there is no dispatcher fencing or exactly-once guarantee. +A **graceful** handover no longer widens that window (NTF-1, 2026-12): the actor's shutdown token is passed to the channel adapter (so CoordinatedShutdown cuts an in-flight send short) but **not** to the write that records the adapter's outcome. Once the adapter has returned — for a success, after the relay accepted the message — the status write runs on its own token bounded by a 30 s timeout, and the audit rows are emitted the same way. Previously that write was cancelled with the shutdown token, the row stayed `Pending`/`Retrying` with no record of the send, and the new active node's first sweep sent the email or SMS again. + ## Dispatcher The dispatcher loop runs on a fixed interval. On each tick the `NotificationOutboxActor`: diff --git a/docs/requirements/Component-NotificationService.md b/docs/requirements/Component-NotificationService.md index cc9a2059..ccdf24b1 100644 --- a/docs/requirements/Component-NotificationService.md +++ b/docs/requirements/Component-NotificationService.md @@ -144,7 +144,8 @@ A small `SmsErrorClassifier` mirrors the External System Gateway pattern: ### Error Classification (Email) Each `Deliver(...)` call returns one of `success | transient failure | permanent failure`, consistent with the External System Gateway pattern. There is **no synchronous permanent-failure return to the script** — `Send()` returns immediately, before any delivery is attempted. -- **Transient failures** (connection refused, timeout, SMTP 4xx temporary errors): The Notification Outbox moves the row to `Retrying` and schedules another attempt per the SMTP configuration's retry settings. +- **Transient failures** (connection refused, timeout, SMTP 4xx temporary errors, a connection dropped mid-session — MailKit's `IOException`, including one wrapping a `SocketException` — a TLS handshake that failed mid-way, and an OAuth2 token-endpoint outage: no response, HTTP 5xx/408/429, or the token request timing out): The Notification Outbox moves the row to `Retrying` and schedules another attempt per the SMTP configuration's retry settings. (NTF-2, 2026-12: before this the dropped connection, the handshake failure and the token-endpoint outage fell through as unclassified and were parked at once with `RetryCount` 0.) `SmtpErrorClassifier` walks the inner-exception chain for the socket/timeout/IO causes. +- **Broken credentials stay permanent**: a 4xx other than 408/429 from the OAuth2 token endpoint, or a malformed credential triple, parks the row — retrying a bad secret only burns token-endpoint calls. - **Permanent failures** (SMTP 5xx permanent errors, e.g., mailbox not found): The Notification Outbox moves the row to `Parked` with the error in `LastError`. The notification will never deliver, and an operator can review or discard it on the Central UI Notification Outbox page. - Retries exhausted on a transient failure also result in a `Parked` row. - A script observes failures only by calling `Notify.Status(id)` and seeing a `Parked` status — not as a synchronous exception. diff --git a/docs/requirements/Component-SiteCallAudit.md b/docs/requirements/Component-SiteCallAudit.md index 007cd740..be5a09b5 100644 --- a/docs/requirements/Component-SiteCallAudit.md +++ b/docs/requirements/Component-SiteCallAudit.md @@ -101,10 +101,19 @@ never regresses. Within an equal *non-terminal* rank (the `Attempted`/`Skipped` retry phase), the packet with the newest `UpdatedAtUtc` wins — so a retrying call's `RetryCount`/`LastError`/`HttpStatus` stay live instead of freezing at the first `Attempted` write. Equal *terminal* rank stays immutable (a later -`Delivered` never overwrites an earlier `Parked`), equal stamps are an idempotent +`Failed` never overwrites an earlier `Delivered`), equal stamps are an idempotent no-op, and a lower rank is always a no-op — so at-least-once and out-of-order telemetry remain harmless. +**`Parked` is the one re-openable state (SCA-1, 2026-12).** A **strictly newer** +`Attempted`, `Delivered`, `Failed` or `Discarded` packet replaces a `Parked` row +(operator Retry re-opens the call, then its retried outcome arrives; operator +Discard closes it). Only strictly newer — a stale pre-park packet replayed late, +or any `Submitted`/`Forwarded`, leaves it `Parked`; `Delivered`/`Failed`/`Discarded` +stay immutable. Before this a relayed Retry or Discard could never land: the row +stayed `Parked` until the 365-day purge, the Parked KPI counted it forever and the +page kept offering Retry/Discard on it. + From v1.x onward, the `CachedCallTelemetry` message additively carries the `AuditEvent` content alongside the existing operational fields. Central's `AuditLogIngestActor` (Audit Log #23) performs both the immutable `AuditLog` @@ -120,6 +129,13 @@ reconnect — pulls "all tracking rows changed since cursor X" from each site. Gaps left by lost telemetry self-heal. Central converges to the site; the site never depends on central. +**Every node is pulled, each with its own cursor (AUD-1, 2026-12).** On a site +pair without LocalDb replication each node's operation-tracking store is its +own, so the pass pulls every configured node (`PullFromEndpointAsync`, no +NodeA→NodeB failover) and keys the cursor below per **(site, node endpoint)**; +the pinned latch stays per site (pinned when any node is). Before, NodeA was +pulled whenever it answered, so a standby NodeA's empty store hid NodeB's rows. + The per-site cursor is a **composite `(UpdatedAtUtc, TrackedOperationId)` keyset**, not a single timestamp. Each pull asks for rows strictly greater than the cursor pair and advances it to the maximum row seen; a burst of more rows @@ -210,7 +226,16 @@ Parked cached calls live in the owning site's S&F buffer. Operator Retry/Discard from the Central UI is relayed to that site as a `RetryParkedOperation` / `DiscardParkedOperation` command over the command/control channel. The site applies the change and emits telemetry reflecting the new state; central never -mutates the `SiteCalls` row directly. If the site is offline the command fails +mutates the `SiteCalls` row directly. Concretely (SCA-1): the S&F service notifies +the cached-call observer with `OperatorRetried` / `OperatorDiscarded`; the +lifecycle bridge writes one `CachedSubmit`/`Submitted` row (operational status +`Attempted`, no terminal stamp, RetryCount 0) for a Retry or one +`CachedResolve`/`Discarded` row for a Discard; the forwarder re-opens the +site tracking row (`ReopenParkedAsync`: `Attempted`, `TerminalAtUtc` cleared) or +closes it (`RecordDiscardedAsync`), so `Tracking.Status(id)` follows too; the +cached-telemetry drain and the reconciliation pull then carry the newer row to +central, whose guard accepts it over `Parked`. A retried call's later attempts and +outcome land normally because the row is no longer terminal. If the site is offline the command fails fast and the UI surfaces a "site unreachable" message. On a **successful** relay (the site acks `Applied`), `SiteCallAuditActor` emits diff --git a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/GrpcPullAuditEventsClient.cs b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/GrpcPullAuditEventsClient.cs index 3ea53192..79b831db 100644 --- a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/GrpcPullAuditEventsClient.cs +++ b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/GrpcPullAuditEventsClient.cs @@ -47,7 +47,7 @@ namespace ZB.MOM.WW.ScadaBridge.AuditLog.Central; /// inject a fake invoker so no real HTTP/2 endpoint is required. /// /// -public sealed class GrpcPullAuditEventsClient : IPullAuditEventsClient +public sealed class GrpcPullAuditEventsClient : IPullAuditEventsClient, IGrpcChannelCachePruner { private readonly ISiteEnumerator _sites; private readonly IPullAuditEventsInvoker _invoker; @@ -88,17 +88,7 @@ public sealed class GrpcPullAuditEventsClient : IPullAuditEventsClient return Empty; } - var request = new ProtoPullRequest - { - // ReadPendingSinceAsync treats DateTime.MinValue as "from the start"; - // EnsureUtc keeps Timestamp.FromDateTime happy (it requires UTC kind). - SinceUtc = Timestamp.FromDateTime(EnsureUtc(sinceUtc)), - BatchSize = batchSize, - // Composite-keyset tiebreak (proto field 3), mirroring PullSiteCalls exactly. - // proto3 has no nullable string — an unset/empty AfterId is the site's signal to - // keep the legacy inclusive-timestamp contract (also what a first pull sends). - AfterId = afterId ?? string.Empty, - }; + var request = BuildRequest(sinceUtc, afterId, batchSize); var (reply, transportFault) = await TryInvokeAsync(endpoint, request, siteId, ct) .ConfigureAwait(false); @@ -119,6 +109,54 @@ public sealed class GrpcPullAuditEventsClient : IPullAuditEventsClient (reply, _) = await TryInvokeAsync(fallback, request, siteId, ct).ConfigureAwait(false); } + return ToResponse(reply); + } + + /// + public async Task PullFromEndpointAsync( + string siteId, + string endpoint, + DateTime sinceUtc, + string? afterId, + int batchSize, + CancellationToken ct) + { + // AUD-1: one node, no failover. The node-local audit store owes its own rows, so the + // actor pulls each node with that node's cursor; a fault on this node is simply an + // empty batch for it (the other node is pulled separately on the same tick). + if (string.IsNullOrWhiteSpace(endpoint)) + { + return Empty; + } + + var (reply, _) = await TryInvokeAsync(endpoint, BuildRequest(sinceUtc, afterId, batchSize), siteId, ct) + .ConfigureAwait(false); + return ToResponse(reply); + } + + /// + /// + /// The per-endpoint path () does not enumerate sites, so the + /// reconciliation actor calls this once per tick to keep the invoker's channel cache pruned + /// (review 2026-10-21 06/MEM-2). + /// + public void RetainOnly(IReadOnlyList liveSites) + => (_invoker as IGrpcChannelCachePruner)?.RetainOnly(liveSites); + + private static ProtoPullRequest BuildRequest(DateTime sinceUtc, string? afterId, int batchSize) => new() + { + // ReadPendingSinceAsync treats DateTime.MinValue as "from the start"; + // EnsureUtc keeps Timestamp.FromDateTime happy (it requires UTC kind). + SinceUtc = Timestamp.FromDateTime(EnsureUtc(sinceUtc)), + BatchSize = batchSize, + // Composite-keyset tiebreak (proto field 3), mirroring PullSiteCalls exactly. + // proto3 has no nullable string — an unset/empty AfterId is the site's signal to + // keep the legacy inclusive-timestamp contract (also what a first pull sends). + AfterId = afterId ?? string.Empty, + }; + + private static PullAuditEventsResponse ToResponse(ProtoPullResponse? reply) + { if (reply is null) { return Empty; diff --git a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/GrpcPullSiteCallsClient.cs b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/GrpcPullSiteCallsClient.cs index f5d83431..644eef73 100644 --- a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/GrpcPullSiteCallsClient.cs +++ b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/GrpcPullSiteCallsClient.cs @@ -54,7 +54,7 @@ namespace ZB.MOM.WW.ScadaBridge.AuditLog.Central; /// inject a fake invoker so no real HTTP/2 endpoint is required. /// /// -public sealed class GrpcPullSiteCallsClient : IPullSiteCallsClient +public sealed class GrpcPullSiteCallsClient : IPullSiteCallsClient, IGrpcChannelCachePruner { private readonly ISiteEnumerator _sites; private readonly IPullSiteCallsInvoker _invoker; @@ -95,17 +95,7 @@ public sealed class GrpcPullSiteCallsClient : IPullSiteCallsClient return Empty; } - var request = new ProtoPullRequest - { - // ReadChangedSinceAsync treats DateTime.MinValue as "from the start"; - // EnsureUtc keeps Timestamp.FromDateTime happy (it requires UTC kind). - SinceUtc = Timestamp.FromDateTime(EnsureUtc(sinceUtc)), - BatchSize = batchSize, - // Composite-keyset tiebreak. proto3 has no nullable string — - // an unset/empty AfterId is the site's signal to keep the legacy - // inclusive-timestamp contract (also what a first pull sends). - AfterId = afterId ?? string.Empty, - }; + var request = BuildRequest(sinceUtc, afterId, batchSize); var (reply, transportFault) = await TryInvokeAsync(endpoint, request, siteId, ct) .ConfigureAwait(false); @@ -126,6 +116,51 @@ public sealed class GrpcPullSiteCallsClient : IPullSiteCallsClient (reply, _) = await TryInvokeAsync(fallback, request, siteId, ct).ConfigureAwait(false); } + return ToResponse(reply, siteId); + } + + /// + public async Task PullFromEndpointAsync( + string siteId, + string endpoint, + DateTime sinceUtc, + string? afterId, + int batchSize, + CancellationToken ct) + { + // AUD-1: one node, no failover — each node is pulled with its own cursor. + if (string.IsNullOrWhiteSpace(endpoint)) + { + return Empty; + } + + var (reply, _) = await TryInvokeAsync(endpoint, BuildRequest(sinceUtc, afterId, batchSize), siteId, ct) + .ConfigureAwait(false); + return ToResponse(reply, siteId); + } + + /// + /// + /// The per-endpoint path does not enumerate sites, so the reconciliation pass calls this once + /// per tick to keep the invoker's channel cache pruned (review 2026-10-21 06/MEM-2). + /// + public void RetainOnly(IReadOnlyList liveSites) + => (_invoker as IGrpcChannelCachePruner)?.RetainOnly(liveSites); + + private static ProtoPullRequest BuildRequest(DateTime sinceUtc, string? afterId, int batchSize) => new() + { + // ReadChangedSinceAsync treats DateTime.MinValue as "from the start"; + // EnsureUtc keeps Timestamp.FromDateTime happy (it requires UTC kind). + SinceUtc = Timestamp.FromDateTime(EnsureUtc(sinceUtc)), + BatchSize = batchSize, + // Composite-keyset tiebreak. proto3 has no nullable string — + // an unset/empty AfterId is the site's signal to keep the legacy + // inclusive-timestamp contract (also what a first pull sends). + AfterId = afterId ?? string.Empty, + }; + + private PullSiteCallsResponse ToResponse(ProtoPullResponse? reply, string siteId) + { if (reply is null) { return Empty; diff --git a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/IPullAuditEventsClient.cs b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/IPullAuditEventsClient.cs index e04357c7..3d13f1b0 100644 --- a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/IPullAuditEventsClient.cs +++ b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/IPullAuditEventsClient.cs @@ -59,4 +59,28 @@ public interface IPullAuditEventsClient string? afterId, int batchSize, CancellationToken ct); + + /// + /// Issues a PullAuditEvents RPC against ONE specific node of the site — no + /// NodeA→NodeB failover (AUD-1). The site audit store is a per-node, unreplicated SQLite + /// file, so each node owes its own rows; the reconciliation actor pulls every configured + /// node with its own cursor through this method. The default implementation (for test + /// doubles and any client without per-endpoint dialling) falls back to the site-level + /// . + /// + /// The site being pulled (selects the preshared key). + /// The node's gRPC authority to dial. + /// The node's composite-cursor timestamp half. + /// The node's composite-cursor id half (see ). + /// Maximum number of events to return per call. + /// Cancellation token. + /// A task that resolves to the next batch from that node. + Task PullFromEndpointAsync( + string siteId, + string endpoint, + DateTime sinceUtc, + string? afterId, + int batchSize, + CancellationToken ct) + => PullAsync(siteId, sinceUtc, afterId, batchSize, ct); } diff --git a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/IPullSiteCallsClient.cs b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/IPullSiteCallsClient.cs index f58c0ab7..1396874f 100644 --- a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/IPullSiteCallsClient.cs +++ b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/IPullSiteCallsClient.cs @@ -64,4 +64,27 @@ public interface IPullSiteCallsClient string? afterId, int batchSize, CancellationToken ct); + + /// + /// Issues a PullSiteCalls RPC against ONE specific node of the site — no NodeA→NodeB + /// failover (AUD-1). On a site pair that does not run LocalDb replication each node's + /// operation-tracking store is its own, so the reconciliation pass pulls every configured + /// node with its own cursor. The default implementation (test doubles) falls back to the + /// site-level . + /// + /// The site being pulled (selects the preshared key; re-stamped on rows). + /// The node's gRPC authority to dial. + /// The node's composite-cursor timestamp half. + /// The node's composite-cursor id half. + /// Maximum number of rows to return per call. + /// Cancellation token. + /// A task that resolves to the next batch from that node. + Task PullFromEndpointAsync( + string siteId, + string endpoint, + DateTime sinceUtc, + string? afterId, + int batchSize, + CancellationToken ct) + => PullAsync(siteId, sinceUtc, afterId, batchSize, ct); } diff --git a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/SiteAuditReconciliationActor.cs b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/SiteAuditReconciliationActor.cs index 0fb43806..4b681022 100644 --- a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/SiteAuditReconciliationActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/SiteAuditReconciliationActor.cs @@ -106,7 +106,14 @@ public class SiteAuditReconciliationActor : ReceiveActor /// write, so the cursor is an optimization for exactness, never a correctness crutch. /// /// - private readonly Dictionary _cursors = new(); + /// + /// Keyed per (site, node endpoint) since AUD-1 (2026-12): the site audit store is a + /// per-node, unreplicated SQLite file, so each node owes its own rows and a cursor produced by + /// one node's rows proves nothing about the other's. One shared per-site cursor used to skip + /// the other node's owed rows and let MarkReconciledUpToAsync retire rows central never + /// received. + /// + private readonly Dictionary<(string SiteId, string Endpoint), (DateTime Since, string? AfterId)> _cursors = new(); /// /// Per-site count of consecutive non-draining cycles. Resets to zero on the @@ -212,10 +219,18 @@ public class SiteAuditReconciliationActor : ReceiveActor private void PruneUnknownSites(IReadOnlyList sites, Akka.Event.EventStream eventStream) { var live = new HashSet(sites.Select(s => s.SiteId), StringComparer.Ordinal); - foreach (var siteId in _cursors.Keys.Concat(_nonDrainingCycles.Keys).Concat(_stalled.Keys) + var liveNodes = new HashSet<(string, string)>(sites.SelectMany(s => NodeEndpoints(s).Select(e => (s.SiteId, e)))); + + // A node whose address was edited away (or a deleted site) drops its cursor; a new + // address starts from the beginning of what that node owes, which is conservative. + foreach (var key in _cursors.Keys.Where(k => !liveNodes.Contains(k)).ToList()) + { + _cursors.Remove(key); + } + + foreach (var siteId in _nonDrainingCycles.Keys.Concat(_stalled.Keys) .Where(id => !live.Contains(id)).Distinct().ToList()) { - _cursors.Remove(siteId); _nonDrainingCycles.Remove(siteId); if (_stalled.Remove(siteId, out var wasStalled) && wasStalled) { @@ -224,8 +239,29 @@ public class SiteAuditReconciliationActor : ReceiveActor } } - /// Test seam: number of sites with a held reconciliation cursor. - internal int TrackedSiteCountForTests => _cursors.Count; + /// Test seam: number of sites with at least one held reconciliation cursor. + internal int TrackedSiteCountForTests => _cursors.Keys.Select(k => k.SiteId).Distinct().Count(); + + /// Test seam: number of (site, node) cursors held. + internal int TrackedNodeCursorCountForTests => _cursors.Count; + + /// + /// The distinct node endpoints of a site: the primary (NodeA where configured) and, when a + /// distinct one exists, the second node (AUD-1 — both are pulled every tick). + /// + private static IEnumerable NodeEndpoints(SiteEntry site) + { + if (!string.IsNullOrWhiteSpace(site.GrpcEndpoint)) + { + yield return site.GrpcEndpoint; + } + + if (!string.IsNullOrWhiteSpace(site.FallbackGrpcEndpoint) + && !string.Equals(site.FallbackGrpcEndpoint, site.GrpcEndpoint, StringComparison.Ordinal)) + { + yield return site.FallbackGrpcEndpoint; + } + } /// /// Initializes the reconciliation actor with its dependencies and registers the tick handler. @@ -310,6 +346,7 @@ public class SiteAuditReconciliationActor : ReceiveActor // After the empty guard: an empty enumeration is as likely a transient lookup glitch // as a fleet with no sites, and pruning on it would throw away every cursor. PruneUnknownSites(sites, eventStream); + (_client as IGrpcChannelCachePruner)?.RetainOnly(sites); // Use CreateAsyncScope + await using so scoped EF Core // services (IAsyncDisposable DbContexts) dispose asynchronously @@ -364,18 +401,40 @@ public class SiteAuditReconciliationActor : ReceiveActor private async Task PullSiteAsync(SiteEntry site, IAuditLogRepository repository, Akka.Event.EventStream eventStream) { var maxPages = Math.Max(1, _options.MaxPagesPerTick); - var nonDraining = false; - for (var page = 0; page < maxPages; page++) + var siteNonDraining = false; + + // AUD-1: pull EVERY node of the site, each with its own cursor. The pull used to go to + // NodeA whenever NodeA answered — after any NodeA restart (NodeB active, NodeA a healthy + // standby with an empty store) every pull returned "drained" and NodeB's PushAbandoned / + // Rejected rows never reached central. One node failing must not skip the other. + foreach (var endpoint in NodeEndpoints(site)) { - var (response, cursorAdvanced) = await PullPageAsync(site, repository).ConfigureAwait(false); - nonDraining = response.MoreAvailable && response.Events.Count > 0; - if (!nonDraining || !cursorAdvanced) + var nonDraining = false; + try { - break; + for (var page = 0; page < maxPages; page++) + { + var (response, cursorAdvanced) = await PullPageAsync(site, endpoint, repository).ConfigureAwait(false); + nonDraining = response.MoreAvailable && response.Events.Count > 0; + if (!nonDraining || !cursorAdvanced) + { + break; + } + } } + catch (Exception ex) + { + // Per-node isolation: this node's cursor stays where it was; the other node + // is still pulled on this tick. + _logger.LogWarning(ex, + "Reconciliation pull failed for site {SiteId} node {Endpoint}; the site's other node continues.", + site.SiteId, endpoint); + } + + siteNonDraining |= nonDraining; } - UpdateStalledState(site.SiteId, draining: !nonDraining, eventStream); + UpdateStalledState(site.SiteId, draining: !siteNonDraining, eventStream); } /// @@ -403,16 +462,17 @@ public class SiteAuditReconciliationActor : ReceiveActor /// /// The site's response and whether the cursor moved. private async Task<(PullAuditEventsResponse Response, bool CursorAdvanced)> PullPageAsync( - SiteEntry site, IAuditLogRepository repository) + SiteEntry site, string endpoint, IAuditLogRepository repository) { - var cursor = _cursors.TryGetValue(site.SiteId, out var c) + var cursorKey = (site.SiteId, endpoint); + var cursor = _cursors.TryGetValue(cursorKey, out var c) ? c : (Since: DateTime.MinValue, AfterId: (string?)null); var since = cursor.Since; var afterId = cursor.AfterId; - var response = await _client.PullAsync( - site.SiteId, since, afterId, _options.BatchSize, CancellationToken.None) + var response = await _client.PullFromEndpointAsync( + site.SiteId, endpoint, since, afterId, _options.BatchSize, CancellationToken.None) .ConfigureAwait(false); var maxOccurred = since; @@ -598,7 +658,7 @@ public class SiteAuditReconciliationActor : ReceiveActor var next = hasUnresolvedFailure ? (since, afterId) : (maxOccurred, maxAfterId); - _cursors[site.SiteId] = next; + _cursors[cursorKey] = next; var advanced = next.Item1 != since || !string.Equals(next.Item2, afterId, StringComparison.Ordinal); return (response, advanced); diff --git a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/Telemetry/CachedCallLifecycleBridge.cs b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/Telemetry/CachedCallLifecycleBridge.cs index 73e880a1..7203ef2b 100644 --- a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/Telemetry/CachedCallLifecycleBridge.cs +++ b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/Telemetry/CachedCallLifecycleBridge.cs @@ -36,6 +36,19 @@ namespace ZB.MOM.WW.ScadaBridge.AuditLog.Site.Telemetry; /// public sealed class CachedCallLifecycleBridge : ICachedCallLifecycleObserver { + /// + /// Operational status a re-opened (operator-retried) Parked call carries (SCA-1). A + /// packet whose operational status is this value — rather + /// than the initial submit's "Submitted" — tells + /// to re-open the tracking row instead of + /// inserting one. Attempted is also what central's SiteCalls guard accepts over + /// Parked when newer. + /// + public const string ReopenedOperationalStatus = "Attempted"; + + /// Operational status of an operator-discarded call (SCA-1). + public const string DiscardedOperationalStatus = "Discarded"; + private readonly ICachedCallTelemetryForwarder _forwarder; private readonly ILogger _logger; @@ -70,6 +83,19 @@ public sealed class CachedCallLifecycleBridge : ICachedCallLifecycleObserver try { + // SCA-1: operator transitions out of Parked are not attempts — one row each. + if (context.Outcome == CachedCallAttemptOutcome.OperatorRetried) + { + await EmitReopenAsync(context, ct).ConfigureAwait(false); + return; + } + + if (context.Outcome == CachedCallAttemptOutcome.OperatorDiscarded) + { + await EmitResolveAsync(context, ct).ConfigureAwait(false); + return; + } + await EmitAttemptedAsync(context, ct).ConfigureAwait(false); if (IsTerminal(context.Outcome)) @@ -113,6 +139,27 @@ public sealed class CachedCallLifecycleBridge : ICachedCallLifecycleObserver await _forwarder.ForwardAsync(packet, ct).ConfigureAwait(false); } + /// + /// Operator Retry of a Parked call (SCA-1): one / + /// row — the call was re-submitted to the retry loop — + /// whose operational half is with no terminal + /// stamp, RetryCount 0 and no error. The forwarder re-opens the tracking row from it, and + /// the cached-telemetry drain carries the re-opened state to central. + /// + private async Task EmitReopenAsync(CachedCallAttemptContext context, CancellationToken ct) + { + var packet = BuildPacket( + context, + kind: AuditKind.CachedSubmit, + status: AuditStatus.Submitted, + operationalStatus: ReopenedOperationalStatus, + terminalAtUtc: null, + lastError: null, + httpStatus: null); + + await _forwarder.ForwardAsync(packet, ct).ConfigureAwait(false); + } + private async Task EmitResolveAsync(CachedCallAttemptContext context, CancellationToken ct) { var (auditStatus, operationalStatus) = TerminalOutcomeToStatuses(context.Outcome); @@ -214,6 +261,8 @@ public sealed class CachedCallLifecycleBridge : ICachedCallLifecycleObserver (AuditStatus.Parked, "Parked"), CachedCallAttemptOutcome.ParkedMaxRetries => (AuditStatus.Parked, "Parked"), + CachedCallAttemptOutcome.OperatorDiscarded => + (AuditStatus.Discarded, DiscardedOperationalStatus), // TransientFailure isn't terminal — see IsTerminal — but the switch // is exhaustive so we route it through Failed for safety. CachedCallAttemptOutcome.TransientFailure => diff --git a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/Telemetry/CachedCallTelemetryForwarder.cs b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/Telemetry/CachedCallTelemetryForwarder.cs index cfb3644a..8286455f 100644 --- a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/Telemetry/CachedCallTelemetryForwarder.cs +++ b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/Telemetry/CachedCallTelemetryForwarder.cs @@ -174,6 +174,14 @@ public sealed class CachedCallTelemetryForwarder : ICachedCallTelemetryForwarder { switch (audit.Kind) { + case AuditKind.CachedSubmit + when telemetry.Operational.Status == CachedCallLifecycleBridge.ReopenedOperationalStatus: + // SCA-1: an operator re-queued a Parked call — re-open the row + // (clears TerminalAtUtc) so the retried attempts and outcome land. + await _trackingStore.ReopenParkedAsync( + telemetry.Operational.TrackedOperationId, ct).ConfigureAwait(false); + break; + case AuditKind.CachedSubmit: // Enqueue — insert-if-not-exists with the operational // channel as the kind discriminator. RetryCount is fixed @@ -205,6 +213,16 @@ public sealed class CachedCallTelemetryForwarder : ICachedCallTelemetryForwarder ct).ConfigureAwait(false); break; + case AuditKind.CachedResolve + when telemetry.Operational.Status == CachedCallLifecycleBridge.DiscardedOperationalStatus: + // SCA-1: an operator discard closes a Parked row as Discarded (the + // first-write-wins terminal flip below would leave it Parked). + await _trackingStore.RecordDiscardedAsync( + telemetry.Operational.TrackedOperationId, + telemetry.Operational.LastError, + ct).ConfigureAwait(false); + break; + case AuditKind.CachedResolve: // Terminal — first-write-wins on the resolve flip. await _trackingStore.RecordTerminalAsync( diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Entities/Kpi/KpiRollupBackfillState.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Entities/Kpi/KpiRollupBackfillState.cs new file mode 100644 index 00000000..3bd83201 --- /dev/null +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Entities/Kpi/KpiRollupBackfillState.cs @@ -0,0 +1,29 @@ +namespace ZB.MOM.WW.ScadaBridge.Commons.Entities.Kpi; + +/// +/// The KPI rollup backfill's own persisted progress marker (KPI-1, 2026-12): a single row +/// ( = ) recording that every whole hour before +/// has been folded by the one-shot backfill. +/// +/// +/// The backfill used to plan from MAX(KpiRollupHourly.HourStartUtc), which the periodic +/// lookback fold advances seconds before the backfill reads it — so the backfill was skipped +/// whenever samples existed in the last few hours, and an interrupted backfill was never resumed. +/// This marker moves only when a backfill slice folds successfully, so it says exactly how far +/// the backfill got. Persistence-ignorant POCO; the EF mapping lives in the Configuration +/// Database component. +/// +public sealed class KpiRollupBackfillState +{ + /// The id of the one and only row. + public const int SingletonId = 1; + + /// Always . + public int Id { get; set; } + + /// Exclusive upper hour boundary (UTC) the backfill has folded through. + public DateTime BackfilledThroughUtc { get; set; } + + /// When the marker last moved (UTC). + public DateTime UpdatedAtUtc { get; set; } +} diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/IAuditLogRepository.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/IAuditLogRepository.cs index f4905224..c3b70f8d 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/IAuditLogRepository.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/IAuditLogRepository.cs @@ -203,6 +203,13 @@ public interface IAuditLogRepository /// . Boundaries whose partition is empty are /// excluded (a no-op switch is wasted work). Used by the purge actor /// to enumerate retention-eligible months on every tick. + /// + /// Partition 1 — everything before the first boundary, which has no lower boundary of its + /// own — is included too (AUD-6): it is reported as the month start of its newest row, a + /// value that lies inside partition 1, so and the cold + /// archive (both resolve the partition with $partition.pf_AuditLog_Month(value)) + /// purge and archive it like any other month. + /// /// /// Only partitions whose data is entirely older than this UTC datetime are returned. /// Cancellation token. diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/IKpiHistoryRepository.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/IKpiHistoryRepository.cs index 774f9a11..b3759858 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/IKpiHistoryRepository.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/IKpiHistoryRepository.cs @@ -111,14 +111,47 @@ public interface IKpiHistoryRepository /// /// Returns the newest KpiRollupHourly.HourStartUtc across all series, or - /// null when no rollups exist. The recorder's one-shot backfill consults - /// this watermark to skip (or shrink to) the un-rolled tail instead of re-folding - /// the whole raw-retention window on every failover (arch-review 04 round 2, R1). + /// null when no rollups exist. No longer used to plan the backfill (KPI-1): the + /// periodic lookback fold advances this MAX seconds before the backfill reads it and it + /// says nothing about gaps below it — see . /// /// Cancellation token. /// A task resolving to the newest folded hour start, or null when empty. Task GetLatestRollupHourAsync(CancellationToken cancellationToken = default); + /// + /// Returns the rollup backfill's OWN persisted progress marker (KPI-1): the exclusive hour + /// boundary every whole hour before which the backfill has folded, or null when the + /// backfill has never completed a slice. The recorder plans the backfill from this — never + /// from the periodic fold's — so an upgrade with raw + /// history and an interrupted backfill are both folded. The default implementation (test + /// doubles) reports no progress. + /// + /// Cancellation token. + /// The backfilled-through hour, or null. + Task GetRollupBackfillWatermarkAsync(CancellationToken cancellationToken = default) + => Task.FromResult(null); + + /// + /// Advances the backfill's persisted progress marker to + /// — monotonically: a value at or below the stored one is a no-op. Called after each backfill + /// slice folds successfully, and after each periodic fold with + /// = the fold's lower bound, so a COMPLETED backfill's + /// marker keeps pace with the periodic fold without ever jumping a gap (the marker moves only + /// when it already reaches the fold window; it is never created that way). The default + /// implementation (test doubles) does nothing. + /// + /// The exclusive hour boundary now folded through. + /// + /// When set, advance only if the stored marker is already at or past this instant (contiguity); + /// never inserts the marker. + /// + /// Cancellation token. + /// A task that represents the asynchronous operation. + Task AdvanceRollupBackfillWatermarkAsync( + DateTime backfilledThroughUtc, DateTime? onlyIfReachedUtc = null, CancellationToken cancellationToken = default) + => Task.CompletedTask; + /// /// Bulk-deletes hourly rollup rows whose /// is diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/ICachedCallLifecycleObserver.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/ICachedCallLifecycleObserver.cs index 33d1d0c1..ef110306 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/ICachedCallLifecycleObserver.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/ICachedCallLifecycleObserver.cs @@ -120,4 +120,17 @@ public enum CachedCallAttemptOutcome /// Retry budget exhausted — terminal Parked state. ParkedMaxRetries, + + /// + /// An operator re-queued a PARKED cached call (Retry on the Site Calls / Parked Messages + /// page). Not an attempt: the call is back in the retry loop, so its tracking row leaves + /// Parked (SCA-1, 2026-12). Additive. + /// + OperatorRetried, + + /// + /// An operator discarded a PARKED cached call — terminal Discarded state (SCA-1, + /// 2026-12). Not an attempt. Additive. + /// + OperatorDiscarded, } diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/ICentralHealthAggregator.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/ICentralHealthAggregator.cs index 31dd1684..e6bd3917 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/ICentralHealthAggregator.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/ICentralHealthAggregator.cs @@ -12,7 +12,12 @@ public interface ICentralHealthAggregator /// Processes an incoming health report from a site and updates the aggregated state. /// /// The health report received from the site. - void ProcessReport(SiteHealthReport report); + /// + /// true when the report was applied; false when it was rejected as stale + /// (its sequence number is not above the last one applied for the site). The caller acks + /// the site with the result so a drop is never silent (COMM-1). + /// + bool ProcessReport(SiteHealthReport report); /// /// Bumps the last-seen timestamp for a site, keeping it marked online @@ -29,7 +34,10 @@ public interface ICentralHealthAggregator /// shown as "unknown" during the failover window. /// /// The string identifier of the site that sent the heartbeat. - /// The UTC timestamp when the heartbeat was received. + /// + /// The UTC time CENTRAL received the heartbeat (its own clock — never the site-stamped + /// timestamp, COMM-4). A value in the aggregator's future is clamped to its current time. + /// void MarkHeartbeat(string siteId, DateTimeOffset receivedAt); /// Returns a snapshot of all currently tracked site health states. diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/IOperationTrackingStore.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/IOperationTrackingStore.cs index d13b5309..822ffbd0 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/IOperationTrackingStore.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/IOperationTrackingStore.cs @@ -96,6 +96,30 @@ public interface IOperationTrackingStore int? httpStatus, CancellationToken ct = default); + /// + /// Re-opens a Parked row after an operator Retry re-queued the call (SCA-1): sets + /// Status = Attempted, RetryCount = 0, clears LastError/HttpStatus + /// and TerminalAtUtc, and stamps UpdatedAtUtc, so the attempts and terminal + /// outcome of the retried delivery land on the row again. A row that is not Parked + /// is left untouched. + /// + /// Operation ID to re-open. + /// Cancellation token. + /// A task that represents the asynchronous operation. + Task ReopenParkedAsync(TrackedOperationId id, CancellationToken ct = default); + + /// + /// Records an operator Discard (SCA-1): sets Status = Discarded and stamps + /// TerminalAtUtc/UpdatedAtUtc on a row that is Parked or not yet + /// terminal. Any other terminal row (Delivered, Failed, an earlier Discarded) is left + /// untouched. + /// + /// Operation ID that was discarded. + /// Optional note recorded as the row's last error. + /// Cancellation token. + /// A task that represents the asynchronous operation. + Task RecordDiscardedAsync(TrackedOperationId id, string? lastError, CancellationToken ct = default); + /// /// Return the latest snapshot for the supplied id, or null when no /// tracking row exists (purged or never recorded). diff --git a/src/ZB.MOM.WW.ScadaBridge.Communication/Actors/CentralCommunicationActor.cs b/src/ZB.MOM.WW.ScadaBridge.Communication/Actors/CentralCommunicationActor.cs index 1ea0cb6a..10989815 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Communication/Actors/CentralCommunicationActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Communication/Actors/CentralCommunicationActor.cs @@ -142,7 +142,10 @@ public class CentralCommunicationActor : ReceiveActor // Health monitoring: heartbeats and health reports from sites Receive(HandleHeartbeat); Receive(HandleSiteHealthReport); - Receive(r => ProcessLocally(r.Report)); + // Block-bodied on purpose: ProcessLocally returns bool, and an expression lambda would + // bind Receive(Predicate), where false means "unhandled" — every stale replica + // (including this node's own self-delivered one) would then be logged as unhandled. + Receive(r => { ProcessLocally(r.Report); }); Receive(r => MarkHeartbeatLocally(r.Heartbeat)); Receive(_ => { /* DistributedPubSub subscribe confirmation */ }); @@ -320,8 +323,12 @@ public class CentralCommunicationActor : ReceiveActor return; } + // Liveness is keyed on CENTRAL's receive time (COMM-4), never the site-stamped + // heartbeat.Timestamp: the offline check compares against central's clock, so a site + // clock running X ahead used to stretch the 60 s offline timeout to 60 s + X (a site + // without NTP, 30 min fast, read Online for ~31 min after its link dropped). var aggregator = _serviceProvider.GetService(); - aggregator?.MarkHeartbeat(heartbeat.SiteId, heartbeat.Timestamp); + aggregator?.MarkHeartbeat(heartbeat.SiteId, DateTimeOffset.UtcNow); } /// @@ -331,7 +338,7 @@ public class CentralCommunicationActor : ReceiveActor /// private void HandleSiteHealthReport(SiteHealthReport report) { - ProcessLocally(report); + var accepted = ProcessLocally(report); try { @@ -349,7 +356,13 @@ public class CentralCommunicationActor : ReceiveActor // which arrives without an Ask sender) never dead-letters an ack. if (!Sender.IsNobody()) { - Sender.Tell(new SiteHealthReportAck(report.SiteId, report.SequenceNumber, Accepted: true)); + // The ack carries the aggregator's verdict (COMM-1): a report rejected as stale is + // nacked, so the site's transport throws, its per-interval counters are restored, and + // the drop is logged at the site instead of vanishing behind an "Accepted" ack. + Sender.Tell(accepted + ? new SiteHealthReportAck(report.SiteId, report.SequenceNumber, Accepted: true) + : new SiteHealthReportAck(report.SiteId, report.SequenceNumber, Accepted: false, + Error: "Rejected as stale: sequence number is not above the last report central applied for this site")); } } @@ -358,17 +371,16 @@ public class CentralCommunicationActor : ReceiveActor /// Used for both site-originated reports and peer-replicated ones — the /// aggregator is idempotent via sequence-number comparison. /// - private void ProcessLocally(SiteHealthReport report) + private bool ProcessLocally(SiteHealthReport report) { var aggregator = _serviceProvider.GetService(); if (aggregator != null) { - aggregator.ProcessReport(report); - } - else - { - _log.Warning("ICentralHealthAggregator not available, dropping health report from site {0}", report.SiteId); + return aggregator.ProcessReport(report); } + + _log.Warning("ICentralHealthAggregator not available, dropping health report from site {0}", report.SiteId); + return false; } // HandleConnectionStateChanged removed — no production diff --git a/src/ZB.MOM.WW.ScadaBridge.Communication/Actors/DebugStreamBridgeActor.cs b/src/ZB.MOM.WW.ScadaBridge.Communication/Actors/DebugStreamBridgeActor.cs index ebc5cc32..e92cead3 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Communication/Actors/DebugStreamBridgeActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Communication/Actors/DebugStreamBridgeActor.cs @@ -291,6 +291,37 @@ public class DebugStreamBridgeActor : ReceiveActor, IWithTimers _snapshotDelivered = true; }); + // Fail-fast reply from the command transport (COMM-7). GrpcSiteTransport answers a + // send it cannot complete (no channel for the site, an immediate RPC error) with + // Status.Failure to the reply target — this actor, for the snapshot request. Before + // the snapshot that is the end of the session: fail it now with the real cause instead + // of waiting out the 30 s snapshot deadline and reporting a generic timeout. After the + // snapshot (e.g. a failed unsubscribe) it is informational only. + Receive(failure => + { + if (_stopped) return; + if (_snapshotDelivered) + { + _log.Debug("Ignoring command-plane failure for {0} after the snapshot: {1}", + _instanceUniqueName, failure.Cause?.Message); + return; + } + + _log.Warning("Debug snapshot request for {0} on site {1} failed: {2}", + _instanceUniqueName, _siteIdentifier, failure.Cause?.Message); + Timers.Cancel(SnapshotTimerKey); + CleanupGrpc(); + SendUnsubscribe(); + _stopped = true; + _preSnapshotBuffer.Clear(); + // Hand the cause to DebugStreamService (it intercepts this marker and fails the + // pending StartStreamAsync with it) before the generic termination callback. + _onEvent(new DebugSnapshotRequestFailed( + failure.Cause ?? new InvalidOperationException("The debug snapshot request failed."))); + _onTerminated(); + Context.Stop(Self); + }); + // Hard snapshot deadline. Nothing else ends a session stuck in the // buffering phase: the site's reply was lost, so no gRPC error fires, the stream // keeps delivering events, and stream traffic does not renew the orphan net (which @@ -577,7 +608,7 @@ public class DebugStreamBridgeActor : ReceiveActor, IWithTimers /// key via (e.g. two entries with null AttributePath /// would otherwise share a key with any entry whose AttributePath is the empty string). /// - private static string AttributeKey(AttributeValueChanged a) => + internal static string AttributeKey(AttributeValueChanged a) => string.Concat( a.InstanceUniqueName ?? string.Empty, KeyDelimiter, a.AttributePath ?? string.Empty, KeyDelimiter, @@ -589,7 +620,7 @@ public class DebugStreamBridgeActor : ReceiveActor, IWithTimers /// reference) are not conflated; empty for computed alarms. Each nullable component is /// guarded with ?? string.Empty to prevent silent key collisions. /// - private static string AlarmKey(AlarmStateChanged al) => + internal static string AlarmKey(AlarmStateChanged al) => string.Concat( al.InstanceUniqueName ?? string.Empty, KeyDelimiter, al.AlarmName ?? string.Empty, KeyDelimiter, @@ -862,6 +893,15 @@ internal record ConsumerLivenessTick; /// internal record DebugSnapshotDeadline; +/// +/// Delivered through the bridge's onEvent callback when the snapshot request failed +/// fast at the command transport (COMM-7). intercepts it and +/// fails the pending StartStreamAsync with ; it never reaches a +/// consumer. +/// +/// The transport failure. +internal sealed record DebugSnapshotRequestFailed(Exception Cause); + /// /// Internal message indicating a gRPC stream error occurred, stamped with the stream /// generation it came from so a late error out of a cancelled stream can be ignored. diff --git a/src/ZB.MOM.WW.ScadaBridge.Communication/Actors/SiteAlarmAggregatorActor.cs b/src/ZB.MOM.WW.ScadaBridge.Communication/Actors/SiteAlarmAggregatorActor.cs index 138e6852..69aa4908 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Communication/Actors/SiteAlarmAggregatorActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Communication/Actors/SiteAlarmAggregatorActor.cs @@ -420,8 +420,18 @@ public sealed class SiteAlarmAggregatorActor : ReceiveActor, IWithTimers _openInFlight = false; _log.Warning( "Site-alarm gRPC stream open for {0} did not report connected, error or completion within {1}; " + - "releasing the in-flight guard so the next reconcile tick can reopen", + "treating it as a stream error (flip node, count a retry)", _siteIdentifier, _openAttemptTimeout); + + // COMM-5: an attempt that never resolves is a failed attempt — the node did not + // accept the subscription. Treat it like a stream error so the aggregator flips to + // the other node and spends retry budget; before, it only released the guard and + // the next reconcile tick reopened on the SAME node (bumping the generation, so the + // cancelled attempt's eventual connect error was discarded as stale) — a black-holed + // NodeA was never left. Cancel the stalled attempt first so its late callbacks are + // silent (a cancelled attempt reports neither error nor completion). + _grpcCts?.Cancel(); + HandleGrpcError(); }); // Coalesced-publish tick: one publish for a batch of dirtying deltas (N6). diff --git a/src/ZB.MOM.WW.ScadaBridge.Communication/CommunicationOptions.cs b/src/ZB.MOM.WW.ScadaBridge.Communication/CommunicationOptions.cs index 9ccb75b0..f16215c2 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Communication/CommunicationOptions.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Communication/CommunicationOptions.cs @@ -134,6 +134,17 @@ public class CommunicationOptions /// gRPC keepalive ping timeout — stream is considered dead if no response within this period. public TimeSpan GrpcKeepAlivePingTimeout { get; set; } = TimeSpan.FromSeconds(10); + /// + /// TCP connect timeout (SocketsHttpHandler.ConnectTimeout) for every cross-cluster gRPC + /// channel — the central→site command pair, the site→central control pair and the site stream + /// clients (COMM-5). Without it a peer whose host silently drops SYNs (powered off behind a + /// router, firewall drop, WAN black hole) held the connect for the OS TCP timeout (~21 s on + /// Windows, ~2 min on Linux), so calls with shorter deadlines ended DeadlineExceeded and + /// never failed over. With it the connect fails as Unavailable well inside every call + /// deadline. Default 5 s. + /// + public TimeSpan GrpcConnectTimeout { get; set; } = TimeSpan.FromSeconds(5); + /// Maximum lifetime for a single gRPC stream before the server forces re-establishment. public TimeSpan GrpcMaxStreamLifetime { get; set; } = TimeSpan.FromHours(4); diff --git a/src/ZB.MOM.WW.ScadaBridge.Communication/CommunicationOptionsValidator.cs b/src/ZB.MOM.WW.ScadaBridge.Communication/CommunicationOptionsValidator.cs index 5b110277..fad47b78 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Communication/CommunicationOptionsValidator.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Communication/CommunicationOptionsValidator.cs @@ -64,6 +64,8 @@ public sealed class CommunicationOptionsValidator : OptionsValidatorBase TimeSpan.Zero, $"ScadaBridge:Communication:GrpcKeepAlivePingTimeout must be a positive duration (was {options.GrpcKeepAlivePingTimeout})."); + builder.RequireThat(options.GrpcConnectTimeout > TimeSpan.Zero, + $"ScadaBridge:Communication:GrpcConnectTimeout must be a positive duration (was {options.GrpcConnectTimeout})."); builder.RequireThat(options.GrpcMaxStreamLifetime > TimeSpan.Zero, $"ScadaBridge:Communication:GrpcMaxStreamLifetime must be a positive duration (was {options.GrpcMaxStreamLifetime})."); diff --git a/src/ZB.MOM.WW.ScadaBridge.Communication/DebugStreamService.cs b/src/ZB.MOM.WW.ScadaBridge.Communication/DebugStreamService.cs index 02a01cd8..a62f5a1f 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Communication/DebugStreamService.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Communication/DebugStreamService.cs @@ -4,6 +4,7 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories; using ZB.MOM.WW.ScadaBridge.Commons.Messages.DebugView; +using ZB.MOM.WW.ScadaBridge.Commons.Messages.Streaming; using ZB.MOM.WW.ScadaBridge.Communication.Actors; using ZB.MOM.WW.ScadaBridge.Communication.Grpc; @@ -138,16 +139,39 @@ public class DebugStreamService : IDisposable // Capture the initial snapshot via a TaskCompletionSource var snapshotTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + // COMM-3: events that follow the snapshot (the bridge flushes its gap-window buffer + // synchronously, right after the snapshot) are HELD here until this method hands the + // snapshot back, then folded into it. Passing them straight to onEvent delivered them + // before the caller had applied the snapshot, so a consumer that replaces its state + // from the snapshot regressed to the older value (the SignalR hub sent + // OnAttributeChanged before OnSnapshot). All three fields are guarded by `gate`. + var gate = new object(); + var handedOver = false; + var held = new List(); + Action onEventWrapper = evt => { - if (evt is DebugViewSnapshot snapshot && !snapshotTcs.Task.IsCompleted) + if (evt is DebugSnapshotRequestFailed failed) { - snapshotTcs.TrySetResult(snapshot); + // COMM-7: the snapshot request failed fast at the transport — fail the + // pending start with the real cause (onTerminatedWrapper follows). + snapshotTcs.TrySetException(failed.Cause); + return; } - else + + lock (gate) { - onEvent(evt); + if (!handedOver) + { + if (evt is DebugViewSnapshot snapshot && !snapshotTcs.Task.IsCompleted) + snapshotTcs.TrySetResult(snapshot); + else + held.Add(evt); + return; + } } + + onEvent(evt); }; Action onTerminatedWrapper = () => @@ -185,6 +209,17 @@ public class DebugStreamService : IDisposable try { snapshot = await snapshotTcs.Task.WaitAsync(timeoutCts.Token); + + // Hand over (COMM-3): fold every event held since the snapshot into it, then switch + // the wrapper to pass-through. Under the gate, so an event racing this either lands + // in `held` (and is folded) or is delivered after the switch — never both, never + // ahead of the snapshot it postdates. + lock (gate) + { + snapshot = FoldIntoSnapshot(snapshot, held); + held.Clear(); + handedOver = true; + } } catch (Exception ex) { @@ -203,7 +238,7 @@ public class DebugStreamService : IDisposable $"Timed out waiting for debug snapshot from {instanceUniqueName} on site {siteIdentifier}."); throw new InvalidOperationException( - $"Debug stream for {instanceUniqueName} on site {siteIdentifier} terminated before a snapshot was received.", + $"Debug stream for {instanceUniqueName} on site {siteIdentifier} terminated before a snapshot was received: {ex.Message}", ex); } @@ -226,6 +261,67 @@ public class DebugStreamService : IDisposable return new DebugStreamSession(sessionId, snapshot); } + /// + /// Folds live events that arrived after into it (COMM-3): each + /// / replaces the snapshot + /// row for the same entity (same identity key the bridge's dedup uses) when it is at least as + /// new, or is appended when the snapshot has no row for it. Events are applied in arrival + /// order, so the result is the state as of the last held event. + /// + /// The snapshot the site returned. + /// Events received after the snapshot, in arrival order. + /// The snapshot with the events applied (the same instance when there are none). + internal static DebugViewSnapshot FoldIntoSnapshot(DebugViewSnapshot snapshot, IReadOnlyList events) + { + if (events.Count == 0 || snapshot.InstanceNotFound) return snapshot; + + var attributes = snapshot.AttributeValues.ToList(); + var alarms = snapshot.AlarmStates.ToList(); + var attrIndex = new Dictionary(); + for (var i = 0; i < attributes.Count; i++) + attrIndex[DebugStreamBridgeActor.AttributeKey(attributes[i])] = i; + var alarmIndex = new Dictionary(); + for (var i = 0; i < alarms.Count; i++) + alarmIndex[DebugStreamBridgeActor.AlarmKey(alarms[i])] = i; + + foreach (var evt in events) + { + switch (evt) + { + case AttributeValueChanged a: + { + var key = DebugStreamBridgeActor.AttributeKey(a); + if (attrIndex.TryGetValue(key, out var i)) + { + if (a.Timestamp >= attributes[i].Timestamp) attributes[i] = a; + } + else + { + attrIndex[key] = attributes.Count; + attributes.Add(a); + } + break; + } + case AlarmStateChanged al: + { + var key = DebugStreamBridgeActor.AlarmKey(al); + if (alarmIndex.TryGetValue(key, out var i)) + { + if (al.Timestamp >= alarms[i].Timestamp) alarms[i] = al; + } + else + { + alarmIndex[key] = alarms.Count; + alarms.Add(al); + } + break; + } + } + } + + return snapshot with { AttributeValues = attributes, AlarmStates = alarms }; + } + /// /// Re-reads a site's current streaming endpoints for a running session's reconnect. /// diff --git a/src/ZB.MOM.WW.ScadaBridge.Communication/Grpc/CentralChannelProvider.cs b/src/ZB.MOM.WW.ScadaBridge.Communication/Grpc/CentralChannelProvider.cs index 907cad7f..60f8df28 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Communication/Grpc/CentralChannelProvider.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Communication/Grpc/CentralChannelProvider.cs @@ -114,6 +114,7 @@ public sealed class CentralChannelProvider : IDisposable { KeepAlivePingDelay = options.GrpcKeepAlivePingDelay, KeepAlivePingTimeout = options.GrpcKeepAlivePingTimeout, + ConnectTimeout = options.GrpcConnectTimeout, KeepAlivePingPolicy = HttpKeepAlivePingPolicy.Always, EnableMultipleHttp2Connections = true, }, @@ -151,6 +152,18 @@ public sealed class CentralChannelProvider : IDisposable return (idx, _clients[idx]); } + /// + /// True when is a that expired + /// while the endpoint at was still not accepting a connection + /// (COMM-5) — see . + /// + /// The RPC failure. + /// The endpoint index the failed call used. + /// true for a connect-phase deadline. + public bool IsConnectPhaseDeadline(RpcException error, int index) + => index >= 0 && index < _channels.Length + && GrpcRetrySafety.IsConnectPhaseDeadline(error, _channels[index]); + /// /// Reports that the endpoint at refused a connection (an /// / connect failure). If it is still the current endpoint diff --git a/src/ZB.MOM.WW.ScadaBridge.Communication/Grpc/GrpcCentralTransport.cs b/src/ZB.MOM.WW.ScadaBridge.Communication/Grpc/GrpcCentralTransport.cs index a942dd08..e8f8aaf3 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Communication/Grpc/GrpcCentralTransport.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Communication/Grpc/GrpcCentralTransport.cs @@ -141,10 +141,12 @@ public sealed class GrpcCentralTransport : ICentralTransport using var call = client.HeartbeatAsync(dto, options); await call.ResponseAsync.ConfigureAwait(false); } - catch (RpcException ex) when (IsConnectFailure(ex)) + catch (RpcException ex) when (IsConnectFailure(ex) || _channels.IsConnectPhaseDeadline(ex, index)) { // Nudge the pair so the next call tries the peer, but never fault: a heartbeat - // failure must not surface on the site's heartbeat timer path. + // failure must not surface on the site's heartbeat timer path. A connect-phase + // deadline (COMM-5: black-holed central node) counts too — otherwise a quiet site + // whose only traffic is the heartbeat never leaves a dead central-a. _channels.ReportUnavailable(index); _logger.LogDebug(ex, "Heartbeat to central endpoint {Endpoint} was unavailable.", CurrentEndpointSafe()); } @@ -213,6 +215,13 @@ public sealed class GrpcCentralTransport : ICentralTransport replyTo.Tell(new AkkaStatus.Failure(ex)); } + catch (RpcException ex) when (_channels.IsConnectPhaseDeadline(ex, index)) + { + // COMM-5: the deadline expired before the endpoint accepted a connection. Move the + // pair so the next call tries the peer; the deadline is spent, so no retry here. + _channels.ReportUnavailable(index); + replyTo.Tell(new AkkaStatus.Failure(ex)); + } catch (Exception ex) { // DeadlineExceeded / Internal / PermissionDenied / a PSK-resolution throw — do NOT diff --git a/src/ZB.MOM.WW.ScadaBridge.Communication/Grpc/GrpcRetrySafety.cs b/src/ZB.MOM.WW.ScadaBridge.Communication/Grpc/GrpcRetrySafety.cs index 1ee6d01c..f9193265 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Communication/Grpc/GrpcRetrySafety.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Communication/Grpc/GrpcRetrySafety.cs @@ -1,6 +1,7 @@ using System.Net.Http; using System.Net.Sockets; using Grpc.Core; +using Grpc.Net.Client; namespace ZB.MOM.WW.ScadaBridge.Communication.Grpc; @@ -31,11 +32,12 @@ public static class GrpcRetrySafety /// /// True only when the client failed while OPENING a connection, so the request provably never /// left this process (ScadaBridge#136 — the first command to a stopped node of a site pair). - /// Two shapes qualify, both with a - /// in the debug-exception chain: + /// Two shapes qualify, both : /// - /// Grpc.Net.Client's subchannel connect failure (): - /// the balancer never handed the call a connection, whatever the socket error. + /// Grpc.Net.Client's subchannel connect failure () + /// with a or a (the + /// SocketsHttpHandler.ConnectTimeout firing on a black-holed peer — COMM-5) in the + /// debug-exception chain: the balancer never handed the call a connection. /// An classified as a name-resolution or connection /// error whose socket error can only arise before a connection exists (refused, host not /// found, DNS try-again / no-data). @@ -54,10 +56,18 @@ public static class GrpcRetrySafety HttpRequestException? http = null; SocketException? socket = null; + TimeoutException? connectTimeout = null; for (var e = error.Status.DebugException; e is not null; e = e.InnerException) { http ??= e as HttpRequestException; socket ??= e as SocketException; + connectTimeout ??= e as TimeoutException; + } + + if (http is null) + { + return (socket is not null || connectTimeout is not null) + && string.Equals(error.Status.Detail, SubchannelConnectFailureDetail, StringComparison.Ordinal); } if (socket is null) @@ -65,16 +75,41 @@ public static class GrpcRetrySafety return false; } - if (http is null) - { - return string.Equals(error.Status.Detail, SubchannelConnectFailureDetail, StringComparison.Ordinal); - } - return http.HttpRequestError is HttpRequestError.NameResolutionError or HttpRequestError.ConnectionError && socket.SocketErrorCode is SocketError.ConnectionRefused or SocketError.HostNotFound or SocketError.TryAgain or SocketError.NoData; } + /// + /// True when a ended the call while + /// was still trying to connect (state Connecting or + /// TransientFailure), i.e. the peer never accepted a connection (COMM-5). That is a + /// reason to move the channel pair to the other node; it is NOT proof the request was unsent + /// for replay purposes, and the spent deadline leaves nothing to retry with anyway. A + /// deadline on a connected (Ready) channel is a slow peer and returns false, as does a + /// channel that does not expose a connectivity state. + /// + /// The RPC failure to inspect. + /// The channel the call ran on. + /// true for a deadline that expired in the connect phase. + public static bool IsConnectPhaseDeadline(RpcException error, GrpcChannel channel) + { + if (error.StatusCode != StatusCode.DeadlineExceeded) + { + return false; + } + + try + { + return channel.State is ConnectivityState.Connecting or ConnectivityState.TransientFailure; + } + catch (InvalidOperationException) + { + // Channel built without the subchannel balancer (a custom test handler): unknown. + return false; + } + } + /// /// True when a mutation may be replayed on the peer node: the server rejected it before /// dispatch (), or the client never sent it (). diff --git a/src/ZB.MOM.WW.ScadaBridge.Communication/Grpc/SitePairChannelProvider.cs b/src/ZB.MOM.WW.ScadaBridge.Communication/Grpc/SitePairChannelProvider.cs index 27b3dffa..3fdc6793 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Communication/Grpc/SitePairChannelProvider.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Communication/Grpc/SitePairChannelProvider.cs @@ -322,6 +322,17 @@ public sealed class SitePairChannelProvider : IDisposable if (primaryIsA) ConfirmFailback(pair); return result; } + catch (RpcException ex) when (secondary is not null && GrpcRetrySafety.IsConnectPhaseDeadline(ex, primary)) + { + // COMM-5: the deadline expired while the node was still not accepting a connection + // (black-holed host, deadline shorter than the connect timeout). Move the pair so the + // next call goes to the other node; the spent deadline leaves nothing to retry with. + FlipTo(pair, toIsA: !primaryIsA); + _logger.LogWarning( + "Site {TargetSiteId} node {FromNode} did not accept a connection before the call deadline; next calls go to node {ToNode}", + siteId, primaryIsA ? "A" : "B", primaryIsA ? "B" : "A"); + throw; + } catch (RpcException ex) when (ex.StatusCode == StatusCode.Unavailable) { if (secondary is not null) FlipTo(pair, toIsA: !primaryIsA); @@ -586,6 +597,7 @@ public sealed class SitePairChannelProvider : IDisposable { KeepAlivePingDelay = _options.GrpcKeepAlivePingDelay, KeepAlivePingTimeout = _options.GrpcKeepAlivePingTimeout, + ConnectTimeout = _options.GrpcConnectTimeout, KeepAlivePingPolicy = HttpKeepAlivePingPolicy.Always, EnableMultipleHttp2Connections = true } diff --git a/src/ZB.MOM.WW.ScadaBridge.Communication/Grpc/SiteStreamGrpcClient.cs b/src/ZB.MOM.WW.ScadaBridge.Communication/Grpc/SiteStreamGrpcClient.cs index d6849543..8f330a92 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Communication/Grpc/SiteStreamGrpcClient.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Communication/Grpc/SiteStreamGrpcClient.cs @@ -92,7 +92,8 @@ public class SiteStreamGrpcClient : IAsyncDisposable, IDisposable { KeepAlivePingDelay = options.GrpcKeepAlivePingDelay, KeepAlivePingTimeout = options.GrpcKeepAlivePingTimeout, - KeepAlivePingPolicy = HttpKeepAlivePingPolicy.Always + KeepAlivePingPolicy = HttpKeepAlivePingPolicy.Always, + ConnectTimeout = options.GrpcConnectTimeout } }.WithMessageLimits().WithSiteCredentials(pskProvider, siteIdentifier, endpoint)); _client = new SiteStreamService.SiteStreamServiceClient(_channel); diff --git a/src/ZB.MOM.WW.ScadaBridge.Communication/Grpc/SiteStreamGrpcServer.cs b/src/ZB.MOM.WW.ScadaBridge.Communication/Grpc/SiteStreamGrpcServer.cs index 00795858..270bd208 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Communication/Grpc/SiteStreamGrpcServer.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Communication/Grpc/SiteStreamGrpcServer.cs @@ -19,7 +19,7 @@ namespace ZB.MOM.WW.ScadaBridge.Communication.Grpc; /// Creates a StreamRelayActor per subscription to bridge Akka domain events /// through a Channel<T> to the gRPC response stream. /// -public class SiteStreamGrpcServer : SiteStreamService.SiteStreamServiceBase +public class SiteStreamGrpcServer : SiteStreamService.SiteStreamServiceBase, IDisposable { private readonly ISiteStreamSubscriber _streamSubscriber; private ActorSystem? _actorSystem; @@ -38,6 +38,19 @@ public class SiteStreamGrpcServer : SiteStreamService.SiteStreamServiceBase // true, never reset (the server is single-lifetime per host). private volatile bool _shuttingDown; private long _actorCounter; + // Active-node gate (COMM-2). The site stream hub is node-local — Instance Actors, and so + // every event, exist only on the ACTIVE node — so a subscription accepted by a standby + // is a live-looking stream that never carries an event. When the host supplies the gate + // (ActiveNodeEvaluator.SelfIsOldestUp for the site role), Subscribe* refuses with + // Unavailable on a non-active node and the watchdog ends every open stream with + // Unavailable once the node loses the active role; both surface on central's stream + // client as an error, which flips it to the other node. Null = no gate (tests composing + // the server in isolation, and hosts that predate the gate). + private Func? _isActiveNode; + private Timer? _activeRoleWatchdog; + + /// How often the active-role watchdog re-checks the gate while streams are open. + internal static readonly TimeSpan DefaultActiveRoleCheckInterval = TimeSpan.FromSeconds(2); // Ask timeout is 30 s. The ingest actor's repo // calls take under 100 ms in steady state; a generous timeout absorbs a slow // MSSQL connection without surfacing as a gRPC failure on a healthy site. @@ -142,12 +155,111 @@ public class SiteStreamGrpcServer : SiteStreamService.SiteStreamServiceBase /// the gRPC server can be created by DI before the actor system exists. /// /// The initialized Akka actor system. - public void SetReady(ActorSystem actorSystem) + public void SetReady(ActorSystem actorSystem) => SetReady(actorSystem, isActiveNode: null); + + /// + /// Marks the server ready and installs the active-node gate (COMM-2): while + /// returns false, and + /// refuse with , and a + /// watchdog ends every open stream with once the node + /// stops being active. Central's stream clients treat both as a stream error and flip to + /// the other site node, so a viewer always lands on the node whose Instance Actors produce + /// events. Only the two subscription RPCs are gated — the reconciliation/trace pulls read + /// node-local stores and must keep answering on either node. + /// + /// The initialized Akka actor system. + /// + /// Returns whether this node is the active node for its site + /// (ActiveNodeEvaluator.SelfIsOldestUp(cluster, "site-{SiteId}")); null disables the gate. + /// + /// Watchdog cadence; defaults to . + public void SetReady(ActorSystem actorSystem, Func? isActiveNode, TimeSpan? activeRoleCheckInterval = null) { _actorSystem = actorSystem; + _isActiveNode = isActiveNode; + if (isActiveNode is not null && _activeRoleWatchdog is null) + { + var interval = activeRoleCheckInterval ?? DefaultActiveRoleCheckInterval; + _activeRoleWatchdog = new Timer(_ => EndStreamsIfNotActive(), null, interval, interval); + } _ready = true; } + /// + /// Evaluates the active-node gate for a NEW subscription. A gate that throws (the cluster + /// extension going away during shutdown) counts as "not active" — refusing is the safe + /// answer, since the client simply tries the other node. + /// + private bool IsActiveForNewSubscription() + { + var gate = _isActiveNode; + if (gate is null) return true; + try + { + return gate(); + } + catch (Exception ex) + { + _logger.LogDebug(ex, "Active-node gate threw; refusing the stream subscription"); + return false; + } + } + + /// + /// Watchdog body (COMM-2): when the node is no longer the active node, ends every open + /// stream so its client sees and flips to the other + /// node. A gate that throws leaves the streams alone (an open stream is only ended on a + /// definite "not active"). Returns the number of streams ended; exposed for tests. + /// + /// The number of streams this call ended. + internal int EndStreamsIfNotActive() + { + var gate = _isActiveNode; + if (gate is null || _activeStreams.IsEmpty || _shuttingDown) return 0; + + bool active; + try + { + active = gate(); + } + catch (Exception ex) + { + _logger.LogDebug(ex, "Active-node gate threw in the stream watchdog; leaving streams open"); + return 0; + } + if (active) return 0; + + var ended = 0; + foreach (var entry in _activeStreams.Values) + { + entry.LostActiveRole = true; + try + { + entry.Cts.Cancel(); + ended++; + } + catch (ObjectDisposedException) + { + // Its own handler already finished — nothing to end. + } + } + + if (ended > 0) + { + _logger.LogInformation( + "This site node is no longer the active node; ended {Count} stream(s) with Unavailable so central reconnects to the active node", + ended); + } + return ended; + } + + /// + public void Dispose() + { + _activeRoleWatchdog?.Dispose(); + GC.SuppressFinalize(this); + } + /// /// Hands the site-local (the same /// SqliteAuditWriter singleton that backs @@ -322,6 +434,14 @@ public class SiteStreamGrpcServer : SiteStreamService.SiteStreamServiceBase if (_shuttingDown) throw new RpcException(new GrpcStatus(StatusCode.Unavailable, "Server shutting down")); + // COMM-2: a standby node's hub carries no events (Instance Actors run only on the + // active node), so accepting here would hand central a stream that looks live and is + // silent forever. Refuse; central's client treats Unavailable as a stream error and + // flips to the other node. + if (!IsActiveForNewSubscription()) + throw new RpcException(new GrpcStatus(StatusCode.Unavailable, + "Not the active node for this site; subscribe to the other site node")); + // correlation_id arrives off the wire on a public gRPC // endpoint and is used (below) to compose an Akka actor name. Akka actor names // have a restricted character set — a id containing '/', whitespace, or other @@ -513,6 +633,16 @@ public class SiteStreamGrpcServer : SiteStreamService.SiteStreamServiceBase : null, streamCts.Token); } + catch (OperationCanceledException) + when (entry.LostActiveRole && !context.CancellationToken.IsCancellationRequested) + { + // COMM-2: ended by the active-role watchdog. End with Unavailable, NOT a graceful + // OK — central's clients deliberately do not flip nodes on a graceful completion + // (that is the 4h lifetime / clean shutdown path), so only an error status moves + // them to the node that is now active. + throw new RpcException(new GrpcStatus(StatusCode.Unavailable, + "This site node is no longer the active node; reconnect to the other site node")); + } catch (OperationCanceledException) { // Normal cancellation (client disconnect or duplicate replacement) @@ -787,5 +917,16 @@ public class SiteStreamGrpcServer : SiteStreamService.SiteStreamServiceBase /// /// Tracks a single active stream so cleanup only removes its own entry. /// - private sealed record StreamEntry(CancellationTokenSource Cts); + /// + /// A class, not a record: _activeStreams.TryRemove(KeyValuePair) must match by + /// reference, and is mutable. + /// + private sealed class StreamEntry(CancellationTokenSource cts) + { + /// The stream's cancellation source. + public CancellationTokenSource Cts { get; } = cts; + + /// Set by the active-role watchdog before it cancels the stream (COMM-2). + public volatile bool LostActiveRole; + } } diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Configurations/KpiRollupBackfillStateEntityTypeConfiguration.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Configurations/KpiRollupBackfillStateEntityTypeConfiguration.cs new file mode 100644 index 00000000..1eed463b --- /dev/null +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Configurations/KpiRollupBackfillStateEntityTypeConfiguration.cs @@ -0,0 +1,28 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using ZB.MOM.WW.ScadaBridge.Commons.Entities.Kpi; + +namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Configurations; + +/// +/// Maps the single-row to the central +/// KpiRollupBackfillState table — the rollup backfill's own progress marker (KPI-1). +/// +public class KpiRollupBackfillStateEntityTypeConfiguration : IEntityTypeConfiguration +{ + /// + /// Configures the EF Core entity type mapping for . + /// + /// The entity type builder to configure. + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("KpiRollupBackfillState"); + + // A fixed singleton key, never store-generated. + builder.HasKey(s => s.Id); + builder.Property(s => s.Id).ValueGeneratedNever(); + + builder.Property(s => s.BackfilledThroughUtc).IsRequired(); + builder.Property(s => s.UpdatedAtUtc).IsRequired(); + } +} diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Migrations/20261203152501_AddKpiRollupBackfillState.Designer.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Migrations/20261203152501_AddKpiRollupBackfillState.Designer.cs new file mode 100644 index 00000000..eb1a9d36 --- /dev/null +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Migrations/20261203152501_AddKpiRollupBackfillState.Designer.cs @@ -0,0 +1,2330 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase; + +#nullable disable + +namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Migrations +{ + [DbContext(typeof(ScadaBridgeDbContext))] + [Migration("20261203152501_AddKpiRollupBackfillState")] + partial class AddKpiRollupBackfillState + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.13") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("Microsoft.AspNetCore.DataProtection.EntityFrameworkCore.DataProtectionKey", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("FriendlyName") + .HasColumnType("nvarchar(max)"); + + b.Property("Xml") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("DataProtectionKeys"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Audit.AuditLogEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("AfterStateJson") + .HasColumnType("nvarchar(max)"); + + b.Property("BundleImportId") + .HasColumnType("uniqueidentifier"); + + b.Property("EntityId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("EntityName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("EntityType") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("Timestamp") + .HasColumnType("datetimeoffset"); + + b.Property("User") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.HasKey("Id"); + + b.HasIndex("Action"); + + b.HasIndex("BundleImportId") + .HasDatabaseName("IX_AuditLogEntries_BundleImportId"); + + b.HasIndex("EntityId"); + + b.HasIndex("EntityName") + .HasDatabaseName("IX_AuditLogEntries_EntityName"); + + b.HasIndex("EntityType"); + + b.HasIndex("Timestamp"); + + b.HasIndex("User"); + + b.HasIndex("EntityType", "Timestamp") + .IsDescending(false, true) + .HasDatabaseName("IX_AuditLogEntries_EntityType_Timestamp"); + + b.HasIndex("Timestamp", "Id") + .IsDescending() + .HasDatabaseName("IX_AuditLogEntries_Timestamp_Id"); + + b.HasIndex("User", "Timestamp") + .IsDescending(false, true) + .HasDatabaseName("IX_AuditLogEntries_User_Timestamp"); + + b.ToTable("AuditLogEntries"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Audit.SiteCall", b => + { + b.Property("TrackedOperationId") + .HasMaxLength(36) + .IsUnicode(false) + .HasColumnType("varchar(36)"); + + b.Property("Channel") + .IsRequired() + .HasMaxLength(32) + .IsUnicode(false) + .HasColumnType("varchar(32)"); + + b.Property("CreatedAtUtc") + .HasColumnType("datetime2"); + + b.Property("HttpStatus") + .HasColumnType("int"); + + b.Property("IngestedAtUtc") + .HasColumnType("datetime2"); + + b.Property("LastError") + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("RetryCount") + .HasColumnType("int"); + + b.Property("SourceNode") + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)"); + + b.Property("SourceSite") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(32) + .IsUnicode(false) + .HasColumnType("varchar(32)"); + + b.Property("Target") + .IsRequired() + .HasMaxLength(256) + .IsUnicode(false) + .HasColumnType("varchar(256)"); + + b.Property("TerminalAtUtc") + .HasColumnType("datetime2"); + + b.Property("UpdatedAtUtc") + .HasColumnType("datetime2"); + + b.HasKey("TrackedOperationId"); + + b.HasIndex("CreatedAtUtc") + .HasDatabaseName("IX_SiteCalls_NonTerminal") + .HasFilter("[TerminalAtUtc] IS NULL"); + + SqlServerIndexBuilderExtensions.IncludeProperties(b.HasIndex("CreatedAtUtc"), new[] { "SourceSite", "SourceNode", "Status" }); + + b.HasIndex("TerminalAtUtc") + .HasDatabaseName("IX_SiteCalls_Terminal") + .HasFilter("[TerminalAtUtc] IS NOT NULL"); + + b.HasIndex("CreatedAtUtc", "TrackedOperationId") + .IsDescending() + .HasDatabaseName("IX_SiteCalls_Created_TrackedOperationId"); + + b.HasIndex("SourceSite", "CreatedAtUtc") + .IsDescending(false, true) + .HasDatabaseName("IX_SiteCalls_Source_Created"); + + b.HasIndex("Status", "UpdatedAtUtc") + .IsDescending(false, true) + .HasDatabaseName("IX_SiteCalls_Status_Updated"); + + b.ToTable("SiteCalls", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Deployment.DeployedConfigSnapshot", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ConfigurationJson") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("DeployedAt") + .HasColumnType("datetimeoffset"); + + b.Property("DeploymentId") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("InstanceId") + .HasColumnType("int"); + + b.Property("RevisionHash") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.HasKey("Id"); + + b.HasIndex("DeploymentId"); + + b.HasIndex("InstanceId") + .IsUnique(); + + b.HasIndex("RowVersion"); + + b.ToTable("DeployedConfigSnapshots"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Deployment.DeploymentRecord", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("CompletedAt") + .HasColumnType("datetimeoffset"); + + b.Property("DeployedAt") + .HasColumnType("datetimeoffset"); + + b.Property("DeployedBy") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("DeploymentId") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("ErrorMessage") + .HasColumnType("nvarchar(max)"); + + b.Property("InstanceId") + .HasColumnType("int"); + + b.Property("RevisionHash") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.HasKey("Id"); + + b.HasIndex("DeployedBy") + .HasDatabaseName("IX_DeploymentRecords_DeployedBy"); + + b.HasIndex("DeploymentId") + .IsUnique(); + + b.HasIndex("InstanceId"); + + b.HasIndex("RevisionHash") + .HasDatabaseName("IX_DeploymentRecords_RevisionHash"); + + b.HasIndex("DeployedAt", "Id") + .IsDescending() + .HasDatabaseName("IX_DeploymentRecords_DeployedAt_Id"); + + b.ToTable("DeploymentRecords"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Deployment.PendingDeployment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ConfigurationJson") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedAtUtc") + .HasColumnType("datetimeoffset"); + + b.Property("DeploymentId") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("ExpiresAtUtc") + .HasColumnType("datetimeoffset"); + + b.Property("InstanceId") + .HasColumnType("int"); + + b.Property("RevisionHash") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("Token") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Id"); + + b.HasIndex("DeploymentId") + .IsUnique(); + + b.HasIndex("ExpiresAtUtc"); + + b.HasIndex("InstanceId"); + + b.ToTable("PendingDeployments", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Deployment.SystemArtifactDeploymentRecord", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ArtifactType") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("DeployedAt") + .HasColumnType("datetimeoffset"); + + b.Property("DeployedBy") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("PerSiteStatus") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Id"); + + b.HasIndex("DeployedAt"); + + b.ToTable("SystemArtifactDeploymentRecords"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.ExternalSystems.DatabaseConnectionDefinition", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ConnectionString") + .IsRequired() + .HasMaxLength(8000) + .HasColumnType("nvarchar(max)"); + + b.Property("MaxRetries") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("RetryDelay") + .HasColumnType("time"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("RowVersion"); + + b.ToTable("DatabaseConnectionDefinitions"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.ExternalSystems.ExternalSystemDefinition", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AuthConfiguration") + .HasMaxLength(8000) + .HasColumnType("nvarchar(max)"); + + b.Property("AuthType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("EndpointUrl") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("nvarchar(2000)"); + + b.Property("MaxRetries") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("RetryDelay") + .HasColumnType("time"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("TimeoutSeconds") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(0); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("RowVersion"); + + b.ToTable("ExternalSystemDefinitions"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.ExternalSystems.ExternalSystemMethod", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ExternalSystemDefinitionId") + .HasColumnType("int"); + + b.Property("HttpMethod") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("nvarchar(10)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("ParameterDefinitions") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("nvarchar(2000)"); + + b.Property("ReturnDefinition") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.HasKey("Id"); + + b.HasIndex("RowVersion"); + + b.HasIndex("ExternalSystemDefinitionId", "Name") + .IsUnique(); + + b.ToTable("ExternalSystemMethods"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.InboundApi.ApiMethod", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("ParameterDefinitions") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("ReturnDefinition") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Script") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("TimeoutSeconds") + .HasColumnType("int"); + + b.Property("TraceAllCalls") + .ValueGeneratedOnAdd() + .HasColumnType("bit") + .HasDefaultValue(false); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("ApiMethods"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Area", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("ParentAreaId") + .HasColumnType("int"); + + b.Property("SiteId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ParentAreaId"); + + b.HasIndex("SiteId", "ParentAreaId", "Name") + .IsUnique() + .HasFilter("[ParentAreaId] IS NOT NULL"); + + b.ToTable("Areas"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Instance", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AreaId") + .HasColumnType("int"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SiteId") + .HasColumnType("int"); + + b.Property("State") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("TemplateId") + .HasColumnType("int"); + + b.Property("UniqueName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.HasKey("Id"); + + b.HasIndex("AreaId"); + + b.HasIndex("RowVersion"); + + b.HasIndex("SiteId"); + + b.HasIndex("TemplateId"); + + b.HasIndex("UniqueName") + .IsUnique(); + + b.ToTable("Instances"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.InstanceAlarmOverride", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AlarmCanonicalName") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("nvarchar(400)"); + + b.Property("InstanceId") + .HasColumnType("int"); + + b.Property("IsMesReportableOverride") + .HasColumnType("bit"); + + b.Property("PriorityLevelOverride") + .HasColumnType("int"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("TriggerConfigurationOverride") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Id"); + + b.HasIndex("RowVersion"); + + b.HasIndex("InstanceId", "AlarmCanonicalName") + .IsUnique(); + + b.ToTable("InstanceAlarmOverrides"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.InstanceAttributeOverride", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AttributeName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("ElementDataType") + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("InstanceId") + .HasColumnType("int"); + + b.Property("OverrideValue") + .HasColumnType("nvarchar(max)"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.HasKey("Id"); + + b.HasIndex("RowVersion"); + + b.HasIndex("InstanceId", "AttributeName") + .IsUnique(); + + b.ToTable("InstanceAttributeOverrides"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.InstanceConnectionBinding", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AttributeName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("DataConnectionId") + .HasColumnType("int"); + + b.Property("DataSourceReferenceOverride") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("InstanceId") + .HasColumnType("int"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.HasKey("Id"); + + b.HasIndex("DataConnectionId"); + + b.HasIndex("RowVersion"); + + b.HasIndex("InstanceId", "AttributeName") + .IsUnique(); + + b.ToTable("InstanceConnectionBindings"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.InstanceNativeAlarmSourceOverride", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ConditionFilterOverride") + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("ConnectionNameOverride") + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("InstanceId") + .HasColumnType("int"); + + b.Property("IsMesReportableOverride") + .HasColumnType("bit"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SourceCanonicalName") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("nvarchar(400)"); + + b.Property("SourceReferenceOverride") + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.HasKey("Id"); + + b.HasIndex("RowVersion"); + + b.HasIndex("InstanceId", "SourceCanonicalName") + .IsUnique(); + + b.ToTable("InstanceNativeAlarmSourceOverrides"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Kpi.KpiRollupBackfillState", b => + { + b.Property("Id") + .HasColumnType("int"); + + b.Property("BackfilledThroughUtc") + .HasColumnType("datetime2"); + + b.Property("UpdatedAtUtc") + .HasColumnType("datetime2"); + + b.HasKey("Id"); + + b.ToTable("KpiRollupBackfillState", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Kpi.KpiRollupHourly", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("HourStartUtc") + .HasColumnType("datetime2"); + + b.Property("MaxValue") + .HasColumnType("float"); + + b.Property("Metric") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)"); + + b.Property("MinValue") + .HasColumnType("float"); + + b.Property("SampleCount") + .HasColumnType("int"); + + b.Property("Scope") + .IsRequired() + .HasMaxLength(16) + .IsUnicode(false) + .HasColumnType("varchar(16)"); + + b.Property("ScopeKey") + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)"); + + b.Property("Source") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)"); + + b.Property("Value") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.HasIndex("HourStartUtc") + .HasDatabaseName("IX_KpiRollupHourly_Hour"); + + b.HasIndex("Source", "Metric", "Scope", "ScopeKey", "HourStartUtc") + .IsUnique() + .HasDatabaseName("IX_KpiRollupHourly_Series"); + + b.ToTable("KpiRollupHourly", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Kpi.KpiSample", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("CapturedAtUtc") + .HasColumnType("datetime2"); + + b.Property("Metric") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)"); + + b.Property("Scope") + .IsRequired() + .HasMaxLength(16) + .IsUnicode(false) + .HasColumnType("varchar(16)"); + + b.Property("ScopeKey") + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)"); + + b.Property("Source") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)"); + + b.Property("Value") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.HasIndex("CapturedAtUtc") + .HasDatabaseName("IX_KpiSample_Captured"); + + b.HasIndex("Source", "Metric", "Scope", "ScopeKey", "CapturedAtUtc") + .HasDatabaseName("IX_KpiSample_Series"); + + b.ToTable("KpiSample", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Notifications.Notification", b => + { + b.Property("NotificationId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Body") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedAt") + .HasColumnType("datetimeoffset"); + + b.Property("DeliveredAt") + .HasColumnType("datetimeoffset"); + + b.Property("LastAttemptAt") + .HasColumnType("datetimeoffset"); + + b.Property("LastError") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("ListName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("NextAttemptAt") + .HasColumnType("datetimeoffset"); + + b.Property("OriginExecutionId") + .HasColumnType("uniqueidentifier"); + + b.Property("OriginParentExecutionId") + .HasColumnType("uniqueidentifier"); + + b.Property("ResolvedTargets") + .HasColumnType("nvarchar(max)"); + + b.Property("RetryCount") + .HasColumnType("int"); + + b.Property("SiteEnqueuedAt") + .HasColumnType("datetimeoffset"); + + b.Property("SourceInstanceId") + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("SourceNode") + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)"); + + b.Property("SourceScript") + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("SourceSiteId") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Subject") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("TypeData") + .HasColumnType("nvarchar(max)"); + + b.HasKey("NotificationId"); + + b.HasIndex("DeliveredAt") + .HasDatabaseName("IX_Notifications_Delivered") + .HasFilter("[Status] = 'Delivered'"); + + b.HasIndex("CreatedAt", "NotificationId") + .IsDescending() + .HasDatabaseName("IX_Notifications_Created_NotificationId"); + + b.HasIndex("SourceSiteId", "CreatedAt"); + + b.HasIndex("Status", "NextAttemptAt"); + + b.ToTable("Notifications"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Notifications.NotificationList", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("NotificationLists"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Notifications.NotificationRecipient", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("EmailAddress") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("NotificationListId") + .HasColumnType("int"); + + b.Property("PhoneNumber") + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Id"); + + b.HasIndex("NotificationListId"); + + b.ToTable("NotificationRecipients"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Notifications.SmsConfiguration", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AccountSid") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("ApiBaseUrl") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("AuthToken") + .HasMaxLength(8000) + .HasColumnType("nvarchar(max)"); + + b.Property("ConnectionTimeoutSeconds") + .HasColumnType("int"); + + b.Property("FromNumber") + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("MaxRetries") + .HasColumnType("int"); + + b.Property("MessagingServiceSid") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("RetryDelay") + .HasColumnType("time"); + + b.HasKey("Id"); + + b.ToTable("SmsConfigurations"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Notifications.SmtpConfiguration", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AuthType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("ConnectionTimeoutSeconds") + .HasColumnType("int"); + + b.Property("Credentials") + .HasMaxLength(8000) + .HasColumnType("nvarchar(max)"); + + b.Property("FromAddress") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("Host") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("MaxConcurrentConnections") + .HasColumnType("int"); + + b.Property("MaxRetries") + .HasColumnType("int"); + + b.Property("OAuth2Authority") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("OAuth2Scope") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("Port") + .HasColumnType("int"); + + b.Property("RetryDelay") + .HasColumnType("time"); + + b.Property("TlsMode") + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("Transport") + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.HasKey("Id"); + + b.ToTable("SmtpConfigurations"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Schemas.SharedSchema", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("SchemaJson") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Scope") + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SharedSchemas"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Scripts.SharedScript", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Code") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("ParameterDefinitions") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("ReturnDefinition") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("RowVersion"); + + b.ToTable("SharedScripts"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.SecuredWrites.PendingSecuredWrite", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ConnectionName") + .IsRequired() + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("varchar(128)"); + + b.Property("DecidedAtUtc") + .HasColumnType("datetime2"); + + b.Property("ExecutedAtUtc") + .HasColumnType("datetime2"); + + b.Property("ExecutionError") + .HasMaxLength(2048) + .IsUnicode(false) + .HasColumnType("varchar(2048)"); + + b.Property("OperatorComment") + .HasMaxLength(1024) + .IsUnicode(false) + .HasColumnType("varchar(1024)"); + + b.Property("OperatorUser") + .IsRequired() + .HasMaxLength(256) + .IsUnicode(false) + .HasColumnType("varchar(256)"); + + b.Property("SiteId") + .IsRequired() + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("varchar(128)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(32) + .IsUnicode(false) + .HasColumnType("varchar(32)"); + + b.Property("SubmittedAtUtc") + .HasColumnType("datetime2"); + + b.Property("TagPath") + .IsRequired() + .HasMaxLength(512) + .IsUnicode(false) + .HasColumnType("varchar(512)"); + + b.Property("ValueJson") + .IsRequired() + .HasMaxLength(4000) + .IsUnicode(false) + .HasColumnType("varchar(4000)"); + + b.Property("ValueType") + .IsRequired() + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("varchar(128)"); + + b.Property("VerifierComment") + .HasMaxLength(1024) + .IsUnicode(false) + .HasColumnType("varchar(1024)"); + + b.Property("VerifierUser") + .HasMaxLength(256) + .IsUnicode(false) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("SiteId") + .HasDatabaseName("IX_PendingSecuredWrites_Site"); + + b.HasIndex("Status", "SubmittedAtUtc") + .HasDatabaseName("IX_PendingSecuredWrites_Status_Submitted"); + + b.ToTable("PendingSecuredWrites", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Security.LdapGroupMapping", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("LdapGroupName") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.HasKey("Id"); + + b.HasIndex("LdapGroupName") + .IsUnique(); + + b.ToTable("LdapGroupMappings"); + + b.HasData( + new + { + Id = 1, + LdapGroupName = "SCADA-Admins", + Role = "Administrator" + }, + new + { + Id = 2, + LdapGroupName = "SCADA-Designers", + Role = "Designer" + }, + new + { + Id = 3, + LdapGroupName = "SCADA-Deploy-All", + Role = "Deployer" + }, + new + { + Id = 4, + LdapGroupName = "SCADA-Deploy-SiteA", + Role = "Deployer" + }, + new + { + Id = 5, + LdapGroupName = "SCADA-Viewers", + Role = "Viewer" + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Security.SiteScopeRule", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("LdapGroupMappingId") + .HasColumnType("int"); + + b.Property("SiteId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("SiteId"); + + b.HasIndex("LdapGroupMappingId", "SiteId") + .IsUnique(); + + b.ToTable("SiteScopeRules"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites.DataConnection", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("BackupConfiguration") + .HasColumnType("nvarchar(max)"); + + b.Property("FailoverRetryCount") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(3); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("PrimaryConfiguration") + .HasColumnType("nvarchar(max)"); + + b.Property("Protocol") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SiteId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("RowVersion"); + + b.HasIndex("SiteId", "Name") + .IsUnique(); + + b.ToTable("DataConnections"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites.Site", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ArtifactRevisionHash") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("ArtifactsDeployedAt") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("nvarchar(2000)"); + + b.Property("GrpcNodeAAddress") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("GrpcNodeBAddress") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("NodeAAddress") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("NodeBAddress") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SiteIdentifier") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("RowVersion"); + + b.HasIndex("SiteIdentifier") + .IsUnique(); + + b.ToTable("Sites"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.Template", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("nvarchar(2000)"); + + b.Property("FolderId") + .HasColumnType("int"); + + b.Property("IsDerived") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("OwnerCompositionId") + .HasColumnType("int"); + + b.Property("ParentTemplateId") + .HasColumnType("int"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.HasKey("Id"); + + b.HasIndex("FolderId"); + + b.HasIndex("Name") + .IsUnique() + .HasFilter("[IsDerived] = 0"); + + b.HasIndex("ParentTemplateId"); + + b.HasIndex("RowVersion"); + + b.ToTable("Templates"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateAlarm", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("nvarchar(2000)"); + + b.Property("IsInherited") + .HasColumnType("bit"); + + b.Property("IsLocked") + .HasColumnType("bit"); + + b.Property("IsMesReportable") + .HasColumnType("bit"); + + b.Property("LockedInDerived") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("OnTriggerScriptId") + .HasColumnType("int"); + + b.Property("PriorityLevel") + .HasColumnType("int"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("TemplateId") + .HasColumnType("int"); + + b.Property("TriggerConfiguration") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("TriggerType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.HasKey("Id"); + + b.HasIndex("RowVersion"); + + b.HasIndex("TemplateId", "Name") + .IsUnique(); + + b.ToTable("TemplateAlarms"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateAttribute", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("DataSourceReference") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("DataType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("nvarchar(2000)"); + + b.Property("ElementDataType") + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("IsInherited") + .HasColumnType("bit"); + + b.Property("IsLocked") + .HasColumnType("bit"); + + b.Property("LockedInDerived") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("TemplateId") + .HasColumnType("int"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.HasIndex("RowVersion"); + + b.HasIndex("TemplateId", "Name") + .IsUnique(); + + b.ToTable("TemplateAttributes"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateComposition", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComposedTemplateId") + .HasColumnType("int"); + + b.Property("InstanceName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("TemplateId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ComposedTemplateId"); + + b.HasIndex("RowVersion"); + + b.HasIndex("TemplateId", "InstanceName") + .IsUnique(); + + b.ToTable("TemplateCompositions"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateFolder", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("ParentFolderId") + .HasColumnType("int"); + + b.Property("SortOrder") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ParentFolderId", "Name") + .IsUnique() + .HasFilter("[ParentFolderId] IS NOT NULL"); + + b.ToTable("TemplateFolders"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateNativeAlarmSource", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ConditionFilter") + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("ConnectionName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("nvarchar(2000)"); + + b.Property("IsInherited") + .HasColumnType("bit"); + + b.Property("IsLocked") + .HasColumnType("bit"); + + b.Property("IsMesReportable") + .HasColumnType("bit"); + + b.Property("LockedInDerived") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SourceReference") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("TemplateId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("RowVersion"); + + b.HasIndex("TemplateId", "Name") + .IsUnique(); + + b.ToTable("TemplateNativeAlarmSources"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateScript", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Code") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ExecutionTimeoutSeconds") + .HasColumnType("int"); + + b.Property("IsInherited") + .HasColumnType("bit"); + + b.Property("IsLocked") + .HasColumnType("bit"); + + b.Property("LockedInDerived") + .HasColumnType("bit"); + + b.Property("MinTimeBetweenRuns") + .HasColumnType("time"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("ParameterDefinitions") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("ReturnDefinition") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("TemplateId") + .HasColumnType("int"); + + b.Property("TriggerConfiguration") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("TriggerType") + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.HasKey("Id"); + + b.HasIndex("RowVersion"); + + b.HasIndex("TemplateId", "Name") + .IsUnique(); + + b.ToTable("TemplateScripts"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Transport.BundleUnlockAttempt", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AttemptedAtUtc") + .HasColumnType("datetime2"); + + b.Property("ClientKey") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)"); + + b.HasKey("Id"); + + b.HasIndex("ClientKey", "AttemptedAtUtc") + .HasDatabaseName("IX_BundleUnlockAttempt_Client_Attempted"); + + b.ToTable("BundleUnlockAttempt", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Entities.AuditLogRow", b => + { + b.Property("OccurredAtUtc") + .HasColumnType("datetime2"); + + b.Property("EventId") + .HasColumnType("uniqueidentifier"); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Channel") + .IsRequired() + .HasMaxLength(32) + .IsUnicode(false) + .HasColumnType("varchar(32)") + .HasColumnName("Category"); + + b.Property("CorrelationId") + .HasColumnType("uniqueidentifier"); + + b.Property("DetailsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("ExecutionId") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("uniqueidentifier") + .HasComputedColumnSql("CAST(JSON_VALUE(DetailsJson,'$.executionId') AS uniqueidentifier)", true); + + b.Property("IngestedAtUtc") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime2(7)") + .HasComputedColumnSql("CAST(SWITCHOFFSET(CAST(JSON_VALUE(DetailsJson,'$.ingestedAtUtc') AS datetimeoffset), 0) AS datetime2(7))", false); + + b.Property("Kind") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasMaxLength(32) + .IsUnicode(false) + .HasColumnType("varchar(32)") + .HasComputedColumnSql("JSON_VALUE(DetailsJson,'$.kind')", true); + + b.Property("Outcome") + .IsRequired() + .HasMaxLength(16) + .IsUnicode(false) + .HasColumnType("varchar(16)"); + + b.Property("ParentExecutionId") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("uniqueidentifier") + .HasComputedColumnSql("CAST(JSON_VALUE(DetailsJson,'$.parentExecutionId') AS uniqueidentifier)", true); + + b.Property("SourceNode") + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)"); + + b.Property("SourceSiteId") + .ValueGeneratedOnAddOrUpdate() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)") + .HasComputedColumnSql("JSON_VALUE(DetailsJson,'$.sourceSiteId')", true); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasMaxLength(32) + .IsUnicode(false) + .HasColumnType("varchar(32)") + .HasComputedColumnSql("JSON_VALUE(DetailsJson,'$.status')", true); + + b.Property("Target") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("OccurredAtUtc", "EventId"); + + b.HasIndex("CorrelationId") + .HasDatabaseName("IX_AuditLog_CorrelationId") + .HasFilter("[CorrelationId] IS NOT NULL"); + + b.HasIndex("ExecutionId") + .HasDatabaseName("IX_AuditLog_Execution"); + + b.HasIndex("OccurredAtUtc") + .IsDescending() + .HasDatabaseName("IX_AuditLog_OccurredAtUtc"); + + SqlServerIndexBuilderExtensions.IncludeProperties(b.HasIndex("OccurredAtUtc"), new[] { "Status" }); + + b.HasIndex("ParentExecutionId") + .HasDatabaseName("IX_AuditLog_ParentExecution"); + + b.HasIndex("Actor", "OccurredAtUtc") + .IsDescending(false, true) + .HasDatabaseName("IX_AuditLog_Actor_Occurred"); + + b.HasIndex("EventId", "OccurredAtUtc") + .IsUnique() + .HasDatabaseName("UX_AuditLog_EventId_Occurred"); + + b.HasIndex("Kind", "OccurredAtUtc") + .IsDescending(false, true) + .HasDatabaseName("IX_AuditLog_Kind_Occurred"); + + b.HasIndex("SourceNode", "OccurredAtUtc") + .HasDatabaseName("IX_AuditLog_Node_Occurred"); + + b.HasIndex("SourceSiteId", "OccurredAtUtc") + .IsDescending(false, true) + .HasDatabaseName("IX_AuditLog_Site_Occurred"); + + b.HasIndex("Target", "OccurredAtUtc") + .IsDescending(false, true) + .HasDatabaseName("IX_AuditLog_Target_Occurred") + .HasFilter("[Target] IS NOT NULL"); + + b.HasIndex("Channel", "Status", "OccurredAtUtc") + .IsDescending(false, false, true) + .HasDatabaseName("IX_AuditLog_Channel_Status_Occurred"); + + b.ToTable("AuditLog", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Deployment.DeployedConfigSnapshot", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Instance", null) + .WithMany() + .HasForeignKey("InstanceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Deployment.DeploymentRecord", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Instance", null) + .WithMany() + .HasForeignKey("InstanceId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Deployment.PendingDeployment", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Instance", null) + .WithMany() + .HasForeignKey("InstanceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.ExternalSystems.ExternalSystemMethod", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.ExternalSystems.ExternalSystemDefinition", null) + .WithMany() + .HasForeignKey("ExternalSystemDefinitionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Area", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Area", null) + .WithMany("Children") + .HasForeignKey("ParentAreaId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites.Site", null) + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Instance", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Area", null) + .WithMany() + .HasForeignKey("AreaId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites.Site", null) + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.Template", null) + .WithMany() + .HasForeignKey("TemplateId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.InstanceAlarmOverride", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Instance", null) + .WithMany("AlarmOverrides") + .HasForeignKey("InstanceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.InstanceAttributeOverride", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Instance", null) + .WithMany("AttributeOverrides") + .HasForeignKey("InstanceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.InstanceConnectionBinding", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites.DataConnection", null) + .WithMany() + .HasForeignKey("DataConnectionId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Instance", null) + .WithMany("ConnectionBindings") + .HasForeignKey("InstanceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.InstanceNativeAlarmSourceOverride", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Instance", null) + .WithMany("NativeAlarmSourceOverrides") + .HasForeignKey("InstanceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Notifications.NotificationRecipient", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Notifications.NotificationList", null) + .WithMany("Recipients") + .HasForeignKey("NotificationListId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Security.SiteScopeRule", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Security.LdapGroupMapping", null) + .WithMany() + .HasForeignKey("LdapGroupMappingId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites.Site", null) + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites.DataConnection", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites.Site", null) + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.Template", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateFolder", null) + .WithMany() + .HasForeignKey("FolderId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.Template", null) + .WithMany() + .HasForeignKey("ParentTemplateId") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateAlarm", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.Template", null) + .WithMany("Alarms") + .HasForeignKey("TemplateId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateAttribute", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.Template", null) + .WithMany("Attributes") + .HasForeignKey("TemplateId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateComposition", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.Template", null) + .WithMany() + .HasForeignKey("ComposedTemplateId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.Template", null) + .WithMany("Compositions") + .HasForeignKey("TemplateId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateFolder", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateFolder", null) + .WithMany() + .HasForeignKey("ParentFolderId") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateNativeAlarmSource", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.Template", null) + .WithMany("NativeAlarmSources") + .HasForeignKey("TemplateId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateScript", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.Template", null) + .WithMany("Scripts") + .HasForeignKey("TemplateId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Area", b => + { + b.Navigation("Children"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Instance", b => + { + b.Navigation("AlarmOverrides"); + + b.Navigation("AttributeOverrides"); + + b.Navigation("ConnectionBindings"); + + b.Navigation("NativeAlarmSourceOverrides"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Notifications.NotificationList", b => + { + b.Navigation("Recipients"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.Template", b => + { + b.Navigation("Alarms"); + + b.Navigation("Attributes"); + + b.Navigation("Compositions"); + + b.Navigation("NativeAlarmSources"); + + b.Navigation("Scripts"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Migrations/20261203152501_AddKpiRollupBackfillState.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Migrations/20261203152501_AddKpiRollupBackfillState.cs new file mode 100644 index 00000000..d039b290 --- /dev/null +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Migrations/20261203152501_AddKpiRollupBackfillState.cs @@ -0,0 +1,35 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Migrations +{ + /// + public partial class AddKpiRollupBackfillState : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "KpiRollupBackfillState", + columns: table => new + { + Id = table.Column(type: "int", nullable: false), + BackfilledThroughUtc = table.Column(type: "datetime2", nullable: false), + UpdatedAtUtc = table.Column(type: "datetime2", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_KpiRollupBackfillState", x => x.Id); + }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "KpiRollupBackfillState"); + } + } +} diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Migrations/ScadaBridgeDbContextModelSnapshot.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Migrations/ScadaBridgeDbContextModelSnapshot.cs index eef72f42..7283f246 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Migrations/ScadaBridgeDbContextModelSnapshot.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Migrations/ScadaBridgeDbContextModelSnapshot.cs @@ -815,6 +815,22 @@ namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Migrations b.ToTable("InstanceNativeAlarmSourceOverrides"); }); + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Kpi.KpiRollupBackfillState", b => + { + b.Property("Id") + .HasColumnType("int"); + + b.Property("BackfilledThroughUtc") + .HasColumnType("datetime2"); + + b.Property("UpdatedAtUtc") + .HasColumnType("datetime2"); + + b.HasKey("Id"); + + b.ToTable("KpiRollupBackfillState", (string)null); + }); + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Kpi.KpiRollupHourly", b => { b.Property("Id") diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/AuditLogRepository.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/AuditLogRepository.cs index 1c6daddc..c91c6939 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/AuditLogRepository.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/AuditLogRepository.cs @@ -827,7 +827,23 @@ VALUES ) x WHERE x.MaxOccurredAt IS NOT NULL AND x.MaxOccurredAt < CAST('{thresholdStr}' AS datetime2(7)) - ORDER BY b.BoundaryValue;"; + UNION ALL + -- AUD-6: partition 1 (everything before the FIRST boundary — back-dated rows from a + -- site whose clock was reset, or test rows) has no boundary of its own, so the + -- per-boundary enumeration above never offered it and its rows outlived retention + -- and the cold archive forever. It is identified by a stand-in value inside it: the + -- month start of its newest row (always below the first boundary, so + -- $partition.pf_AuditLog_Month maps it to partition 1 for the switch-out and the + -- archive, and it labels the archive by the age of the data). + SELECT CAST(DATEFROMPARTS(YEAR(p1.MaxOccurredAt), MONTH(p1.MaxOccurredAt), 1) AS datetime2(7)) + FROM ( + SELECT MAX(a.OccurredAtUtc) AS MaxOccurredAt + FROM dbo.AuditLog a + WHERE $PARTITION.pf_AuditLog_Month(a.OccurredAtUtc) = 1 + ) p1 + WHERE p1.MaxOccurredAt IS NOT NULL + AND p1.MaxOccurredAt < CAST('{thresholdStr}' AS datetime2(7)) + ORDER BY 1;"; var conn = _context.Database.GetDbConnection(); var openedHere = false; diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/KpiHistoryRepository.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/KpiHistoryRepository.cs index a0692df4..0521e9b2 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/KpiHistoryRepository.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/KpiHistoryRepository.cs @@ -293,6 +293,68 @@ public sealed class KpiHistoryRepository : IKpiHistoryRepository .MaxAsync(r => (DateTime?)r.HourStartUtc, cancellationToken); } + /// + public async Task GetRollupBackfillWatermarkAsync(CancellationToken cancellationToken = default) + { + return await _context.KpiRollupBackfillState + .AsNoTracking() + .Where(s => s.Id == KpiRollupBackfillState.SingletonId) + .Select(s => (DateTime?)s.BackfilledThroughUtc) + .FirstOrDefaultAsync(cancellationToken); + } + + /// + public async Task AdvanceRollupBackfillWatermarkAsync( + DateTime backfilledThroughUtc, DateTime? onlyIfReachedUtc = null, CancellationToken cancellationToken = default) + { + var now = DateTime.UtcNow; + var reached = onlyIfReachedUtc ?? DateTime.MinValue; + // Monotonic (only ever moves forward) and, when asked, contiguous (only when the marker + // already reaches the folded window). One statement, so a concurrent writer (a failover + // overlap) cannot move it back. + var moved = await _context.KpiRollupBackfillState + .Where(s => s.Id == KpiRollupBackfillState.SingletonId + && s.BackfilledThroughUtc < backfilledThroughUtc + && s.BackfilledThroughUtc >= reached) + .ExecuteUpdateAsync(set => set + .SetProperty(s => s.BackfilledThroughUtc, backfilledThroughUtc) + .SetProperty(s => s.UpdatedAtUtc, now), cancellationToken); + if (moved > 0 || onlyIfReachedUtc is not null) + { + // A contiguity-guarded advance never creates the marker: only the backfill does. + return; + } + + var exists = await _context.KpiRollupBackfillState + .AnyAsync(s => s.Id == KpiRollupBackfillState.SingletonId, cancellationToken); + if (exists) + { + return; // already at or past this boundary + } + + _context.KpiRollupBackfillState.Add(new KpiRollupBackfillState + { + Id = KpiRollupBackfillState.SingletonId, + BackfilledThroughUtc = backfilledThroughUtc, + UpdatedAtUtc = now, + }); + try + { + await _context.SaveChangesAsync(cancellationToken); + } + catch (DbUpdateException) + { + // Lost a first-insert race — the winner's row stands; re-apply the monotonic update. + _context.ChangeTracker.Clear(); + await _context.KpiRollupBackfillState + .Where(s => s.Id == KpiRollupBackfillState.SingletonId + && s.BackfilledThroughUtc < backfilledThroughUtc) + .ExecuteUpdateAsync(set => set + .SetProperty(s => s.BackfilledThroughUtc, backfilledThroughUtc) + .SetProperty(s => s.UpdatedAtUtc, now), cancellationToken); + } + } + /// public async Task PurgeRollupsOlderThanAsync(DateTime before, CancellationToken cancellationToken = default) { diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/SiteCallAuditRepository.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/SiteCallAuditRepository.cs index d4065b3b..80cefb2b 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/SiteCallAuditRepository.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/SiteCallAuditRepository.cs @@ -27,6 +27,9 @@ public class SiteCallAuditRepository : ISiteCallAuditRepository // Monotonic status ordering: // Submitted < Forwarded < Attempted == Skipped < Delivered == Failed == Parked == Discarded. + // One deliberate exception (SCA-1, 2026-12): Parked is re-openable — a STRICTLY NEWER + // Attempted / Delivered / Failed / Discarded replaces a Parked row (operator Retry or + // Discard at the site); see the last clause of MonotonicUpdateSql. // A higher incoming rank always wins. WITHIN an equal NON-terminal rank // (Attempted/Skipped, rank 2 — and the transient Submitted/Forwarded ranks), // the newest UpdatedAtUtc wins so a retrying call's live RetryCount/LastError @@ -324,6 +327,14 @@ WHERE TrackedOperationId = @Id ELSE -1 END) AND @Rank < @TerminalRank + AND UpdatedAtUtc < @UpdatedAtUtc ) + -- SCA-1: Parked is re-openable. An operator Retry re-queues a parked call at the + -- site (Attempted, then the retried outcome) and a Discard closes it (Discarded); + -- both reach central as NEWER packets. Accept them over Parked only — Delivered, + -- Failed and Discarded stay immutable — and only when strictly newer, so a stale + -- pre-park packet replayed late can never reopen the row. + OR ( Status = 'Parked' + AND @Status IN ('Attempted', 'Delivered', 'Failed', 'Discarded') AND UpdatedAtUtc < @UpdatedAtUtc ) );"; /// diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/ScadaBridgeDbContext.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/ScadaBridgeDbContext.cs index 0d1bf49d..fc020b1c 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/ScadaBridgeDbContext.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/ScadaBridgeDbContext.cs @@ -153,6 +153,9 @@ public class ScadaBridgeDbContext : DbContext, IDataProtectionKeyContext /// Gets the set of hourly KPI rollups (pre-aggregated long-range trend backbone). public DbSet KpiRollupHourly => Set(); + /// Gets the single-row KPI rollup backfill progress marker (KPI-1). + public DbSet KpiRollupBackfillState => Set(); + // Transport (bundle export/import) /// Gets the set of recorded bundle-unlock attempts — the fleet-wide sliding window behind the per-client unlock throttle (register row 52). public DbSet BundleUnlockAttempts => Set(); diff --git a/src/ZB.MOM.WW.ScadaBridge.DelmiaNotifier/ConnectPhase.cs b/src/ZB.MOM.WW.ScadaBridge.DelmiaNotifier/ConnectPhase.cs new file mode 100644 index 00000000..d5ce0ec8 --- /dev/null +++ b/src/ZB.MOM.WW.ScadaBridge.DelmiaNotifier/ConnectPhase.cs @@ -0,0 +1,84 @@ +using System.Net.Http; +using System.Net.Sockets; + +namespace ZB.MOM.WW.ScadaBridge.DelmiaNotifier; + +/// +/// Makes "the request was never sent" observable (DLM-1). The handler built here owns the TCP +/// connect through and wraps every connect +/// failure — refusal, DNS, an unreachable/black-holed host, the +/// firing — in , which keeps in the +/// exception chain it surfaces. A failure carrying the marker happened before any byte of the request +/// was written, so trying the next base URL is safe. Anything without it (a reset or timeout after the +/// connection was up) may have reached the server and stays OUTCOME_UNKNOWN. +/// +internal static class ConnectPhase +{ + /// + /// Default TCP connect timeout. Well below the notifier's overall request timeout, so a powered-off + /// node fails as a connect failure (and the next URL is tried) instead of eating the whole budget. + /// + public static readonly TimeSpan DefaultConnectTimeout = TimeSpan.FromSeconds(5); + + /// + /// The connect timeout for a given overall request timeout: , + /// but never more than half the overall budget, so it always fires first on a black-holed host. + /// + /// The overall request timeout. + /// The connect timeout to use. + public static TimeSpan ConnectTimeoutFor(TimeSpan overall) + { + var half = overall / 2; + return half < DefaultConnectTimeout ? half : DefaultConnectTimeout; + } + + /// Creates a handler whose connect failures carry . + /// The TCP connect timeout. + /// The configured handler. + public static SocketsHttpHandler CreateHandler(TimeSpan connectTimeout) => new() + { + ConnectTimeout = connectTimeout, + ConnectCallback = async (context, ct) => + { + var socket = new Socket(SocketType.Stream, ProtocolType.Tcp) { NoDelay = true }; + try + { + await socket.ConnectAsync(context.DnsEndPoint, ct).ConfigureAwait(false); + return new NetworkStream(socket, ownsSocket: true); + } + catch (Exception ex) + { + socket.Dispose(); + throw new ConnectPhaseException( + $"could not connect to {context.DnsEndPoint.Host}:{context.DnsEndPoint.Port}: {ex.Message}", ex); + } + }, + }; + + /// + /// True when provably failed before the request was sent: the connect + /// marker is in its chain, or (handlers built without the marker) DNS failed or the connection + /// was refused. + /// + /// The failure from HttpClient.SendAsync. + /// true when the request was never sent. + public static bool WasNotSent(Exception error) + { + for (var e = error; e is not null; e = e.InnerException) + { + if (e is ConnectPhaseException) + return true; + if (e is HttpRequestException { HttpRequestError: HttpRequestError.NameResolutionError }) + return true; + if (e is HttpRequestException { InnerException: SocketException { SocketErrorCode: SocketError.ConnectionRefused } }) + return true; + } + + return false; + } +} + +/// Marks a failure that happened while opening the TCP connection — nothing was sent. +/// The failure description. +/// The underlying connect failure. +internal sealed class ConnectPhaseException(string message, Exception inner) : Exception(message, inner); diff --git a/src/ZB.MOM.WW.ScadaBridge.DelmiaNotifier/HttpRecipeSender.cs b/src/ZB.MOM.WW.ScadaBridge.DelmiaNotifier/HttpRecipeSender.cs index cc756f3d..4ec786c8 100644 --- a/src/ZB.MOM.WW.ScadaBridge.DelmiaNotifier/HttpRecipeSender.cs +++ b/src/ZB.MOM.WW.ScadaBridge.DelmiaNotifier/HttpRecipeSender.cs @@ -6,9 +6,10 @@ namespace ZB.MOM.WW.ScadaBridge.DelmiaNotifier; /// /// over a real : POSTs the recipe payload to /// {baseUrl}/api/DelmiaRecipeDownload with the X-API-Key header. A reachable server -/// response is final except for the explicit pre-execution standby marker. Only proven -/// connection refusal/name resolution failures permit another URL; timeouts and other -/// transport failures have an uncertain application outcome. +/// response is final except for the explicit pre-execution standby marker. Only a proven +/// connect-phase failure (refused, name resolution, unreachable host, connect timeout — see +/// ) permits another URL; timeouts and other transport failures after +/// the connection was up have an uncertain application outcome. /// internal sealed class HttpRecipeSender(HttpClient http, string apiKey) : IRecipeSender { @@ -41,12 +42,18 @@ internal sealed class HttpRecipeSender(HttpClient http, string apiKey) : IRecipe } catch (HttpRequestException ex) { - var knownNotSent = ex.HttpRequestError == HttpRequestError.NameResolutionError - || ex.InnerException is System.Net.Sockets.SocketException { SocketErrorCode: System.Net.Sockets.SocketError.ConnectionRefused }; + // DLM-1: any connect-phase failure (refused, DNS, unreachable/black-holed host) is + // "not sent", so the next URL is tried; a failure after the send stays unknown. + var knownNotSent = ConnectPhase.WasNotSent(ex); return new AttemptOutcome(knownNotSent ? AttemptKind.ConnectFailed : AttemptKind.OutcomeUnknown, 0, null, ex.Message); } catch (OperationCanceledException ex) when (!ct.IsCancellationRequested) { + // The handler's ConnectTimeout firing on a powered-off node surfaces as a + // cancellation carrying the connect marker: nothing was sent (DLM-1). + if (ConnectPhase.WasNotSent(ex)) + return new AttemptOutcome(AttemptKind.ConnectFailed, 0, null, "connect timeout: " + ex.Message); + // A missing response does not prove the node failed to apply the request. return new AttemptOutcome(AttemptKind.OutcomeUnknown, 0, null, "timeout: " + ex.Message); } diff --git a/src/ZB.MOM.WW.ScadaBridge.DelmiaNotifier/Program.cs b/src/ZB.MOM.WW.ScadaBridge.DelmiaNotifier/Program.cs index 6db080d5..8c752d60 100644 --- a/src/ZB.MOM.WW.ScadaBridge.DelmiaNotifier/Program.cs +++ b/src/ZB.MOM.WW.ScadaBridge.DelmiaNotifier/Program.cs @@ -51,7 +51,13 @@ internal static class Program log.Write("api key source: " + apiKeySource); - using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(cfg.ScadaBridge.TimeoutSeconds) }; + // DLM-1: a connect-timeout-bounded handler that marks connect-phase failures, so a + // powered-off node fails over to the next URL instead of reporting OUTCOME_UNKNOWN. + var overall = TimeSpan.FromSeconds(cfg.ScadaBridge.TimeoutSeconds); + // Strictly inside the overall timeout, so the connect timeout (which keeps the marker) + // always fires before HttpClient.Timeout (which does not) on an unanswered SYN. + var connectTimeout = ConnectPhase.ConnectTimeoutFor(overall); + using var http = new HttpClient(ConnectPhase.CreateHandler(connectTimeout)) { Timeout = overall }; var sender = new LoggingRecipeSender(new HttpRecipeSender(http, apiKey), log); log.Write($"notifying {baseUrls.Length} URL(s) for machine {parse.Payload!.MachineCode}"); diff --git a/src/ZB.MOM.WW.ScadaBridge.DelmiaNotifier/README.md b/src/ZB.MOM.WW.ScadaBridge.DelmiaNotifier/README.md index 86dcfb4c..1d422b79 100644 --- a/src/ZB.MOM.WW.ScadaBridge.DelmiaNotifier/README.md +++ b/src/ZB.MOM.WW.ScadaBridge.DelmiaNotifier/README.md @@ -54,9 +54,14 @@ WWNotifier.exe -m Z28061 -d "C:\recipes\job.nc" -w WO12345 -p PN-7788 -s 0100 -u ## Delivery semantics -The notifier retries only when a request is known not to have executed: connection refusal, -name-resolution failure, or the server's explicit standby rejection. A connection reset after -sending or a response timeout returns `OUTCOME_UNKNOWN` without replay. Operators must verify +The notifier retries only when a request is known not to have executed: any failure to open the +TCP connection (refusal, name resolution, an unreachable or powered-off host, or the connect +timeout — `min(5 s, TimeoutSeconds / 2)` — firing on an unanswered SYN), or the server's explicit +standby rejection. A connection reset after sending or a response timeout returns `OUTCOME_UNKNOWN` +without replay. (DLM-1, 2026-12: before, a powered-off first node waited out the whole timeout and +reported `OUTCOME_UNKNOWN` without ever trying the healthy second node; the client now owns the +connect through `SocketsHttpHandler.ConnectCallback` and marks every connect-phase failure, so the +"not sent" case is provable.) Operators must verify an uncertain result before manually retrying. Idempotent method implementations remain useful because callers can deliberately retry, but the notifier does not blindly repeat ambiguous sends. @@ -76,8 +81,8 @@ Placed next to the exe (copied to the output on build/publish): ``` - **`BaseUrls`** — comma-separated failover list of **base URLs only**; the app appends - `/api/DelmiaRecipeDownload`. URLs are tried in order after proven DNS/connection refusal or - explicit standby rejection. Other HTTP responses are final; ambiguous transport errors return + `/api/DelmiaRecipeDownload`. URLs are tried in order after a proven connect-phase failure + (refused, DNS, unreachable host, connect timeout) or explicit standby rejection. Other HTTP responses are final; ambiguous transport errors return `NO` + `OUTCOME_UNKNOWN` without trying another URL. - **`TimeoutSeconds`** — per-attempt HTTP timeout (default `30`). - **`LogPath`** — optional diagnostic log file, relative to the exe. Omit to log to stderr only. @@ -155,6 +160,6 @@ bash docker/verify-delmia-notifier.sh # runs the managed build from a scratc ### Safe failover -The notifier advances to the next configured URL after a proven connection refusal/name-resolution failure, or HTTP 503 carrying the server's exact `X-ScadaBridge-Standby: 1` pre-execution marker. A generic 503 or business rejection is final. Both centrals may therefore be listed even when their internal standby-forwarding peer lists are absent. +The notifier advances to the next configured URL after a proven connect-phase failure (refusal, name resolution, unreachable host, connect timeout), or HTTP 503 carrying the server's exact `X-ScadaBridge-Standby: 1` pre-execution marker. A generic 503 or business rejection is final. Both centrals may therefore be listed even when their internal standby-forwarding peer lists are absent. A timeout or other response loss is reported as `OUTCOME_UNKNOWN` with a failed result and no automatic replay: the first node may already have applied the download. Verify the operation before manually retrying. Configure trusted central endpoints; the standby marker is a server protocol contract, not permission to retry arbitrary HTTP errors. diff --git a/src/ZB.MOM.WW.ScadaBridge.ExternalSystemGateway/ExternalSystemClient.cs b/src/ZB.MOM.WW.ScadaBridge.ExternalSystemGateway/ExternalSystemClient.cs index 357b628a..c6f9a8e2 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ExternalSystemGateway/ExternalSystemClient.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ExternalSystemGateway/ExternalSystemClient.cs @@ -396,6 +396,22 @@ public class ExternalSystemClient : IExternalSystemClient throw ErrorClassifier.AsTransient( $"Timeout reading response from {system.Name} after {effectiveTimeout.TotalSeconds:0.##}s", ex); } + catch (Exception ex) when (ex is IOException or HttpRequestException) + { + // ESG-1: headers arrived, then the connection was reset or the body truncated + // (IOException / HttpIOException / HttpRequestException from the stream read). + // Nothing classified it, so a raw IOException escaped into the script and a + // CachedCall buffered nothing. A success or transient status is a transient + // failure — the call never completed. A permanent status stays permanent: + // losing its error body does not make it retryable. + if (response.IsSuccessStatusCode || ErrorClassifier.IsTransient(response.StatusCode)) + { + throw ErrorClassifier.AsTransient( + $"Connection lost reading the response from {system.Name}: {ex.Message}", ex); + } + + body = $"(response body unreadable: {ex.Message})"; + } if (response.IsSuccessStatusCode) { diff --git a/src/ZB.MOM.WW.ScadaBridge.HealthMonitoring/CentralHealthAggregator.cs b/src/ZB.MOM.WW.ScadaBridge.HealthMonitoring/CentralHealthAggregator.cs index 765d558c..a9b113a2 100644 --- a/src/ZB.MOM.WW.ScadaBridge.HealthMonitoring/CentralHealthAggregator.cs +++ b/src/ZB.MOM.WW.ScadaBridge.HealthMonitoring/CentralHealthAggregator.cs @@ -34,7 +34,7 @@ public class CentralHealthAggregator : BackgroundService, ICentralHealthAggregat } /// - public void ProcessReport(SiteHealthReport report) + public bool ProcessReport(SiteHealthReport report) { var now = _timeProvider.GetUtcNow(); @@ -60,7 +60,7 @@ public class CentralHealthAggregator : BackgroundService, ICentralHealthAggregat { _logger.LogInformation( "Site {SiteId} registered with sequence #{Seq}", report.SiteId, report.SequenceNumber); - return; + return true; } // Lost the race — another thread registered first; retry as an update. @@ -72,7 +72,7 @@ public class CentralHealthAggregator : BackgroundService, ICentralHealthAggregat _logger.LogDebug( "Rejecting stale report from site {SiteId}: seq {Incoming} <= {Last}", report.SiteId, report.SequenceNumber, existing.LastSequenceNumber); - return; + return false; } var updated = existing with @@ -98,7 +98,7 @@ public class CentralHealthAggregator : BackgroundService, ICentralHealthAggregat _logger.LogInformation( "Site {SiteId} is back online (seq #{Seq})", report.SiteId, report.SequenceNumber); } - return; + return true; } // CAS lost — the entry changed under us; retry with the fresh value. @@ -108,6 +108,14 @@ public class CentralHealthAggregator : BackgroundService, ICentralHealthAggregat /// public void MarkHeartbeat(string siteId, DateTimeOffset receivedAt) { + // Never let a heartbeat stamp land in central's future (COMM-4): the offline check + // measures `now - LastHeartbeatAt` on central's clock, so a future stamp silently + // extends the offline timeout by the skew. Callers pass central's receive time; this + // clamp keeps a skewed caller from reintroducing the drift. + var clampNow = _timeProvider.GetUtcNow(); + if (receivedAt > clampNow) + receivedAt = clampNow; + while (true) { if (!_siteStates.TryGetValue(siteId, out var existing)) @@ -151,8 +159,7 @@ public class CentralHealthAggregator : BackgroundService, ICentralHealthAggregat DateTimeOffset newHeartbeat; if (!existing.IsOnline) { - var now = _timeProvider.GetUtcNow(); - newHeartbeat = receivedAt > now ? receivedAt : now; + newHeartbeat = _timeProvider.GetUtcNow(); } else { diff --git a/src/ZB.MOM.WW.ScadaBridge.HealthMonitoring/CentralHealthReportLoop.cs b/src/ZB.MOM.WW.ScadaBridge.HealthMonitoring/CentralHealthReportLoop.cs index ac668e53..100fde17 100644 --- a/src/ZB.MOM.WW.ScadaBridge.HealthMonitoring/CentralHealthReportLoop.cs +++ b/src/ZB.MOM.WW.ScadaBridge.HealthMonitoring/CentralHealthReportLoop.cs @@ -44,12 +44,13 @@ public class CentralHealthReportLoop : BackgroundService private readonly HealthMonitoringOptions _options; private readonly ILogger _logger; - // Seeded with Unix-ms so reports from a node that has newly become active - // (oldest Up member) always sort after reports from any previously-active - // node for siteId="central". - // The clock is read through the injected TimeProvider so the seeding is - // deterministically testable. + // Advanced to max(previous + 1, now-ms) on every report (COMM-1, see + // HealthReportSender.NextSequenceNumber) so reports from a node that has newly become + // active (oldest Up member) always sort after reports from any previously-active node + // for siteId="central". The clock is read through the injected TimeProvider so the + // sequence is deterministically testable. private long _sequenceNumber; + private readonly TimeProvider _timeProvider; /// /// Initializes the central health report loop. @@ -73,7 +74,8 @@ public class CentralHealthReportLoop : BackgroundService _clusterNodeProvider = clusterNodeProvider; _options = options.Value; _logger = logger; - _sequenceNumber = (timeProvider ?? TimeProvider.System).GetUtcNow().ToUnixTimeMilliseconds(); + _timeProvider = timeProvider ?? TimeProvider.System; + _sequenceNumber = _timeProvider.GetUtcNow().ToUnixTimeMilliseconds(); } /// @@ -98,11 +100,16 @@ public class CentralHealthReportLoop : BackgroundService _collector.SetActiveNode(isPrimary); if (!isPrimary) + { + // Drain the per-interval counters on a standby tick (COMM-6) so a failover's + // first report covers one interval, not the node's whole standby life. + _collector.CollectReport(CentralSiteId); continue; + } _collector.SetClusterNodes(_clusterNodeProvider.GetClusterNodes()); - var seq = Interlocked.Increment(ref _sequenceNumber); + var seq = HealthReportSender.NextSequenceNumber(ref _sequenceNumber, _timeProvider); // CollectReport atomically read-and-resets // the per-interval error counters via Interlocked.Exchange. If diff --git a/src/ZB.MOM.WW.ScadaBridge.HealthMonitoring/HealthReportSender.cs b/src/ZB.MOM.WW.ScadaBridge.HealthMonitoring/HealthReportSender.cs index ee9356f5..3647d24f 100644 --- a/src/ZB.MOM.WW.ScadaBridge.HealthMonitoring/HealthReportSender.cs +++ b/src/ZB.MOM.WW.ScadaBridge.HealthMonitoring/HealthReportSender.cs @@ -9,12 +9,14 @@ namespace ZB.MOM.WW.ScadaBridge.HealthMonitoring; /// /// Periodically collects a SiteHealthReport and sends it to central via Akka remoting. -/// Sequence numbers are monotonic and reset on service restart. They are not -/// zero/one-based: the per-process counter is seeded with the current Unix epoch -/// (milliseconds) at construction so that, after a failover, reports from a -/// freshly-active node always sort after reports from any prior active node for the -/// same site — otherwise the central aggregator's sequence-number guard would -/// silently reject the new active's first reports as stale. +/// Sequence numbers are monotonic and not zero/one-based: every report takes +/// max(previous + 1, now as Unix-ms) (see ), so a +/// node that has just become active always sorts after anything the prior active node +/// sent — otherwise the central aggregator's sequence-number guard would reject the new +/// active's reports as stale. Seeding once at process construction and then adding 1 per +/// report (the pre-2026-12 shape) only worked while the two nodes' start gap in ms +/// exceeded the reports already sent (COMM-1): a pair started 5 s apart broke after +/// ~42 h of uptime. /// public class HealthReportSender : BackgroundService { @@ -26,13 +28,11 @@ public class HealthReportSender : BackgroundService private readonly StoreAndForwardStorage? _sfStorage; private readonly IClusterNodeProvider? _clusterNodeProvider; - // Seeded with Unix-ms at construction so reports from a freshly-active - // node always sort after reports from any prior active node for the same - // site. Without this seeding, failover would silently drop the new - // active's first reports because their per-process counter starts below - // the prior active's last sequence number. The clock is read through the - // injected TimeProvider so the seeding is deterministically testable. + // Advanced to max(previous + 1, now-ms) on every report (COMM-1) so a freshly-active + // node always sorts after the prior active node's last report. The clock is read through + // the injected TimeProvider so the sequence is deterministically testable. private long _sequenceNumber; + private readonly TimeProvider _timeProvider; /// Initializes the sender, seeds the monotonic sequence number from the current Unix timestamp. /// Site health metric collector supplying the report payload. @@ -60,7 +60,30 @@ public class HealthReportSender : BackgroundService _siteId = siteIdentityProvider.SiteId; _sfStorage = sfStorage; _clusterNodeProvider = clusterNodeProvider; - _sequenceNumber = (timeProvider ?? TimeProvider.System).GetUtcNow().ToUnixTimeMilliseconds(); + _timeProvider = timeProvider ?? TimeProvider.System; + _sequenceNumber = _timeProvider.GetUtcNow().ToUnixTimeMilliseconds(); + } + + /// + /// Advances the sequence number to max(previous + 1, now as Unix-ms) and returns it. + /// Wall-clock anchored on every call, so after a failover the new active node's first report + /// sorts above the old active's last one regardless of how long either process has run + /// (COMM-1); the previous + 1 floor keeps it strictly monotonic within the process even + /// if the clock steps backwards. + /// + /// The sequence field to advance. + /// The clock to anchor on. + /// The new sequence number. + internal static long NextSequenceNumber(ref long sequence, TimeProvider timeProvider) + { + while (true) + { + var previous = Interlocked.Read(ref sequence); + var nowMs = timeProvider.GetUtcNow().ToUnixTimeMilliseconds(); + var next = Math.Max(previous + 1, nowMs); + if (Interlocked.CompareExchange(ref sequence, next, previous) == previous) + return next; + } } /// @@ -83,8 +106,14 @@ public class HealthReportSender : BackgroundService { // Only the active node (running the DeploymentManager singleton) sends health reports. // The standby node has no instance/connection data and would overwrite the active's report. + // The standby still DRAINS its per-interval counters each tick (COMM-6): increments keep + // landing on a standby (dead letters, etc.), and without the drain weeks of them would + // be reported as one 30 s interval on the first report after a failover. if (!_collector.IsActiveNode) + { + _collector.CollectReport(_siteId); continue; + } if (_clusterNodeProvider != null) { @@ -147,7 +176,7 @@ public class HealthReportSender : BackgroundService } } - var seq = Interlocked.Increment(ref _sequenceNumber); + var seq = NextSequenceNumber(ref _sequenceNumber, _timeProvider); // CollectReport atomically read-and-resets // the per-interval error counters via Interlocked.Exchange. The diff --git a/src/ZB.MOM.WW.ScadaBridge.Host/Actors/AkkaHostedService.cs b/src/ZB.MOM.WW.ScadaBridge.Host/Actors/AkkaHostedService.cs index f45f9c17..51c4c2fa 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Host/Actors/AkkaHostedService.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Host/Actors/AkkaHostedService.cs @@ -1433,7 +1433,15 @@ akka {{ { grpcServer?.SetOperationTrackingStore(siteTrackingStore); } - grpcServer?.SetReady(_actorSystem!); + // COMM-2: only the active node (oldest Up member of THIS site's role — where the + // DeploymentManager singleton and so every Instance Actor runs) accepts stream + // subscriptions; a standby refuses with Unavailable and ends its streams on losing the + // role, so central's stream clients flip to the node that actually produces events. + var streamActorSystem = _actorSystem!; + grpcServer?.SetReady( + streamActorSystem, + () => ZB.MOM.WW.ScadaBridge.Communication.ClusterState.ActiveNodeEvaluator.SelfIsOldestUp( + Cluster.Get(streamActorSystem), siteRole)); // Site command plane: hand the shared dispatcher to the gRPC command service and flip it // ready at the same point as the streaming server — the actor graph exists and the local diff --git a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/HttpStandbyRequestForwarder.cs b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/HttpStandbyRequestForwarder.cs index 3b90c39f..c5b4f963 100644 --- a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/HttpStandbyRequestForwarder.cs +++ b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/HttpStandbyRequestForwarder.cs @@ -146,6 +146,12 @@ public sealed class HttpStandbyRequestForwarder : IStandbyRequestForwarder { throw; // caller went away — nothing to answer } + catch (OperationCanceledException ex) when (!deadline.IsCancellationRequested && RelayConnectPhase.WasNotSent(ex)) + { + // DLM-1: the connect timeout fired on a powered-off/black-holed peer — nothing was + // sent, so the next peer is safe to try. + _logger.LogWarning(ex, "Inbound relay could not connect to {Peer} (connect timeout); trying next peer", peer); + } catch (OperationCanceledException) { _logger.LogWarning("Inbound relay deadline expired after dispatch to {Peer}; outcome uncertain", peer); @@ -199,9 +205,11 @@ public sealed class HttpStandbyRequestForwarder : IStandbyRequestForwarder return request; } - private static bool KnownNotDispatched(HttpRequestException error) - => error.HttpRequestError == HttpRequestError.NameResolutionError - || error.InnerException is System.Net.Sockets.SocketException { SocketErrorCode: System.Net.Sockets.SocketError.ConnectionRefused }; + /// + /// A connect-phase failure — refused, DNS, unreachable/black-holed host (DLM-1, via the + /// handler's marker) — never sent the request. + /// + private static bool KnownNotDispatched(HttpRequestException error) => RelayConnectPhase.WasNotSent(error); private static IResult OutcomeUnknown() => Results.Json(new { diff --git a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/RelayConnectPhase.cs b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/RelayConnectPhase.cs new file mode 100644 index 00000000..520fc1e9 --- /dev/null +++ b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/RelayConnectPhase.cs @@ -0,0 +1,74 @@ +using System.Net.Http; +using System.Net.Sockets; + +namespace ZB.MOM.WW.ScadaBridge.InboundAPI; + +/// +/// Standby-relay copy of the DelmiaNotifier's ConnectPhase (the notifier is a separate, +/// dependency-free client tool, so the two cannot share it). Makes "the request was never sent" +/// observable (DLM-1). The handler built here owns the TCP +/// connect through and wraps every connect +/// failure — refusal, DNS, an unreachable/black-holed host, the +/// firing — in , which keeps in the +/// exception chain it surfaces. A failure carrying the marker happened before any byte of the request +/// was written, so trying the next base URL is safe. Anything without it (a reset or timeout after the +/// connection was up) may have reached the active peer and stays OUTCOME_UNKNOWN. +/// +internal static class RelayConnectPhase +{ + /// + /// Default TCP connect timeout. Well below the relay's StandbyForwardTimeout, so a powered-off + /// peer fails as a connect failure (and the next peer is tried) instead of eating the whole budget. + /// + public static readonly TimeSpan DefaultConnectTimeout = TimeSpan.FromSeconds(5); + + /// Creates a handler whose connect failures carry . + /// The TCP connect timeout. + /// The configured handler. + public static SocketsHttpHandler CreateHandler(TimeSpan connectTimeout) => new() + { + ConnectTimeout = connectTimeout, + ConnectCallback = async (context, ct) => + { + var socket = new Socket(SocketType.Stream, ProtocolType.Tcp) { NoDelay = true }; + try + { + await socket.ConnectAsync(context.DnsEndPoint, ct).ConfigureAwait(false); + return new NetworkStream(socket, ownsSocket: true); + } + catch (Exception ex) + { + socket.Dispose(); + throw new RelayConnectPhaseException( + $"could not connect to {context.DnsEndPoint.Host}:{context.DnsEndPoint.Port}: {ex.Message}", ex); + } + }, + }; + + /// + /// True when provably failed before the request was sent: the connect + /// marker is in its chain, or (handlers built without the marker) DNS failed or the connection + /// was refused. + /// + /// The failure from HttpClient.SendAsync. + /// true when the request was never sent. + public static bool WasNotSent(Exception error) + { + for (var e = error; e is not null; e = e.InnerException) + { + if (e is RelayConnectPhaseException) + return true; + if (e is HttpRequestException { HttpRequestError: HttpRequestError.NameResolutionError }) + return true; + if (e is HttpRequestException { InnerException: SocketException { SocketErrorCode: SocketError.ConnectionRefused } }) + return true; + } + + return false; + } +} + +/// Marks a failure that happened while opening the TCP connection — nothing was sent. +/// The failure description. +/// The underlying connect failure. +internal sealed class RelayConnectPhaseException(string message, Exception inner) : Exception(message, inner); diff --git a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/ServiceCollectionExtensions.cs b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/ServiceCollectionExtensions.cs index 3b9d4087..acf0fd42 100644 --- a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/ServiceCollectionExtensions.cs +++ b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/ServiceCollectionExtensions.cs @@ -42,8 +42,12 @@ public static class ServiceCollectionExtensions // named client has no HttpClient.Timeout of its own — the forwarder's per-attempt // CTS (InboundApiOptions.StandbyForwardTimeout) is the single deadline, so a // long-running method on the active node is not cut off by a second, hidden cap. + // DLM-1: the primary handler bounds the TCP connect (5 s) and marks connect-phase + // failures, so a powered-off peer is "not dispatched" (next peer / 503 + // ACTIVE_NODE_UNREACHABLE) rather than a 60 s wait ending in 502 OUTCOME_UNKNOWN. services.AddHttpClient(HttpStandbyRequestForwarder.HttpClientName) - .ConfigureHttpClient(c => c.Timeout = Timeout.InfiniteTimeSpan); + .ConfigureHttpClient(c => c.Timeout = Timeout.InfiniteTimeSpan) + .ConfigurePrimaryHttpMessageHandler(() => RelayConnectPhase.CreateHandler(RelayConnectPhase.DefaultConnectTimeout)); services.AddSingleton(); // N1: the ApiMethod consumer of the script-artifact invalidation bus. diff --git a/src/ZB.MOM.WW.ScadaBridge.KpiHistory/KpiHistoryRecorderActor.cs b/src/ZB.MOM.WW.ScadaBridge.KpiHistory/KpiHistoryRecorderActor.cs index d0af3d48..af35e623 100644 --- a/src/ZB.MOM.WW.ScadaBridge.KpiHistory/KpiHistoryRecorderActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.KpiHistory/KpiHistoryRecorderActor.cs @@ -164,6 +164,18 @@ public class KpiHistoryRecorderActor : ReceiveActor, IWithTimers /// private bool _backfillDone; + /// Consecutive failed backfill slices in this actor lifetime (KPI-1). + private int _backfillFailures; + + /// Consecutive failed slices after which the backfill gives up for this lifetime. + private const int MaxConsecutiveBackfillFailures = 3; + + /// + /// Delay before re-planning (from the persisted watermark) after a failed backfill slice. + /// Settable for tests. + /// + internal static TimeSpan BackfillRetryDelay { get; set; } = TimeSpan.FromMinutes(5); + /// Akka timer scheduler, assigned by the actor system via . public ITimerScheduler Timers { get; set; } = null!; @@ -191,9 +203,34 @@ public class KpiHistoryRecorderActor : ReceiveActor, IWithTimers Receive(_ => _rollupInFlight = false); // lower the in-flight guard (success or fault) Receive(_ => HandleBackfillTick()); Receive(HandleBackfillPlan); - Receive(_ => + Receive(complete => { _backfillInFlight = false; // release the fold path BETWEEN slices (R1) + + if (!complete.Succeeded) + { + // KPI-1: the persisted watermark stops at the last slice that folded, so the + // remaining queue is dropped and the backfill re-plans from that watermark after a + // delay — a later slice must never advance the marker past a gap. A few + // consecutive failures give up for this actor lifetime; the next singleton start + // resumes from the watermark. + _backfillSlices.Clear(); + _backfillFailures++; + if (_backfillFailures >= MaxConsecutiveBackfillFailures) + { + _backfillDone = true; + _logger.LogWarning( + "KPI rollup backfill stopped after {Failures} consecutive failed slices; it resumes " + + "from its persisted watermark on the next singleton start.", + _backfillFailures); + return; + } + + Timers.StartSingleTimer(BackfillTimerKey, BackfillTick.Instance, BackfillRetryDelay); + return; + } + + _backfillFailures = 0; if (_backfillSlices.Count == 0) { _backfillDone = true; // latch: at most once per actor lifetime (unchanged semantics) @@ -536,6 +573,11 @@ public class KpiHistoryRecorderActor : ReceiveActor, IWithTimers await using var scope = _serviceProvider.CreateAsyncScope(); var repository = scope.ServiceProvider.GetRequiredService(); await repository.FoldHourlyRollupsAsync(fromHourUtc, toHourUtc, cancellationToken); + + // KPI-1: keep a COMPLETED backfill's marker current — it moves only when it already + // reaches this fold's window, so it can never jump a gap the backfill has not folded. + await repository.AdvanceRollupBackfillWatermarkAsync( + toHourUtc, onlyIfReachedUtc: fromHourUtc, cancellationToken: cancellationToken); } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { @@ -602,11 +644,11 @@ public class KpiHistoryRecorderActor : ReceiveActor, IWithTimers RunBackfillPass(slice.FromHourUtc, slice.ToHourUtc, cancellationToken).PipeTo( Self, - success: () => BackfillSliceComplete.Instance, + success: ok => ok ? BackfillSliceComplete.Success : BackfillSliceComplete.Failure, failure: ex => { _logger.LogError(ex, "KPI rollup backfill slice faulted unexpectedly."); - return BackfillSliceComplete.Instance; + return BackfillSliceComplete.Failure; }); } @@ -658,7 +700,7 @@ public class KpiHistoryRecorderActor : ReceiveActor, IWithTimers _backfillInFlight = false; _backfillDone = true; _logger.LogInformation( - "KPI rollup backfill skipped — rollups current through {Watermark:o}.", plan.Watermark); + "KPI rollup backfill skipped — the backfill has already folded through {Watermark:o}.", plan.Watermark); return; } @@ -682,10 +724,13 @@ public class KpiHistoryRecorderActor : ReceiveActor, IWithTimers } /// - /// Resolves the newest folded rollup hour (the backfill watermark) off the actor thread in a - /// fresh DI scope. Never faults — on cancellation or error it returns null, which the - /// plan treats as "no rollups", keeping the full retention window (best-effort, mirrors the - /// other passes). + /// Resolves the backfill's OWN persisted watermark (KPI-1 — the hour boundary its completed + /// slices have folded through) off the actor thread in a fresh DI scope. Deliberately NOT + /// MAX(KpiRollupHourly.HourStartUtc): the periodic lookback fold advances that seconds + /// before this runs, so it used to latch the backfill "current" on every start that had + /// recent samples, and it says nothing about gaps below it. Never faults — on cancellation or + /// error it returns null, which the plan treats as "nothing backfilled", keeping the + /// full retention window (idempotent; best-effort, mirrors the other passes). /// private async Task RunBackfillPlanPass(CancellationToken cancellationToken) { @@ -693,7 +738,7 @@ public class KpiHistoryRecorderActor : ReceiveActor, IWithTimers { await using var scope = _serviceProvider.CreateAsyncScope(); var repository = scope.ServiceProvider.GetRequiredService(); - return await repository.GetLatestRollupHourAsync(cancellationToken); + return await repository.GetRollupBackfillWatermarkAsync(cancellationToken); } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { @@ -715,7 +760,7 @@ public class KpiHistoryRecorderActor : ReceiveActor, IWithTimers /// disrupt startup. The fold method returns no count, so each slice is logged at Debug with its /// window and elapsed wall time (the queue-drained completion is logged at Information). /// - private async Task RunBackfillPass( + private async Task RunBackfillPass( DateTime fromHourUtc, DateTime toHourUtc, CancellationToken cancellationToken) { var startedAt = DateTime.UtcNow; @@ -725,17 +770,25 @@ public class KpiHistoryRecorderActor : ReceiveActor, IWithTimers var repository = scope.ServiceProvider.GetRequiredService(); await repository.FoldHourlyRollupsAsync(fromHourUtc, toHourUtc, cancellationToken); + // KPI-1: record the backfill's own progress only once the slice has folded, so the + // marker means exactly "every hour before this is rolled up". + await repository.AdvanceRollupBackfillWatermarkAsync(toHourUtc, cancellationToken: cancellationToken); + _logger.LogDebug( "KPI rollup backfill slice folded [{FromHour:o}, {ToHour:o}) in {ElapsedMs:F0} ms.", fromHourUtc, toHourUtc, (DateTime.UtcNow - startedAt).TotalMilliseconds); + return true; } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { - // Shutdown interrupted the backfill; a failover re-runs it (idempotent). Not a failure. + // Shutdown interrupted the backfill; the next singleton resumes from the persisted + // watermark (idempotent). Not a failure worth retrying in this lifetime. + return true; } catch (Exception ex) { - _logger.LogError(ex, "KPI rollup backfill failed unexpectedly."); + _logger.LogError(ex, "KPI rollup backfill slice [{FromHour:o}, {ToHour:o}) failed.", fromHourUtc, toHourUtc); + return false; } } @@ -823,7 +876,18 @@ public class KpiHistoryRecorderActor : ReceiveActor, IWithTimers /// internal sealed class BackfillSliceComplete { - public static readonly BackfillSliceComplete Instance = new(); - private BackfillSliceComplete() { } + /// The slice folded and the persisted watermark advanced. + public static readonly BackfillSliceComplete Success = new(true); + + /// The slice failed; the backfill re-plans from the persisted watermark (KPI-1). + public static readonly BackfillSliceComplete Failure = new(false); + + /// Backwards-compatible alias for . + public static BackfillSliceComplete Instance => Success; + + private BackfillSliceComplete(bool succeeded) => Succeeded = succeeded; + + /// Whether the slice folded successfully. + public bool Succeeded { get; } } } diff --git a/src/ZB.MOM.WW.ScadaBridge.NotificationOutbox/Delivery/EmailNotificationDeliveryAdapter.cs b/src/ZB.MOM.WW.ScadaBridge.NotificationOutbox/Delivery/EmailNotificationDeliveryAdapter.cs index be61eb67..937203f4 100644 --- a/src/ZB.MOM.WW.ScadaBridge.NotificationOutbox/Delivery/EmailNotificationDeliveryAdapter.cs +++ b/src/ZB.MOM.WW.ScadaBridge.NotificationOutbox/Delivery/EmailNotificationDeliveryAdapter.cs @@ -199,9 +199,11 @@ public sealed class EmailNotificationDeliveryAdapter : INotificationDeliveryAdap } catch (Exception ex) { - // An unclassified failure — chiefly an OAuth2 token-fetch failure. The - // outbox treats it as permanent: retrying a broken credential burns - // token-endpoint calls. (Mirrors the default-to-permanent stance.) + // An unclassified failure — chiefly a broken OAuth2 credential (a malformed + // credential triple, a 4xx from the token endpoint). The outbox treats it as + // permanent: retrying a broken credential burns token-endpoint calls. A token + // endpoint outage (5xx/408/429, no response, timeout) and a dropped SMTP + // connection are classified transient above (NTF-2) and never reach here. var detail = CredentialRedactor.Scrub(ex.Message, smtpConfig.Credentials); _logger.LogError( "Unclassified failure delivering email to list '{List}' ({ExceptionType}): {Detail}", diff --git a/src/ZB.MOM.WW.ScadaBridge.NotificationOutbox/NotificationOutboxActor.cs b/src/ZB.MOM.WW.ScadaBridge.NotificationOutbox/NotificationOutboxActor.cs index e41a3a60..aac54b79 100644 --- a/src/ZB.MOM.WW.ScadaBridge.NotificationOutbox/NotificationOutboxActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.NotificationOutbox/NotificationOutboxActor.cs @@ -683,7 +683,7 @@ public class NotificationOutboxActor : ReceiveActor, IWithTimers notification.Status = NotificationStatus.Parked; notification.LastError = missingAdapterError; notification.LastAttemptAt = parkedAt; - await WarnIfVanishedAsync(outboxRepository, notification, cancellationToken); + await WarnIfVanishedAsync(outboxRepository, notification); await EmitAttemptAuditAsync( notification, parkedAt, @@ -741,7 +741,12 @@ public class NotificationOutboxActor : ReceiveActor, IWithTimers break; } - await WarnIfVanishedAsync(outboxRepository, notification, cancellationToken); + // NTF-1: from here on the shutdown token is NOT used. The adapter has returned an + // outcome — for a Success the email/SMS has already been accepted by the relay — so + // the write that records it must land even when a singleton handover cancelled the + // token mid-delivery. With the shutdown token the write threw, the row stayed + // Pending/Retrying with no record of the send, and the new active node re-sent it. + await WarnIfVanishedAsync(outboxRepository, notification); // Emit the per-attempt Attempted row exactly once regardless of the // outcome (B2). The error message comes from the outcome, not from @@ -767,6 +772,14 @@ public class NotificationOutboxActor : ReceiveActor, IWithTimers } } + /// + /// Upper bound on the write that records a delivery outcome (NTF-1). That write runs on + /// its own token rather than the actor's shutdown token, so a handover cannot cancel the + /// record of a send that already happened; this keeps a wedged database from pinning a + /// stopping actor's delivery task forever. Settable for tests. + /// + internal static TimeSpan OutcomePersistTimeout { get; set; } = TimeSpan.FromSeconds(30); + /// /// Persists the dispatcher's delivery-state write and logs when the row has /// VANISHED underneath it — @@ -783,10 +796,12 @@ public class NotificationOutboxActor : ReceiveActor, IWithTimers /// private async Task WarnIfVanishedAsync( INotificationOutboxRepository repository, - Notification notification, - CancellationToken cancellationToken) + Notification notification) { - var persisted = await repository.UpdateAsync(notification, cancellationToken); + // Deliberately NOT the actor's shutdown token (NTF-1): this records an outcome the + // channel already produced, so it is bounded by its own timeout instead. + using var persistCts = new CancellationTokenSource(OutcomePersistTimeout); + var persisted = await repository.UpdateAsync(notification, persistCts.Token); if (!persisted) { _logger.LogWarning( diff --git a/src/ZB.MOM.WW.ScadaBridge.NotificationService/SmtpErrorClassifier.cs b/src/ZB.MOM.WW.ScadaBridge.NotificationService/SmtpErrorClassifier.cs index ece41c98..f22dcb88 100644 --- a/src/ZB.MOM.WW.ScadaBridge.NotificationService/SmtpErrorClassifier.cs +++ b/src/ZB.MOM.WW.ScadaBridge.NotificationService/SmtpErrorClassifier.cs @@ -1,6 +1,7 @@ using System.Net.Sockets; using MailKit; using MailKit.Net.Smtp; +using MailKit.Security; namespace ZB.MOM.WW.ScadaBridge.NotificationService; @@ -72,16 +73,44 @@ public static class SmtpErrorClassifier return SmtpErrorClass.Unknown; } - // Protocol errors, a dropped/unavailable service, socket failures and - // timeouts are all retryable — the message has not been rejected. - if (ex is SmtpProtocolException - or ServiceNotConnectedException - or SocketException - or TimeoutException) + // OAuth2 token endpoint (NTF-2): classify the HTTP failure by status. No status means + // the request never got an answer (DNS, connect, reset) — transient; a 5xx/408/429 is + // an outage or throttle — transient; any other 4xx is a broken credential or request + // and stays permanent so a bad secret does not burn token-endpoint calls on retry. + if (ex is HttpRequestException http) + { + return http.StatusCode is not { } status + || (int)status >= 500 + || (int)status is 408 or 429 + ? SmtpErrorClass.Transient + : SmtpErrorClass.Permanent; + } + + // A cancellation the caller did NOT request is a timeout (HttpClient.Timeout on the + // token fetch surfaces as TaskCanceledException) — transient (NTF-2). + if (ex is OperationCanceledException) { return SmtpErrorClass.Transient; } + // Protocol errors, a dropped/unavailable service, socket failures, timeouts, a dropped + // connection (IOException — MailKit's documented connection-loss exception on + // Connect/Authenticate/Send) and a TLS handshake that failed mid-way are all retryable: + // the message has not been rejected (NTF-2). The inner-exception chain is walked + // because MailKit typically wraps the SocketException in an IOException. + for (var e = ex; e is not null; e = e.InnerException) + { + if (e is SmtpProtocolException + or ServiceNotConnectedException + or SocketException + or TimeoutException + or SslHandshakeException + or IOException) + { + return SmtpErrorClass.Transient; + } + } + return SmtpErrorClass.Unknown; } diff --git a/src/ZB.MOM.WW.ScadaBridge.SiteCallAudit/SiteCallAuditActor.cs b/src/ZB.MOM.WW.ScadaBridge.SiteCallAudit/SiteCallAuditActor.cs index dcb130ec..77552857 100644 --- a/src/ZB.MOM.WW.ScadaBridge.SiteCallAudit/SiteCallAuditActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.SiteCallAudit/SiteCallAuditActor.cs @@ -132,7 +132,12 @@ public class SiteCallAuditActor : ReceiveActor /// next tick re-pulls from the start and idempotent upsert dedupes). Mirrors /// SiteAuditReconciliationActor's cursor (now composite). /// - private readonly Dictionary _reconciliationCursors = new(); + /// + /// Keyed per (site, node endpoint) since AUD-1 (2026-12): on a site pair that does not + /// run LocalDb replication each node's operation-tracking store is its own, so each node is + /// pulled with its own cursor; one per-site cursor fed by NodeA's rows skipped NodeB's. + /// + private readonly Dictionary<(string SiteId, string Endpoint), (DateTime Since, string? AfterId)> _reconciliationCursors = new(); /// /// Per-site "pinned" latch — true once a site's composite @@ -500,6 +505,7 @@ public class SiteCallAuditActor : ReceiveActor } PruneRemovedSites(sites); + (client as IGrpcChannelCachePruner)?.RetainOnly(sites); if (sites.Count == 0) { @@ -536,12 +542,35 @@ public class SiteCallAuditActor : ReceiveActor _reconciliationPinned.Remove(siteId); } - foreach (var siteId in _reconciliationCursors.Keys.Where(k => !live.Contains(k)).ToList()) + var liveNodes = new HashSet<(string, string)>( + sites.SelectMany(s => NodeEndpoints(s).Select(e => (s.SiteId, e)))); + foreach (var key in _reconciliationCursors.Keys.Where(k => !liveNodes.Contains(k)).ToList()) { - _reconciliationCursors.Remove(siteId); + _reconciliationCursors.Remove(key); } } + /// + /// The distinct node endpoints of a site: the primary (NodeA where configured) and, when a + /// distinct one exists, the second node (AUD-1 — both are pulled every tick). + /// + private static IEnumerable NodeEndpoints(SiteEntry site) + { + if (!string.IsNullOrWhiteSpace(site.GrpcEndpoint)) + { + yield return site.GrpcEndpoint; + } + + if (!string.IsNullOrWhiteSpace(site.FallbackGrpcEndpoint) + && !string.Equals(site.FallbackGrpcEndpoint, site.GrpcEndpoint, StringComparison.Ordinal)) + { + yield return site.FallbackGrpcEndpoint; + } + } + + /// Test seam: number of (site, node) reconciliation cursors held. + internal int ReconciliationCursorCountForTests => _reconciliationCursors.Count; + /// /// Reconciles every site in the tick against a single resolved repository, /// isolating per-site faults so one bad site never sinks the rest of the @@ -640,7 +669,37 @@ public class SiteCallAuditActor : ReceiveActor private async Task ReconcileSiteAsync( SiteEntry site, IPullSiteCallsClient client, ISiteCallAuditRepository repository) { - var cursor = _reconciliationCursors.TryGetValue(site.SiteId, out var c) + // AUD-1: pull EVERY node with its own cursor. One node faulting must not skip the + // other; the site is pinned when any node is. + var anyPinned = false; + foreach (var endpoint in NodeEndpoints(site)) + { + try + { + anyPinned |= await ReconcileNodeAsync(site, endpoint, client, repository).ConfigureAwait(false); + } + catch (Exception ex) + { + _logger.LogWarning(ex, + "SiteCallAudit reconciliation pull failed for site {SiteId} node {Endpoint}; the site's other node continues.", + site.SiteId, endpoint); + anyPinned |= _reconciliationPinned.TryGetValue(site.SiteId, out var wasPinned) && wasPinned; + } + } + + SetReconciliationPinned(site.SiteId, anyPinned); + } + + /// + /// Drains one node of a site (see for the cursor, page and + /// pinned semantics). Returns true when the node's cursor is pinned (a legacy node that + /// ignores the after_id keyset). + /// + private async Task ReconcileNodeAsync( + SiteEntry site, string endpoint, IPullSiteCallsClient client, ISiteCallAuditRepository repository) + { + var cursorKey = (site.SiteId, endpoint); + var cursor = _reconciliationCursors.TryGetValue(cursorKey, out var c) ? c : (Since: DateTime.MinValue, AfterId: (string?)null); @@ -655,7 +714,7 @@ public class SiteCallAuditActor : ReceiveActor var since = cursor.Since; var afterId = cursor.AfterId; var response = await client - .PullAsync(site.SiteId, since, afterId, _options.ReconciliationBatchSize, CancellationToken.None) + .PullFromEndpointAsync(site.SiteId, endpoint, since, afterId, _options.ReconciliationBatchSize, CancellationToken.None) .ConfigureAwait(false); var maxUpdated = since; @@ -694,19 +753,12 @@ public class SiteCallAuditActor : ReceiveActor // Persist the advanced cursor after every page so a fault on a later // page (caught per-site upstream) still keeps the rows already drained. cursor = (maxUpdated, maxAfterId); - _reconciliationCursors[site.SiteId] = cursor; - - // Progress resumed → clear any prior pinned latch (publishes the - // Pinned=false transition exactly once). - if (advanced) - { - SetReconciliationPinned(site.SiteId, pinned: false); - } + _reconciliationCursors[cursorKey] = cursor; if (!response.MoreAvailable) { - // Backlog fully drained for this site this tick. - return; + // Backlog fully drained for this node this tick. + return false; } if (!advanced) @@ -716,16 +768,16 @@ public class SiteCallAuditActor : ReceiveActor // site), so a continuation would re-pull the identical window // forever. Latch + publish the pinned state and stop; the next tick // re-checks and unpins if the site catches up. - SetReconciliationPinned(site.SiteId, pinned: true); _logger.LogWarning( - "SiteCallAudit reconciliation for site {SiteId} is pinned: the composite " + "SiteCallAudit reconciliation for site {SiteId} node {Endpoint} is pinned: the composite " + "(UpdatedAtUtc, TrackedOperationId) cursor did not advance past ({CursorUtc:o}, {AfterId}) " + "yet the site reports more rows available — the site does not honour the after_id keyset " + "(legacy). The backlog tail will not reconcile until the site is upgraded.", site.SiteId, + endpoint, since, afterId ?? "(none)"); - return; + return true; } } @@ -734,11 +786,13 @@ public class SiteCallAuditActor : ReceiveActor // simply more than MaxReconciliationPagesPerTick × batch-size of it. The // next tick resumes from the advanced cursor. _logger.LogInformation( - "SiteCallAudit reconciliation for site {SiteId} hit the per-tick page ceiling " + "SiteCallAudit reconciliation for site {SiteId} node {Endpoint} hit the per-tick page ceiling " + "({MaxPages} pages); the cursor advanced each page and the remaining backlog " + "drains on the next tick.", site.SiteId, + endpoint, MaxReconciliationPagesPerTick); + return false; } /// diff --git a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Tracking/OperationTrackingStore.cs b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Tracking/OperationTrackingStore.cs index ec2e37b4..fe44ddf8 100644 --- a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Tracking/OperationTrackingStore.cs +++ b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Tracking/OperationTrackingStore.cs @@ -259,6 +259,65 @@ public class OperationTrackingStore : IOperationTrackingStore, IAsyncDisposable, }, ct).ConfigureAwait(false); } + /// + public async Task ReopenParkedAsync(TrackedOperationId id, CancellationToken ct = default) + { + var now = DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture); + var idText = id.ToString(); + + await EnqueueAsync($"reopen {idText}", (conn, tx) => + { + using var cmd = conn.CreateCommand(); + cmd.Transaction = tx; + // SCA-1: Parked is re-openable. Only a Parked row moves — every other terminal + // state stays immutable, and a non-terminal row is already in the loop. + cmd.CommandText = """ + UPDATE OperationTracking + SET Status = 'Attempted', + RetryCount = 0, + LastError = NULL, + HttpStatus = NULL, + UpdatedAtUtc = $now, + TerminalAtUtc = NULL + WHERE TrackedOperationId = $id + AND Status = 'Parked'; + """; + cmd.Parameters.AddWithValue("$id", idText); + cmd.Parameters.AddWithValue("$now", now); + + cmd.ExecuteNonQuery(); + }, ct).ConfigureAwait(false); + } + + /// + public async Task RecordDiscardedAsync(TrackedOperationId id, string? lastError, CancellationToken ct = default) + { + var now = DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture); + var idText = id.ToString(); + + await EnqueueAsync($"discard {idText}", (conn, tx) => + { + using var cmd = conn.CreateCommand(); + cmd.Transaction = tx; + // SCA-1: an operator discard closes a Parked (or still-open) row as Discarded; + // Delivered/Failed/Discarded stay immutable. + cmd.CommandText = """ + UPDATE OperationTracking + SET Status = 'Discarded', + LastError = COALESCE($lastError, LastError), + UpdatedAtUtc = $now, + TerminalAtUtc = $now + WHERE TrackedOperationId = $id + AND (TerminalAtUtc IS NULL OR Status = 'Parked'); + """; + cmd.Parameters.AddWithValue("$id", idText); + cmd.Parameters.AddWithValue("$lastError", (object?)lastError ?? DBNull.Value); + cmd.Parameters.AddWithValue("$now", now); + + cmd.ExecuteNonQuery(); + }, ct).ConfigureAwait(false); + } + /// public async Task RecordTerminalAsync( TrackedOperationId id, diff --git a/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardService.cs b/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardService.cs index bec02b88..769c4116 100644 --- a/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardService.cs +++ b/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardService.cs @@ -1364,6 +1364,17 @@ public class StoreAndForwardService RaiseActivity("Retry", captured.Category, $"Parked message {messageId} moved back to queue"); + + // SCA-1: a re-queued cached call leaves Parked end to end — the observer re-opens the + // site tracking row and emits telemetry so central's SiteCalls row follows. Without it + // the row stayed Parked forever (later attempts were no-ops on a terminal row). + await PostObserverNotification( + captured, + CachedCallAttemptOutcome.OperatorRetried, + lastError: null, + httpStatus: null, + occurredAtUtc: DateTime.UtcNow, + durationMs: null); return true; } @@ -1389,6 +1400,19 @@ public class StoreAndForwardService { RaiseActivity("Discard", message?.Category ?? StoreAndForwardCategory.ExternalSystem, $"Parked message {messageId} discarded"); + + // SCA-1: record the discard on the tracking row (Parked → Discarded) and emit + // telemetry, so Tracking.Status and central's SiteCalls row stop reporting Parked. + if (message is not null) + { + await PostObserverNotification( + message, + CachedCallAttemptOutcome.OperatorDiscarded, + lastError: "Discarded by operator", + httpStatus: null, + occurredAtUtc: DateTime.UtcNow, + durationMs: null); + } } return success; } diff --git a/tests/ZB.MOM.WW.ScadaBridge.AuditLog.Tests/Central/ReconciliationPerNodeTests.cs b/tests/ZB.MOM.WW.ScadaBridge.AuditLog.Tests/Central/ReconciliationPerNodeTests.cs new file mode 100644 index 00000000..5d8f087c --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.AuditLog.Tests/Central/ReconciliationPerNodeTests.cs @@ -0,0 +1,145 @@ +using System.Collections.Concurrent; +using Akka.Actor; +using Akka.TestKit.Xunit2; +using Grpc.Core; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using NSubstitute; +using ZB.MOM.WW.Audit; +using ZB.MOM.WW.ScadaBridge.AuditLog.Central; +using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories; +using ZB.MOM.WW.ScadaBridge.Commons.Messages.Integration; +using ZB.MOM.WW.ScadaBridge.Commons.Types.Audit; +using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums; +using ProtoPullRequest = ZB.MOM.WW.ScadaBridge.Communication.Grpc.PullAuditEventsRequest; +using ProtoPullResponse = ZB.MOM.WW.ScadaBridge.Communication.Grpc.PullAuditEventsResponse; + +namespace ZB.MOM.WW.ScadaBridge.AuditLog.Tests.Central; + +/// +/// AUD-1: the site audit store is per node and unreplicated, so the reconciliation pull reaches +/// BOTH nodes of a site every tick, each with its own (site, node) cursor — not NodeA whenever +/// NodeA answers, with one cursor shared by two unrelated stores. +/// +public class ReconciliationPerNodeTests : TestKit +{ + private const string NodeA = "http://site-a-node-a:8083"; + private const string NodeB = "http://site-a-node-b:8083"; + + private static readonly DateTime OwedAt = new(2026, 12, 1, 8, 0, 0, DateTimeKind.Utc); + + private sealed class StaticEnumerator(params SiteEntry[] sites) : ISiteEnumerator + { + public Task> EnumerateAsync(CancellationToken ct = default) => + Task.FromResult>(sites); + } + + /// + /// NodeA (a healthy standby after a restart) owes nothing; NodeB (active) owes one + /// PushAbandoned row. Records every per-node pull with the cursor it was sent. + /// + private sealed class PerNodeClient : IPullAuditEventsClient + { + public readonly AuditEvent NodeBRow = ScadaBridgeAuditEventFactory.Create( + eventId: Guid.NewGuid(), + occurredAtUtc: OwedAt, + channel: AuditChannel.ApiOutbound, + kind: AuditKind.ApiCall, + status: AuditStatus.Delivered, + sourceSiteId: "site-a"); + + public ConcurrentQueue<(string Endpoint, DateTime Since, string? AfterId)> Calls { get; } = new(); + + public Task PullAsync( + string siteId, DateTime sinceUtc, string? afterId, int batchSize, CancellationToken ct) => + throw new InvalidOperationException("the actor must pull per node"); + + public Task PullFromEndpointAsync( + string siteId, string endpoint, DateTime sinceUtc, string? afterId, int batchSize, CancellationToken ct) + { + Calls.Enqueue((endpoint, sinceUtc, afterId)); + var events = endpoint == NodeB && sinceUtc < OwedAt + ? new[] { NodeBRow } + : Array.Empty(); + return Task.FromResult(new PullAuditEventsResponse(events, MoreAvailable: false)); + } + } + + /// + /// Regression: the NodeB-owed row reaches central even though NodeA answers, and each node + /// keeps its own cursor (NodeA's never moves off its start; NodeB's advances past its row). + /// + [Fact] + public void BothNodesArePulled_EachWithItsOwnCursor() + { + var client = new PerNodeClient(); + var repo = Substitute.For(); + var inserted = new ConcurrentBag(); + repo.InsertManyIfNotExistsAsync(Arg.Any>(), Arg.Any(), Arg.Any()) + .Returns(ci => + { + foreach (var e in (IReadOnlyList)ci[0]) inserted.Add(e.EventId); + return Task.FromResult(((IReadOnlyList)ci[0]).Count); + }); + var services = new ServiceCollection(); + services.AddScoped(_ => repo); + + var actor = Sys.ActorOf(Props.Create(() => new SiteAuditReconciliationActor( + new StaticEnumerator(new SiteEntry("site-a", NodeA, NodeB)), + client, + services.BuildServiceProvider(), + Options.Create(new SiteAuditReconciliationOptions + { + ReconciliationIntervalOverride = TimeSpan.FromMilliseconds(100), + }), + NullLogger.Instance))); + + // Two ticks' worth of pulls on each node. + AwaitCondition(() => client.Calls.Count(c => c.Endpoint == NodeB) >= 2 + && client.Calls.Count(c => c.Endpoint == NodeA) >= 2, + TimeSpan.FromSeconds(10)); + + Assert.Contains(client.NodeBRow.EventId, inserted); + + var nodeACalls = client.Calls.Where(c => c.Endpoint == NodeA).ToList(); + Assert.All(nodeACalls, c => Assert.Equal(DateTime.MinValue, c.Since)); + + var nodeBCalls = client.Calls.Where(c => c.Endpoint == NodeB).ToList(); + Assert.Equal(DateTime.MinValue, nodeBCalls[0].Since); + Assert.Equal(OwedAt, nodeBCalls[1].Since); + Assert.Equal(client.NodeBRow.EventId.ToString(), nodeBCalls[1].AfterId); + + Watch(actor); + Sys.Stop(actor); + ExpectTerminated(actor); + } + + private sealed class RecordingInvoker : GrpcPullAuditEventsClient.IPullAuditEventsInvoker + { + public ConcurrentQueue Endpoints { get; } = new(); + + public Task InvokeAsync(string siteId, string endpoint, ProtoPullRequest request, CancellationToken ct) + { + Endpoints.Enqueue(endpoint); + throw new RpcException(new Grpc.Core.Status(StatusCode.Unavailable, "node down")); + } + } + + /// The per-node pull dials only the node it is given — no NodeA→NodeB failover. + /// A task that represents the asynchronous operation. + [Fact] + public async Task PullFromEndpoint_DialsOnlyThatNode_AndCollapsesAFaultToEmpty() + { + var invoker = new RecordingInvoker(); + var client = new GrpcPullAuditEventsClient( + new StaticEnumerator(new SiteEntry("site-a", NodeA, NodeB)), + invoker, + NullLogger.Instance); + + var response = await client.PullFromEndpointAsync("site-a", NodeA, DateTime.MinValue, null, 10, CancellationToken.None); + + Assert.Empty(response.Events); + Assert.Equal(new[] { NodeA }, invoker.Endpoints.ToArray()); + } +} diff --git a/tests/ZB.MOM.WW.ScadaBridge.AuditLog.Tests/Integration/ParkedReopenCombinedTelemetryTests.cs b/tests/ZB.MOM.WW.ScadaBridge.AuditLog.Tests/Integration/ParkedReopenCombinedTelemetryTests.cs new file mode 100644 index 00000000..fb7bbfe8 --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.AuditLog.Tests/Integration/ParkedReopenCombinedTelemetryTests.cs @@ -0,0 +1,137 @@ +using Akka.TestKit.Xunit2; +using Microsoft.EntityFrameworkCore; +using ZB.MOM.WW.Audit; +using ZB.MOM.WW.ScadaBridge.AuditLog.Tests.Integration.Infrastructure; +using ZB.MOM.WW.ScadaBridge.Commons.Entities.Audit; +using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services; +using ZB.MOM.WW.ScadaBridge.Commons.Messages.Integration; +using ZB.MOM.WW.ScadaBridge.Commons.Types; +using ZB.MOM.WW.ScadaBridge.Commons.Types.Audit; +using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums; +using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Entities; +using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests.Migrations; + +namespace ZB.MOM.WW.ScadaBridge.AuditLog.Tests.Integration; + +/// +/// SCA-1 end to end: Parked is re-openable. An operator Retry of a parked cached call +/// re-opens the site tracking row and the central SiteCalls row, so the retried delivery's +/// outcome lands on both; an operator Discard closes both as Discarded. Before the fix both +/// stayed Parked forever (site: later writes were no-ops on a terminal row; central: equal +/// terminal rank was immutable). +/// +public class ParkedReopenCombinedTelemetryTests : TestKit, IClassFixture +{ + private readonly MsSqlMigrationFixture _fixture; + + /// Initializes the test with the shared SQL Server migration fixture. + /// The shared MS SQL migration fixture. + public ParkedReopenCombinedTelemetryTests(MsSqlMigrationFixture fixture) => _fixture = fixture; + + private static string NewSiteId() => "test-sca1-" + Guid.NewGuid().ToString("N")[..8]; + + private static CachedCallTelemetry SubmitPacket(TrackedOperationId id, string siteId, DateTime nowUtc) => + new( + Audit: ScadaBridgeAuditEventFactory.Create( + eventId: Guid.NewGuid(), + occurredAtUtc: nowUtc, + channel: AuditChannel.ApiOutbound, + kind: AuditKind.CachedSubmit, + correlationId: id.Value, + sourceSiteId: siteId, + target: "ERP.GetOrder", + status: AuditStatus.Submitted), + Operational: new SiteCallOperational( + id, "ApiOutbound", "ERP.GetOrder", siteId, null, "Submitted", 0, null, null, + nowUtc, nowUtc, null)); + + private static CachedCallAttemptContext Ctx( + TrackedOperationId id, string siteId, CachedCallAttemptOutcome outcome, int retryCount, + string? lastError, DateTime createdUtc, DateTime occurredUtc) => + new(id, "ApiOutbound", "ERP.GetOrder", siteId, outcome, retryCount, lastError, null, + createdUtc, occurredUtc, null, "Plant.Pump42"); + + private static async Task ParkAsync(CombinedTelemetryHarness harness, TrackedOperationId id, string siteId, DateTime t0) + { + await harness.EmitSubmitAsync(SubmitPacket(id, siteId, t0)); + await harness.EmitAttemptAsync(Ctx(id, siteId, CachedCallAttemptOutcome.ParkedMaxRetries, 3, "HTTP 500", t0, t0.AddSeconds(30))); + Assert.Equal("Parked", (await harness.TrackingStore.GetStatusAsync(id))!.Status); + } + + /// Retry of a parked call, then a successful delivery: site and central both end Delivered. + /// A task that represents the asynchronous operation. + [SkippableFact] + public async Task ParkedThenOperatorRetryThenDelivered_SiteAndCentral_EndDelivered() + { + Skip.IfNot(_fixture.Available, _fixture.SkipReason); + + var siteId = NewSiteId(); + var id = TrackedOperationId.New(); + var t0 = new DateTime(2026, 12, 1, 9, 0, 0, DateTimeKind.Utc); + await using var harness = new CombinedTelemetryHarness(_fixture, this); + await ParkAsync(harness, id, siteId, t0); + + await harness.EmitAttemptAsync(Ctx(id, siteId, CachedCallAttemptOutcome.OperatorRetried, 0, null, t0, t0.AddMinutes(5))); + await harness.TrackingStore.FlushAsync(); + + var reopened = await harness.TrackingStore.GetStatusAsync(id); + Assert.Equal("Attempted", reopened!.Status); + Assert.Null(reopened.TerminalAtUtc); + + await using (var read = harness.CreateReadContext()) + { + var row = await read.Set().SingleAsync(s => s.TrackedOperationId == id); + Assert.Equal("Attempted", row.Status); + Assert.Null(row.TerminalAtUtc); + } + + await harness.EmitAttemptAsync(Ctx(id, siteId, CachedCallAttemptOutcome.Delivered, 1, null, t0, t0.AddMinutes(6))); + + var delivered = await harness.TrackingStore.GetStatusAsync(id); + Assert.Equal("Delivered", delivered!.Status); + Assert.NotNull(delivered.TerminalAtUtc); + + await using (var read = harness.CreateReadContext()) + { + var row = await read.Set().SingleAsync(s => s.TrackedOperationId == id); + Assert.Equal("Delivered", row.Status); + Assert.NotNull(row.TerminalAtUtc); + + // The re-queue is recorded as a second CachedSubmit (Submitted) row. + var submits = await read.Set() + .Where(e => e.SourceSiteId == siteId && e.Kind == AuditKind.CachedSubmit) + .CountAsync(); + Assert.Equal(2, submits); + } + } + + /// Discard of a parked call: site and central both end Discarded. + /// A task that represents the asynchronous operation. + [SkippableFact] + public async Task ParkedThenOperatorDiscard_SiteAndCentral_EndDiscarded() + { + Skip.IfNot(_fixture.Available, _fixture.SkipReason); + + var siteId = NewSiteId(); + var id = TrackedOperationId.New(); + var t0 = new DateTime(2026, 12, 1, 10, 0, 0, DateTimeKind.Utc); + await using var harness = new CombinedTelemetryHarness(_fixture, this); + await ParkAsync(harness, id, siteId, t0); + + await harness.EmitAttemptAsync(Ctx(id, siteId, CachedCallAttemptOutcome.OperatorDiscarded, 3, "Discarded by operator", t0, t0.AddMinutes(5))); + + var site = await harness.TrackingStore.GetStatusAsync(id); + Assert.Equal("Discarded", site!.Status); + Assert.NotNull(site.TerminalAtUtc); + + await using var read = harness.CreateReadContext(); + var row = await read.Set().SingleAsync(s => s.TrackedOperationId == id); + Assert.Equal("Discarded", row.Status); + + var resolves = await read.Set() + .Where(e => e.SourceSiteId == siteId && e.Kind == AuditKind.CachedResolve) + .Select(e => e.Status) + .ToListAsync(); + Assert.Contains(AuditStatus.Discarded, resolves); + } +} diff --git a/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/CentralCommunicationActorTests.cs b/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/CentralCommunicationActorTests.cs index 44ea3f0f..2c7cb14a 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/CentralCommunicationActorTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/CentralCommunicationActorTests.cs @@ -65,10 +65,14 @@ public class CentralCommunicationActorTests : TestKit var centralActor = Sys.ActorOf( Props.Create(() => new CentralCommunicationActor(sp, transport))); - var timestamp = DateTimeOffset.UtcNow; - centralActor.Tell(new HeartbeatMessage("site1", "host1", true, timestamp)); + // COMM-4: the site stamps its own (here: 30 min fast) clock, but liveness is keyed on + // central's receive time. + var siteStamp = DateTimeOffset.UtcNow.AddMinutes(30); + var before = DateTimeOffset.UtcNow; + centralActor.Tell(new HeartbeatMessage("site1", "host1", true, siteStamp)); - AwaitAssert(() => aggregator.Received(1).MarkHeartbeat("site1", timestamp)); + AwaitAssert(() => aggregator.Received(1).MarkHeartbeat("site1", + Arg.Is(t => t >= before && t <= DateTimeOffset.UtcNow))); } /// Verifies that a replicated heartbeat marks the local aggregator without being rebroadcast. @@ -93,10 +97,13 @@ public class CentralCommunicationActorTests : TestKit var centralActor = Sys.ActorOf( Props.Create(() => new CentralCommunicationActor(sp, transport))); - var ts = DateTimeOffset.UtcNow; - centralActor.Tell(new SiteHeartbeatReplica(new HeartbeatMessage("site-1", "host-a", true, ts))); + var before = DateTimeOffset.UtcNow; + centralActor.Tell(new SiteHeartbeatReplica( + new HeartbeatMessage("site-1", "host-a", true, before.AddMinutes(-30)))); - AwaitAssert(() => aggregator.Received(1).MarkHeartbeat("site-1", ts)); + // Keyed on this node's receive time, not the site stamp (COMM-4). + AwaitAssert(() => aggregator.Received(1).MarkHeartbeat("site-1", + Arg.Is(t => t >= before && t <= DateTimeOffset.UtcNow))); } /// Verifies that a failure loading site addresses is logged rather than silently swallowed. diff --git a/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/DebugStreamServiceTests.cs b/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/DebugStreamServiceTests.cs index 14b31bab..b5e38a5c 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/DebugStreamServiceTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/DebugStreamServiceTests.cs @@ -224,6 +224,140 @@ public class DebugStreamServiceTests : TestKit ExpectTerminated(bridgeActor, TimeSpan.FromSeconds(3)); } + // --- COMM-3 / COMM-7 --- + + private (DebugStreamService Service, Akka.TestKit.TestProbe CommProbe, ServiceProvider Provider, IDisposable Factory) NewMockedService() + { + var instance = new Instance("Site1.Pump01") { Id = 7, SiteId = 3 }; + var site = new Site("Site One", "site-1") + { + Id = 3, + GrpcNodeAAddress = "http://localhost:5100", + GrpcNodeBAddress = "http://localhost:5200" + }; + var instanceRepo = Substitute.For(); + instanceRepo.GetInstanceByIdAsync(7, Arg.Any()).Returns(instance); + var siteRepo = Substitute.For(); + siteRepo.GetSiteByIdAsync(3, Arg.Any()).Returns(site); + var services = new ServiceCollection(); + services.AddScoped(_ => instanceRepo); + services.AddScoped(_ => siteRepo); + var provider = services.BuildServiceProvider(); + + var commProbe = CreateTestProbe(); + var commService = new CommunicationService( + Options.Create(new CommunicationOptions()), + NullLogger.Instance); + commService.SetCommunicationActor(commProbe.Ref); + + var grpcFactory = new Grpc.MockSiteStreamGrpcClientFactory(new Grpc.MockSiteStreamGrpcClient()); + var service = new DebugStreamService( + commService, provider, grpcFactory, NullLogger.Instance); + service.SetActorSystem(Sys); + return (service, commProbe, provider, grpcFactory); + } + + private static ZB.MOM.WW.ScadaBridge.Commons.Messages.Streaming.AttributeValueChanged Attr( + string name, object? value, DateTimeOffset ts) => + new("Site1.Pump01", "", name, value, "Good", ts); + + /// + /// COMM-3 regression: a gap-window event (captured while the snapshot was being built, newer + /// than the snapshot row) must not reach the consumer ahead of the snapshot. It is folded into + /// the snapshot StartStreamAsync returns, and only later events are delivered to onEvent. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task Comm3_GapWindowEvent_IsFoldedIntoTheSnapshot_NotDeliveredAheadOfIt() + { + var (service, commProbe, provider, factory) = NewMockedService(); + using var _p = provider; + using var _f = factory; + using var _s = service; + + var delivered = new System.Collections.Concurrent.ConcurrentQueue(); + var t0 = DateTimeOffset.UtcNow; + var startTask = service.StartStreamAsync(7, onEvent: e => delivered.Enqueue(e), onTerminated: () => { }); + + commProbe.ExpectMsg(TimeSpan.FromSeconds(5)); + var bridge = commProbe.LastSender; + + // Arrives on the stream BEFORE the snapshot (stream-first), but is newer than the row. + bridge.Tell(Attr("Speed", 42.0, t0.AddSeconds(2))); + bridge.Tell(new ZB.MOM.WW.ScadaBridge.Commons.Messages.DebugView.DebugViewSnapshot( + "Site1.Pump01", + new List { Attr("Speed", 10.0, t0.AddSeconds(1)) }, + new List(), + t0.AddSeconds(1))); + + var session = await startTask; + + var speed = Assert.Single(session.InitialSnapshot.AttributeValues); + Assert.Equal(42.0, speed.Value); + Assert.Empty(delivered); + + // After the hand-over, events pass straight through. + bridge.Tell(Attr("Speed", 43.0, t0.AddSeconds(3))); + AwaitCondition(() => !delivered.IsEmpty, TimeSpan.FromSeconds(3)); + var live = Assert.IsType(Assert.Single(delivered)); + Assert.Equal(43.0, live.Value); + + service.StopStream(session.SessionId); + } + + /// COMM-3: the fold keeps a newer snapshot row over an older event and appends unseen entities. + [Fact] + public void Comm3_FoldIntoSnapshot_RespectsTimestamps_AndAppendsNewEntities() + { + var t0 = DateTimeOffset.UtcNow; + var snapshot = new ZB.MOM.WW.ScadaBridge.Commons.Messages.DebugView.DebugViewSnapshot( + "Site1.Pump01", + new List { Attr("A", 1, t0.AddSeconds(5)) }, + new List(), + t0); + + var folded = DebugStreamService.FoldIntoSnapshot(snapshot, new object[] + { + Attr("A", 0, t0.AddSeconds(1)), // older than the row: ignored + Attr("B", 2, t0.AddSeconds(2)), // not in the snapshot: appended + new ZB.MOM.WW.ScadaBridge.Commons.Messages.Streaming.AlarmStateChanged( + "Site1.Pump01", "Hi", ZB.MOM.WW.ScadaBridge.Commons.Types.Enums.AlarmState.Active, 500, t0.AddSeconds(3)), + }); + + Assert.Equal(1, folded.AttributeValues.Single(a => a.AttributeName == "A").Value); + Assert.Equal(2, folded.AttributeValues.Single(a => a.AttributeName == "B").Value); + Assert.Single(folded.AlarmStates); + } + + /// + /// COMM-7 regression: the command transport's fail-fast Status.Failure reply to the + /// snapshot request ends the start immediately with the real cause, instead of the 30 s + /// timeout, and tears the bridge actor down. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task Comm7_SnapshotRequestFailure_FailsStartFastWithTheCause() + { + var (service, commProbe, provider, factory) = NewMockedService(); + using var _p = provider; + using var _f = factory; + using var _s = service; + + var terminated = false; + var startTask = service.StartStreamAsync(7, onEvent: _ => { }, onTerminated: () => terminated = true); + commProbe.ExpectMsg(TimeSpan.FromSeconds(5)); + var bridge = commProbe.LastSender; + Watch(bridge); + + bridge.Tell(new Status.Failure(new InvalidOperationException("no gRPC channel for site site-1"))); + + var ex = await Assert.ThrowsAsync(() => startTask.WaitAsync(TimeSpan.FromSeconds(5))); + Assert.Contains("no gRPC channel for site site-1", ex.Message); + Assert.True(terminated); + ExpectTerminated(bridge, TimeSpan.FromSeconds(3)); + Assert.Equal(0, service.SessionCount); + } + // --- single-endpoint sites --- /// Verifies that a single-endpoint site uses its sole address for both node slots. diff --git a/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/Grpc/GrpcConnectTimeoutTests.cs b/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/Grpc/GrpcConnectTimeoutTests.cs new file mode 100644 index 00000000..e8405c11 --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/Grpc/GrpcConnectTimeoutTests.cs @@ -0,0 +1,168 @@ +using Grpc.Core; +using Grpc.Net.Client; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using ZB.MOM.WW.ScadaBridge.Communication.Grpc; + +namespace ZB.MOM.WW.ScadaBridge.Communication.Tests.Grpc; + +/// +/// COMM-5: a black-holed peer (SYNs silently dropped) must surface as a failover-worthy error +/// well inside a call deadline, not as a DeadlineExceeded that never moves the channel pair. +/// The live cases dial 192.0.2.1 (TEST-NET-1, never routed). On a host with a default +/// route the SYN is dropped (the black-hole shape); on a host without one the connect fails +/// fast with a socket error instead — every assertion here holds for either, since both are +/// failover-worthy. +/// +public sealed class GrpcConnectTimeoutTests +{ + private const string BlackHole = "http://192.0.2.1:8083"; + + /// A ConnectTimeout firing on the subchannel is a provably-unsent connect failure. + [Fact] + public void SubchannelConnectTimeout_IsNeverSent() + { + var ex = new RpcException(new Status(StatusCode.Unavailable, GrpcRetrySafety.SubchannelConnectFailureDetail, + new TimeoutException("A connection could not be established within the configured ConnectTimeout.", + new OperationCanceledException()))); + + Assert.True(GrpcRetrySafety.WasNeverSent(ex)); + Assert.True(GrpcRetrySafety.ProvablyNotApplied(ex)); + } + + /// The option defaults to 5 s and is validated positive. + [Fact] + public void GrpcConnectTimeout_DefaultsToFiveSeconds_AndMustBePositive() + { + Assert.Equal(TimeSpan.FromSeconds(5), new CommunicationOptions().GrpcConnectTimeout); + var result = new CommunicationOptionsValidator().Validate(null, new CommunicationOptions { GrpcConnectTimeout = TimeSpan.Zero }); + Assert.True(result.Failed); + Assert.Contains("GrpcConnectTimeout", result.FailureMessage); + } + + /// + /// With the connect timeout shorter than the deadline, a black-holed peer fails Unavailable + /// and provably unsent — so the pair fails over even for a mutation. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task BlackHoledPeer_WithConnectTimeout_FailsUnavailableAndNeverSent() + { + using var channel = GrpcChannel.ForAddress(BlackHole, new GrpcChannelOptions + { + HttpHandler = new SocketsHttpHandler { ConnectTimeout = TimeSpan.FromMilliseconds(500) }, + }); + var client = new SiteStreamService.SiteStreamServiceClient(channel); + + var ex = await Assert.ThrowsAsync(() => client.PullAuditEventsAsync( + new PullAuditEventsRequest(), deadline: DateTime.UtcNow.AddSeconds(10)).ResponseAsync); + + Assert.Equal(StatusCode.Unavailable, ex.StatusCode); + Assert.True(GrpcRetrySafety.WasNeverSent(ex), $"expected a never-sent connect failure, got: {ex.Status.DebugException}"); + } + + /// + /// With the deadline shorter than the connect timeout, the call ends DeadlineExceeded while the + /// channel is still connecting — recognised as a connect-phase deadline. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task BlackHoledPeer_DeadlineBeforeConnectTimeout_IsAConnectPhaseDeadline() + { + using var channel = GrpcChannel.ForAddress(BlackHole, new GrpcChannelOptions + { + HttpHandler = new SocketsHttpHandler { ConnectTimeout = TimeSpan.FromSeconds(30) }, + }); + var client = new SiteStreamService.SiteStreamServiceClient(channel); + + var ex = await Assert.ThrowsAsync(() => client.PullAuditEventsAsync( + new PullAuditEventsRequest(), deadline: DateTime.UtcNow.AddMilliseconds(400)).ResponseAsync); + + if (ex.StatusCode == StatusCode.DeadlineExceeded) + Assert.True(GrpcRetrySafety.IsConnectPhaseDeadline(ex, channel)); + else + Assert.True(GrpcRetrySafety.WasNeverSent(ex), "no default route: the connect fails fast instead"); + } + + /// A deadline on a non-connecting state (a plain server-side deadline) is not connect-phase. + [Fact] + public void NonDeadlineStatuses_AreNotConnectPhaseDeadlines() + { + using var channel = GrpcChannel.ForAddress(BlackHole); + Assert.False(GrpcRetrySafety.IsConnectPhaseDeadline( + new RpcException(new Status(StatusCode.Unavailable, "x")), channel)); + // A fresh channel that never attempted a connection is Idle, not connecting. + Assert.False(GrpcRetrySafety.IsConnectPhaseDeadline( + new RpcException(new Status(StatusCode.DeadlineExceeded, "")), channel)); + } + + /// + /// SitePairChannelProvider: a connect-phase DeadlineExceeded on node A moves the pair to node B + /// (before COMM-5 only Unavailable did, so a black-holed NodeA kept every command). + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task SitePair_ConnectPhaseDeadlineOnNodeA_FlipsToNodeB() + { + using var provider = new SitePairChannelProvider( + new NoKeyProvider(), + Options.Create(new CommunicationOptions()), + NullLogger.Instance, + handlerFactory: _ => new SocketsHttpHandler { ConnectTimeout = TimeSpan.FromSeconds(30) }, + reachabilityProbe: (_, _) => Task.FromResult(false)); + provider.UpdateSite("site-1", BlackHole, "http://localhost:15399"); + + var ex = await Assert.ThrowsAsync(() => provider.ExecuteAsync("site-1", + (channel, ct) => new SiteStreamService.SiteStreamServiceClient(channel) + .PullAuditEventsAsync(new PullAuditEventsRequest(), deadline: DateTime.UtcNow.AddMilliseconds(400), + cancellationToken: ct).ResponseAsync, + CancellationToken.None, retrySafe: false)); + + // Either shape moves the pair: a connect-phase deadline (black hole) or a fast connect + // failure (no default route). + Assert.True(ex.StatusCode is StatusCode.DeadlineExceeded or StatusCode.Unavailable or StatusCode.Aborted, + $"unexpected {ex.StatusCode}"); + Assert.False(provider.IsOnPreferredNode("site-1")); + } + + /// + /// GrpcCentralTransport: a heartbeat that times out against a black-holed central-a moves the + /// pair to central-b (before COMM-5 a quiet site whose only traffic is the heartbeat never left + /// a dead central-a and read Offline at central). + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task CentralTransport_HeartbeatConnectPhaseDeadline_FlipsToTheOtherCentral() + { + var options = new CommunicationOptions { HealthReportTimeout = TimeSpan.FromMilliseconds(400) }; + using var provider = new CentralChannelProvider( + new[] { BlackHole, "http://localhost:15397" }, + new NoKeyProvider(), + "site-1", + options, + NullLogger.Instance, + handlerFactory: _ => new SocketsHttpHandler { ConnectTimeout = TimeSpan.FromSeconds(30) }, + backoffBase: TimeSpan.FromMinutes(10), + backoffCap: TimeSpan.FromMinutes(10)); + var transport = new GrpcCentralTransport(provider, options, NullLogger.Instance); + + transport.SendHeartbeat( + new ZB.MOM.WW.ScadaBridge.Commons.Messages.Health.HeartbeatMessage("site-1", "node-a", true, DateTimeOffset.UtcNow), + Akka.Actor.ActorRefs.Nobody); + + var deadline = DateTime.UtcNow.AddSeconds(10); + while (provider.CurrentIndex == 0 && DateTime.UtcNow < deadline) + await Task.Delay(50); + + Assert.Equal(1, provider.CurrentIndex); + } + + private sealed class NoKeyProvider : ISitePskProvider + { + /// + public ValueTask GetAsync(string siteId, CancellationToken ct) => new("k"); + /// + public void Invalidate(string siteId) { } + } +} diff --git a/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/Grpc/SiteAlarmAggregatorActorTests.cs b/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/Grpc/SiteAlarmAggregatorActorTests.cs index d6b743ef..29ec66da 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/Grpc/SiteAlarmAggregatorActorTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/Grpc/SiteAlarmAggregatorActorTests.cs @@ -932,13 +932,20 @@ public class SiteAlarmAggregatorActorTests : TestKit /// this suite can demonstrate. The deadline is therefore a self-healing guard rather than /// a fix for a measured production incident. /// + /// + /// COMM-5 (2026-12) changed what the deadline does: it is now a stream ERROR (flip node, + /// spend a retry) rather than only a release of the in-flight guard, because a black-holed + /// node never resolves the attempt either, and reopening on the same node never left it. If + /// the stalled attempt was in fact a slow-headers stream on the active node, the flip lands on + /// the standby, which refuses at once (COMM-2), and the next error flips back. + /// /// [Fact] - public void OpenAttemptThatNeverResolves_ReleasesTheInFlightGuard_SoTheTickCanReopen() + public void OpenAttemptThatNeverResolves_IsAStreamError_FlipsToTheOtherNode() { - // 250 ms deadline; the reconcile timer is parked 10 minutes away so the ONLY tick is - // the one this test issues by hand. - var (actor, seed, sink, factory) = CreateActor( + // 250 ms deadline; the reconcile timer is parked 10 minutes away so nothing but the + // open deadline can move the stream. + var (_, seed, sink, factory) = CreateActor( reconcileInterval: TimeSpan.FromMinutes(10), autoConnect: false, openAttemptTimeout: TimeSpan.FromMilliseconds(250)); @@ -947,18 +954,18 @@ public class SiteAlarmAggregatorActorTests : TestKit AwaitCondition(() => factory.ClientFor(GrpcNodeA).Subs.Count == 1, TimeSpan.FromSeconds(3)); seed.CompleteNext(); - // The stream never reports connected, never faults, never completes — the quiet-site - // header-timeout shape. Liveness is (correctly) false the whole time. - AssertHoldsFor(TimeSpan.FromMilliseconds(300), - (() => !sink.StreamLive, "a stream that never connected must never read as live")); + // The stream never reports connected, never faults, never completes — the black-holed + // node / header-timeout shape. Liveness is (correctly) false the whole time. + Assert.False(sink.StreamLive, "a stream that never connected must never read as live"); - // Pre-fix this tick found _openInFlight still true and skipped the reopen, leaving - // node A on one subscription forever. Post-fix the deadline has released the flag. - actor.Tell(new RunReconcile()); - AwaitCondition(() => factory.ClientFor(GrpcNodeA).Subs.Count == 2, TimeSpan.FromSeconds(5)); + // COMM-5: the open deadline is a stream error — the aggregator flips to node B on its + // own (pre-fix it only released the in-flight guard and the next reconcile tick reopened + // on the SAME node, so a black-holed node A was never left). + AwaitCondition(() => factory.ClientFor(GrpcNodeB).Subs.Count == 1, TimeSpan.FromSeconds(5)); + Assert.Single(factory.ClientFor(GrpcNodeA).Subs); // And the reopen is a real one: its connect brings the feed up and earns a re-seed. - factory.ClientFor(GrpcNodeA).Subs[1].OnConnected!(); + factory.ClientFor(GrpcNodeB).Subs[0].OnConnected!(); AwaitCondition(() => seed.CallCount == 2, TimeSpan.FromSeconds(3)); seed.CompleteNext(); AwaitCondition(() => sink.StreamLive, TimeSpan.FromSeconds(3)); diff --git a/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/Grpc/SiteStreamGrpcServerTests.cs b/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/Grpc/SiteStreamGrpcServerTests.cs index daca7c56..1e685bec 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/Grpc/SiteStreamGrpcServerTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/Grpc/SiteStreamGrpcServerTests.cs @@ -158,6 +158,116 @@ public class SiteStreamGrpcServerTests : TestKit Assert.Equal(0, server.ActiveStreamCount); } + // --- Active-node gate (COMM-2) --- + + /// + /// COMM-2 regression: a standby site node's stream hub carries no events, so it must refuse + /// both subscription RPCs with Unavailable (which central's clients treat as a stream error + /// and flip to the other node) instead of handing back a live-looking silent stream. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task Comm2_StandbyNode_RefusesSubscriptionsWithUnavailable() + { + using var server = CreateServer(); + server.SetReady(Sys, isActiveNode: () => false, activeRoleCheckInterval: TimeSpan.FromHours(1)); + + var writer = Substitute.For>(); + var instanceEx = await Assert.ThrowsAsync( + () => server.SubscribeInstance(MakeRequest("corr-standby-1"), writer, CreateMockContext())); + Assert.Equal(StatusCode.Unavailable, instanceEx.StatusCode); + Assert.Contains("active node", instanceEx.Status.Detail, StringComparison.OrdinalIgnoreCase); + + var siteEx = await Assert.ThrowsAsync( + () => server.SubscribeSite(new SiteStreamRequest { CorrelationId = "corr-standby-2" }, writer, CreateMockContext())); + Assert.Equal(StatusCode.Unavailable, siteEx.StatusCode); + + Assert.Equal(0, server.ActiveStreamCount); + _subscriber.DidNotReceive().Subscribe(Arg.Any(), Arg.Any()); + _subscriber.DidNotReceive().SubscribeSiteAlarms(Arg.Any()); + } + + /// COMM-2: a gate that throws (cluster going away) refuses rather than accepts. + /// A task that represents the asynchronous operation. + [Fact] + public async Task Comm2_GateThrows_RefusesSubscription() + { + using var server = CreateServer(); + server.SetReady(Sys, isActiveNode: () => throw new InvalidOperationException("cluster gone"), + activeRoleCheckInterval: TimeSpan.FromHours(1)); + + var ex = await Assert.ThrowsAsync(() => server.SubscribeInstance( + MakeRequest("corr-throws"), Substitute.For>(), CreateMockContext())); + Assert.Equal(StatusCode.Unavailable, ex.StatusCode); + } + + /// + /// COMM-2 regression: when the node loses the active role, the watchdog ends every open + /// stream with Unavailable (NOT a graceful OK — central does not flip nodes on OK), and the + /// server-side state is cleaned up. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task Comm2_LosingActiveRole_EndsOpenStreamsWithUnavailable() + { + var active = true; + using var server = CreateServer(); + server.SetReady(Sys, isActiveNode: () => Volatile.Read(ref active), activeRoleCheckInterval: TimeSpan.FromHours(1)); + + var writer = Substitute.For>(); + var streamTask = Task.Run(() => server.SubscribeSite( + new SiteStreamRequest { CorrelationId = "corr-active-1" }, writer, CreateMockContext())); + await WaitForConditionAsync(() => server.ActiveStreamCount == 1); + + // Still active: the watchdog leaves the stream alone. + Assert.Equal(0, server.EndStreamsIfNotActive()); + Assert.Equal(1, server.ActiveStreamCount); + + Volatile.Write(ref active, false); + Assert.Equal(1, server.EndStreamsIfNotActive()); + + var ex = await Assert.ThrowsAsync(() => streamTask); + Assert.Equal(StatusCode.Unavailable, ex.StatusCode); + Assert.Equal(0, server.ActiveStreamCount); + _subscriber.Received().RemoveSubscriber(Arg.Any()); + } + + /// COMM-2: the watchdog timer itself (not just a direct call) ends the stream. + /// A task that represents the asynchronous operation. + [Fact] + public async Task Comm2_Watchdog_EndsStreamOnItsOwnTick() + { + var active = true; + using var server = CreateServer(); + server.SetReady(Sys, isActiveNode: () => Volatile.Read(ref active), activeRoleCheckInterval: TimeSpan.FromMilliseconds(50)); + + var streamTask = Task.Run(() => server.SubscribeInstance( + MakeRequest("corr-watchdog"), Substitute.For>(), CreateMockContext())); + await WaitForConditionAsync(() => server.ActiveStreamCount == 1); + + Volatile.Write(ref active, false); + var ex = await Assert.ThrowsAsync(() => streamTask.WaitAsync(TimeSpan.FromSeconds(10))); + Assert.Equal(StatusCode.Unavailable, ex.StatusCode); + } + + /// COMM-2: a client cancel on an active node still ends quietly (no Unavailable). + /// A task that represents the asynchronous operation. + [Fact] + public async Task Comm2_ActiveNode_ClientCancel_EndsWithoutError() + { + using var server = CreateServer(); + server.SetReady(Sys, isActiveNode: () => true, activeRoleCheckInterval: TimeSpan.FromHours(1)); + + var cts = new CancellationTokenSource(); + var streamTask = Task.Run(() => server.SubscribeInstance( + MakeRequest("corr-active-cancel"), Substitute.For>(), CreateMockContext(cts.Token))); + await WaitForConditionAsync(() => server.ActiveStreamCount == 1); + + cts.Cancel(); + await streamTask; + Assert.Equal(0, server.ActiveStreamCount); + } + // --- Site-shutdown ordering --- /// Verifies that cancelling all streams cancels the active streams and refuses new ones. diff --git a/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/HealthReportAckTests.cs b/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/HealthReportAckTests.cs index a67b4b18..a3028da7 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/HealthReportAckTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/HealthReportAckTests.cs @@ -51,6 +51,7 @@ public class HealthReportAckTests : TestKit var mockRepo = Substitute.For(); mockRepo.GetAllSitesAsync(Arg.Any()).Returns(new List()); var aggregator = Substitute.For(); + aggregator.ProcessReport(Arg.Any()).Returns(true); var services = new ServiceCollection(); services.AddScoped(_ => mockRepo); @@ -66,4 +67,31 @@ public class HealthReportAckTests : TestKit Assert.Equal(3, ack.SequenceNumber); AwaitAssert(() => aggregator.Received().ProcessReport(Arg.Is(r => r.SequenceNumber == 3))); } + + /// + /// COMM-1 regression: a report the aggregator rejects as stale is nacked (Accepted=false with an + /// error), so the site's transport throws and the drop is visible instead of being acked as accepted. + /// + [Fact] + public void CentralCommunicationActor_OnStaleReport_NacksWithError() + { + var mockRepo = Substitute.For(); + mockRepo.GetAllSitesAsync(Arg.Any()).Returns(new List()); + var aggregator = Substitute.For(); + aggregator.ProcessReport(Arg.Any()).Returns(false); + + var services = new ServiceCollection(); + services.AddScoped(_ => mockRepo); + services.AddSingleton(aggregator); + var sp = services.BuildServiceProvider(); + + var transport = Substitute.For(); + var actor = Sys.ActorOf(Props.Create(() => new CentralCommunicationActor(sp, transport))); + + actor.Tell(SampleReport(seq: 4)); + var ack = ExpectMsg(); + Assert.False(ack.Accepted); + Assert.Equal(4, ack.SequenceNumber); + Assert.False(string.IsNullOrEmpty(ack.Error)); + } } diff --git a/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/SyntheticHeartbeatTests.cs b/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/SyntheticHeartbeatTests.cs index 3efceaac..30d2222c 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/SyntheticHeartbeatTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/SyntheticHeartbeatTests.cs @@ -57,7 +57,8 @@ public class SyntheticHeartbeatTests : TestKit actor.Tell(new HeartbeatMessage("site-1", "node-a", IsActive: true, Timestamp: T0)); - AwaitAssert(() => aggregator.Received(1).MarkHeartbeat("site-1", T0)); + // Marked with central's receive time, not the site stamp T0 (COMM-4). + AwaitAssert(() => aggregator.Received(1).MarkHeartbeat("site-1", Arg.Is(t => t > T0))); } /// Verifies that a replicated synthetic heartbeat is also skipped. diff --git a/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/AuditLogRepositoryTests.cs b/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/AuditLogRepositoryTests.cs index ea7e59b3..a99e1fb7 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/AuditLogRepositoryTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/AuditLogRepositoryTests.cs @@ -1209,6 +1209,54 @@ public class AuditLogRepositoryTests : IClassFixture Assert.DoesNotContain(new DateTime(2026, 8, 1, 0, 0, 0, DateTimeKind.Utc), boundaries); } + /// + /// AUD-6 regression: rows stamped before the FIRST partition boundary (partition 1 — a site + /// with a reset clock, a back-dated row) used to be invisible to the purge enumeration, so + /// they outlived retention and the archive forever. Partition 1 is now offered as the month + /// start of its newest row, and switching that value out purges exactly partition 1. + /// + /// A task that represents the asynchronous operation. + [SkippableFact] + public async Task GetPartitionBoundariesOlderThanAsync_IncludesPartitionOne_AndItSwitchesOut() + { + Skip.IfNot(_fixture.Available, _fixture.SkipReason); + + var siteId = NewSiteId(); + await using var context = CreateContext(); + var repo = new AuditLogRepository(context); + + // Two rows before the first boundary (2026-01-01) and one inside a regular partition. + await repo.InsertIfNotExistsAsync(NewEvent(siteId, occurredAtUtc: new DateTime(2019, 3, 10, 0, 0, 0, DateTimeKind.Utc))); + await repo.InsertIfNotExistsAsync(NewEvent(siteId, occurredAtUtc: new DateTime(2019, 5, 15, 12, 0, 0, DateTimeKind.Utc))); + var survivor = NewEvent(siteId, occurredAtUtc: new DateTime(2026, 7, 12, 0, 0, 0, DateTimeKind.Utc)); + await repo.InsertIfNotExistsAsync(survivor); + + var boundaries = await repo.GetPartitionBoundariesOlderThanAsync(new DateTime(2026, 7, 1, 0, 0, 0, DateTimeKind.Utc)); + + // Partition 1 is offered as the month start of its newest row. + var partitionOne = new DateTime(2019, 5, 1, 0, 0, 0, DateTimeKind.Utc); + Assert.Contains(partitionOne, boundaries); + Assert.Equal(partitionOne, boundaries[0]); + + var purged = await repo.SwitchOutPartitionAsync(partitionOne); + Assert.True(purged >= 2, $"expected the two partition-1 rows to be purged, got {purged}"); + + await using var read = CreateContext(); + var left = await read.Database + .SqlQueryRaw("SELECT COUNT(*) AS Value FROM dbo.AuditLog WHERE OccurredAtUtc < '2026-01-01'") + .SingleAsync(); + Assert.Equal(0, left); + var survivorId = survivor.EventId; + var survived = await read.Database + .SqlQuery($"SELECT COUNT(*) AS Value FROM dbo.AuditLog WHERE EventId = {survivorId}") + .SingleAsync(); + Assert.Equal(1, survived); + + // Nothing is left in partition 1, so it is no longer offered. + var after = await repo.GetPartitionBoundariesOlderThanAsync(new DateTime(2026, 7, 1, 0, 0, 0, DateTimeKind.Utc)); + Assert.DoesNotContain(after, b => b < new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc)); + } + // ------------------------------------------------------------------------ // GetKpiSnapshotAsync — Health-dashboard Audit KPI tiles // ------------------------------------------------------------------------ diff --git a/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/KpiHistoryRepositoryTests.cs b/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/KpiHistoryRepositoryTests.cs index 39c1aa97..0cf950be 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/KpiHistoryRepositoryTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/KpiHistoryRepositoryTests.cs @@ -487,6 +487,40 @@ public class KpiHistoryRepositoryTests Assert.Empty(ctx.ChangeTracker.Entries()); } + /// + /// KPI-1: the backfill's own watermark is absent until a slice advances it, then moves only + /// forward, and a contiguity-guarded advance neither creates it nor jumps a gap. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task RollupBackfillWatermark_IsMonotonic_AndContiguityGuarded() + { + await using var ctx = NewContext(); + var repo = new KpiHistoryRepository(ctx); + + Assert.Null(await repo.GetRollupBackfillWatermarkAsync()); + + // A contiguity-guarded advance (the periodic fold's) never creates the marker. + await repo.AdvanceRollupBackfillWatermarkAsync(Base.AddHours(5), onlyIfReachedUtc: Base.AddHours(2)); + Assert.Null(await repo.GetRollupBackfillWatermarkAsync()); + + // A backfill slice creates and advances it. + await repo.AdvanceRollupBackfillWatermarkAsync(Base.AddHours(24)); + Assert.Equal(Base.AddHours(24), await repo.GetRollupBackfillWatermarkAsync()); + + // Never backwards. + await repo.AdvanceRollupBackfillWatermarkAsync(Base.AddHours(10)); + Assert.Equal(Base.AddHours(24), await repo.GetRollupBackfillWatermarkAsync()); + + // A periodic fold whose window starts past the marker (a gap) does not move it… + await repo.AdvanceRollupBackfillWatermarkAsync(Base.AddHours(30), onlyIfReachedUtc: Base.AddHours(27)); + Assert.Equal(Base.AddHours(24), await repo.GetRollupBackfillWatermarkAsync()); + + // …one that the marker reaches does. + await repo.AdvanceRollupBackfillWatermarkAsync(Base.AddHours(26), onlyIfReachedUtc: Base.AddHours(23)); + Assert.Equal(Base.AddHours(26), await repo.GetRollupBackfillWatermarkAsync()); + } + /// Verifies that the latest rollup hour is null when no rollups exist. /// A task that represents the asynchronous operation. [Fact] diff --git a/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/SiteCallAuditRepositoryTests.cs b/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/SiteCallAuditRepositoryTests.cs index 49db9c26..586ab84b 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/SiteCallAuditRepositoryTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/SiteCallAuditRepositoryTests.cs @@ -372,33 +372,111 @@ public class SiteCallAuditRepositoryTests : IClassFixture Assert.Equal(0, row.RetryCount); } - /// Verifies that one terminal status cannot overwrite another terminal status. + /// + /// Verifies that one terminal status cannot overwrite another terminal status — except + /// Parked, which is re-openable (SCA-1; see the Parked tests below). + /// /// A task that represents the asynchronous operation. [SkippableFact] public async Task UpsertAsync_TerminalOverTerminal_IsNoOp() { Skip.IfNot(_fixture.Available, _fixture.SkipReason); - // Terminal statuses share rank 3 and are mutually - // exclusive — Delivered cannot overwrite Parked. Note that the - // Delivered packet carries a STRICTLY-NEWER UpdatedAtUtc, yet the row - // stays Parked — the same-rank freshness tiebreaker is scoped to - // NON-terminal ranks (< 3), so terminal immutability is preserved. + // Delivered/Failed/Discarded share rank 3 and are mutually exclusive: a later + // Failed (STRICTLY-NEWER UpdatedAtUtc) cannot overwrite Delivered. The same-rank + // freshness tiebreaker is scoped to NON-terminal ranks (< 3). + var id = TrackedOperationId.New(); + var t0 = new DateTime(2026, 6, 1, 13, 0, 0, DateTimeKind.Utc); + await using var context = CreateContext(); + var repo = new SiteCallAuditRepository(context); + + await repo.UpsertAsync(NewRow(id, status: "Delivered", retryCount: 3, lastError: null, updatedAtUtc: t0, terminal: true, terminalAtUtc: t0)); + var afterDelivered = await repo.GetAsync(id); + + await repo.UpsertAsync(NewRow(id, status: "Failed", retryCount: 4, lastError: "late", updatedAtUtc: t0.AddMinutes(5), terminal: true, terminalAtUtc: t0.AddMinutes(5))); + await repo.UpsertAsync(NewRow(id, status: "Parked", retryCount: 4, lastError: "late", updatedAtUtc: t0.AddMinutes(6), terminal: true, terminalAtUtc: t0.AddMinutes(6))); + var after = await repo.GetAsync(id); + + Assert.NotNull(after); + Assert.Equal("Delivered", after!.Status); + Assert.Equal(afterDelivered!.UpdatedAtUtc, after.UpdatedAtUtc); + } + + /// + /// SCA-1 regression: an operator Retry of a Parked call re-opens it at the site, so a + /// NEWER Attempted and then Delivered must replace the Parked row (it used to stay Parked + /// until the 365-day purge). + /// + /// A task that represents the asynchronous operation. + [SkippableFact] + public async Task UpsertAsync_ParkedThenNewerAttemptedThenDelivered_Reopens() + { + Skip.IfNot(_fixture.Available, _fixture.SkipReason); + var id = TrackedOperationId.New(); var t0 = new DateTime(2026, 6, 1, 13, 0, 0, DateTimeKind.Utc); await using var context = CreateContext(); var repo = new SiteCallAuditRepository(context); await repo.UpsertAsync(NewRow(id, status: "Parked", retryCount: 3, lastError: "parked-reason", updatedAtUtc: t0, terminal: true, terminalAtUtc: t0)); - var afterPark = await repo.GetAsync(id); - await repo.UpsertAsync(NewRow(id, status: "Delivered", retryCount: 4, lastError: null, updatedAtUtc: t0.AddMinutes(5), terminal: true, terminalAtUtc: t0.AddMinutes(5))); - var afterDeliveredAttempt = await repo.GetAsync(id); + await repo.UpsertAsync(NewRow(id, status: "Attempted", retryCount: 0, lastError: null, updatedAtUtc: t0.AddMinutes(5))); + var reopened = await repo.GetAsync(id); + Assert.Equal("Attempted", reopened!.Status); + Assert.Null(reopened.TerminalAtUtc); + Assert.Null(reopened.LastError); - Assert.NotNull(afterDeliveredAttempt); - Assert.Equal("Parked", afterDeliveredAttempt!.Status); - Assert.Equal("parked-reason", afterDeliveredAttempt.LastError); - Assert.Equal(afterPark!.UpdatedAtUtc, afterDeliveredAttempt.UpdatedAtUtc); + await repo.UpsertAsync(NewRow(id, status: "Delivered", retryCount: 1, lastError: null, updatedAtUtc: t0.AddMinutes(6), terminal: true, terminalAtUtc: t0.AddMinutes(6))); + // Fresh context: the first GetAsync left the row tracked, and a raw-SQL upsert does + // not refresh a tracked entity. + await using var readContext = CreateContext(); + var delivered = await new SiteCallAuditRepository(readContext).GetAsync(id); + Assert.Equal("Delivered", delivered!.Status); + Assert.NotNull(delivered.TerminalAtUtc); + } + + /// SCA-1: an operator Discard of a Parked call (newer) closes it as Discarded. + /// A task that represents the asynchronous operation. + [SkippableFact] + public async Task UpsertAsync_ParkedThenNewerDiscarded_IsDiscarded() + { + Skip.IfNot(_fixture.Available, _fixture.SkipReason); + + var id = TrackedOperationId.New(); + var t0 = new DateTime(2026, 6, 1, 13, 0, 0, DateTimeKind.Utc); + await using var context = CreateContext(); + var repo = new SiteCallAuditRepository(context); + + await repo.UpsertAsync(NewRow(id, status: "Parked", retryCount: 3, lastError: "parked-reason", updatedAtUtc: t0, terminal: true, terminalAtUtc: t0)); + await repo.UpsertAsync(NewRow(id, status: "Discarded", retryCount: 3, lastError: "Discarded by operator", updatedAtUtc: t0.AddMinutes(5), terminal: true, terminalAtUtc: t0.AddMinutes(5))); + + var row = await repo.GetAsync(id); + Assert.Equal("Discarded", row!.Status); + } + + /// + /// SCA-1: Parked is re-opened only by a STRICTLY NEWER Attempted/Delivered/Failed/Discarded — a + /// stale pre-park packet replayed late, or a newer Submitted/Forwarded, leaves it Parked. + /// + /// A task that represents the asynchronous operation. + [SkippableFact] + public async Task UpsertAsync_Parked_StaleOrLowRankPacket_StaysParked() + { + Skip.IfNot(_fixture.Available, _fixture.SkipReason); + + var id = TrackedOperationId.New(); + var t0 = new DateTime(2026, 6, 1, 13, 0, 0, DateTimeKind.Utc); + await using var context = CreateContext(); + var repo = new SiteCallAuditRepository(context); + + await repo.UpsertAsync(NewRow(id, status: "Parked", retryCount: 3, lastError: "parked-reason", updatedAtUtc: t0, terminal: true, terminalAtUtc: t0)); + await repo.UpsertAsync(NewRow(id, status: "Attempted", retryCount: 2, lastError: "old", updatedAtUtc: t0.AddMinutes(-5))); + await repo.UpsertAsync(NewRow(id, status: "Delivered", retryCount: 2, updatedAtUtc: t0, terminal: true, terminalAtUtc: t0)); + await repo.UpsertAsync(NewRow(id, status: "Submitted", retryCount: 0, updatedAtUtc: t0.AddMinutes(5))); + + var row = await repo.GetAsync(id); + Assert.Equal("Parked", row!.Status); + Assert.Equal("parked-reason", row.LastError); } /// Verifies that concurrent inserts of the same id leave only one row. diff --git a/tests/ZB.MOM.WW.ScadaBridge.DelmiaNotifier.Tests/HttpRecipeSenderTests.cs b/tests/ZB.MOM.WW.ScadaBridge.DelmiaNotifier.Tests/HttpRecipeSenderTests.cs index f8abfa64..acab5cb4 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.DelmiaNotifier.Tests/HttpRecipeSenderTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.DelmiaNotifier.Tests/HttpRecipeSenderTests.cs @@ -102,4 +102,86 @@ public class HttpRecipeSenderTests Assert.Equal(AttemptKind.Connected, outcome.Kind); Assert.Equal(500, outcome.StatusCode); } + + /// + /// DLM-1 regression: a powered-off / black-holed node (TEST-NET-1 never answers the SYN) is a + /// connect failure — the next URL is tried — not OUTCOME_UNKNOWN. On a host without a default + /// route the connect fails fast instead; both carry the connect marker. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task DLM1_BlackHoledHost_IsConnectFailed_NotOutcomeUnknown() + { + using var http = new HttpClient(ConnectPhase.CreateHandler(TimeSpan.FromMilliseconds(500))) + { + Timeout = TimeSpan.FromSeconds(10), + }; + var sender = new HttpRecipeSender(http, "sbk_x"); + + var outcome = await sender.SendAsync("http://192.0.2.1:8083", Payload, CancellationToken.None); + + Assert.Equal(AttemptKind.ConnectFailed, outcome.Kind); + } + + /// DLM-1: with the real handler a refused connection is still a connect failure. + /// A task that represents the asynchronous operation. + [Fact] + public async Task DLM1_RefusedWithRealHandler_IsConnectFailed() + { + using var http = new HttpClient(ConnectPhase.CreateHandler(TimeSpan.FromSeconds(5))); + var outcome = await new HttpRecipeSender(http, "sbk_x").SendAsync("http://127.0.0.1:1", Payload, CancellationToken.None); + Assert.Equal(AttemptKind.ConnectFailed, outcome.Kind); + } + + /// + /// DLM-1: the notifier moves past a black-holed first URL to the second one instead of stopping + /// at OUTCOME_UNKNOWN (both are unreachable here, so the run reports a connect failure for all). + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task DLM1_BlackHoledFirstUrl_TriesTheNextUrl() + { + using var http = new HttpClient(ConnectPhase.CreateHandler(TimeSpan.FromMilliseconds(500))) + { + Timeout = TimeSpan.FromSeconds(10), + }; + var tried = new List(); + var sender = new RecordingSender(new HttpRecipeSender(http, "sbk_x"), tried); + + var outcome = await Notifier.RunAsync(["http://192.0.2.1:8083", "http://127.0.0.1:1"], Payload, sender, CancellationToken.None); + + Assert.False(outcome.Ok); + Assert.Equal(2, tried.Count); + Assert.DoesNotContain("OUTCOME_UNKNOWN", outcome.Reason); + } + + /// DLM-1: a failure after the connection was up (no marker) stays outcome-unknown. + [Fact] + public void DLM1_WasNotSent_RequiresTheConnectMarker() + { + Assert.True(ConnectPhase.WasNotSent(new TaskCanceledException("canceled", + new TimeoutException("connect timeout", new ConnectPhaseException("x", new OperationCanceledException()))))); + Assert.False(ConnectPhase.WasNotSent(new TaskCanceledException("HttpClient.Timeout", + new TimeoutException("A task was canceled.", new TaskCanceledException())))); + Assert.False(ConnectPhase.WasNotSent(new HttpRequestException(HttpRequestError.ResponseEnded, "ended", + new IOException("reset")))); + } + + /// ConnectTimeoutFor stays strictly inside the overall timeout. + [Fact] + public void ConnectTimeoutFor_IsCappedAtHalfTheOverallTimeout() + { + Assert.Equal(TimeSpan.FromSeconds(5), ConnectPhase.ConnectTimeoutFor(TimeSpan.FromSeconds(30))); + Assert.Equal(TimeSpan.FromSeconds(1.5), ConnectPhase.ConnectTimeoutFor(TimeSpan.FromSeconds(3))); + } + + private sealed class RecordingSender(IRecipeSender inner, List tried) : IRecipeSender + { + /// + public Task SendAsync(string baseUrl, RecipeDownload payload, CancellationToken ct) + { + tried.Add(baseUrl); + return inner.SendAsync(baseUrl, payload, ct); + } + } } diff --git a/tests/ZB.MOM.WW.ScadaBridge.ExternalSystemGateway.Tests/ExternalSystemClientTests.cs b/tests/ZB.MOM.WW.ScadaBridge.ExternalSystemGateway.Tests/ExternalSystemClientTests.cs index f9f48ea5..c2162454 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.ExternalSystemGateway.Tests/ExternalSystemClientTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.ExternalSystemGateway.Tests/ExternalSystemClientTests.cs @@ -159,6 +159,55 @@ public class ExternalSystemClientTests : IDisposable Assert.Contains("Transient error", result.ErrorMessage); } + /// + /// ESG-1 regression: the external system sends 200 headers, then drops the connection + /// mid-body. The call is a transient failure — not a raw IOException escaping into the + /// script. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task Call_ConnectionLostReadingBody_ReturnsTransientError() + { + var system = new ExternalSystemDefinition("TestAPI", "https://api.example.com", "none") { Id = 1 }; + var method = new ExternalSystemMethod("getData", "GET", "/data") { Id = 1, ExternalSystemDefinitionId = 1 }; + StubResolution(system, method); + + var httpClient = new HttpClient(new BodyFailsHandler(HttpStatusCode.OK, new IOException("connection reset mid-body"))); + _httpClientFactory.CreateClient(Arg.Any()).Returns(httpClient); + + var client = new ExternalSystemClient( + _httpClientFactory, _repository, + NullLogger.Instance); + + var result = await client.CallAsync("TestAPI", "getData"); + + Assert.False(result.Success); + Assert.Contains("Transient error", result.ErrorMessage); + } + + /// ESG-1: a permanent status whose error body is unreadable stays permanent. + /// A task that represents the asynchronous operation. + [Fact] + public async Task Call_Permanent400WithUnreadableBody_StaysPermanent() + { + var system = new ExternalSystemDefinition("TestAPI", "https://api.example.com", "none") { Id = 1 }; + var method = new ExternalSystemMethod("getData", "GET", "/data") { Id = 1, ExternalSystemDefinitionId = 1 }; + StubResolution(system, method); + + var httpClient = new HttpClient(new BodyFailsHandler(HttpStatusCode.BadRequest, new HttpIOException(HttpRequestError.ResponseEnded))); + _httpClientFactory.CreateClient(Arg.Any()).Returns(httpClient); + + var client = new ExternalSystemClient( + _httpClientFactory, _repository, + NullLogger.Instance); + + var result = await client.CallAsync("TestAPI", "getData"); + + Assert.False(result.Success); + Assert.DoesNotContain("Transient error", result.ErrorMessage); + Assert.Contains("400", result.ErrorMessage); + } + /// Verifies that an HTTP 400 response is returned as a permanent error. /// A task that represents the asynchronous operation. [Fact] @@ -1239,6 +1288,30 @@ public class ExternalSystemClientTests : IDisposable /// /// Test helper: mock HTTP message handler. /// + /// Answers with the given status, then fails the body read with error. + private sealed class BodyFailsHandler(HttpStatusCode statusCode, Exception error) : HttpMessageHandler + { + /// + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + => Task.FromResult(new HttpResponseMessage(statusCode) { Content = new StreamContent(new FailingStream(error)) }); + + private sealed class FailingStream(Exception error) : Stream + { + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => throw new NotSupportedException(); + public override long Position { get => 0; set => throw new NotSupportedException(); } + public override void Flush() { } + public override int Read(byte[] buffer, int offset, int count) => throw error; + public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + => ValueTask.FromException(error); + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } + } + private class MockHttpMessageHandler : HttpMessageHandler { private readonly HttpStatusCode _statusCode; diff --git a/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/CentralHealthAggregatorTests.cs b/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/CentralHealthAggregatorTests.cs index f1f2387b..733feea0 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/CentralHealthAggregatorTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/CentralHealthAggregatorTests.cs @@ -113,6 +113,17 @@ public class CentralHealthAggregatorTests } /// Verifies that a report with a sequence number equal to the stored one is rejected. + /// COMM-1: ProcessReport reports its verdict so the caller can nack a dropped report. + [Fact] + public void ProcessReport_ReturnsFalseOnlyWhenRejectedAsStale() + { + Assert.True(_aggregator.ProcessReport(MakeReport("site-1", 5))); + Assert.True(_aggregator.ProcessReport(MakeReport("site-1", 6))); + Assert.False(_aggregator.ProcessReport(MakeReport("site-1", 6))); + Assert.False(_aggregator.ProcessReport(MakeReport("site-1", 2))); + Assert.Equal(6, _aggregator.GetSiteState("site-1")!.LastSequenceNumber); + } + [Fact] public void ProcessReport_RejectsEqualSequence() { @@ -342,6 +353,22 @@ public class CentralHealthAggregatorTests Assert.True(_aggregator.GetSiteState("site-1")!.IsOnline); } + /// + /// COMM-4 regression: a heartbeat stamped in central's future (a fast site clock) must not + /// extend the offline timeout by the skew — it is clamped to central's now. + /// + [Fact] + public void MarkHeartbeat_FutureStamp_DoesNotDelayOfflineDetection() + { + _aggregator.ProcessReport(MakeReport("site-1", 1)); + _aggregator.MarkHeartbeat("site-1", _timeProvider.GetUtcNow().AddMinutes(30)); + + _timeProvider.Advance(TimeSpan.FromSeconds(61)); + _aggregator.CheckForOfflineSites(); + + Assert.False(_aggregator.GetSiteState("site-1")!.IsOnline); + } + /// /// Regression test: an offline-to-online transition must /// be backed by a fresh LastHeartbeatAt. Previously MarkHeartbeat used diff --git a/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/CentralHealthReportLoopTests.cs b/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/CentralHealthReportLoopTests.cs index 5bfa2e04..3b7cce89 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/CentralHealthReportLoopTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/CentralHealthReportLoopTests.cs @@ -28,7 +28,7 @@ public class CentralHealthReportLoopTests /// Gets the reports passed to . public List Processed { get; } = []; /// - public void ProcessReport(SiteHealthReport report) => Processed.Add(report); + public bool ProcessReport(SiteHealthReport report) { Processed.Add(report); return true; } /// public void MarkHeartbeat(string siteId, DateTimeOffset receivedAt) { } /// @@ -262,7 +262,7 @@ public class CentralHealthReportLoopTests public List Processed { get; } = []; /// - public void ProcessReport(SiteHealthReport report) + public bool ProcessReport(SiteHealthReport report) { var n = Interlocked.Increment(ref _callCount); if (n == 1) @@ -270,6 +270,7 @@ public class CentralHealthReportLoopTests throw new InvalidOperationException("aggregator temporarily unavailable"); } Processed.Add(report); + return true; } /// diff --git a/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/HealthReportSenderTests.cs b/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/HealthReportSenderTests.cs index fae7155d..4f9bec17 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/HealthReportSenderTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/HealthReportSenderTests.cs @@ -478,4 +478,104 @@ public class HealthReportSenderTests Assert.Equal(fixedInstant.ToUnixTimeMilliseconds(), sender.CurrentSequenceNumber); } + + /// + /// COMM-1 regression: two site nodes started 5 s apart; the older one (A) is active and has + /// sent 6 000 reports (~50 h at 30 s). B becomes active. Under the old "seed at construction, + /// +1 per report" scheme B's first sequence (T_B + 1) sorted below A's last (T_A + 6000) and + /// central rejected every B report. With max(prev + 1, now-ms) B's first report sorts + /// above anything A ever sent. + /// + [Fact] + public void NextSequenceNumber_AfterFailover_SortsAboveLongRunningPeer() + { + var t0 = new DateTimeOffset(2026, 12, 1, 0, 0, 0, TimeSpan.Zero); + var clock = new TestTimeProvider(t0); + + long seqA = t0.ToUnixTimeMilliseconds(); + long seqB = t0.AddSeconds(5).ToUnixTimeMilliseconds(); + + long lastA = 0; + for (var i = 0; i < 6000; i++) + { + clock.Advance(TimeSpan.FromSeconds(30)); + lastA = HealthReportSender.NextSequenceNumber(ref seqA, clock); + } + + clock.Advance(TimeSpan.FromSeconds(30)); + var firstB = HealthReportSender.NextSequenceNumber(ref seqB, clock); + + Assert.True(firstB > lastA, $"B's first sequence {firstB} must sort above A's last {lastA}"); + // The old scheme would have produced T_B + 1, below A's T_A + 6000. + Assert.True(t0.AddSeconds(5).ToUnixTimeMilliseconds() + 1 < t0.ToUnixTimeMilliseconds() + 6000); + } + + /// COMM-1: the sequence stays strictly monotonic when the wall clock steps backwards. + [Fact] + public void NextSequenceNumber_ClockStepsBack_StillStrictlyIncreasing() + { + var t0 = new DateTimeOffset(2026, 12, 1, 0, 0, 0, TimeSpan.Zero); + var clock = new TestTimeProvider(t0); + long seq = t0.ToUnixTimeMilliseconds(); + + var a = HealthReportSender.NextSequenceNumber(ref seq, clock); + clock.Advance(TimeSpan.FromMinutes(-10)); + var b = HealthReportSender.NextSequenceNumber(ref seq, clock); + var c = HealthReportSender.NextSequenceNumber(ref seq, clock); + + Assert.True(b > a); + Assert.True(c > b); + } + + /// + /// COMM-6 regression: a standby node drains its per-interval counters every tick, so the first + /// report after it becomes active does not carry its whole standby life as one interval. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task StandbyTicks_DrainIntervalCounters_SoFirstActiveReportIsOneInterval() + { + var transport = new FakeTransport(); + var collector = new SiteHealthCollector(); + collector.SetActiveNode(false); + for (var i = 0; i < 4000; i++) collector.IncrementDeadLetter(); + collector.IncrementScriptError(); + + var sender = new HealthReportSender( + collector, + transport, + Options.Create(new HealthMonitoringOptions { ReportInterval = TimeSpan.FromMilliseconds(30) }), + NullLogger.Instance, + new FakeSiteIdentityProvider()); + + await sender.StartAsync(CancellationToken.None); + try + { + // Let several standby ticks run (30 ms interval), then promote the node. + await Task.Delay(300); + Assert.Empty(transport.SentReports); + + collector.SetActiveNode(true); + await WaitUntilAsync(() => transport.SentReports.Count > 0, TimeSpan.FromSeconds(5)); + } + finally + { + await sender.StopAsync(CancellationToken.None); + } + + var first = transport.SentReports[0]; + Assert.Equal(0, first.DeadLetterCount); + Assert.Equal(0, first.ScriptErrorCount); + } + + private static async Task WaitUntilAsync(Func condition, TimeSpan timeout) + { + var deadline = DateTime.UtcNow + timeout; + while (DateTime.UtcNow < deadline) + { + if (condition()) return; + await Task.Delay(20); + } + Assert.Fail("Condition not met within timeout"); + } } diff --git a/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/Kpi/CentralHealthAuditBacklogProviderTests.cs b/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/Kpi/CentralHealthAuditBacklogProviderTests.cs index 30f5f69f..0deaf974 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/Kpi/CentralHealthAuditBacklogProviderTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/Kpi/CentralHealthAuditBacklogProviderTests.cs @@ -100,7 +100,7 @@ public class CentralHealthAuditBacklogProviderTests States.TryGetValue(siteId, out var state) ? state : null; /// - public void ProcessReport(SiteHealthReport report) => throw new NotSupportedException(); + public bool ProcessReport(SiteHealthReport report) => throw new NotSupportedException(); /// public void MarkHeartbeat(string siteId, DateTimeOffset receivedAt) => throw new NotSupportedException(); diff --git a/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/Kpi/SiteHealthKpiSampleSourceTests.cs b/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/Kpi/SiteHealthKpiSampleSourceTests.cs index 2792ec91..051b4121 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/Kpi/SiteHealthKpiSampleSourceTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/Kpi/SiteHealthKpiSampleSourceTests.cs @@ -265,7 +265,7 @@ public class SiteHealthKpiSampleSourceTests States.TryGetValue(siteId, out var state) ? state : null; /// - public void ProcessReport(SiteHealthReport report) => + public bool ProcessReport(SiteHealthReport report) => throw new NotSupportedException(); /// diff --git a/tests/ZB.MOM.WW.ScadaBridge.InboundAPI.Tests/StandbyRequestForwardingTests.cs b/tests/ZB.MOM.WW.ScadaBridge.InboundAPI.Tests/StandbyRequestForwardingTests.cs index ebda7dbe..e8b4b006 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.InboundAPI.Tests/StandbyRequestForwardingTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.InboundAPI.Tests/StandbyRequestForwardingTests.cs @@ -297,6 +297,33 @@ public class StandbyRequestForwardingTests AssertStatus(result, StatusCodes.Status503ServiceUnavailable); } + /// + /// DLM-1 regression: a powered-off / black-holed peer (TEST-NET-1 never answers the SYN) is a + /// not-dispatched connect failure with the production handler — the relay moves on and, with + /// every peer unreachable, answers 503 ACTIVE_NODE_UNREACHABLE instead of a 60 s wait ending + /// in 502 OUTCOME_UNKNOWN. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task Forwarder_BlackHoledPeer_IsNotDispatched_TriesNextPeer() + { + using var handler = RelayConnectPhase.CreateHandler(TimeSpan.FromMilliseconds(500)); + var forwarder = new HttpStandbyRequestForwarder( + new FakeHttpClientFactory(handler), + new StaticOptionsMonitor(new InboundApiOptions + { + StandbyForwardPeerEndpoints = ["http://192.0.2.1:5000", "http://127.0.0.1:1"], + StandbyForwardTimeout = TimeSpan.FromSeconds(20), + }), + NullLogger.Instance); + + var sw = System.Diagnostics.Stopwatch.StartNew(); + var result = await forwarder.ForwardAsync(BuildRequestContext("{}"), CancellationToken.None); + + AssertStatus(result, StatusCodes.Status503ServiceUnavailable); + Assert.True(sw.Elapsed < TimeSpan.FromSeconds(15), $"took {sw.Elapsed}"); + } + /// Verifies that a peer timeout returns an uncertain result without trying the next peer. /// A task that represents the asynchronous operation. [Fact] diff --git a/tests/ZB.MOM.WW.ScadaBridge.KpiHistory.Tests/KpiHistoryRecorderActorTests.cs b/tests/ZB.MOM.WW.ScadaBridge.KpiHistory.Tests/KpiHistoryRecorderActorTests.cs index 83a81274..3a2e8905 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.KpiHistory.Tests/KpiHistoryRecorderActorTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.KpiHistory.Tests/KpiHistoryRecorderActorTests.cs @@ -239,6 +239,57 @@ public class KpiHistoryRecorderActorTests : TestKit return Task.FromResult(_latestRollupHour); } } + + private DateTime? _backfillWatermark; + private int _backfillWatermarkQueryCount; + private readonly List<(DateTime Through, DateTime? OnlyIfReached)> _advances = new(); + + /// The backfill's own persisted watermark the fake reports (settable; KPI-1). + public DateTime? BackfillWatermark + { + get { lock (_gate) { return _backfillWatermark; } } + set { lock (_gate) { _backfillWatermark = value; } } + } + + /// Number of times the backfill plan pass read the backfill watermark. + public int BackfillWatermarkQueryCount + { + get { lock (_gate) { return _backfillWatermarkQueryCount; } } + } + + /// Every watermark advance requested, in call order. + public IReadOnlyList<(DateTime Through, DateTime? OnlyIfReached)> Advances + { + get { lock (_gate) { return _advances.ToArray(); } } + } + + /// + public Task GetRollupBackfillWatermarkAsync(CancellationToken cancellationToken = default) + { + lock (_gate) + { + _backfillWatermarkQueryCount++; + return Task.FromResult(_backfillWatermark); + } + } + + /// + public Task AdvanceRollupBackfillWatermarkAsync( + DateTime backfilledThroughUtc, DateTime? onlyIfReachedUtc = null, CancellationToken cancellationToken = default) + { + lock (_gate) + { + _advances.Add((backfilledThroughUtc, onlyIfReachedUtc)); + var reached = onlyIfReachedUtc is null + || (_backfillWatermark is { } w && w >= onlyIfReachedUtc.Value); + if (reached && (onlyIfReachedUtc is null || _backfillWatermark is not null) + && (_backfillWatermark is null || _backfillWatermark < backfilledThroughUtc)) + { + _backfillWatermark = backfilledThroughUtc; + } + } + return Task.CompletedTask; + } } /// @@ -1168,7 +1219,7 @@ public class KpiHistoryRecorderActorTests : TestKit interval: TimeSpan.FromMilliseconds(50)); } - /// Verifies that the backfill is skipped when rollups are already current. + /// Verifies that the backfill is skipped when its own watermark is already current. [Fact] public void Backfill_Skips_WhenRollupsAlreadyCurrent() { @@ -1187,17 +1238,18 @@ public class KpiHistoryRecorderActorTests : TestKit RollupLookbackHours = 3, }); - // Rollups current through one hour ago — well inside the 3 h lookback tail. + // The BACKFILL's own watermark is current through one hour ago (KPI-1: the plan reads its + // own persisted marker, never the periodic fold's MAX(HourStartUtc)). var nowHour = new DateTime( DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, DateTime.UtcNow.Hour, 0, 0, DateTimeKind.Utc); - repository.LatestRollupHour = nowHour - TimeSpan.FromHours(1); + repository.BackfillWatermark = nowHour - TimeSpan.FromHours(1); actor.Tell(KpiHistoryRecorderActor.BackfillTick.Instance); // The plan pass must consult the watermark… AwaitAssert( - () => Assert.True(repository.LatestRollupHourQueryCount >= 1), + () => Assert.True(repository.BackfillWatermarkQueryCount >= 1), duration: TimeSpan.FromSeconds(3), interval: TimeSpan.FromMilliseconds(50)); @@ -1234,7 +1286,7 @@ public class KpiHistoryRecorderActorTests : TestKit DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, DateTime.UtcNow.Hour, 0, 0, DateTimeKind.Utc); var watermark = nowHour - TimeSpan.FromDays(2); - repository.LatestRollupHour = watermark; + repository.BackfillWatermark = watermark; actor.Tell(KpiHistoryRecorderActor.BackfillTick.Instance); @@ -1250,4 +1302,114 @@ public class KpiHistoryRecorderActorTests : TestKit duration: TimeSpan.FromSeconds(5), interval: TimeSpan.FromMilliseconds(50)); } + + /// + /// KPI-1 regression: the periodic fold has just written the last few hours (so + /// MAX(HourStartUtc) is an hour ago) but the backfill has never run — e.g. an upgrade onto 90 + /// days of raw samples. The backfill must fold the whole retention window, not latch itself + /// "current" from the periodic fold's MAX. + /// + [Fact] + public void Backfill_IgnoresThePeriodicFoldsMax_AndFoldsTheWholeWindow() + { + var repository = new RecordingRepository(); + var sp = BuildServiceProvider(repository, new HealthySource()); + var actor = CreateActor(sp, new KpiHistoryOptions + { + SampleInterval = TimeSpan.FromHours(1), + PurgeInterval = TimeSpan.FromHours(1), + RollupInterval = TimeSpan.FromHours(1), + RetentionDays = 5, + RollupLookbackHours = 3, + }); + + var nowHour = new DateTime( + DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, + DateTime.UtcNow.Hour, 0, 0, DateTimeKind.Utc); + repository.LatestRollupHour = nowHour - TimeSpan.FromHours(1); // periodic fold's MAX + repository.BackfillWatermark = null; // backfill never ran + + actor.Tell(KpiHistoryRecorderActor.BackfillTick.Instance); + + AwaitAssert( + () => + { + var windows = repository.FoldWindows; + Assert.Equal(5, windows.Count); + Assert.Equal(nowHour - TimeSpan.FromDays(5), windows[0].FromHourUtc); + // Each folded slice advanced the backfill's own marker, ending at the plan's end. + Assert.Equal(nowHour, repository.BackfillWatermark); + }, + duration: TimeSpan.FromSeconds(5), + interval: TimeSpan.FromMilliseconds(50)); + } + + /// + /// KPI-1: an interrupted backfill resumes from its own watermark (the next singleton plans from + /// where the completed slices got to), not from the rollup table's MAX. + /// + [Fact] + public void Backfill_ResumesFromItsOwnWatermark() + { + var repository = new RecordingRepository(); + var sp = BuildServiceProvider(repository, new HealthySource()); + var actor = CreateActor(sp, new KpiHistoryOptions + { + SampleInterval = TimeSpan.FromHours(1), + PurgeInterval = TimeSpan.FromHours(1), + RollupInterval = TimeSpan.FromHours(1), + RetentionDays = 90, + RollupLookbackHours = 3, + }); + + var nowHour = new DateTime( + DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, + DateTime.UtcNow.Hour, 0, 0, DateTimeKind.Utc); + repository.LatestRollupHour = nowHour - TimeSpan.FromHours(1); + repository.BackfillWatermark = nowHour - TimeSpan.FromDays(40); + + actor.Tell(KpiHistoryRecorderActor.BackfillTick.Instance); + + AwaitAssert( + () => + { + var windows = repository.FoldWindows; + Assert.NotEmpty(windows); + Assert.Equal(nowHour - TimeSpan.FromDays(40), windows[0].FromHourUtc); + }, + duration: TimeSpan.FromSeconds(5), + interval: TimeSpan.FromMilliseconds(50)); + } + + /// + /// KPI-1: the periodic fold extends a completed backfill's marker only with the contiguity + /// guard (only-if-reached = the fold's lower bound), so it can never jump a gap. + /// + [Fact] + public void PeriodicFold_AdvancesTheBackfillMarker_OnlyContiguously() + { + var repository = new RecordingRepository(); + var sp = BuildServiceProvider(repository, new HealthySource()); + var actor = CreateActor(sp, new KpiHistoryOptions + { + SampleInterval = TimeSpan.FromHours(1), + PurgeInterval = TimeSpan.FromHours(1), + RollupInterval = TimeSpan.FromHours(1), + RetentionDays = 90, + RollupLookbackHours = 3, + }); + + actor.Tell(KpiHistoryRecorderActor.RollupTick.Instance); + + AwaitAssert( + () => + { + var advance = Assert.Single(repository.Advances); + Assert.Equal(repository.FoldFromHourUtc, advance.OnlyIfReached); + Assert.Equal(repository.FoldToHourUtc, advance.Through); + Assert.Null(repository.BackfillWatermark); // never created by the periodic fold + }, + duration: TimeSpan.FromSeconds(5), + interval: TimeSpan.FromMilliseconds(50)); + } } diff --git a/tests/ZB.MOM.WW.ScadaBridge.NotificationOutbox.Tests/Delivery/EmailNotificationDeliveryAdapterTests.cs b/tests/ZB.MOM.WW.ScadaBridge.NotificationOutbox.Tests/Delivery/EmailNotificationDeliveryAdapterTests.cs index 9bbc8762..0738a6ff 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.NotificationOutbox.Tests/Delivery/EmailNotificationDeliveryAdapterTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.NotificationOutbox.Tests/Delivery/EmailNotificationDeliveryAdapterTests.cs @@ -206,6 +206,30 @@ public class EmailNotificationDeliveryAdapterTests Assert.Equal(DeliveryResult.TransientFailure, outcome.Result); } + /// + /// NTF-2 regression: the relay drops the connection during DATA (MailKit throws IOException) + /// or the OAuth2 token endpoint answers 503 — both are retried, not parked with RetryCount 0. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task Deliver_ConnectionDropAndTokenEndpointOutage_ReturnTransient() + { + SetupHappyPath(); + _smtpClient + .SendAsync(Arg.Any(), Arg.Any>(), + Arg.Any(), Arg.Any(), Arg.Any()) + .ThrowsAsync(new IOException("connection reset during DATA")); + var dropped = await CreateAdapter().DeliverAsync(MakeNotification()); + Assert.Equal(DeliveryResult.TransientFailure, dropped.Result); + + _smtpClient + .SendAsync(Arg.Any(), Arg.Any>(), + Arg.Any(), Arg.Any(), Arg.Any()) + .ThrowsAsync(new HttpRequestException("503", null, System.Net.HttpStatusCode.ServiceUnavailable)); + var outage = await CreateAdapter().DeliverAsync(MakeNotification()); + Assert.Equal(DeliveryResult.TransientFailure, outage.Result); + } + /// Verifies that an unclassified exception returns a permanent failure. /// A task that represents the asynchronous operation. [Fact] diff --git a/tests/ZB.MOM.WW.ScadaBridge.NotificationOutbox.Tests/NotificationOutboxActorDispatchTests.cs b/tests/ZB.MOM.WW.ScadaBridge.NotificationOutbox.Tests/NotificationOutboxActorDispatchTests.cs index a2aca4ee..1e34ac23 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.NotificationOutbox.Tests/NotificationOutboxActorDispatchTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.NotificationOutbox.Tests/NotificationOutboxActorDispatchTests.cs @@ -116,6 +116,69 @@ public class NotificationOutboxActorDispatchTests : TestKit .Returns(new[] { config }); } + /// + /// Adapter whose send completes only when the test releases it, ignoring the cancellation + /// token — the shape of a relay that has already accepted the message when shutdown lands. + /// + private sealed class GatedAdapter : INotificationDeliveryAdapter + { + public readonly TaskCompletionSource Entered = new(TaskCreationOptions.RunContinuationsAsynchronously); + public readonly TaskCompletionSource Release = new(TaskCreationOptions.RunContinuationsAsynchronously); + + /// + public NotificationType Type => NotificationType.Email; + + /// + public async Task DeliverAsync( + Notification notification, CancellationToken cancellationToken = default) + { + Entered.TrySetResult(); + await Release.Task; + return DeliveryOutcome.Success("ops@example.com"); + } + } + + /// + /// NTF-1 regression: the singleton is stopped (handover) while a send is in flight; the relay + /// has already accepted it. The Delivered write must still land — on a token the shutdown did + /// not cancel — or the next active node re-sends the email/SMS. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task ShutdownMidDelivery_StillPersistsTheDeliveredOutcome() + { + SetupSmtpRetryPolicy(maxRetries: 5, retryDelay: TimeSpan.FromMinutes(1)); + var notification = MakeNotification(); + _outboxRepository.GetDueAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(new[] { notification }); + + // A real EF ExecuteUpdateAsync throws on a cancelled token; model that. + var persisted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + _outboxRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(ci => + { + ((CancellationToken)ci[1]).ThrowIfCancellationRequested(); + persisted.TrySetResult(((Notification)ci[0]).Status); + return Task.FromResult(true); + }); + + var adapter = new GatedAdapter(); + var actor = CreateActor([adapter]); + Watch(actor); + + actor.Tell(InternalMessages.DispatchTick.Instance); + await adapter.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5)); + + // Handover: PostStop cancels the shutdown token while the send is in flight. + Sys.Stop(actor); + ExpectTerminated(actor); + + adapter.Release.TrySetResult(); + + var status = await persisted.Task.WaitAsync(TimeSpan.FromSeconds(5)); + Assert.Equal(NotificationStatus.Delivered, status); + } + /// Verifies that a dispatch tick claims due notifications and invokes the adapter. [Fact] public void DispatchTick_ClaimsDueNotifications_AndInvokesAdapter() diff --git a/tests/ZB.MOM.WW.ScadaBridge.NotificationService.Tests/SmtpErrorClassifierTests.cs b/tests/ZB.MOM.WW.ScadaBridge.NotificationService.Tests/SmtpErrorClassifierTests.cs index 78d48090..dca3e630 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.NotificationService.Tests/SmtpErrorClassifierTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.NotificationService.Tests/SmtpErrorClassifierTests.cs @@ -102,14 +102,64 @@ public class SmtpErrorClassifierTests SmtpErrorClassifier.Classify(new OperationCanceledException(), cts.Token)); } - /// Verifies that an operation cancellation without a requested cancellation is classified as unknown. + /// + /// NTF-2: a cancellation the caller did not request is a timeout (HttpClient.Timeout on the + /// OAuth2 token fetch surfaces as TaskCanceledException) and is transient. Before NTF-2 it + /// was Unknown, which the outbox adapter parks as permanent. + /// [Fact] - public void Classify_OperationCanceledWithoutRequestedCancellation_IsUnknown() + public void Classify_OperationCanceledWithoutRequestedCancellation_IsTransient() { - // Not a recognised SMTP error, and cancellation was not requested. Assert.Equal( - SmtpErrorClass.Unknown, + SmtpErrorClass.Transient, SmtpErrorClassifier.Classify(new OperationCanceledException(), CancellationToken.None)); + Assert.Equal( + SmtpErrorClass.Transient, + SmtpErrorClassifier.Classify(new TaskCanceledException("HttpClient.Timeout"), CancellationToken.None)); + } + + /// NTF-2: a dropped connection (MailKit's documented IOException) is transient, wrapped or not. + [Fact] + public void Classify_IOException_IsTransient_IncludingAWrappedSocketException() + { + Assert.Equal(SmtpErrorClass.Transient, + SmtpErrorClassifier.Classify(new IOException("connection reset"), CancellationToken.None)); + Assert.Equal(SmtpErrorClass.Transient, + SmtpErrorClassifier.Classify( + new IOException("Unable to read data", new SocketException((int)SocketError.ConnectionReset)), + CancellationToken.None)); + // An unrecognised wrapper whose cause is a socket failure is unwrapped too. + Assert.Equal(SmtpErrorClass.Transient, + SmtpErrorClassifier.Classify( + new InvalidOperationException("wrapper", new TimeoutException()), CancellationToken.None)); + } + + /// NTF-2: a TLS handshake that failed mid-way (relay restarting) is transient. + [Fact] + public void Classify_SslHandshakeException_IsTransient() + { + Assert.Equal(SmtpErrorClass.Transient, + SmtpErrorClassifier.Classify(new MailKit.Security.SslHandshakeException("handshake failed"), CancellationToken.None)); + } + + /// + /// NTF-2: OAuth2 token-endpoint failures are classified by HTTP status — no status (network), + /// 5xx, 408 and 429 are transient; any other 4xx (a broken credential) is permanent. + /// + /// The token endpoint's status, or null for a network failure. + /// The expected classification. + [Theory] + [InlineData(null, SmtpErrorClass.Transient)] + [InlineData(503, SmtpErrorClass.Transient)] + [InlineData(500, SmtpErrorClass.Transient)] + [InlineData(408, SmtpErrorClass.Transient)] + [InlineData(429, SmtpErrorClass.Transient)] + [InlineData(400, SmtpErrorClass.Permanent)] + [InlineData(401, SmtpErrorClass.Permanent)] + public void Classify_TokenEndpointHttpRequestException_ByStatus(int? status, SmtpErrorClass expected) + { + var ex = new HttpRequestException("token endpoint", null, (System.Net.HttpStatusCode?)status); + Assert.Equal(expected, SmtpErrorClassifier.Classify(ex, CancellationToken.None)); } /// Verifies that an unrecognised exception is classified as unknown. diff --git a/tests/ZB.MOM.WW.ScadaBridge.SiteCallAudit.Tests/SiteCallAuditReconciliationTests.cs b/tests/ZB.MOM.WW.ScadaBridge.SiteCallAudit.Tests/SiteCallAuditReconciliationTests.cs index 4141187d..e0adbafe 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.SiteCallAudit.Tests/SiteCallAuditReconciliationTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.SiteCallAudit.Tests/SiteCallAuditReconciliationTests.cs @@ -1192,4 +1192,57 @@ public class SiteCallAuditReconciliationTests : TestKit return new PullSiteCallsResponse(Array.Empty(), MoreAvailable: false); } } + + /// Records each per-node pull; only NodeB owes a row (an unreplicated pair after a NodeA restart). + private sealed class PerNodePullClient(SiteCall nodeBRow) : IPullSiteCallsClient + { + public System.Collections.Concurrent.ConcurrentQueue<(string Endpoint, DateTime Since)> Calls { get; } = new(); + + /// + public Task PullAsync( + string siteId, DateTime sinceUtc, string? afterId, int batchSize, CancellationToken ct) => + throw new InvalidOperationException("the actor must pull per node"); + + /// + public Task PullFromEndpointAsync( + string siteId, string endpoint, DateTime sinceUtc, string? afterId, int batchSize, CancellationToken ct) + { + Calls.Enqueue((endpoint, sinceUtc)); + var rows = endpoint == "http://nodeB:8083" && sinceUtc < nodeBRow.UpdatedAtUtc + ? new[] { nodeBRow } + : Array.Empty(); + return Task.FromResult(new PullSiteCallsResponse(rows, MoreAvailable: false)); + } + } + + /// + /// AUD-1 regression: both nodes of the site are pulled every tick, each with its own cursor, + /// so a row owed only by NodeB reaches central although NodeA answers. + /// + [Fact] + public void Reconciliation_PullsBothNodes_EachWithItsOwnCursor() + { + var row = NewRow(TrackedOperationId.New(), "siteA", status: "Parked", + updatedAtUtc: new DateTime(2026, 12, 1, 8, 0, 0, DateTimeKind.Utc)); + var client = new PerNodePullClient(row); + var repo = new RecordingRepo(); + var actor = CreateActor( + new StaticEnumerator(new SiteEntry("siteA", "http://nodeA:8083", "http://nodeB:8083")), + client, repo, FastTickOptions()); + + AwaitCondition(() => client.Calls.Count(c => c.Endpoint == "http://nodeB:8083") >= 2 + && client.Calls.Count(c => c.Endpoint == "http://nodeA:8083") >= 2, + TimeSpan.FromSeconds(10)); + + Assert.True(repo.Upserted.ContainsKey(row.TrackedOperationId)); + Assert.All(client.Calls.Where(c => c.Endpoint == "http://nodeA:8083"), + c => Assert.Equal(DateTime.MinValue, c.Since)); + var nodeB = client.Calls.Where(c => c.Endpoint == "http://nodeB:8083").ToList(); + Assert.Equal(DateTime.MinValue, nodeB[0].Since); + Assert.Equal(row.UpdatedAtUtc, nodeB[1].Since); + + Watch(actor); + Sys.Stop(actor); + ExpectTerminated(actor); + } } diff --git a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Tracking/OperationTrackingStoreTests.cs b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Tracking/OperationTrackingStoreTests.cs index 68389a04..3ee6838c 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Tracking/OperationTrackingStoreTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Tracking/OperationTrackingStoreTests.cs @@ -389,6 +389,81 @@ public class OperationTrackingStoreTests : IDisposable Assert.True(snapshot.UpdatedAtUtc >= snapshot.CreatedAtUtc); } + /// + /// SCA-1: a Parked row re-opens on an operator Retry — TerminalAtUtc cleared, RetryCount and + /// error reset — so the retried attempts and outcome land on it again. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task ReopenParkedAsync_ReopensParkedRow_SoTheRetriedOutcomeLands() + { + var (store, _) = CreateStore(nameof(ReopenParkedAsync_ReopensParkedRow_SoTheRetriedOutcomeLands)); + await using var _store = store; + + var id = TrackedOperationId.New(); + await store.RecordEnqueueAsync(id, "ApiCallCached", "ERP.GetOrder", null, null, sourceNode: null); + await store.RecordAttemptAsync(id, nameof(AuditStatus.Attempted), 3, "HTTP 500", 500); + await store.RecordTerminalAsync(id, nameof(AuditStatus.Parked), "HTTP 500", 500); + var parked = await store.GetStatusAsync(id); + + await store.ReopenParkedAsync(id); + var reopened = await store.GetStatusAsync(id); + Assert.Equal(nameof(AuditStatus.Attempted), reopened!.Status); + Assert.Null(reopened.TerminalAtUtc); + Assert.Equal(0, reopened.RetryCount); + Assert.Null(reopened.LastError); + Assert.True(reopened.UpdatedAtUtc >= parked!.UpdatedAtUtc); + + await store.RecordAttemptAsync(id, nameof(AuditStatus.Attempted), 1, null, 200); + await store.RecordTerminalAsync(id, nameof(AuditStatus.Delivered), null, 200); + var delivered = await store.GetStatusAsync(id); + Assert.Equal(nameof(AuditStatus.Delivered), delivered!.Status); + Assert.NotNull(delivered.TerminalAtUtc); + } + + /// SCA-1: re-open touches only a Parked row — a Delivered row stays Delivered. + /// A task that represents the asynchronous operation. + [Fact] + public async Task ReopenParkedAsync_OnNonParkedTerminalRow_IsNoOp() + { + var (store, _) = CreateStore(nameof(ReopenParkedAsync_OnNonParkedTerminalRow_IsNoOp)); + await using var _store = store; + + var id = TrackedOperationId.New(); + await store.RecordEnqueueAsync(id, "ApiCallCached", "ERP.GetOrder", null, null, sourceNode: null); + await store.RecordTerminalAsync(id, nameof(AuditStatus.Delivered), null, 200); + + await store.ReopenParkedAsync(id); + + var row = await store.GetStatusAsync(id); + Assert.Equal(nameof(AuditStatus.Delivered), row!.Status); + Assert.NotNull(row.TerminalAtUtc); + } + + /// SCA-1: an operator Discard closes a Parked row as Discarded; Delivered stays immutable. + /// A task that represents the asynchronous operation. + [Fact] + public async Task RecordDiscardedAsync_ClosesParkedRow_ButNotADeliveredOne() + { + var (store, _) = CreateStore(nameof(RecordDiscardedAsync_ClosesParkedRow_ButNotADeliveredOne)); + await using var _store = store; + + var parkedId = TrackedOperationId.New(); + await store.RecordEnqueueAsync(parkedId, "ApiCallCached", "ERP.GetOrder", null, null, sourceNode: null); + await store.RecordTerminalAsync(parkedId, nameof(AuditStatus.Parked), "HTTP 500", 500); + await store.RecordDiscardedAsync(parkedId, "Discarded by operator"); + var discarded = await store.GetStatusAsync(parkedId); + Assert.Equal(nameof(AuditStatus.Discarded), discarded!.Status); + Assert.NotNull(discarded.TerminalAtUtc); + Assert.Equal("Discarded by operator", discarded.LastError); + + var deliveredId = TrackedOperationId.New(); + await store.RecordEnqueueAsync(deliveredId, "ApiCallCached", "ERP.GetOrder", null, null, sourceNode: null); + await store.RecordTerminalAsync(deliveredId, nameof(AuditStatus.Delivered), null, 200); + await store.RecordDiscardedAsync(deliveredId, "Discarded by operator"); + Assert.Equal(nameof(AuditStatus.Delivered), (await store.GetStatusAsync(deliveredId))!.Status); + } + /// Verifies that recording an attempt on a terminal row is a no-op. /// A task that represents the asynchronous operation. [Fact] diff --git a/tests/ZB.MOM.WW.ScadaBridge.StoreAndForward.Tests/CachedCallAttemptEmissionTests.cs b/tests/ZB.MOM.WW.ScadaBridge.StoreAndForward.Tests/CachedCallAttemptEmissionTests.cs index af062880..6420162a 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.StoreAndForward.Tests/CachedCallAttemptEmissionTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.StoreAndForward.Tests/CachedCallAttemptEmissionTests.cs @@ -113,6 +113,63 @@ public class CachedCallAttemptEmissionTests : IAsyncLifetime, IDisposable return trackedId; } + // ── SCA-1: operator transitions out of Parked ── + + private async Task ParkAsync() + { + _service.RegisterDeliveryHandler(StoreAndForwardCategory.ExternalSystem, _ => Task.FromResult(false)); + var id = await EnqueueBufferedAsync(StoreAndForwardCategory.ExternalSystem, "ERP", maxRetries: 5); + await _service.RetryPendingMessagesAsync(); + Assert.Equal(CachedCallAttemptOutcome.PermanentFailure, Assert.Single(_observer.Notifications).Outcome); + _observer.Notifications.Clear(); + return id; + } + + /// + /// SCA-1 regression: an operator Retry of a parked cached call notifies the observer with + /// , so the tracking row re-opens and + /// telemetry carries the change to central (it used to raise an activity only). + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task OperatorRetryOfParkedCall_NotifiesOperatorRetried() + { + var id = await ParkAsync(); + + Assert.True(await _service.RetryParkedMessageAsync(id.ToString())); + + var n = Assert.Single(_observer.Notifications); + Assert.Equal(id, n.TrackedOperationId); + Assert.Equal(CachedCallAttemptOutcome.OperatorRetried, n.Outcome); + Assert.Equal(0, n.RetryCount); + Assert.Null(n.LastError); + } + + /// SCA-1 regression: an operator Discard notifies . + /// A task that represents the asynchronous operation. + [Fact] + public async Task OperatorDiscardOfParkedCall_NotifiesOperatorDiscarded() + { + var id = await ParkAsync(); + + Assert.True(await _service.DiscardParkedMessageAsync(id.ToString())); + + var n = Assert.Single(_observer.Notifications); + Assert.Equal(id, n.TrackedOperationId); + Assert.Equal(CachedCallAttemptOutcome.OperatorDiscarded, n.Outcome); + } + + /// A retry/discard of a message that is not parked notifies nothing. + /// A task that represents the asynchronous operation. + [Fact] + public async Task OperatorRetryOfNonParkedCall_NotifiesNothing() + { + var id = await EnqueueBufferedAsync(StoreAndForwardCategory.ExternalSystem, "ERP", maxRetries: 5); + + Assert.False(await _service.RetryParkedMessageAsync(id.ToString())); + Assert.Empty(_observer.Notifications); + } + // ── Per-attempt observer notifications ── /// Verifies that a failed attempt with an HTTP 500 emits attempted telemetry.