Merge #991: Galaxy secured-write map filled at init, dropped pump events resync, deploy-watch backoff, replay-gap handle release, HTTP/2 keep-alive on driver channels
This commit is contained in:
@@ -458,8 +458,8 @@ The Galaxy/MxAccess connection settings are **not an `appsettings` section.** Th
|
||||
|
||||
| Record | Key fields (default) | Meaning |
|
||||
|---|---|---|
|
||||
| `GalaxyGatewayOptions` (`Gateway`) | `Endpoint`; `ApiKeySecretRef`; `UseTls` (`true`); `CaCertificatePath` (`null`); `ConnectTimeoutSeconds` (`10`); `DefaultCallTimeoutSeconds` (`30`); `StreamTimeoutSeconds` (`0` = unlimited) | mxaccessgw gateway connection. `ApiKeySecretRef` supports `secret:galaxy/<name>` (or `secret:otopcua/galaxy/<name>`) / `env:OTOPCUA_GALAXY_<NAME>` (or legacy `env:GALAXY_MXGW_<NAME>`) / `dev:KEY` / literal forms (resolved at `InitializeAsync`); prefer `secret:` in production. Any other `secret:`/`env:` reference and every `file:` reference is refused at save, deploy (`CredentialReferenceOutOfScope`), Test Connect, browse and resolve — #815, see `docs/security.md` §"Credential references are namespaced per driver". Never store a cleartext key. |
|
||||
| `GalaxyMxAccessOptions` (`MxAccess`) | `ClientName`; `PublishingIntervalMs` (`1000`); `WriteUserId` (`0` = anonymous); `EventPumpChannelCapacity` (`50000`) | MXAccess client identity + tuning. `ClientName` **must be unique per OtOpcUa instance** (redundancy pairs enforce this). |
|
||||
| `GalaxyGatewayOptions` (`Gateway`) | `Endpoint`; `ApiKeySecretRef`; `UseTls` (`true`); `CaCertificatePath` (`null`); `ConnectTimeoutSeconds` (`10`); `DefaultCallTimeoutSeconds` (`30`); `StreamTimeoutSeconds` (`0` = unlimited); `KeepAlivePingDelaySeconds` (`15`, `0` = no pings); `KeepAlivePingTimeoutSeconds` (`10`) — HTTP/2 keep-alive on the driver's gateway channels, so a silently dead connection faults the event stream (#991 G-19) | mxaccessgw gateway connection. `ApiKeySecretRef` supports `secret:galaxy/<name>` (or `secret:otopcua/galaxy/<name>`) / `env:OTOPCUA_GALAXY_<NAME>` (or legacy `env:GALAXY_MXGW_<NAME>`) / `dev:KEY` / literal forms (resolved at `InitializeAsync`); prefer `secret:` in production. Any other `secret:`/`env:` reference and every `file:` reference is refused at save, deploy (`CredentialReferenceOutOfScope`), Test Connect, browse and resolve — #815, see `docs/security.md` §"Credential references are namespaced per driver". Never store a cleartext key. |
|
||||
| `GalaxyMxAccessOptions` (`MxAccess`) | `ClientName`; `PublishingIntervalMs` (`1000`); `WriteUserId` (`0` = anonymous; the user a raw `Write` and a `WriteSecured` carry); `EventPumpChannelCapacity` (`50000`) | MXAccess client identity + tuning. `ClientName` **must be unique per OtOpcUa instance** (redundancy pairs enforce this). |
|
||||
| `GalaxyRepositoryOptions` (`Repository`) | `DiscoverPageSize` (`5000`); `WatchDeployEvents` (`true`) | Galaxy Repository browse paging + deploy-event watching. |
|
||||
| `GalaxyReconnectOptions` (`Reconnect`) | `InitialBackoffMs` (`500`); `MaxBackoffMs` (`30000`); `ReplayOnSessionLost` (`true`) | In-driver reconnect-supervisor backoff. |
|
||||
| (top-level) | `ProbeTimeoutSeconds` (`30`, range 1–60) | AdminUI Test-Connect probe timeout. |
|
||||
|
||||
@@ -81,8 +81,8 @@ Project root files:
|
||||
|
||||
`DriverConfig` JSON binds to `Config/GalaxyDriverOptions.cs`. The four sections are:
|
||||
|
||||
- **`Gateway`** — endpoint, API key secret ref (`secret:galaxy/<name>` · `secret:otopcua/galaxy/<name>` · `env:OTOPCUA_GALAXY_<NAME>` · legacy `env:GALAXY_MXGW_<NAME>` · `dev:KEY` · literal; anything else, incl. `file:`, is refused — #815 (an already-deployed driver keeps resolving a pre-#815 ref on init and every gateway reconnect in deprecated warn-only mode until its next deploy), [`docs/security.md`](../security.md) §"Credential references are namespaced per driver"), TLS knobs, connect/call/stream timeouts. `StreamTimeoutSeconds = 0` keeps the long-lived `StreamEvents` RPC open for the driver's lifetime.
|
||||
- **`MxAccess`** — `ClientName` (must be unique per OtOpcUa instance — redundancy pairs enforce uniqueness at install time), `PublishingIntervalMs` (forwarded as `buffered_update_interval_ms` on subscribe), `WriteUserId` for ArchestrA secured-write, `EventPumpChannelCapacity` (default 50_000 — one second of headroom at 50k tags / 1Hz; tune via the `galaxy.events.dropped` metric).
|
||||
- **`Gateway`** — endpoint, API key secret ref (`secret:galaxy/<name>` · `secret:otopcua/galaxy/<name>` · `env:OTOPCUA_GALAXY_<NAME>` · legacy `env:GALAXY_MXGW_<NAME>` · `dev:KEY` · literal; anything else, incl. `file:`, is refused — #815 (an already-deployed driver keeps resolving a pre-#815 ref on init and every gateway reconnect in deprecated warn-only mode until its next deploy), [`docs/security.md`](../security.md) §"Credential references are namespaced per driver"), TLS knobs, connect/call/stream timeouts. `StreamTimeoutSeconds = 0` keeps the long-lived `StreamEvents` RPC open for the driver's lifetime. `KeepAlivePingDelaySeconds` (`15`) / `KeepAlivePingTimeoutSeconds` (`10`) — HTTP/2 keep-alive pings on every gateway channel (#991 G-19, below); `0` disables them.
|
||||
- **`MxAccess`** — `ClientName` (must be unique per OtOpcUa instance — redundancy pairs enforce uniqueness at install time), `PublishingIntervalMs` (forwarded as `buffered_update_interval_ms` on subscribe), `WriteUserId` — the user id a raw `Write` and (#991 G-1) a `WriteSecured` carry, `EventPumpChannelCapacity` (default 50_000 — one second of headroom at 50k tags / 1Hz; tune via the `galaxy.events.dropped` metric).
|
||||
- **`Repository`** — `DiscoverPageSize`, `WatchDeployEvents`.
|
||||
- **`Reconnect`** — `InitialBackoffMs`, `MaxBackoffMs`, `ReplayOnSessionLost` (default `true`: after a gateway session is recreated, re-issue `SubscribeBulk` for every tracked subscription; `false` leaves them stranded — Bad + Degraded, see [Reconnect + Replay](#reconnect--replay)).
|
||||
- **`AlarmAck`** (optional, lmxopcua#749) — `FallbackUser`, `FallbackDomain`, `FallbackPasswordSecretRef`. See [Alarm acknowledge credential](#alarm-acknowledge-credential). `ConfirmTimeoutMs` (default `10000`, max `120000`, `0` = do not wait, negative = default; #869) — see [Ack confirmation](#ack-confirmation-869).
|
||||
@@ -202,7 +202,7 @@ Full per-field descriptions live in `Config/GalaxyDriverOptions.cs`. The full JS
|
||||
|
||||
The per-platform `ScanState` probe watcher is not replayed when `ReplayOnSessionLost = false` either (unchanged), so `/hosts` per-platform status also stops updating until a re-init.
|
||||
|
||||
The session-less alarm feed (`GatewayGalaxyAlarmFeed`) and alarm acknowledger (`GatewayGalaxyAlarmAcknowledger`) run on a separate always-on `_ownedMxClient` that is intentionally **not** recreated when `ReconnectSupervisor` rebuilds the worker session. The feed has its own re-invoke loop (~5 s backoff) that reopens `StreamAlarms` after any stream fault, and gRPC.NET's channel auto-reconnect recovers the underlying HTTP/2 connection after a gateway restart — so both the alarm stream and individual ack calls recover without client replacement. The acknowledger is completely stateless between calls: each `AcknowledgeAsync` issues a single unary RPC and returns; no dead-client state is latched on failure. Channel-level keepalive hardening (TCP keep-alive intervals, gRPC ping frames) would require exposing additional knobs on `MxGatewayClientOptions` in the sibling `mxaccessgw` repo — a future option if flaky long-lived connections are observed in production.
|
||||
The session-less alarm feed (`GatewayGalaxyAlarmFeed`) and alarm acknowledger (`GatewayGalaxyAlarmAcknowledger`) run on a separate always-on `_ownedMxClient` that is intentionally **not** recreated when `ReconnectSupervisor` rebuilds the worker session. The feed has its own re-invoke loop (~5 s backoff) that reopens `StreamAlarms` after any stream fault, and gRPC.NET's channel auto-reconnect recovers the underlying HTTP/2 connection after a gateway restart — so both the alarm stream and individual ack calls recover without client replacement. The acknowledger is completely stateless between calls: each `AcknowledgeAsync` issues a single unary RPC and returns; no dead-client state is latched on failure. **A silently dead gateway connection now faults the streams (#991 G-19).** The client library's channel (mxaccessgw client 0.4.0) has no HTTP/2 keep-alive, and a server stream sends nothing after its request — so a gateway host that lost power, or a firewall that started dropping the flow (no FIN/RST), left `StreamEvents` waiting forever: the supervisor was never told, Galaxy stayed `Healthy`, and every value was served stale as Good. The driver now builds every long-lived client's channel itself (`Runtime/GalaxyGatewayChannelFactory.cs` — the session's `StreamEvents`, `_ownedMxClient`'s `StreamAlarms`, the repository client's `WatchDeployEvents`) with `KeepAlivePingPolicy.Always` pings; an unanswered PING fails the connection within delay + timeout (~25 s by default), the stream faults, and recovery is the ordinary reconnect path. The handler's TLS settings mirror the client library's (keep them in step until the client exposes keep-alive itself — mxaccessgw follow-up). The short-lived Test Connect probe and `/raw` browser still use the library's channel. Unary calls are unaffected (they carry deadlines already).
|
||||
|
||||
Every (re)open of `StreamAlarms` replays the gateway's active-alarm snapshot. `GatewayGalaxyAlarmFeed` maps each entry to a transition flagged `IsRestatement` (#656): `Active` → `Retrigger` (upstream's unack is authoritative), `ActiveAcked` → `ActiveAcknowledged` (one atomic active+acked projection — the old `Acknowledge` mapping projected an acked alarm **inactive** on a cold host), `Inactive` → `Clear`. The host writes no `/alerts` row for a replayed entry that changes nothing the condition shows, so a gateway reconnect no longer duplicates history; live `Transition` messages are never flagged. The gateway folds UnackRtn and AckRtn into `Inactive`, so an inactive-unacked alarm cannot be distinguished at reconnect (gateway contract limit).
|
||||
|
||||
@@ -235,9 +235,13 @@ Every (re)open of `StreamAlarms` replays the gateway's active-alarm snapshot. `G
|
||||
|
||||
- **MXAccess `ClientName` collisions**: two OtOpcUa instances sharing a `ClientName` cause the older Wonderware session to lose subscription state. Redundancy pairs (decision #149) enforce uniqueness via install scripts.
|
||||
- **Channel saturation**: `galaxy.events.dropped > 0` indicates `EventPump` is back-pressured. Raise `EventPumpChannelCapacity` or investigate downstream slowness in the server-side fan-out.
|
||||
- **A dropped change is re-read (#991 G-4).** MXAccess sends a value only when it changes, so a data change the full channel drops (newest-dropped) used to leave its tag at the previous value, Good, until the attribute next changed. The pump records the item handles of dropped data changes and, once its channel has drained (so the resync is not lost to the same congestion), the driver re-advises exactly those tags — an advise is answered with the current value — rebinds them, and releases the superseded handles. One coalescing background worker; serialised with the replay-gap re-snapshot. The `galaxy.events.dropped` counter is unchanged; each burst logs one Warning ("re-reading them") and one Information line with the re-advised count.
|
||||
- **OPC DA limit bits do not warn (#991 G-2).** `StatusCodeMap.FromQualityByte` masks the two limit bits (`QQSSSSLL`) before its table lookup, so `Good | LowLimited` (0xC1) and friends map like the unlimited quality. A byte still unlisted after the mask logs one Warning per distinct value per process — it used to log one per event on the pump's dispatch thread, enough to back the channel up into drops.
|
||||
- **The deploy watcher paces every stream end (#991 G-3).** A `WatchDeployEvents` stream the gateway completes cleanly is re-subscribed after the same capped exponential backoff as a faulted one (1 s doubling to 30 s), and the backoff resets only after a stream stayed open 60 s — an event alone (the bootstrap every stream delivers) no longer resets it. It used to re-open immediately, hammering a gateway that ends its streams after the bootstrap.
|
||||
- **Secured writes are routed without a discovery pass (#991 G-1).** `WriteAsync` sends SecuredWrite / VerifiedWrite attributes through `WriteSecured` and everything else through the supervisory raw `Write`, by a per-tag classification map. Only `DiscoverAsync` used to fill it — and the runtime never calls `DiscoverAsync` on a served driver (only the `/raw` picker's throwaway instance does) — so every authored tag resolved `FreeAccess` and a secured attribute's writes were refused as `BadUserAccessDenied`. The map is now seeded for the authored tags at `InitializeAsync` and on every deploy-watcher rediscovery, in the background, by one rooted depth-0 `DiscoverHierarchy` per authored object (`Browse/GatewayGalaxyAttributeSecuritySource`, 4 concurrent; cost tracks the authored objects, not the Galaxy). Until the seed lands, or if it fails, a tag keeps the `FreeAccess` default (raw path, fails closed). ⚠️ `WriteSecured` now carries `MxAccess.WriteUserId` as the current user (it was a hard-coded 0) and no verifier: with the default `WriteUserId = 0` MXAccess is expected to refuse a secured write (a Warning says so at seed time), and a VerifiedWrite needs a verifier identity nothing supplies yet. Not live-gated.
|
||||
- **Connectivity surface**: per-platform probe state is exposed through `IHostConnectivityProbe` and aggregated by the server's connectivity bus — there is no driver-private dashboard surface anymore. The Admin UI's Host Status panel is the consumer.
|
||||
- **A stream the gateway ends cleanly is treated as a fault.** A closed or evicted gateway session completes the `StreamEvents` RPC *without an error*, so nothing throws. `EventPump` reports that to the `ReconnectSupervisor` exactly as it reports a transport fault. Before this it exited silently: the supervisor was never told, `GetHealth()` kept reporting `Healthy`, and because the [comms-loss watchdog](../DriverLifecycle.md) requires a **non-Healthy** state to trip, it never fired either — the driver went permanently deaf with no signal anywhere. Nothing else in the system can observe this, so do not remove the notification on the grounds that "a clean end isn't an error".
|
||||
- **Replay gaps** (`galaxy.events.replay_gaps`): the gateway signals that events were evicted from its replay ring before we could read them. The driver responds by re-issuing `SubscribeBulk` for every tracked subscription — MXAccess delivers an initial value per item on subscribe, so re-subscribing *is* the re-snapshot the contract asks for. It does **not** restart the event pump (the stream carrying the sentinel is healthy) and it honours `Reconnect:ReplayOnSessionLost=false` by logging and standing down, on the grounds that an operator who delegated recovery to the gateway did not ask for a re-subscribe on a different trigger.
|
||||
- **Replay gaps** (`galaxy.events.replay_gaps`): the gateway signals that events were evicted from its replay ring before we could read them. The driver responds by re-issuing `SubscribeBulk` for every tracked subscription — MXAccess delivers an initial value per item on subscribe, so re-subscribing *is* the re-snapshot the contract asks for. Since the session is the same, the pre-gap handles are still advised: the re-snapshot releases every handle it supersedes (driver subscriptions and probe handles alike — #991 G-6; a tag whose re-advise fails keeps its live handle), so a gap no longer doubles the gateway's advise count. It does **not** restart the event pump (the stream carrying the sentinel is healthy) and it honours `Reconnect:ReplayOnSessionLost=false` by logging and standing down, on the grounds that an operator who delegated recovery to the gateway did not ask for a re-subscribe on a different trigger.
|
||||
⚠️ This cannot currently fire: the sentinel is only emitted on a stream opened with `after_worker_sequence > 0`, and the driver opens with `0`, which the gateway treats as "fresh stream, not a resume". Enabling resume is a bigger change than it looks — the sequence is only meaningful **within one gateway session**, and the reconnect path recreates the session, so a remembered sequence replayed against a fresh session would set the server's live watermark *above* every event it is about to send, silencing the stream rather than recovering it.
|
||||
- **MXAccess status rows → OPC UA status (`StatusCodeMap.FromMxStatus`, #866/#872)**: an `Ok` row is graded by the item's OPC DA quality. Any other row's `detail` is an MxStatusDetail code (never a quality byte) and maps through the mxaccessgw vocabulary table (e.g. 1007 → `BadNotWritable`, 1008 → `BadUserAccessDenied`, 13/1005 → `BadTypeMismatch`, and the live-captured automation-object code **8001** — write rejected for type conversion → `BadTypeMismatch`). Unmapped details fall back to the category (`SecurityError` → `BadUserAccessDenied`, so 8018 is too; `CommunicationError` → `BadCommunicationError`; `ConfigurationError` → `BadConfigurationError`; else `Bad`), logged once per (detail, category). `detected_by` never decides the code. **`Pending` and `Warning` rows map to `Uncertain` (`0x40000000`) for any detail**: MXAccess sets success = -1 on Pending (accepted, in progress), so they are not failures. On a data change the value is published Uncertain. On a write reply the result is Uncertain, not Good, so the server reports the write as not committed and reverts the node; a commit MXAccess completes later arrives as a normal data change. Neither category has been seen on a data-change or write-reply row yet (mxaccessgw `docs/LiveCaptures-2026-11-13.md` §3), so the first one logs a warning.
|
||||
- **Undecodable values** (`galaxy.events.undecodable`): a value kind this driver has no CLR representation for is published as **`BadTypeMismatch` with a null value**, and the first occurrence of each distinct kind is logged. It is *not* published as a null carrying the event's own quality: an MXAccess event can be Good-quality while the payload is one we cannot map, and a good null is indistinguishable from a genuine null reading — a client would consume a value it never received as a real one, with the failure visible only in a log. Non-zero here means the gateway is sending a wire type `MxValueDecoder` has no mapping for and those readings are being lost; the fix is a decoder mapping, not a quality change.
|
||||
|
||||
@@ -37,7 +37,7 @@ the metrics surface instead.
|
||||
|---------|------|---------|
|
||||
| `galaxy.events.received` | `{event}` | MxEvents read from the gateway StreamEvents stream |
|
||||
| `galaxy.events.dispatched` | `{event}` | MxEvents that made it through the bounded channel into `OnDataChange` |
|
||||
| `galaxy.events.dropped` | `{event}` | MxEvents discarded because the bounded channel was full (newest-dropped) |
|
||||
| `galaxy.events.dropped` | `{event}` | MxEvents discarded because the bounded channel was full (newest-dropped). The affected tags are re-advised once the channel drains (#991 G-4) |
|
||||
| `galaxy.events.replay_gaps` | `{gap}` | Replay-gap sentinels received — the gateway evicted events we can never see |
|
||||
| `galaxy.events.undecodable` | `{event}` | Data-change events carrying a value kind this driver cannot represent |
|
||||
| `galaxy.events.early_parked` | `{event}` | Data-change events that overtook their SubscribeBulk reply and were parked for replay (#859) |
|
||||
|
||||
@@ -129,6 +129,14 @@ public sealed record GalaxyAlarmAckOptions(
|
||||
// legitimate worst case while still failing fast on a wedged worker.
|
||||
// StreamTimeoutSeconds = 0 — unlimited; the StreamEvents RPC must run for the
|
||||
// lifetime of the driver. Set a finite value only for diagnostic runs.
|
||||
// KeepAlivePingDelaySeconds = 15 / KeepAlivePingTimeoutSeconds = 10 (#991 G-19) — HTTP/2 PING
|
||||
// frames on every gateway channel, sent even while no call is active. A long-lived
|
||||
// server stream (StreamEvents, StreamAlarms, WatchDeployEvents) sends nothing after its
|
||||
// request, so a gateway host that loses power or a firewall that starts dropping the
|
||||
// flow (no FIN/RST) used to leave the stream waiting forever — Galaxy stayed Healthy
|
||||
// serving stale Good values. An unanswered ping now fails the connection within
|
||||
// delay + timeout (~25 s), the stream faults and the reconnect supervisor takes over.
|
||||
// 0 disables the pings (the .NET default).
|
||||
public sealed record GalaxyGatewayOptions(
|
||||
string Endpoint,
|
||||
string ApiKeySecretRef,
|
||||
@@ -136,7 +144,9 @@ public sealed record GalaxyGatewayOptions(
|
||||
string? CaCertificatePath = null,
|
||||
int ConnectTimeoutSeconds = 10,
|
||||
int DefaultCallTimeoutSeconds = 30,
|
||||
int StreamTimeoutSeconds = 0);
|
||||
int StreamTimeoutSeconds = 0,
|
||||
int KeepAlivePingDelaySeconds = 15,
|
||||
int KeepAlivePingTimeoutSeconds = 10);
|
||||
|
||||
/// <summary>
|
||||
/// MXAccess-specific knobs the gateway forwards to the worker process.
|
||||
|
||||
@@ -27,17 +27,26 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Browse;
|
||||
/// so a reconnect doesn't fan out a redundant rediscover for state we already
|
||||
/// knew about.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// A stream the gateway COMPLETES without an error is paced exactly like a fault (#991 G-3): it used to
|
||||
/// loop straight back into a new RPC, and since every event — the bootstrap each stream delivers
|
||||
/// included — reset the backoff, a gateway that ends its streams after the bootstrap (a drain, an
|
||||
/// idle-stream limit) was re-subscribed as fast as the RPC round-trips. The backoff now resets only when
|
||||
/// a stream stayed open for <c>stableStreamDuration</c>.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class DeployWatcher : IDisposable
|
||||
{
|
||||
private static readonly TimeSpan DefaultInitialBackoff = TimeSpan.FromSeconds(1);
|
||||
private static readonly TimeSpan DefaultMaxBackoff = TimeSpan.FromSeconds(30);
|
||||
private static readonly TimeSpan DefaultStableStreamDuration = TimeSpan.FromSeconds(60);
|
||||
|
||||
private readonly IGalaxyDeployWatchSource _source;
|
||||
private readonly ILogger _logger;
|
||||
private readonly TimeSpan _initialBackoff;
|
||||
private readonly TimeSpan _maxBackoff;
|
||||
private readonly Func<int, TimeSpan>? _jitter;
|
||||
private readonly TimeSpan _stableStreamDuration;
|
||||
|
||||
private CancellationTokenSource? _cts;
|
||||
private Task? _loopTask;
|
||||
@@ -63,13 +72,19 @@ public sealed class DeployWatcher : IDisposable
|
||||
/// <param name="initialBackoff">Initial backoff duration for retry.</param>
|
||||
/// <param name="maxBackoff">Maximum backoff duration for retry.</param>
|
||||
/// <param name="jitter">Optional function to apply jitter to backoff intervals.</param>
|
||||
/// <param name="stableStreamDuration">
|
||||
/// How long a stream must stay open before its end resets the backoff (default 60 s). A shorter-lived
|
||||
/// stream — clean completion or fault — keeps growing the backoff.
|
||||
/// </param>
|
||||
internal DeployWatcher(
|
||||
IGalaxyDeployWatchSource source,
|
||||
ILogger? logger,
|
||||
TimeSpan initialBackoff,
|
||||
TimeSpan maxBackoff,
|
||||
Func<int, TimeSpan>? jitter)
|
||||
Func<int, TimeSpan>? jitter,
|
||||
TimeSpan? stableStreamDuration = null)
|
||||
{
|
||||
_stableStreamDuration = stableStreamDuration ?? DefaultStableStreamDuration;
|
||||
_source = source ?? throw new ArgumentNullException(nameof(source));
|
||||
_logger = logger ?? NullLogger.Instance;
|
||||
_initialBackoff = initialBackoff;
|
||||
@@ -140,6 +155,8 @@ public sealed class DeployWatcher : IDisposable
|
||||
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
var streamOpened = System.Diagnostics.Stopwatch.StartNew();
|
||||
Exception? fault = null;
|
||||
try
|
||||
{
|
||||
await foreach (DeployEvent ev in _source
|
||||
@@ -147,10 +164,6 @@ public sealed class DeployWatcher : IDisposable
|
||||
.WithCancellation(cancellationToken)
|
||||
.ConfigureAwait(false))
|
||||
{
|
||||
// Successful read — reset retry state.
|
||||
backoff = _initialBackoff;
|
||||
attempt = 0;
|
||||
|
||||
DateTimeOffset? observedTime = ev.TimeOfLastDeployPresent && ev.TimeOfLastDeploy is not null
|
||||
? ev.TimeOfLastDeploy.ToDateTimeOffset()
|
||||
: null;
|
||||
@@ -200,10 +213,9 @@ public sealed class DeployWatcher : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
// Stream completed normally — gateway closed the subscription. Re-open
|
||||
// immediately if we weren't asked to stop.
|
||||
_logger.LogDebug("DeployWatcher stream completed; re-subscribing.");
|
||||
continue;
|
||||
// Stream completed normally — the gateway (or a proxy) closed the subscription. Paced below like
|
||||
// a fault (#991 G-3): an immediate re-open hammered a gateway that ends every stream after the
|
||||
// bootstrap event.
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
@@ -211,26 +223,47 @@ public sealed class DeployWatcher : IDisposable
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
attempt++;
|
||||
TimeSpan jitterAmount = _jitter?.Invoke(attempt) ?? RandomJitter(backoff);
|
||||
TimeSpan delay = backoff + jitterAmount;
|
||||
_logger.LogWarning(ex,
|
||||
fault = ex;
|
||||
}
|
||||
|
||||
if (cancellationToken.IsCancellationRequested) break;
|
||||
|
||||
// Reset only after a stream that stayed up — an event alone (every stream's bootstrap) proves nothing
|
||||
// about the gateway keeping it open.
|
||||
if (streamOpened.Elapsed >= _stableStreamDuration)
|
||||
{
|
||||
backoff = _initialBackoff;
|
||||
attempt = 0;
|
||||
}
|
||||
|
||||
attempt++;
|
||||
TimeSpan jitterAmount = _jitter?.Invoke(attempt) ?? RandomJitter(backoff);
|
||||
TimeSpan delay = backoff + jitterAmount;
|
||||
if (fault is not null)
|
||||
{
|
||||
_logger.LogWarning(fault,
|
||||
"DeployWatcher source threw; retrying in {Delay} (attempt {Attempt}, last-seen time {LastSeen}).",
|
||||
delay, attempt, lastSeenDeployTime);
|
||||
|
||||
try
|
||||
{
|
||||
await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
// Exponential backoff capped at _maxBackoff.
|
||||
var doubled = TimeSpan.FromTicks(Math.Min(_maxBackoff.Ticks, backoff.Ticks * 2));
|
||||
backoff = doubled < _initialBackoff ? _initialBackoff : doubled;
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogDebug(
|
||||
"DeployWatcher stream completed by the gateway after {Open}; re-subscribing in {Delay} (attempt {Attempt}).",
|
||||
streamOpened.Elapsed, delay, attempt);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
// Exponential backoff capped at _maxBackoff.
|
||||
var doubled = TimeSpan.FromTicks(Math.Min(_maxBackoff.Ticks, backoff.Ticks * 2));
|
||||
backoff = doubled < _initialBackoff ? _initialBackoff : doubled;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
using System.Collections.Concurrent;
|
||||
using Grpc.Core;
|
||||
using ZB.MOM.WW.MxGateway.Client;
|
||||
using ZB.MOM.WW.MxGateway.Contracts.Proto.Galaxy;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Browse;
|
||||
|
||||
/// <summary>
|
||||
/// Driver-side seam for the per-attribute <c>security_classification</c> of the AUTHORED Galaxy objects
|
||||
/// (#991 G-1). <c>WriteAsync</c> routes SecuredWrite / VerifiedWrite attributes to <c>WriteSecured</c>; that
|
||||
/// classification used to come only from <c>DiscoverAsync</c>, which the runtime never calls on a served driver,
|
||||
/// so every write took the raw path. The driver seeds its security map from this at <c>InitializeAsync</c> and
|
||||
/// on every deploy-watcher rediscovery.
|
||||
/// </summary>
|
||||
public interface IGalaxyAttributeSecuritySource
|
||||
{
|
||||
/// <summary>The named objects with their attributes. A name the Galaxy does not hold is simply absent.</summary>
|
||||
/// <param name="tagNames">Object <c>tag_name</c>s (the part of an attributeRef before its first dot).</param>
|
||||
/// <param name="cancellationToken">Cancellation token for the query.</param>
|
||||
/// <returns>The objects found, each with its attributes.</returns>
|
||||
Task<IReadOnlyList<GalaxyObject>> GetObjectsAsync(IReadOnlyCollection<string> tagNames, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Default <see cref="IGalaxyAttributeSecuritySource"/>: one <c>DiscoverHierarchy</c> per authored object, rooted
|
||||
/// at its <c>tag_name</c> with <c>max_depth = 0</c> and attributes included — the cost scales with the authored
|
||||
/// objects, not the Galaxy (the full-hierarchy dump the <c>/raw</c> picker pulls would be fetched on every driver
|
||||
/// init). A bounded number run concurrently; an object the gateway reports <c>NotFound</c> is skipped.
|
||||
/// </summary>
|
||||
public sealed class GatewayGalaxyAttributeSecuritySource : IGalaxyAttributeSecuritySource
|
||||
{
|
||||
/// <summary>Concurrent per-object queries.</summary>
|
||||
public const int MaxConcurrency = 4;
|
||||
|
||||
private readonly GalaxyRepositoryClient _client;
|
||||
|
||||
/// <summary>Initializes a new instance of the <see cref="GatewayGalaxyAttributeSecuritySource"/> class.</summary>
|
||||
/// <param name="client">The gateway's Galaxy repository client.</param>
|
||||
public GatewayGalaxyAttributeSecuritySource(GalaxyRepositoryClient client)
|
||||
=> _client = client ?? throw new ArgumentNullException(nameof(client));
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<IReadOnlyList<GalaxyObject>> GetObjectsAsync(
|
||||
IReadOnlyCollection<string> tagNames, CancellationToken cancellationToken)
|
||||
=> QueryAsync(_client.DiscoverHierarchyRawAsync, tagNames, MaxConcurrency, cancellationToken);
|
||||
|
||||
/// <summary>The per-object queries behind a delegate, so they are unit-testable without a channel.</summary>
|
||||
/// <param name="discover">The raw <c>DiscoverHierarchy</c> RPC.</param>
|
||||
/// <param name="tagNames">The objects to fetch.</param>
|
||||
/// <param name="maxConcurrency">Concurrent queries.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>The objects found (only the requested root of each reply).</returns>
|
||||
internal static async Task<IReadOnlyList<GalaxyObject>> QueryAsync(
|
||||
Func<DiscoverHierarchyRequest, CancellationToken, Task<DiscoverHierarchyReply>> discover,
|
||||
IReadOnlyCollection<string> tagNames,
|
||||
int maxConcurrency,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(discover);
|
||||
var found = new ConcurrentBag<GalaxyObject>();
|
||||
await Parallel.ForEachAsync(
|
||||
tagNames,
|
||||
new ParallelOptions { MaxDegreeOfParallelism = Math.Max(1, maxConcurrency), CancellationToken = cancellationToken },
|
||||
async (tagName, token) =>
|
||||
{
|
||||
var request = new DiscoverHierarchyRequest
|
||||
{
|
||||
RootTagName = tagName,
|
||||
MaxDepth = 0,
|
||||
IncludeAttributes = true,
|
||||
PageSize = 1,
|
||||
};
|
||||
DiscoverHierarchyReply reply;
|
||||
try
|
||||
{
|
||||
reply = await discover(request, token).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (IsNotFound(ex))
|
||||
{
|
||||
return; // not deployed (any more) — no classification to learn
|
||||
}
|
||||
foreach (var obj in reply.Objects)
|
||||
{
|
||||
if (string.Equals(obj.TagName, tagName, StringComparison.OrdinalIgnoreCase)) found.Add(obj);
|
||||
}
|
||||
}).ConfigureAwait(false);
|
||||
return [.. found];
|
||||
}
|
||||
|
||||
private static bool IsNotFound(Exception ex)
|
||||
{
|
||||
for (var e = ex; e is not null; e = e.InnerException)
|
||||
{
|
||||
if (e is RpcException { StatusCode: StatusCode.NotFound }) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="IGalaxyAttributeSecuritySource"/> over an injected <see cref="IGalaxyHierarchySource"/> — the
|
||||
/// seam-mode fallback, so a driver built around a hierarchy source seeds the same way production does.
|
||||
/// </summary>
|
||||
internal sealed class HierarchyAttributeSecuritySource(IGalaxyHierarchySource hierarchy) : IGalaxyAttributeSecuritySource
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<GalaxyObject>> GetObjectsAsync(
|
||||
IReadOnlyCollection<string> tagNames, CancellationToken cancellationToken)
|
||||
{
|
||||
var wanted = new HashSet<string>(tagNames, StringComparer.OrdinalIgnoreCase);
|
||||
var all = await hierarchy.GetHierarchyAsync(cancellationToken).ConfigureAwait(false);
|
||||
return [.. all.Where(o => wanted.Contains(o.TagName))];
|
||||
}
|
||||
}
|
||||
@@ -190,6 +190,40 @@ public sealed class GalaxyDriver
|
||||
// BuildProductionRuntimeAsync entirely.
|
||||
private GalaxyMxSession? _ownedMxSession;
|
||||
private MxGatewayClient? _ownedMxClient;
|
||||
// #991 G-19: the keep-alive channels the owned clients run on (a client over a caller-owned channel does not
|
||||
// dispose it), released after their client in the teardown.
|
||||
private Grpc.Net.Client.GrpcChannel? _ownedMxChannel;
|
||||
private Grpc.Net.Client.GrpcChannel? _ownedRepositoryChannel;
|
||||
|
||||
/// <summary>A gateway channel with this driver's HTTP/2 keep-alive settings (#991 G-19).</summary>
|
||||
private Grpc.Net.Client.GrpcChannel CreateGatewayChannel(MxGatewayClientOptions clientOptions) =>
|
||||
GalaxyGatewayChannelFactory.CreateChannel(clientOptions, _options.Gateway);
|
||||
|
||||
/// <summary>
|
||||
/// The owned repository client (deploy watch, platform / security seeds, lazy discovery), built once per
|
||||
/// runtime over a keep-alive channel — <c>WatchDeployEvents</c> is a long-lived server stream too.
|
||||
/// </summary>
|
||||
private async Task<GalaxyRepositoryClient> EnsureOwnedRepositoryClientAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (_ownedRepositoryClient is { } existing) return existing;
|
||||
var clientOptions = await BuildClientOptionsAsync(_options.Gateway, cancellationToken).ConfigureAwait(false);
|
||||
if (_ownedRepositoryClient is { } raced) return raced;
|
||||
var channel = CreateGatewayChannel(clientOptions);
|
||||
try
|
||||
{
|
||||
_ownedRepositoryClient = GalaxyRepositoryClient.Create(channel, clientOptions);
|
||||
}
|
||||
catch
|
||||
{
|
||||
channel.Dispose();
|
||||
throw;
|
||||
}
|
||||
_ownedRepositoryChannel = channel;
|
||||
return _ownedRepositoryClient;
|
||||
}
|
||||
|
||||
/// <summary>Test seam: the keep-alive channel the owned gateway client runs on.</summary>
|
||||
internal Grpc.Net.Client.GrpcChannel? OwnedMxChannelForTests => _ownedMxChannel;
|
||||
|
||||
// PR 4.5 — reconnect supervisor. Reflects in DriverState.Degraded while not Healthy.
|
||||
private ReconnectSupervisor? _supervisor;
|
||||
@@ -216,6 +250,12 @@ public sealed class GalaxyDriver
|
||||
// from DiscoverAsync alone left the production watcher with no platforms, ever.
|
||||
private readonly IGalaxyPlatformSource? _platformSource;
|
||||
private IGalaxyPlatformSource? _ownedPlatformSource;
|
||||
|
||||
// #991 G-1: the authored tags' security classifications, for WriteAsync's WriteSecured routing. Injected seam
|
||||
// (tests) or, on the production path, per-object DiscoverHierarchy queries over the owned repository client.
|
||||
// Seeded by the same background worker as the platform set (init + every rediscovery).
|
||||
private readonly IGalaxyAttributeSecuritySource? _securitySource;
|
||||
private IGalaxyAttributeSecuritySource? _ownedSecuritySource;
|
||||
// Probe-seed requests (init + every rediscovery) not yet served. The first request starts the
|
||||
// background worker; later ones only bump the count, and the worker loops until it has served
|
||||
// every request it saw — so a request that lands while a pass is mid-fetch (a deploy, or the
|
||||
@@ -388,6 +428,10 @@ public sealed class GalaxyDriver
|
||||
/// over <see cref="GalaxyDriverOptions.AlarmAck"/> and <paramref name="secretResolver"/>.
|
||||
/// </param>
|
||||
/// <param name="ackIdentityDirectory">Optional cached key → Galaxy-identity set (lmxopcua#765).</param>
|
||||
/// <param name="securitySource">
|
||||
/// Optional security-classification seam (#991 G-1). Without it, seam mode falls back to
|
||||
/// <paramref name="hierarchySource"/>; production builds a <see cref="GatewayGalaxyAttributeSecuritySource"/>.
|
||||
/// </param>
|
||||
internal GalaxyDriver(
|
||||
string driverInstanceId,
|
||||
GalaxyDriverOptions options,
|
||||
@@ -402,9 +446,11 @@ public sealed class GalaxyDriver
|
||||
IGalaxyDeployWatchSource? deployWatchSource = null,
|
||||
IGalaxyPlatformSource? platformSource = null,
|
||||
IGalaxyAckCredentialResolver? ackCredentialResolver = null,
|
||||
IGalaxyAckIdentityDirectory? ackIdentityDirectory = null)
|
||||
IGalaxyAckIdentityDirectory? ackIdentityDirectory = null,
|
||||
IGalaxyAttributeSecuritySource? securitySource = null)
|
||||
{
|
||||
_ackIdentityDirectory = ackIdentityDirectory;
|
||||
_securitySource = securitySource;
|
||||
_deployWatchSource = deployWatchSource;
|
||||
_platformSource = platformSource;
|
||||
_driverInstanceId = !string.IsNullOrWhiteSpace(driverInstanceId)
|
||||
@@ -754,24 +800,38 @@ public sealed class GalaxyDriver
|
||||
/// </summary>
|
||||
private async Task PrepareProbeSeedAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (_probeWatcher is null) return;
|
||||
var wantsProbe = _probeWatcher is not null;
|
||||
var wantsSecurity = _rawTagByAttributeRef.Count > 0; // #991 G-1: authored tags need their classifications
|
||||
if (!wantsProbe && !wantsSecurity) return;
|
||||
_seedCts ??= new CancellationTokenSource();
|
||||
if (_platformSource is not null || !_ownsRuntime || _ownedPlatformSource is not null) return;
|
||||
if (!_ownsRuntime) return; // seam mode: injected sources only
|
||||
var needPlatform = wantsProbe && _platformSource is null && _ownedPlatformSource is null;
|
||||
var needSecurity = wantsSecurity && _securitySource is null && _ownedSecuritySource is null;
|
||||
if (!needPlatform && !needSecurity) return;
|
||||
try
|
||||
{
|
||||
_ownedRepositoryClient ??= GalaxyRepositoryClient.Create(
|
||||
await BuildClientOptionsAsync(_options.Gateway, cancellationToken).ConfigureAwait(false));
|
||||
_ownedPlatformSource =
|
||||
new GatewayGalaxyPlatformSource(_ownedRepositoryClient, _options.Repository.DiscoverPageSize);
|
||||
var repository = await EnsureOwnedRepositoryClientAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (needPlatform)
|
||||
{
|
||||
_ownedPlatformSource =
|
||||
new GatewayGalaxyPlatformSource(repository, _options.Repository.DiscoverPageSize);
|
||||
}
|
||||
if (needSecurity) _ownedSecuritySource = new GatewayGalaxyAttributeSecuritySource(repository);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException || !cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
_logger.LogWarning(ex,
|
||||
"GalaxyDriver {InstanceId} could not build the platform query — per-platform host status stays unseeded until the next rediscovery.",
|
||||
"GalaxyDriver {InstanceId} could not build the repository queries — per-platform host status and secured-write routing stay unseeded until the next rediscovery.",
|
||||
_driverInstanceId);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The security-classification source for the current runtime (#991 G-1), or null.</summary>
|
||||
private IGalaxyAttributeSecuritySource? ResolveSecuritySource() =>
|
||||
_securitySource
|
||||
?? _ownedSecuritySource
|
||||
?? (!_ownsRuntime && _hierarchySource is { } hierarchy ? new HierarchyAttributeSecuritySource(hierarchy) : null);
|
||||
|
||||
/// <summary>
|
||||
/// Ask for a background probe seed (init and every deploy-watcher rediscovery). Requests
|
||||
/// coalesce onto one worker; each worker pass serves the runtime that is live when the pass
|
||||
@@ -780,7 +840,8 @@ public sealed class GalaxyDriver
|
||||
/// </summary>
|
||||
private void RequestProbeSeed(string reason)
|
||||
{
|
||||
if (_runtimeStopping || _probeWatcher is null) return;
|
||||
if (_runtimeStopping) return;
|
||||
if (_probeWatcher is null && (_rawTagByAttributeRef.Count == 0 || ResolveSecuritySource() is null)) return;
|
||||
_seedReason = reason;
|
||||
if (Interlocked.Increment(ref _reseedRequests) != 1) return; // the running worker will serve it
|
||||
|
||||
@@ -794,7 +855,9 @@ public sealed class GalaxyDriver
|
||||
var seedCts = Volatile.Read(ref _seedCts);
|
||||
if (!_runtimeStopping && seedCts is not null)
|
||||
{
|
||||
await SeedProbePlatformsAsync(_seedReason, generation, seedCts.Token).ConfigureAwait(false);
|
||||
var reason = _seedReason;
|
||||
await SeedProbePlatformsAsync(reason, generation, seedCts.Token).ConfigureAwait(false);
|
||||
await SeedSecurityClassificationsAsync(reason, generation, seedCts.Token).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
while (Interlocked.Add(ref _reseedRequests, -served) != 0);
|
||||
@@ -843,6 +906,89 @@ public sealed class GalaxyDriver
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #991 G-1 — one security seed pass: fetch the authored objects' attributes and record each authored tag's
|
||||
/// <see cref="SecurityClassification"/> under its RawPath, the key <see cref="WriteAsync"/> resolves against.
|
||||
/// Before this the map was filled only by <see cref="DiscoverAsync"/>, which the runtime never calls on a
|
||||
/// served driver, so every write — SecuredWrite / VerifiedWrite attributes included — took the raw path and
|
||||
/// was refused. Never throws; a failed or late pass leaves the map as it was (FreeAccess for anything unseen,
|
||||
/// i.e. the raw path, which fails closed).
|
||||
/// </summary>
|
||||
private async Task SeedSecurityClassificationsAsync(string reason, int generation, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_rawTagByAttributeRef.Count == 0) return;
|
||||
var source = ResolveSecuritySource();
|
||||
if (source is null) return;
|
||||
|
||||
// tag_name is the part of the attributeRef before its first dot; a provider-qualified reference
|
||||
// ("Galaxy!Area.tag.Attr") names an alarm, never a writable value.
|
||||
var tagNames = _rawTagByAttributeRef.Keys
|
||||
.Where(r => !r.Contains('!', StringComparison.Ordinal) && r.IndexOf('.', StringComparison.Ordinal) > 0)
|
||||
.Select(r => r[..r.IndexOf('.', StringComparison.Ordinal)])
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.ToArray();
|
||||
if (tagNames.Length == 0) return;
|
||||
|
||||
try
|
||||
{
|
||||
var objects = await source.GetObjectsAsync(tagNames, cancellationToken).ConfigureAwait(false);
|
||||
if (Volatile.Read(ref _runtimeGeneration) != generation || _runtimeStopping)
|
||||
{
|
||||
_logger.LogDebug(
|
||||
"GalaxyDriver {InstanceId} discarded a security seed ({Reason}) — its runtime was torn down.",
|
||||
_driverInstanceId, reason);
|
||||
return;
|
||||
}
|
||||
|
||||
var seeded = new Dictionary<string, SecurityClassification>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var obj in objects)
|
||||
{
|
||||
foreach (var attr in obj.Attributes)
|
||||
{
|
||||
if (string.IsNullOrEmpty(attr.AttributeName)) continue;
|
||||
// Same attributeRef derivation as GalaxyDiscoverer, so the two paths key identically.
|
||||
var attributeRef = !string.IsNullOrEmpty(attr.FullTagReference)
|
||||
? (attr.FullTagReference.EndsWith("[]", StringComparison.Ordinal)
|
||||
? attr.FullTagReference[..^2]
|
||||
: attr.FullTagReference)
|
||||
: obj.TagName + "." + attr.AttributeName;
|
||||
if (_rawTagByAttributeRef.TryGetValue(attributeRef, out var entry))
|
||||
seeded[entry.RawPath] = SecurityMap.Map(attr.SecurityClassification);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var entry in _rawTagByAttributeRef.Values)
|
||||
{
|
||||
if (seeded.TryGetValue(entry.RawPath, out var classification)) _securityByFullRef[entry.RawPath] = classification;
|
||||
else _securityByFullRef.TryRemove(entry.RawPath, out _); // gone from the Galaxy: back to the default
|
||||
}
|
||||
|
||||
var secured = seeded.Values.Count(c => c is SecurityClassification.SecuredWrite or SecurityClassification.VerifiedWrite);
|
||||
_logger.LogInformation(
|
||||
"GalaxyDriver {InstanceId} security classifications seeded for {Count} authored tag(s), {Secured} secured/verified ({Reason}).",
|
||||
_driverInstanceId, seeded.Count, secured, reason);
|
||||
if (secured > 0 && _options.MxAccess.WriteUserId == 0)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"GalaxyDriver {InstanceId} has {Secured} SecuredWrite/VerifiedWrite tag(s) but MxAccess.WriteUserId is 0 — " +
|
||||
"WriteSecured carries no ArchestrA user, so MXAccess is expected to refuse those writes.",
|
||||
_driverInstanceId, secured);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (cancellationToken.IsCancellationRequested
|
||||
|| Volatile.Read(ref _runtimeGeneration) != generation)
|
||||
{
|
||||
_logger.LogDebug(ex, "GalaxyDriver {InstanceId} security seed ({Reason}) abandoned by a teardown.",
|
||||
_driverInstanceId, reason);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex,
|
||||
"GalaxyDriver {InstanceId} security seed failed ({Reason}) — secured-write routing stays as it was until the next rediscovery.",
|
||||
_driverInstanceId, reason);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Deploy-watcher rediscovery: a redeploy may add or remove platforms / engines.</summary>
|
||||
private void ReseedProbePlatformsOnRediscovery() => RequestProbeSeed("rediscovery");
|
||||
|
||||
@@ -972,10 +1118,14 @@ public sealed class GalaxyDriver
|
||||
|
||||
_ownsRuntime = true;
|
||||
var clientOptions = await BuildClientOptionsAsync(_options.Gateway, cancellationToken).ConfigureAwait(false);
|
||||
_ownedMxClient = MxGatewayClient.Create(clientOptions);
|
||||
// #991 G-19: every long-lived gateway client runs over a channel with HTTP/2 keep-alive pings — the alarm
|
||||
// feed's StreamAlarms on this one, StreamEvents on the session's own (ChannelFactory below).
|
||||
_ownedMxChannel = CreateGatewayChannel(clientOptions);
|
||||
_ownedMxClient = MxGatewayClient.Create(_ownedMxChannel, clientOptions);
|
||||
_ownedMxSession = new GalaxyMxSession(_options.MxAccess, _logger)
|
||||
{
|
||||
OpenAndRegisterOverrideForTests = SessionOpenOverrideForTests,
|
||||
ChannelFactory = CreateGatewayChannel,
|
||||
};
|
||||
await _ownedMxSession.ConnectAsync(clientOptions, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
@@ -1148,6 +1298,10 @@ public sealed class GalaxyDriver
|
||||
_ownedRepositoryClient = null;
|
||||
}
|
||||
|
||||
// #991 G-19: the keep-alive channels, after the clients built over them (which do not dispose them).
|
||||
DisposeChannel(ref _ownedMxChannel, "MxClient");
|
||||
DisposeChannel(ref _ownedRepositoryChannel, "RepositoryClient");
|
||||
|
||||
if (_ownsRuntime || final)
|
||||
{
|
||||
// Null the seams so the next InitializeAsync rebuilds (production) — injected seams
|
||||
@@ -1157,6 +1311,7 @@ public sealed class GalaxyDriver
|
||||
_hierarchySource = null;
|
||||
_alarmAcknowledger = null;
|
||||
_ownedPlatformSource = null;
|
||||
_ownedSecuritySource = null;
|
||||
_ownsRuntime = false;
|
||||
}
|
||||
}
|
||||
@@ -1166,6 +1321,15 @@ public sealed class GalaxyDriver
|
||||
}
|
||||
}
|
||||
|
||||
private void DisposeChannel(ref Grpc.Net.Client.GrpcChannel? channel, string owner)
|
||||
{
|
||||
var c = channel;
|
||||
channel = null;
|
||||
if (c is null) return;
|
||||
try { c.Dispose(); }
|
||||
catch (Exception ex) { _logger.LogWarning(ex, "{Owner} channel dispose failed", owner); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reopen callback for <see cref="ReconnectSupervisor"/>: recreate the gw session. After a
|
||||
/// gateway restart the existing session handle is faulted / stale but non-null, so a plain
|
||||
@@ -1401,12 +1565,20 @@ public sealed class GalaxyDriver
|
||||
/// <see cref="SubscriptionRegistry.Rebind"/>: a teardown bumps it and clears the registry,
|
||||
/// and a Rebind landing after that would resurrect dead handles into the next runtime.
|
||||
/// </param>
|
||||
/// <param name="sameSession">
|
||||
/// True when <paramref name="entries"/> hold handles the CURRENT gateway session issued (the replay-gap
|
||||
/// re-snapshot): those are still advised, so every handle a re-advise supersedes is released (#991 G-6 —
|
||||
/// each gap used to double the gateway's advise count), and a tag whose re-advise fails keeps its live
|
||||
/// handle. False for the reconnect replay, whose handles died with the old session and whose numbers the
|
||||
/// new session reuses — they are never sent.
|
||||
/// </param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>The number of tag references re-subscribed.</returns>
|
||||
private async Task<int> ResubscribeAllAsync(
|
||||
IReadOnlyList<(long SubscriptionId, IReadOnlyList<TagBinding> Bindings)> entries,
|
||||
int generation,
|
||||
CancellationToken cancellationToken)
|
||||
CancellationToken cancellationToken,
|
||||
bool sameSession = false)
|
||||
{
|
||||
var tagCount = 0;
|
||||
// M-b: the session this pass belongs to, read ONCE. Any later change fences the rest of the
|
||||
@@ -1425,44 +1597,106 @@ public sealed class GalaxyDriver
|
||||
{
|
||||
// The probe watcher owns its handles: it re-subscribes its platforms, records the
|
||||
// fresh handles and rebinds the reserved registry entry itself, so ScanState host
|
||||
// status keeps updating after a reconnect (it used to go permanently deaf).
|
||||
// status keeps updating after a reconnect (it used to go permanently deaf). It releases
|
||||
// same-session handles it supersedes on its own (#991 G-6).
|
||||
tagCount += await probeWatcher.ResubscribeAsync(cancellationToken).ConfigureAwait(false);
|
||||
continue;
|
||||
}
|
||||
|
||||
var refs = oldBindings
|
||||
.Select(b => b.FullReference)
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.ToArray();
|
||||
if (refs.Length == 0) continue;
|
||||
var (keepGoing, count) = await ReadviseSubscriptionAsync(
|
||||
subscriptionId, oldBindings, only: null, session, generation, sameSession, cancellationToken).ConfigureAwait(false);
|
||||
tagCount += count;
|
||||
if (!keepGoing) return tagCount;
|
||||
}
|
||||
|
||||
// #859: the re-issued handles' initial values (the whole point of a re-snapshot) can
|
||||
// overtake this SubscribeBulk reply; park them until the Rebind below promotes them.
|
||||
// Scoped to this one iteration (the using is disposed at the end of the loop body): a
|
||||
// window held across all N round-trips would park every unrelated unknown-handle event
|
||||
// for the whole replay and could exhaust the bound before the genuine early values.
|
||||
using var earlyEventWindow = _subscriptions.BeginPendingSubscribe();
|
||||
var results = await _subscriber!
|
||||
return tagCount;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Re-advise one subscription's tags — all of them (<paramref name="only"/> null) or just the named references —
|
||||
/// and rebind the registry to the fresh handles. MXAccess answers every advise with the attribute's current
|
||||
/// value, which is what makes this the re-snapshot primitive for the reconnect replay, the replay-gap
|
||||
/// re-snapshot and the dropped-event resync (#991 G-4).
|
||||
/// </summary>
|
||||
/// <param name="subscriptionId">The subscription.</param>
|
||||
/// <param name="oldBindings">Its bindings as snapshotted.</param>
|
||||
/// <param name="only">The references to re-advise (case-insensitive); null = every reference.</param>
|
||||
/// <param name="session">The registry session this pass runs under.</param>
|
||||
/// <param name="generation">The runtime generation this pass belongs to.</param>
|
||||
/// <param name="sameSession">See <see cref="ResubscribeAllAsync"/>.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>Whether the caller may continue with further subscriptions, and the references re-advised.</returns>
|
||||
private async Task<(bool KeepGoing, int Count)> ReadviseSubscriptionAsync(
|
||||
long subscriptionId,
|
||||
IReadOnlyList<TagBinding> oldBindings,
|
||||
ISet<string>? only,
|
||||
int session,
|
||||
int generation,
|
||||
bool sameSession,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var refs = oldBindings
|
||||
.Select(b => b.FullReference)
|
||||
.Where(r => only is null || only.Contains(r))
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.ToArray();
|
||||
if (refs.Length == 0) return (true, 0);
|
||||
|
||||
// #859: the re-issued handles' initial values (the whole point of a re-snapshot) can
|
||||
// overtake this SubscribeBulk reply; park them until the Rebind below promotes them.
|
||||
// Scoped to this one subscription: a window held across all N round-trips would park every
|
||||
// unrelated unknown-handle event for the whole replay and could exhaust the bound before the
|
||||
// genuine early values.
|
||||
IReadOnlyList<SubscribeResult> results;
|
||||
using (_subscriptions.BeginPendingSubscribe())
|
||||
{
|
||||
results = await _subscriber!
|
||||
.SubscribeBulkAsync(refs, _options.MxAccess.PublishingIntervalMs, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
var byAddress = BuildResultIndex(results);
|
||||
var newBindings = new List<TagBinding>(refs.Length);
|
||||
foreach (var fullRef in refs)
|
||||
List<TagBinding> newBindings;
|
||||
var superseded = new HashSet<int>();
|
||||
if (!sameSession)
|
||||
{
|
||||
var itemHandle = byAddress.TryGetValue(fullRef, out var match) && match.WasSuccessful
|
||||
? match.ItemHandle
|
||||
: 0;
|
||||
newBindings.Add(new TagBinding(fullRef, itemHandle));
|
||||
// Reconnect replay: the old handles are dead — the bindings become exactly the re-advised refs.
|
||||
newBindings = new List<TagBinding>(refs.Length);
|
||||
foreach (var fullRef in refs)
|
||||
{
|
||||
var itemHandle = byAddress.TryGetValue(fullRef, out var match) && match.WasSuccessful
|
||||
? match.ItemHandle
|
||||
: 0;
|
||||
newBindings.Add(new TagBinding(fullRef, itemHandle));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Same session: replace each re-advised binding whose advise succeeded and release the handle it
|
||||
// held; a binding not re-advised, or whose re-advise failed, keeps its (still live) handle.
|
||||
newBindings = new List<TagBinding>(oldBindings.Count);
|
||||
foreach (var binding in oldBindings)
|
||||
{
|
||||
if ((only is null || only.Contains(binding.FullReference))
|
||||
&& byAddress.TryGetValue(binding.FullReference, out var match) && match.WasSuccessful
|
||||
&& match.ItemHandle > 0)
|
||||
{
|
||||
newBindings.Add(new TagBinding(binding.FullReference, match.ItemHandle));
|
||||
if (binding.ItemHandle > 0 && binding.ItemHandle != match.ItemHandle) superseded.Add(binding.ItemHandle);
|
||||
}
|
||||
else
|
||||
{
|
||||
newBindings.Add(binding);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Rebind so the EventPump fan-out reverse map points at the post-reconnect
|
||||
// handles; otherwise events on the new handles miss every subscription. Not after a
|
||||
// teardown: the fresh handles belong to a subscriber that is already being released.
|
||||
// Rebind so the EventPump fan-out reverse map points at the fresh handles; otherwise events
|
||||
// on the new handles miss every subscription. Not after a teardown: the fresh handles belong
|
||||
// to a subscriber that is already being released.
|
||||
SubscriptionRegistry.BindOutcome outcome;
|
||||
lock (_registryGate)
|
||||
{
|
||||
if (Volatile.Read(ref _runtimeGeneration) != generation) return tagCount;
|
||||
if (Volatile.Read(ref _runtimeGeneration) != generation) return (false, 0);
|
||||
outcome = _subscriptions.TryRebind(subscriptionId, newBindings, session);
|
||||
}
|
||||
|
||||
@@ -1473,32 +1707,39 @@ public sealed class GalaxyDriver
|
||||
_logger.LogDebug(
|
||||
"GalaxyDriver {InstanceId} re-subscribe abandoned — the gateway session changed again.",
|
||||
_driverInstanceId);
|
||||
return tagCount;
|
||||
return (false, 0);
|
||||
}
|
||||
if (outcome == SubscriptionRegistry.BindOutcome.UnknownId)
|
||||
{
|
||||
// M-a: the subscription (or a subscribe-once read) was removed while its SubscribeBulk
|
||||
// was in flight. Nothing will ever unsubscribe what was just advised — release it now.
|
||||
var orphaned = newBindings.Where(b => b.ItemHandle > 0).Select(b => b.ItemHandle).ToArray();
|
||||
if (orphaned.Length > 0)
|
||||
{
|
||||
try
|
||||
{
|
||||
await UnsubscribeAndPurgeAsync(_subscriber!, orphaned, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex,
|
||||
"GalaxyDriver {InstanceId} could not release {Count} handle(s) re-subscribed for a subscription removed during the pass.",
|
||||
_driverInstanceId, orphaned.Length);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
var orphaned = results.Where(r => r.WasSuccessful && r.ItemHandle > 0).Select(r => r.ItemHandle).ToArray();
|
||||
await ReleaseHandlesAsync(orphaned,
|
||||
"re-subscribed for a subscription removed during the pass").ConfigureAwait(false);
|
||||
return (true, 0);
|
||||
}
|
||||
tagCount += refs.Length;
|
||||
}
|
||||
|
||||
return tagCount;
|
||||
if (superseded.Count > 0)
|
||||
{
|
||||
await ReleaseHandlesAsync([.. superseded], "superseded by a same-session re-advise").ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
return (true, refs.Length);
|
||||
}
|
||||
|
||||
private async Task ReleaseHandlesAsync(IReadOnlyList<int> handles, string why)
|
||||
{
|
||||
if (handles.Count == 0) return;
|
||||
try
|
||||
{
|
||||
await UnsubscribeAndPurgeAsync(_subscriber!, handles, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex,
|
||||
"GalaxyDriver {InstanceId} could not release {Count} handle(s) {Why}.",
|
||||
_driverInstanceId, handles.Count, why);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -1629,9 +1870,8 @@ public sealed class GalaxyDriver
|
||||
// Reuse the lazily-built repository client (DiscoverAsync constructs it on demand).
|
||||
// Build under a null-check (not an overwrite) so if BuildDefaultHierarchySourceAsync
|
||||
// later runs it reuses this client rather than leaking the first instance.
|
||||
_ownedRepositoryClient ??= GalaxyRepositoryClient.Create(
|
||||
await BuildClientOptionsAsync(_options.Gateway, cancellationToken).ConfigureAwait(false));
|
||||
source = new GatewayGalaxyDeployWatchSource(_ownedRepositoryClient);
|
||||
source = new GatewayGalaxyDeployWatchSource(
|
||||
await EnsureOwnedRepositoryClientAsync(cancellationToken).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
// One watcher per driver: a previous one (an InitializeAsync without a ShutdownAsync in
|
||||
@@ -2371,7 +2611,8 @@ public sealed class GalaxyDriver
|
||||
channelCapacity: _options.MxAccess.EventPumpChannelCapacity,
|
||||
clientName: _options.MxAccess.ClientName,
|
||||
onStreamFault: cause => OnEventPumpStreamFault(created, cause),
|
||||
onReplayGap: OnEventPumpReplayGap);
|
||||
onReplayGap: OnEventPumpReplayGap,
|
||||
onEventsDropped: handles => OnEventPumpEventsDropped(created, handles));
|
||||
_eventPump = created;
|
||||
_eventPump.OnDataChange += OnPumpDataChange;
|
||||
_eventPump.Start();
|
||||
@@ -2662,12 +2903,17 @@ public sealed class GalaxyDriver
|
||||
var generation = Volatile.Read(ref _runtimeGeneration);
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
await _resnapshotGate.WaitAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
var entries = _subscriptions.SnapshotEntries();
|
||||
// Only subscriptions whose handles this session issued: they are still advised, so the re-advise
|
||||
// releases the ones it supersedes (#991 G-6). One still holding an older session's handles is the
|
||||
// reconnect replay's to re-subscribe.
|
||||
var entries = _subscriptions.SnapshotEntriesIn(_subscriptions.CurrentSession);
|
||||
if (entries.Count == 0) return;
|
||||
|
||||
var tagCount = await ResubscribeAllAsync(entries, generation, CancellationToken.None).ConfigureAwait(false);
|
||||
var tagCount = await ResubscribeAllAsync(
|
||||
entries, generation, CancellationToken.None, sameSession: true).ConfigureAwait(false);
|
||||
_logger.LogInformation(
|
||||
"GalaxyDriver {InstanceId} replay-gap re-snapshot completed — {SubCount} subscriptions, {TagCount} tags re-subscribed",
|
||||
_driverInstanceId, entries.Count, tagCount);
|
||||
@@ -2683,11 +2929,139 @@ public sealed class GalaxyDriver
|
||||
}
|
||||
finally
|
||||
{
|
||||
_resnapshotGate.Release();
|
||||
Interlocked.Exchange(ref _resnapshotInFlight, 0);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// #991 G-4: item handles whose data-change events the pump's full channel dropped, waiting for a re-advise.
|
||||
// Keyed by the session that issued them; guarded by _droppedLock.
|
||||
private readonly Lock _droppedLock = new();
|
||||
private readonly HashSet<int> _droppedPending = [];
|
||||
private int _droppedSession;
|
||||
private int _dropResyncRunning;
|
||||
|
||||
// Serialises the same-session re-advise passes (replay-gap re-snapshot, dropped-event resync): both rebind a
|
||||
// subscription from a snapshot of its bindings, so two interleaved passes could rebind over each other and
|
||||
// release handles the other one bound.
|
||||
private readonly SemaphoreSlim _resnapshotGate = new(1, 1);
|
||||
|
||||
/// <summary>
|
||||
/// #991 G-4 — the pump dropped data-change events for <paramref name="itemHandles"/> because its channel was
|
||||
/// full (raised once the channel drained). MXAccess sends a value only when it changes, so each of those tags
|
||||
/// would otherwise keep its previous value, Good, until the attribute happens to change again. Queue them for
|
||||
/// a re-advise — MXAccess answers an advise with the current value — on one coalescing background worker.
|
||||
/// Runs on the pump's dispatch thread: must not block.
|
||||
/// </summary>
|
||||
private void OnEventPumpEventsDropped(EventPump? source, IReadOnlyCollection<int> itemHandles)
|
||||
{
|
||||
if (_runtimeStopping || _subscriber is null || source is null || itemHandles.Count == 0) return;
|
||||
var session = source.Session;
|
||||
// A pump of an older session: the reconnect replay re-advises everything on the new session anyway.
|
||||
if (session != _subscriptions.CurrentSession) return;
|
||||
|
||||
lock (_droppedLock)
|
||||
{
|
||||
if (_droppedSession != session)
|
||||
{
|
||||
_droppedPending.Clear();
|
||||
_droppedSession = session;
|
||||
}
|
||||
_droppedPending.UnionWith(itemHandles);
|
||||
}
|
||||
if (Interlocked.Exchange(ref _dropResyncRunning, 1) == 1) return; // the running worker picks them up
|
||||
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
int[] batch;
|
||||
int batchSession;
|
||||
lock (_droppedLock)
|
||||
{
|
||||
if (_droppedPending.Count == 0 || _runtimeStopping)
|
||||
{
|
||||
_droppedPending.Clear();
|
||||
Volatile.Write(ref _dropResyncRunning, 0); // under the lock: a later add starts a new worker
|
||||
return;
|
||||
}
|
||||
batch = [.. _droppedPending];
|
||||
_droppedPending.Clear();
|
||||
batchSession = _droppedSession;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await ResyncDroppedHandlesAsync(batch, batchSession).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex,
|
||||
"GalaxyDriver {InstanceId} could not re-read {Count} tag(s) whose changes were dropped — they may stay stale until they next change.",
|
||||
_driverInstanceId, batch.Length);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Re-advise exactly the tags bound to <paramref name="itemHandles"/> (still issued by <paramref name="session"/>)
|
||||
/// and release the handles they replace. A handle no subscription holds any more needs nothing.
|
||||
/// </summary>
|
||||
private async Task ResyncDroppedHandlesAsync(IReadOnlyCollection<int> itemHandles, int session)
|
||||
{
|
||||
await _resnapshotGate.WaitAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
var generation = Volatile.Read(ref _runtimeGeneration);
|
||||
if (_runtimeStopping || _subscriber is null || _subscriptions.CurrentSession != session) return;
|
||||
|
||||
var dropped = itemHandles.ToHashSet();
|
||||
var probeAffected = false;
|
||||
var tagCount = 0;
|
||||
foreach (var (subscriptionId, bindings) in _subscriptions.SnapshotEntriesIn(session))
|
||||
{
|
||||
HashSet<string>? affected = null;
|
||||
foreach (var binding in bindings)
|
||||
{
|
||||
if (binding.ItemHandle <= 0 || !dropped.Contains(binding.ItemHandle)) continue;
|
||||
(affected ??= new HashSet<string>(StringComparer.OrdinalIgnoreCase)).Add(binding.FullReference);
|
||||
}
|
||||
if (affected is null) continue;
|
||||
|
||||
if (subscriptionId == SubscriptionRegistry.ProbeSubscriptionId)
|
||||
{
|
||||
probeAffected = true; // the watcher owns its handles
|
||||
continue;
|
||||
}
|
||||
|
||||
var (keepGoing, count) = await ReadviseSubscriptionAsync(
|
||||
subscriptionId, bindings, affected, session, generation, sameSession: true, CancellationToken.None)
|
||||
.ConfigureAwait(false);
|
||||
tagCount += count;
|
||||
if (!keepGoing) return;
|
||||
}
|
||||
|
||||
if (probeAffected && _probeWatcher is { } probeWatcher
|
||||
&& Volatile.Read(ref _runtimeGeneration) == generation && _subscriptions.CurrentSession == session)
|
||||
{
|
||||
tagCount += await probeWatcher.ResubscribeAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (tagCount > 0)
|
||||
{
|
||||
_logger.LogInformation(
|
||||
"GalaxyDriver {InstanceId} re-advised {TagCount} tag(s) whose changes the event channel dropped.",
|
||||
_driverInstanceId, tagCount);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_resnapshotGate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stream-fault callback for the <see cref="EventPump"/>. The gw StreamEvents
|
||||
/// stream faulted (transient gateway drop, network blip, gw restart). Forward
|
||||
@@ -3380,10 +3754,9 @@ public sealed class GalaxyDriver
|
||||
// than always overwriting the field and leaking the first instance. Both paths
|
||||
// produce equivalent clients from the same options. The client-options build is
|
||||
// async now (secret: arm resolves through the shared ISecretResolver).
|
||||
_ownedRepositoryClient ??= GalaxyRepositoryClient.Create(
|
||||
await BuildClientOptionsAsync(_options.Gateway, cancellationToken).ConfigureAwait(false));
|
||||
var repository = await EnsureOwnedRepositoryClientAsync(cancellationToken).ConfigureAwait(false);
|
||||
return new TracedGalaxyHierarchySource(
|
||||
new GatewayGalaxyHierarchySource(_ownedRepositoryClient, _options.Repository.DiscoverPageSize),
|
||||
new GatewayGalaxyHierarchySource(repository, _options.Repository.DiscoverPageSize),
|
||||
_options.MxAccess.ClientName);
|
||||
}
|
||||
|
||||
|
||||
@@ -106,7 +106,9 @@ public static class GalaxyDriverFactoryExtensions
|
||||
CaCertificatePath: dto.Gateway.CaCertificatePath,
|
||||
ConnectTimeoutSeconds: dto.Gateway.ConnectTimeoutSeconds ?? 10,
|
||||
DefaultCallTimeoutSeconds: dto.Gateway.DefaultCallTimeoutSeconds ?? 30,
|
||||
StreamTimeoutSeconds: dto.Gateway.StreamTimeoutSeconds ?? 0),
|
||||
StreamTimeoutSeconds: dto.Gateway.StreamTimeoutSeconds ?? 0,
|
||||
KeepAlivePingDelaySeconds: dto.Gateway.KeepAlivePingDelaySeconds ?? 15,
|
||||
KeepAlivePingTimeoutSeconds: dto.Gateway.KeepAlivePingTimeoutSeconds ?? 10),
|
||||
MxAccess: new GalaxyMxAccessOptions(
|
||||
ClientName: dto.MxAccess?.ClientName
|
||||
?? throw new InvalidOperationException(
|
||||
@@ -199,6 +201,10 @@ public static class GalaxyDriverFactoryExtensions
|
||||
public int? DefaultCallTimeoutSeconds { get; init; }
|
||||
/// <summary>Gets or sets the stream timeout in seconds.</summary>
|
||||
public int? StreamTimeoutSeconds { get; init; }
|
||||
/// <summary>Gets or sets the HTTP/2 keep-alive ping interval in seconds (0 = no pings; #991 G-19).</summary>
|
||||
public int? KeepAlivePingDelaySeconds { get; init; }
|
||||
/// <summary>Gets or sets how long an unanswered keep-alive ping may wait before the connection fails.</summary>
|
||||
public int? KeepAlivePingTimeoutSeconds { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>MX Access configuration section.</summary>
|
||||
|
||||
@@ -241,6 +241,10 @@ public sealed class PerPlatformProbeWatcher : IDisposable
|
||||
// ran while SubscribeBulk was in flight already cleared the map and the registry entry, so
|
||||
// recording now would resurrect the probe entry into the next runtime's registry.
|
||||
bool stopped;
|
||||
// #991 G-6: handles this subscribe replaces that the SAME session issued are still advised on the gateway
|
||||
// (the replay-gap re-snapshot) and are released below. A previous session's handles are dead and their
|
||||
// numbers reused by the current session, so they are never sent.
|
||||
var superseded = new List<int>();
|
||||
lock (_syncLock)
|
||||
{
|
||||
stopped = _disposed;
|
||||
@@ -253,11 +257,32 @@ public sealed class PerPlatformProbeWatcher : IDisposable
|
||||
return false;
|
||||
}
|
||||
foreach (var (platform, itemHandle, _) in acquired)
|
||||
{
|
||||
if (_itemHandlesByPlatform.TryGetValue(platform, out var previous)
|
||||
&& previous.Session == session && previous.ItemHandle > 0 && previous.ItemHandle != itemHandle)
|
||||
{
|
||||
superseded.Add(previous.ItemHandle);
|
||||
}
|
||||
_itemHandlesByPlatform[platform] = new ProbeHandle(itemHandle, session);
|
||||
}
|
||||
if (!PublishBindingsLocked(session)) return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (!stopped && superseded.Count > 0)
|
||||
{
|
||||
try { await _subscriber.UnsubscribeBulkAsync(superseded, CancellationToken.None).ConfigureAwait(false); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex,
|
||||
"PerPlatformProbeWatcher could not release {Count} superseded probe handle(s)", superseded.Count);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_registry?.PurgeParked(superseded, session);
|
||||
}
|
||||
}
|
||||
|
||||
if (stopped)
|
||||
{
|
||||
var orphans = acquired.Where(a => a.ItemHandle > 0).Select(a => a.ItemHandle).ToArray();
|
||||
|
||||
@@ -73,6 +73,13 @@ internal sealed class EventPump : IAsyncDisposable
|
||||
private readonly Func<long, ISubscriptionHandle> _handleFactory;
|
||||
private readonly Action<Exception>? _onStreamFault;
|
||||
private readonly Action<ReplayGap>? _onReplayGap;
|
||||
private readonly Action<IReadOnlyCollection<int>>? _onEventsDropped;
|
||||
|
||||
// #991 G-4: item handles whose data-change events were dropped since the last flush. Written by the read loop,
|
||||
// drained by the dispatch loop once the channel is empty.
|
||||
private readonly Lock _droppedLock = new();
|
||||
private readonly HashSet<int> _droppedHandles = [];
|
||||
private volatile bool _dropsPending;
|
||||
private readonly Channel<MxEvent> _channel;
|
||||
private readonly KeyValuePair<string, object?> _clientTag;
|
||||
private readonly CancellationTokenSource _cts = new();
|
||||
@@ -103,6 +110,12 @@ internal sealed class EventPump : IAsyncDisposable
|
||||
/// Optional callback invoked when the gateway reports a replay gap. The contract
|
||||
/// obliges the client to re-snapshot; see <see cref="HandleReplayGap"/>.
|
||||
/// </param>
|
||||
/// <param name="onEventsDropped">
|
||||
/// #991 G-4 — optional callback receiving the item handles whose data-change events the full channel
|
||||
/// dropped, raised on the dispatch thread once the channel has drained (so a resync is not swallowed by
|
||||
/// the same congestion). MXAccess sends a value only on change, so each such tag is stale until re-read.
|
||||
/// Must not block.
|
||||
/// </param>
|
||||
public EventPump(
|
||||
IGalaxySubscriber subscriber,
|
||||
SubscriptionRegistry registry,
|
||||
@@ -111,7 +124,8 @@ internal sealed class EventPump : IAsyncDisposable
|
||||
int channelCapacity = DefaultChannelCapacity,
|
||||
string? clientName = null,
|
||||
Action<Exception>? onStreamFault = null,
|
||||
Action<ReplayGap>? onReplayGap = null)
|
||||
Action<ReplayGap>? onReplayGap = null,
|
||||
Action<IReadOnlyCollection<int>>? onEventsDropped = null)
|
||||
{
|
||||
_subscriber = subscriber ?? throw new ArgumentNullException(nameof(subscriber));
|
||||
_registry = registry ?? throw new ArgumentNullException(nameof(registry));
|
||||
@@ -119,6 +133,7 @@ internal sealed class EventPump : IAsyncDisposable
|
||||
_handleFactory = handleFactory ?? (id => new GalaxySubscriptionHandle(id));
|
||||
_onStreamFault = onStreamFault;
|
||||
_onReplayGap = onReplayGap;
|
||||
_onEventsDropped = onEventsDropped;
|
||||
|
||||
if (channelCapacity < 1)
|
||||
{
|
||||
@@ -158,6 +173,11 @@ internal sealed class EventPump : IAsyncDisposable
|
||||
/// </summary>
|
||||
internal int Session => _session;
|
||||
|
||||
private long _droppedCount;
|
||||
|
||||
/// <summary>Test seam: events this pump dropped because its bounded channel was full.</summary>
|
||||
internal long DroppedCountForTests => Interlocked.Read(ref _droppedCount);
|
||||
|
||||
/// <summary>True once the stream loop has exited (faulted, completed by the gateway, or disposed).</summary>
|
||||
internal bool HasEnded => Volatile.Read(ref _ended);
|
||||
|
||||
@@ -298,6 +318,8 @@ internal sealed class EventPump : IAsyncDisposable
|
||||
if (!_channel.Writer.TryWrite(ev))
|
||||
{
|
||||
EventsDropped.Add(1, _clientTag);
|
||||
Interlocked.Increment(ref _droppedCount);
|
||||
RecordDrop(ev);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -451,10 +473,13 @@ internal sealed class EventPump : IAsyncDisposable
|
||||
if (ReferenceEquals(ev, WakeSentinel))
|
||||
{
|
||||
DispatchReadyEvents();
|
||||
continue;
|
||||
}
|
||||
Dispatch(ev);
|
||||
EventsDispatched.Add(1, _clientTag);
|
||||
else
|
||||
{
|
||||
Dispatch(ev);
|
||||
EventsDispatched.Add(1, _clientTag);
|
||||
}
|
||||
if (_dropsPending && _channel.Reader.Count == 0) FlushDrops();
|
||||
}
|
||||
}
|
||||
catch (Exception) when (ct.IsCancellationRequested)
|
||||
@@ -473,6 +498,43 @@ internal sealed class EventPump : IAsyncDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #991 G-4 — remember the item handle of a dropped data-change event, then wake the dispatch loop. The wake
|
||||
/// usually fails (the channel is full — the loop is busy and checks after each item); it succeeds exactly when
|
||||
/// the loop drained the channel between this drop and now, and would otherwise sleep with the drop unflushed.
|
||||
/// </summary>
|
||||
private void RecordDrop(MxEvent ev)
|
||||
{
|
||||
if (_onEventsDropped is null || ev.Family != MxEventFamily.OnDataChange || ev.ItemHandle <= 0) return;
|
||||
lock (_droppedLock)
|
||||
{
|
||||
_droppedHandles.Add(ev.ItemHandle);
|
||||
_dropsPending = true;
|
||||
}
|
||||
_channel.Writer.TryWrite(WakeSentinel);
|
||||
}
|
||||
|
||||
/// <summary>Hand every recorded dropped handle to the owner (dispatch thread, channel drained).</summary>
|
||||
private void FlushDrops()
|
||||
{
|
||||
int[] handles;
|
||||
lock (_droppedLock)
|
||||
{
|
||||
handles = [.. _droppedHandles];
|
||||
_droppedHandles.Clear();
|
||||
_dropsPending = false;
|
||||
}
|
||||
if (handles.Length == 0 || _onEventsDropped is null) return;
|
||||
_logger.LogWarning(
|
||||
"Galaxy EventPump dropped data changes for {Count} item(s) while its channel was full — re-reading them.",
|
||||
handles.Length);
|
||||
try { _onEventsDropped(handles); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Galaxy EventPump dropped-events callback threw — those values may stay stale.");
|
||||
}
|
||||
}
|
||||
|
||||
private void Dispatch(MxEvent ev)
|
||||
{
|
||||
switch (ev.Family)
|
||||
@@ -546,7 +608,7 @@ internal sealed class EventPump : IAsyncDisposable
|
||||
var snapshot = ToSnapshot(ev);
|
||||
foreach (var (subscriptionId, fullReference) in subscribers)
|
||||
{
|
||||
var handle = _handleFactory(subscriptionId);
|
||||
var handle = HandleFor(subscriptionId);
|
||||
try
|
||||
{
|
||||
OnDataChange?.Invoke(this, new DataChangeEventArgs(handle, fullReference, snapshot));
|
||||
@@ -560,6 +622,21 @@ internal sealed class EventPump : IAsyncDisposable
|
||||
}
|
||||
}
|
||||
|
||||
// #991 G-5: one handle object per subscription instead of one per subscriber per event. Touched only by the
|
||||
// dispatch thread (every FanOut runs there), so it needs no lock. Subscription ids are never reused, and
|
||||
// subscribe-once reads mint one each, so the cache is simply dropped when it grows past the bound.
|
||||
private readonly Dictionary<long, ISubscriptionHandle> _handleCache = [];
|
||||
private const int HandleCacheBound = 4_096;
|
||||
|
||||
private ISubscriptionHandle HandleFor(long subscriptionId)
|
||||
{
|
||||
if (_handleCache.TryGetValue(subscriptionId, out var cached)) return cached;
|
||||
if (_handleCache.Count >= HandleCacheBound) _handleCache.Clear();
|
||||
var created = _handleFactory(subscriptionId);
|
||||
_handleCache[subscriptionId] = created;
|
||||
return created;
|
||||
}
|
||||
|
||||
private DataValueSnapshot ToSnapshot(MxEvent ev)
|
||||
{
|
||||
if (!MxValueDecoder.TryDecode(ev.Value, out var value))
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
using System.Net.Http;
|
||||
using System.Net.Security;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using Grpc.Net.Client;
|
||||
using ZB.MOM.WW.MxGateway.Client;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
|
||||
|
||||
/// <summary>
|
||||
/// #991 G-19 — builds the gRPC channels the driver's long-lived gateway clients run on, with HTTP/2 keep-alive
|
||||
/// pings. <see cref="MxGatewayClient.Create(MxGatewayClientOptions)"/> (mxaccessgw client 0.4.0) builds its own
|
||||
/// <see cref="SocketsHttpHandler"/> with only <c>ConnectTimeout</c>, so pings are off: a server-streaming call
|
||||
/// (StreamEvents, StreamAlarms, WatchDeployEvents) sends nothing after its request, and a gateway host that loses
|
||||
/// power — or a firewall that starts silently dropping the flow — never surfaces a TCP error. The stream waited
|
||||
/// forever, the reconnect supervisor was never told, and Galaxy stayed Healthy serving stale Good values.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// With <see cref="HttpKeepAlivePingPolicy.Always"/> the client PINGs the connection every
|
||||
/// <c>KeepAlivePingDelaySeconds</c> whether or not a call is active, and fails the connection — and every stream on
|
||||
/// it — when a PING goes unanswered for <c>KeepAlivePingTimeoutSeconds</c>. The stream's fault then reaches the
|
||||
/// supervisor exactly like a gateway crash. A PING is answered by the peer's HTTP/2 stack itself (mandatory per
|
||||
/// RFC 9113 §6.7), so this needs nothing from the gateway; Kestrel applies no client-ping rate policy.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// ⚠️ The TLS settings below MIRROR the client library's own handler (<c>MxGatewayClient.CreateHttpHandler</c>,
|
||||
/// 0.4.0): CA-pinned custom-root trust with the host-name check kept, <c>RequireCertificateValidation</c>, and
|
||||
/// <c>ServerNameOverride</c>. Keep them in step if the client's changes — or, better, retire this once the client
|
||||
/// exposes keep-alive options itself (the cross-repo half of #991 G-19).
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
internal static class GalaxyGatewayChannelFactory
|
||||
{
|
||||
/// <summary>Builds a channel to <paramref name="options"/>' endpoint with keep-alive pings per <paramref name="gateway"/>.</summary>
|
||||
/// <param name="options">The client options (endpoint, TLS, message limits, logging).</param>
|
||||
/// <param name="gateway">The driver's gateway options (keep-alive settings).</param>
|
||||
/// <returns>A channel the caller owns and must dispose after the client built over it.</returns>
|
||||
public static GrpcChannel CreateChannel(MxGatewayClientOptions options, GalaxyGatewayOptions gateway)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
ArgumentNullException.ThrowIfNull(gateway);
|
||||
options.Validate();
|
||||
return GrpcChannel.ForAddress(options.Endpoint, new GrpcChannelOptions
|
||||
{
|
||||
HttpHandler = CreateHttpHandler(options, KeepAliveDelay(gateway), KeepAliveTimeout(gateway)),
|
||||
DisposeHttpClient = true,
|
||||
LoggerFactory = options.LoggerFactory,
|
||||
MaxReceiveMessageSize = options.MaxGrpcMessageBytes,
|
||||
MaxSendMessageSize = options.MaxGrpcMessageBytes,
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>The ping interval; infinite (no pings) when not positive.</summary>
|
||||
internal static TimeSpan KeepAliveDelay(GalaxyGatewayOptions gateway) =>
|
||||
gateway.KeepAlivePingDelaySeconds > 0 ? TimeSpan.FromSeconds(gateway.KeepAlivePingDelaySeconds) : Timeout.InfiniteTimeSpan;
|
||||
|
||||
/// <summary>How long an unanswered ping may wait; the .NET default (20 s) when not positive.</summary>
|
||||
internal static TimeSpan KeepAliveTimeout(GalaxyGatewayOptions gateway) =>
|
||||
gateway.KeepAlivePingTimeoutSeconds > 0 ? TimeSpan.FromSeconds(gateway.KeepAlivePingTimeoutSeconds) : TimeSpan.FromSeconds(20);
|
||||
|
||||
/// <summary>
|
||||
/// The handler: the client library's connect-timeout + TLS behaviour, plus keep-alive pings when
|
||||
/// <paramref name="keepAlivePingDelay"/> is finite.
|
||||
/// </summary>
|
||||
/// <param name="options">The client options.</param>
|
||||
/// <param name="keepAlivePingDelay">Ping interval; <see cref="Timeout.InfiniteTimeSpan"/> = no pings.</param>
|
||||
/// <param name="keepAlivePingTimeout">Unanswered-ping budget.</param>
|
||||
/// <returns>The configured handler.</returns>
|
||||
internal static SocketsHttpHandler CreateHttpHandler(
|
||||
MxGatewayClientOptions options, TimeSpan keepAlivePingDelay, TimeSpan keepAlivePingTimeout)
|
||||
{
|
||||
var handler = new SocketsHttpHandler
|
||||
{
|
||||
ConnectTimeout = options.ConnectTimeout,
|
||||
};
|
||||
if (keepAlivePingDelay != Timeout.InfiniteTimeSpan)
|
||||
{
|
||||
handler.KeepAlivePingDelay = keepAlivePingDelay;
|
||||
handler.KeepAlivePingTimeout = keepAlivePingTimeout;
|
||||
handler.KeepAlivePingPolicy = HttpKeepAlivePingPolicy.Always;
|
||||
}
|
||||
|
||||
if (!options.UseTls) return handler;
|
||||
|
||||
handler.SslOptions = new SslClientAuthenticationOptions();
|
||||
if (!string.IsNullOrWhiteSpace(options.ServerNameOverride))
|
||||
{
|
||||
handler.SslOptions.TargetHost = options.ServerNameOverride;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(options.CaCertificatePath))
|
||||
{
|
||||
var trustedRoot = X509CertificateLoader.LoadCertificateFromFile(options.CaCertificatePath);
|
||||
handler.SslOptions.RemoteCertificateValidationCallback = (_, certificate, _, errors) =>
|
||||
{
|
||||
if ((errors & SslPolicyErrors.RemoteCertificateNameMismatch) != 0) return false;
|
||||
if (certificate is null) return false;
|
||||
|
||||
using var customChain = new X509Chain();
|
||||
customChain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
|
||||
customChain.ChainPolicy.CustomTrustStore.Add(trustedRoot);
|
||||
customChain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
|
||||
customChain.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag;
|
||||
var toValidate = certificate as X509Certificate2
|
||||
?? X509CertificateLoader.LoadCertificate(certificate.Export(X509ContentType.Cert));
|
||||
return customChain.Build(toValidate);
|
||||
};
|
||||
}
|
||||
else if (!options.RequireCertificateValidation)
|
||||
{
|
||||
handler.SslOptions.RemoteCertificateValidationCallback = (_, _, _, _) => true;
|
||||
}
|
||||
|
||||
return handler;
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,15 @@ public sealed class GalaxyMxSession : IAsyncDisposable
|
||||
// Owned gateway client + session — populated when ConnectAsync runs. Tests can leave
|
||||
// them null and exercise the surface via injected IGalaxyDataReader fakes.
|
||||
private MxGatewayClient? _ownedClient;
|
||||
private Grpc.Net.Client.GrpcChannel? _ownedChannel;
|
||||
private MxGatewaySession? _session;
|
||||
|
||||
/// <summary>
|
||||
/// Optional channel builder (#991 G-19). When set, the owned client runs over the channel it returns (the
|
||||
/// driver supplies one with HTTP/2 keep-alive pings); the session disposes it after the client. Null = the
|
||||
/// client library builds its own channel.
|
||||
/// </summary>
|
||||
internal Func<MxGatewayClientOptions, Grpc.Net.Client.GrpcChannel>? ChannelFactory { get; init; }
|
||||
private int _serverHandle;
|
||||
private bool _connected;
|
||||
private bool _disposed;
|
||||
@@ -88,7 +96,17 @@ public sealed class GalaxyMxSession : IAsyncDisposable
|
||||
}
|
||||
else
|
||||
{
|
||||
_ownedClient = MxGatewayClient.Create(clientOptions);
|
||||
// #991 G-19: over a driver-built channel with HTTP/2 keep-alive pings when one is supplied — the
|
||||
// client's own handler has none, so a silently dead gateway never faulted StreamEvents.
|
||||
if (ChannelFactory is { } channelFactory)
|
||||
{
|
||||
_ownedChannel = channelFactory(clientOptions);
|
||||
_ownedClient = MxGatewayClient.Create(_ownedChannel, clientOptions);
|
||||
}
|
||||
else
|
||||
{
|
||||
_ownedClient = MxGatewayClient.Create(clientOptions);
|
||||
}
|
||||
_session = await _ownedClient.OpenSessionAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
_serverHandle = await _session.RegisterAsync(_options.ClientName, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
@@ -209,5 +227,16 @@ public sealed class GalaxyMxSession : IAsyncDisposable
|
||||
catch (Exception ex) { _logger.LogWarning(ex, "GalaxyMxSession client dispose failed (best-effort)"); }
|
||||
_ownedClient = null;
|
||||
}
|
||||
|
||||
if (_ownedChannel is not null)
|
||||
{
|
||||
// A client created over a caller-owned channel does not dispose it.
|
||||
try { _ownedChannel.Dispose(); }
|
||||
catch (Exception ex) { _logger.LogWarning(ex, "GalaxyMxSession channel dispose failed (best-effort)"); }
|
||||
_ownedChannel = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Test seam: the driver-built channel the owned client runs on, or null.</summary>
|
||||
internal Grpc.Net.Client.GrpcChannel? OwnedChannelForTests => _ownedChannel;
|
||||
}
|
||||
|
||||
@@ -361,8 +361,12 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter
|
||||
/// directly and route through <c>InvokeAsync</c>. Verifier user is left at zero
|
||||
/// for SecuredWrite; VerifiedWrite uses the same path because the gw's worker
|
||||
/// interprets the underlying MXAccess command kind.
|
||||
/// <para>#991 G-1: the current user is the configured <c>MxAccess.WriteUserId</c> — the same identity the
|
||||
/// raw path writes under — instead of a hard-coded 0. With the default 0 a secured write carries no
|
||||
/// ArchestrA user and MXAccess is expected to refuse it; a VerifiedWrite additionally needs a verifier,
|
||||
/// which nothing supplies yet (follow-up: a per-caller Galaxy identity, like the #749 ack credential).</para>
|
||||
/// </summary>
|
||||
private static Task<MxCommandReply> InvokeWriteSecuredAsync(
|
||||
private Task<MxCommandReply> InvokeWriteSecuredAsync(
|
||||
IMxWriteOps ops, int itemHandle, MxValue value, CancellationToken ct)
|
||||
{
|
||||
var command = new MxCommand
|
||||
@@ -373,7 +377,7 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter
|
||||
ServerHandle = ops.ServerHandle,
|
||||
ItemHandle = itemHandle,
|
||||
Value = value,
|
||||
CurrentUserId = 0,
|
||||
CurrentUserId = _writeUserId,
|
||||
VerifierUserId = 0,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -79,7 +79,13 @@ internal static class StatusCodeMap
|
||||
/// <param name="q">The OPC DA quality byte to convert.</param>
|
||||
/// <param name="logger">Optional logger for diagnostics on unknown quality bytes.</param>
|
||||
/// <returns>The OPC UA status code.</returns>
|
||||
public static uint FromQualityByte(byte q, ILogger? logger = null) => q switch
|
||||
/// <remarks>
|
||||
/// #991 G-2: the two OPC DA LIMIT bits (<c>LL</c> in <c>QQSSSSLL</c> — low-limited, high-limited, constant) are
|
||||
/// masked off before the lookup. They never change the quality category or substatus and every table entry has
|
||||
/// them clear, so <c>Good | LowLimited</c> (0xC1) used to miss the table and log a Warning on EVERY event — on
|
||||
/// the pump's single dispatch thread. A byte still unlisted after the mask warns once per distinct value.
|
||||
/// </remarks>
|
||||
public static uint FromQualityByte(byte q, ILogger? logger = null) => (byte)(q & QualityLimitMask) switch
|
||||
{
|
||||
// Good family — top two bits 11b (192-255).
|
||||
192 => Good,
|
||||
@@ -256,13 +262,21 @@ internal static class StatusCodeMap
|
||||
return Bad;
|
||||
}
|
||||
|
||||
/// <summary>Clears the OPC DA limit bits (the low two bits of the quality byte).</summary>
|
||||
private const byte QualityLimitMask = 0xFC;
|
||||
|
||||
/// <summary>One flag per quality byte, set once that byte has been warned about (#991 G-2). Process-wide.</summary>
|
||||
private static readonly int[] UnrecognisedQualityWarned = new int[256];
|
||||
|
||||
private static void Log(ILogger? logger, byte q, string bucket)
|
||||
{
|
||||
// Best-effort diagnostic so field captures can extend the table — once per bucket
|
||||
// per session is plenty (the LogWarning level is rate-limited by Serilog filters
|
||||
// in production).
|
||||
logger?.LogWarning(
|
||||
// Best-effort diagnostic so field captures can extend the table — once per distinct byte per process
|
||||
// (#991 G-2). This runs on the event pump's dispatch thread for every event carrying the byte, and a
|
||||
// per-event Warning slowed dispatch until the bounded channel started dropping events.
|
||||
if (logger is null || Interlocked.Exchange(ref UnrecognisedQualityWarned[q], 1) != 0) return;
|
||||
logger.LogWarning(
|
||||
"Unrecognised MXAccess quality byte 0x{Q:X2} — falling back to {Bucket} category. " +
|
||||
"Field capture welcome — extend StatusCodeMap.FromQualityByte.", q, bucket);
|
||||
"Field capture welcome — extend StatusCodeMap.FromQualityByte. Further occurrences of this byte are not logged.",
|
||||
q, bucket);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Immutable;
|
||||
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
|
||||
@@ -31,7 +30,10 @@ internal sealed class SubscriptionRegistry
|
||||
public const long ProbeSubscriptionId = -1;
|
||||
|
||||
private readonly ConcurrentDictionary<long, SubscriptionEntry> _bySubscriptionId = new();
|
||||
private readonly ConcurrentDictionary<int, ImmutableHashSet<long>> _subscribersByItemHandle = new();
|
||||
// #991 G-5: each item handle's subscribers as a pre-built, never-mutated array — rebuilt (copy-on-write, under
|
||||
// _parkGate) only when a subscription binds or unbinds, so the per-event lookup on the dispatch thread hands the
|
||||
// array out as-is instead of allocating a list, a LINQ Distinct and a boxed set enumerator per event.
|
||||
private readonly ConcurrentDictionary<int, (long SubscriptionId, string FullReference)[]> _subscribersByItemHandle = new();
|
||||
private long _nextSubscriptionId;
|
||||
|
||||
/// <summary>True when <paramref name="subscriptionId"/> is currently registered.</summary>
|
||||
@@ -154,14 +156,15 @@ internal sealed class SubscriptionRegistry
|
||||
return BindOutcome.UnknownId;
|
||||
}
|
||||
|
||||
_bySubscriptionId[subscriptionId] = new SubscriptionEntry(subscriptionId, bindings, _session);
|
||||
foreach (var binding in bindings)
|
||||
var entry = new SubscriptionEntry(subscriptionId, bindings, _session);
|
||||
_bySubscriptionId[subscriptionId] = entry;
|
||||
// The entry's index holds each positive handle once (failed gw subscribes — handle <= 0 — expect no
|
||||
// events), with the subscription's reference for it.
|
||||
foreach (var (itemHandle, fullRef) in entry.FullRefByItemHandle)
|
||||
{
|
||||
if (binding.ItemHandle <= 0) continue; // failed gw subscribe — no events expected
|
||||
_subscribersByItemHandle.AddOrUpdate(
|
||||
binding.ItemHandle,
|
||||
_ => [subscriptionId],
|
||||
(_, set) => set.Add(subscriptionId));
|
||||
_subscribersByItemHandle[itemHandle] = _subscribersByItemHandle.TryGetValue(itemHandle, out var current)
|
||||
? WithSubscriber(current, subscriptionId, fullRef)
|
||||
: [(subscriptionId, fullRef)];
|
||||
}
|
||||
AfterMapWriteForTests?.Invoke();
|
||||
promoted = PromoteParkedEventsLocked(bindings);
|
||||
@@ -172,19 +175,32 @@ internal sealed class SubscriptionRegistry
|
||||
|
||||
private void RemoveFromReverseMap(SubscriptionEntry entry)
|
||||
{
|
||||
foreach (var binding in entry.Bindings)
|
||||
foreach (var itemHandle in entry.FullRefByItemHandle.Keys)
|
||||
{
|
||||
if (binding.ItemHandle <= 0) continue;
|
||||
if (!_subscribersByItemHandle.TryGetValue(binding.ItemHandle, out var set)) continue;
|
||||
var remaining = set.Remove(entry.SubscriptionId);
|
||||
if (remaining.IsEmpty)
|
||||
{
|
||||
_subscribersByItemHandle.TryRemove(binding.ItemHandle, out _);
|
||||
}
|
||||
else _subscribersByItemHandle[binding.ItemHandle] = remaining;
|
||||
if (!_subscribersByItemHandle.TryGetValue(itemHandle, out var current)) continue;
|
||||
var remaining = Array.FindAll(current, s => s.SubscriptionId != entry.SubscriptionId);
|
||||
if (remaining.Length == 0) _subscribersByItemHandle.TryRemove(itemHandle, out _);
|
||||
else if (remaining.Length != current.Length) _subscribersByItemHandle[itemHandle] = remaining;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A copy of <paramref name="current"/> with <paramref name="subscriptionId"/> set to <paramref name="fullRef"/>.</summary>
|
||||
private static (long SubscriptionId, string FullReference)[] WithSubscriber(
|
||||
(long SubscriptionId, string FullReference)[] current, long subscriptionId, string fullRef)
|
||||
{
|
||||
var index = Array.FindIndex(current, s => s.SubscriptionId == subscriptionId);
|
||||
if (index >= 0)
|
||||
{
|
||||
var replaced = ((long SubscriptionId, string FullReference)[])current.Clone();
|
||||
replaced[index] = (subscriptionId, fullRef);
|
||||
return replaced;
|
||||
}
|
||||
var grown = new (long SubscriptionId, string FullReference)[current.Length + 1];
|
||||
current.CopyTo(grown, 0);
|
||||
grown[^1] = (subscriptionId, fullRef);
|
||||
return grown;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Remove a subscription. Returns the bindings the caller should pass to
|
||||
/// <c>UnsubscribeBulkAsync</c>; null when the id was never registered.
|
||||
@@ -220,21 +236,14 @@ internal sealed class SubscriptionRegistry
|
||||
/// </summary>
|
||||
/// <param name="itemHandle">The gateway item handle.</param>
|
||||
/// <returns>A list of subscription and reference pairs for the item handle.</returns>
|
||||
public IReadOnlyList<(long SubscriptionId, string FullReference)> ResolveSubscribers(int itemHandle)
|
||||
{
|
||||
if (!_subscribersByItemHandle.TryGetValue(itemHandle, out var bag)) return [];
|
||||
|
||||
// Each subscription may include the tag once. Walk every active subscription that
|
||||
// claims this handle and pull the full ref from its index in O(1).
|
||||
var result = new List<(long, string)>();
|
||||
foreach (var subId in bag.Distinct())
|
||||
{
|
||||
if (!_bySubscriptionId.TryGetValue(subId, out var entry)) continue;
|
||||
if (entry.FullRefByItemHandle.TryGetValue(itemHandle, out var fullRef))
|
||||
result.Add((subId, fullRef));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
/// <remarks>
|
||||
/// Allocation-free (#991 G-5): returns the handle's pre-built subscriber array itself. It is never mutated —
|
||||
/// a bind or unbind publishes a new array — so the caller may enumerate it while the map changes.
|
||||
/// </remarks>
|
||||
public IReadOnlyList<(long SubscriptionId, string FullReference)> ResolveSubscribers(int itemHandle) =>
|
||||
_subscribersByItemHandle.TryGetValue(itemHandle, out var subscribers)
|
||||
? subscribers
|
||||
: Array.Empty<(long SubscriptionId, string FullReference)>();
|
||||
|
||||
/// <summary>
|
||||
/// Drop every subscription and the whole reverse map. Used by the driver's runtime teardown:
|
||||
@@ -650,6 +659,17 @@ internal sealed class SubscriptionRegistry
|
||||
public IReadOnlyList<(long SubscriptionId, IReadOnlyList<TagBinding> Bindings)> SnapshotEntriesNotIn(int session) =>
|
||||
[.. _bySubscriptionId.Values.Where(e => e.Session != session).Select(e => (e.SubscriptionId, e.Bindings))];
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="SnapshotEntries"/> limited to subscriptions whose handles WERE issued by <paramref name="session"/>
|
||||
/// — the same-session re-advise work list (#991: replay-gap re-snapshot, dropped-event resync). Their handles
|
||||
/// are live, so a re-advise must release the ones it supersedes; a subscription still holding an older
|
||||
/// session's handles belongs to the reconnect replay instead.
|
||||
/// </summary>
|
||||
/// <param name="session">The current session.</param>
|
||||
/// <returns>The current-session subscriptions with their bindings.</returns>
|
||||
public IReadOnlyList<(long SubscriptionId, IReadOnlyList<TagBinding> Bindings)> SnapshotEntriesIn(int session) =>
|
||||
[.. _bySubscriptionId.Values.Where(e => e.Session == session).Select(e => (e.SubscriptionId, e.Bindings))];
|
||||
|
||||
/// <summary>
|
||||
/// Per-subscription bookkeeping. <see cref="FullRefByItemHandle"/> is an index
|
||||
/// over <see cref="Bindings"/> keyed by item handle so <c>ResolveSubscribers</c>
|
||||
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using Google.Protobuf.WellKnownTypes;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.MxGateway.Contracts.Proto.Galaxy;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Browse;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.Browse;
|
||||
|
||||
/// <summary>
|
||||
/// #991 G-3 — a <c>WatchDeployEvents</c> stream the gateway (or a proxy in front of it) COMPLETES without an error
|
||||
/// used to loop straight back into a new RPC: backoff lived only in the fault arm, and every received event reset
|
||||
/// it. A gateway that delivers the bootstrap event and then ends the stream (a drain, an idle-stream limit) was
|
||||
/// re-subscribed as fast as the RPC round-trips, indefinitely, with health unaffected.
|
||||
/// </summary>
|
||||
public sealed class DeployWatcherCleanCompletionTests
|
||||
{
|
||||
/// <summary>Each <c>WatchAsync</c> yields the bootstrap event and then completes cleanly.</summary>
|
||||
private sealed class BootstrapThenCompleteSource : IGalaxyDeployWatchSource
|
||||
{
|
||||
private int _calls;
|
||||
|
||||
/// <summary>Gets the number of <c>WatchAsync</c> calls so far.</summary>
|
||||
public int Calls => Volatile.Read(ref _calls);
|
||||
|
||||
/// <inheritdoc />
|
||||
public async IAsyncEnumerable<DeployEvent> WatchAsync(
|
||||
DateTimeOffset? lastSeenDeployTime, [EnumeratorCancellation] CancellationToken cancellationToken)
|
||||
{
|
||||
Interlocked.Increment(ref _calls);
|
||||
await Task.Yield();
|
||||
yield return new DeployEvent
|
||||
{
|
||||
Sequence = 0,
|
||||
TimeOfLastDeployPresent = true,
|
||||
TimeOfLastDeploy = Timestamp.FromDateTimeOffset(DateTimeOffset.Parse("2026-04-01T00:00:00Z")),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A stream that completes after one event is paced by the backoff (50 ms doubling to 200 ms here): within
|
||||
/// ~700 ms that is at most a handful of subscribes, not thousands — and it does keep re-subscribing (positive
|
||||
/// control: the watcher is not simply dead).
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_cleanly_completing_stream_is_resubscribed_with_backoff_not_in_a_tight_loop()
|
||||
{
|
||||
var source = new BootstrapThenCompleteSource();
|
||||
using var watcher = new DeployWatcher(
|
||||
source, logger: null,
|
||||
initialBackoff: TimeSpan.FromMilliseconds(50),
|
||||
maxBackoff: TimeSpan.FromMilliseconds(200),
|
||||
jitter: _ => TimeSpan.Zero);
|
||||
|
||||
await watcher.StartAsync(CancellationToken.None);
|
||||
await TestWait.UntilAsync(() => source.Calls >= 3, "the watcher must keep re-subscribing after a clean completion");
|
||||
await Task.Delay(700, TestContext.Current.CancellationToken);
|
||||
await watcher.StopAsync();
|
||||
|
||||
// 50 + 100 + 200 + 200 + ... ms: ~5 subscribes in ~0.75 s. Generous ceiling for a loaded runner; the
|
||||
// unpaced loop managed thousands.
|
||||
source.Calls.ShouldBeLessThanOrEqualTo(15, "a clean completion must be paced like a fault");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The backoff resets only after a stream stayed open for the stable-stream window — an event alone (the
|
||||
/// bootstrap every stream delivers) must not reset it, or a bootstrap-then-complete gateway is re-subscribed
|
||||
/// at the initial backoff forever. With a 100 ms initial backoff growing to 400 ms, the subscribe count in
|
||||
/// ~1.2 s stays well below the 12 a per-event reset would allow.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task An_event_alone_does_not_reset_the_backoff()
|
||||
{
|
||||
var source = new BootstrapThenCompleteSource();
|
||||
using var watcher = new DeployWatcher(
|
||||
source, logger: null,
|
||||
initialBackoff: TimeSpan.FromMilliseconds(100),
|
||||
maxBackoff: TimeSpan.FromMilliseconds(400),
|
||||
jitter: _ => TimeSpan.Zero,
|
||||
stableStreamDuration: TimeSpan.FromMinutes(1));
|
||||
|
||||
await watcher.StartAsync(CancellationToken.None);
|
||||
await Task.Delay(1_200, TestContext.Current.CancellationToken);
|
||||
await watcher.StopAsync();
|
||||
|
||||
// 0 + 100 + 200 + 400 + 400 = 1.1 s → ~5 subscribes; a per-event reset would give ~12 (every 100 ms).
|
||||
source.Calls.ShouldBeInRange(2, 8);
|
||||
}
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
using System.Collections.Concurrent;
|
||||
using Grpc.Core;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.MxGateway.Client;
|
||||
using ZB.MOM.WW.MxGateway.Contracts.Proto.Galaxy;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Browse;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.Browse;
|
||||
|
||||
/// <summary>
|
||||
/// #991 G-1 — the production security-classification source asks for each authored object on its own
|
||||
/// (rooted, depth 0, attributes included), so the cost tracks the authored tags rather than the Galaxy.
|
||||
/// </summary>
|
||||
public sealed class GatewayGalaxyAttributeSecuritySourceTests
|
||||
{
|
||||
private static GalaxyObject Obj(string tag) => new() { TagName = tag, ContainedName = tag };
|
||||
|
||||
/// <summary>One rooted, depth-0, attribute-bearing request per object; replies reduced to the requested root.</summary>
|
||||
[Fact]
|
||||
public async Task Each_object_is_fetched_rooted_at_depth_zero_with_attributes()
|
||||
{
|
||||
var requests = new ConcurrentBag<DiscoverHierarchyRequest>();
|
||||
Task<DiscoverHierarchyReply> Discover(DiscoverHierarchyRequest r, CancellationToken _)
|
||||
{
|
||||
requests.Add(r);
|
||||
var reply = new DiscoverHierarchyReply();
|
||||
reply.Objects.Add(Obj(r.RootTagName));
|
||||
reply.Objects.Add(Obj(r.RootTagName + "_Child")); // a gateway ignoring max_depth must not leak children
|
||||
return Task.FromResult(reply);
|
||||
}
|
||||
|
||||
var objects = await GatewayGalaxyAttributeSecuritySource.QueryAsync(
|
||||
Discover, ["Tank1", "Pump7"], maxConcurrency: 2, TestContext.Current.CancellationToken);
|
||||
|
||||
objects.Select(o => o.TagName).OrderBy(n => n).ShouldBe(["Pump7", "Tank1"]);
|
||||
requests.Count.ShouldBe(2);
|
||||
requests.ShouldAllBe(r => r.MaxDepth == 0 && r.IncludeAttributes && r.RootCase == DiscoverHierarchyRequest.RootOneofCase.RootTagName);
|
||||
}
|
||||
|
||||
/// <summary>An object the gateway reports NotFound (undeployed) is skipped; the others still load.</summary>
|
||||
[Fact]
|
||||
public async Task A_not_found_object_is_skipped()
|
||||
{
|
||||
Task<DiscoverHierarchyReply> Discover(DiscoverHierarchyRequest r, CancellationToken _)
|
||||
{
|
||||
if (r.RootTagName == "Gone")
|
||||
{
|
||||
// The client maps an RpcException to MxGatewayException, keeping it as the inner exception.
|
||||
throw new MxGatewayException("not found", new RpcException(new Status(StatusCode.NotFound, "no such object")));
|
||||
}
|
||||
var reply = new DiscoverHierarchyReply();
|
||||
reply.Objects.Add(Obj(r.RootTagName));
|
||||
return Task.FromResult(reply);
|
||||
}
|
||||
|
||||
var objects = await GatewayGalaxyAttributeSecuritySource.QueryAsync(
|
||||
Discover, ["Gone", "Tank1"], maxConcurrency: 1, TestContext.Current.CancellationToken);
|
||||
|
||||
objects.ShouldHaveSingleItem().TagName.ShouldBe("Tank1");
|
||||
}
|
||||
|
||||
/// <summary>Any other failure (gateway down) propagates — the driver keeps the previous map and logs.</summary>
|
||||
[Fact]
|
||||
public async Task Any_other_failure_propagates()
|
||||
{
|
||||
static Task<DiscoverHierarchyReply> Discover(DiscoverHierarchyRequest r, CancellationToken _)
|
||||
=> throw new MxGatewayException("unavailable", new RpcException(new Status(StatusCode.Unavailable, "down")));
|
||||
|
||||
await Should.ThrowAsync<MxGatewayException>(() => GatewayGalaxyAttributeSecuritySource.QueryAsync(
|
||||
Discover, ["Tank1"], maxConcurrency: 1, TestContext.Current.CancellationToken));
|
||||
}
|
||||
}
|
||||
@@ -41,6 +41,26 @@ public sealed class GalaxyDriverFactoryTests
|
||||
driver.Options.Reconnect.ReplayOnSessionLost.ShouldBeTrue();
|
||||
}
|
||||
|
||||
/// <summary>#991 G-19: keep-alive pings default on (15 s / 10 s) and both knobs bind, 0 included.</summary>
|
||||
[Fact]
|
||||
public void CreateInstance_BindsKeepAliveKnobs_DefaultingOn()
|
||||
{
|
||||
var defaults = GalaxyDriverFactoryExtensions.CreateInstance("g", MinimalConfig).Options.Gateway;
|
||||
defaults.KeepAlivePingDelaySeconds.ShouldBe(15);
|
||||
defaults.KeepAlivePingTimeoutSeconds.ShouldBe(10);
|
||||
|
||||
const string json = """
|
||||
{
|
||||
"Gateway": { "Endpoint": "https://mxgw.test:5001", "ApiKeySecretRef": "galaxy:apiKey",
|
||||
"KeepAlivePingDelaySeconds": 0, "KeepAlivePingTimeoutSeconds": 5 },
|
||||
"MxAccess": { "ClientName": "OtOpcUa-A" }
|
||||
}
|
||||
""";
|
||||
var gw = GalaxyDriverFactoryExtensions.CreateInstance("g", json).Options.Gateway;
|
||||
gw.KeepAlivePingDelaySeconds.ShouldBe(0);
|
||||
gw.KeepAlivePingTimeoutSeconds.ShouldBe(5);
|
||||
}
|
||||
|
||||
/// <summary>lmxopcua#749: the AlarmAck fallback section binds; absent means no fallback.</summary>
|
||||
[Fact]
|
||||
public void CreateInstance_BindsAlarmAckFallback()
|
||||
|
||||
+38
@@ -82,6 +82,44 @@ public sealed class PerPlatformProbeWatcherRegistryTests
|
||||
registry.TrackedSubscriptionCount.ShouldBe(1);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #991 G-6: a same-session resubscribe (the replay-gap re-snapshot) releases the handles it superseded — they
|
||||
/// are still advised on the gateway, and keeping them doubled the advise count per gap.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_same_session_resubscribe_releases_the_superseded_handles()
|
||||
{
|
||||
var registry = new SubscriptionRegistry();
|
||||
var subscriber = new FakeSubscriber();
|
||||
using var watcher = new PerPlatformProbeWatcher(subscriber, new HostStatusAggregator(), registry);
|
||||
await watcher.SyncPlatformsAsync(["A", "B"], CancellationToken.None);
|
||||
var old = watcher.CurrentBindings.Select(b => b.ItemHandle).OrderBy(h => h).ToArray();
|
||||
|
||||
await watcher.ResubscribeAsync(CancellationToken.None);
|
||||
|
||||
subscriber.Unsubscribes.ShouldHaveSingleItem().OrderBy(h => h).ShouldBe(old);
|
||||
watcher.CurrentBindings.Select(b => b.ItemHandle).ShouldAllBe(h => !old.Contains(h));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A resubscribe after a reconnect must NOT release the superseded handles: they belong to the dead session
|
||||
/// and the new session reuses the numbers, so an unsubscribe would unadvise some other live item.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_resubscribe_after_a_session_change_never_releases_dead_session_handles()
|
||||
{
|
||||
var registry = new SubscriptionRegistry();
|
||||
var subscriber = new FakeSubscriber();
|
||||
using var watcher = new PerPlatformProbeWatcher(subscriber, new HostStatusAggregator(), registry);
|
||||
await watcher.SyncPlatformsAsync(["A"], CancellationToken.None);
|
||||
|
||||
registry.StartNewSession();
|
||||
await watcher.ResubscribeAsync(CancellationToken.None);
|
||||
|
||||
subscriber.Unsubscribes.ShouldBeEmpty();
|
||||
watcher.CurrentBindings.ShouldHaveSingleItem().ItemHandle.ShouldBeGreaterThan(0, "positive control: rebound");
|
||||
}
|
||||
|
||||
/// <summary>StopAsync unsubscribes the live handles and removes the reserved entry.</summary>
|
||||
[Fact]
|
||||
public async Task StopAsync_unsubscribes_and_removes_the_reserved_entry()
|
||||
|
||||
+219
@@ -0,0 +1,219 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading.Channels;
|
||||
using Google.Protobuf.WellKnownTypes;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.Runtime;
|
||||
|
||||
/// <summary>
|
||||
/// #991 G-4 / G-6 — the two re-advise paths of the event stream.
|
||||
/// <list type="bullet">
|
||||
/// <item><b>G-4</b>: MXAccess sends a value only when it changes, so a data-change event the full bounded
|
||||
/// <see cref="EventPump"/> channel drops (newest-dropped) left its tag at the previous value, Good, until the
|
||||
/// attribute happened to change again. The pump now records the dropped item handles and, once the channel
|
||||
/// has drained, the driver re-advises exactly those tags — MXAccess answers an advise with the current
|
||||
/// value — and releases the superseded handles.</item>
|
||||
/// <item><b>G-6</b>: the replay-gap re-snapshot re-advised every tag on the SAME gateway session without
|
||||
/// releasing the previous handles, doubling the gateway's advise count per gap. It now releases them (only
|
||||
/// same-session handles — a dead session's numbers are reused by the next one and must never be sent).</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
public sealed class DroppedEventResyncTests
|
||||
{
|
||||
private static GalaxyDriverOptions Opts(int capacity) => new(
|
||||
new GalaxyGatewayOptions("https://mxgw.test:5001", "key"),
|
||||
new GalaxyMxAccessOptions("OtOpcUa-A", EventPumpChannelCapacity: capacity),
|
||||
new GalaxyRepositoryOptions(WatchDeployEvents: false),
|
||||
new GalaxyReconnectOptions());
|
||||
|
||||
private static GalaxyDriver NewDriver(AdvisingSubscriber subscriber, int capacity = 64) =>
|
||||
new("g", Opts(capacity), hierarchySource: null, dataReader: null, dataWriter: null, subscriber: subscriber);
|
||||
|
||||
/// <summary>
|
||||
/// Capacity-1 pump, handler wedged: the last two changes of a burst are dropped. Before the fix the tag ended
|
||||
/// at the last value that made it through the channel (2.0) — Good, and wrong — indefinitely. Now it ends at
|
||||
/// the real current value (4.0), and the handle the drop affected is released once its replacement is bound.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_value_dropped_by_a_full_event_channel_is_resynced_once_the_channel_drains()
|
||||
{
|
||||
var subscriber = new AdvisingSubscriber();
|
||||
subscriber.Current["Tank.SP"] = 0.0;
|
||||
using var driver = NewDriver(subscriber, capacity: 1);
|
||||
|
||||
var values = new ConcurrentQueue<double>();
|
||||
using var gate = new ManualResetEventSlim(true);
|
||||
using var blocked = new SemaphoreSlim(0);
|
||||
driver.OnDataChange += (_, e) =>
|
||||
{
|
||||
if (e.Snapshot.Value is double d) values.Enqueue(d);
|
||||
if (!gate.IsSet)
|
||||
{
|
||||
blocked.Release();
|
||||
gate.Wait(TimeSpan.FromSeconds(20));
|
||||
}
|
||||
};
|
||||
|
||||
await driver.SubscribeAsync(["Tank.SP"], TimeSpan.Zero, TestContext.Current.CancellationToken);
|
||||
await TestWait.UntilAsync(() => values.Contains(0.0), "the initial value must be published");
|
||||
var firstHandle = subscriber.LiveHandlesFor("Tank.SP").ShouldHaveSingleItem();
|
||||
|
||||
gate.Reset();
|
||||
subscriber.Set("Tank.SP", 1.0);
|
||||
(await blocked.WaitAsync(TimeSpan.FromSeconds(20), TestContext.Current.CancellationToken))
|
||||
.ShouldBeTrue("the dispatch thread must be wedged in the handler on 1.0");
|
||||
|
||||
subscriber.Set("Tank.SP", 2.0);
|
||||
subscriber.Set("Tank.SP", 3.0);
|
||||
subscriber.Set("Tank.SP", 4.0);
|
||||
var pump = (EventPump)driver.EventPumpInstanceForTests.ShouldNotBeNull();
|
||||
await TestWait.UntilAsync(() => pump.DroppedCountForTests >= 2,
|
||||
"with one slot and the dispatcher wedged, the burst's tail must be dropped");
|
||||
|
||||
gate.Set();
|
||||
|
||||
await TestWait.UntilAsync(() => values.LastOrDefault() == 4.0,
|
||||
"a dropped change must be resynced — the tag must not stay at the last value that fit in the channel",
|
||||
() => $"published=[{string.Join(", ", values)}] subscribes={subscriber.SubscribeCalls}");
|
||||
await TestWait.UntilAsync(() => subscriber.Unsubscribed.Contains(firstHandle),
|
||||
"the handle superseded by the re-advise must be released, not leaked on the gateway");
|
||||
subscriber.LiveHandlesFor("Tank.SP").ShouldHaveSingleItem().ShouldNotBe(firstHandle);
|
||||
|
||||
// Positive control: the re-advised tag keeps receiving live changes on its new handle.
|
||||
subscriber.Set("Tank.SP", 5.0);
|
||||
await TestWait.UntilAsync(() => values.LastOrDefault() == 5.0, "live data must keep flowing after the resync");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// No drop, no re-advise: an unwedged pump delivers every change and the subscriber sees exactly one
|
||||
/// SubscribeBulk. Guards the resync against firing on ordinary traffic.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Without_a_drop_nothing_is_re_advised()
|
||||
{
|
||||
var subscriber = new AdvisingSubscriber();
|
||||
subscriber.Current["Tank.SP"] = 0.0;
|
||||
using var driver = NewDriver(subscriber);
|
||||
var values = new ConcurrentQueue<double>();
|
||||
driver.OnDataChange += (_, e) => { if (e.Snapshot.Value is double d) values.Enqueue(d); };
|
||||
|
||||
await driver.SubscribeAsync(["Tank.SP"], TimeSpan.Zero, TestContext.Current.CancellationToken);
|
||||
for (var i = 1; i <= 20; i++) subscriber.Set("Tank.SP", i);
|
||||
await TestWait.UntilAsync(() => values.LastOrDefault() == 20.0, "every change must be delivered");
|
||||
|
||||
subscriber.SubscribeCalls.ShouldBe(1);
|
||||
subscriber.Unsubscribed.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// G-6: a replay gap re-advises every tag on the same session; the pre-gap handles are released once the
|
||||
/// fresh ones are bound, and data keeps flowing on the fresh handles (positive control).
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_replay_gap_resnapshot_releases_the_pre_gap_handles()
|
||||
{
|
||||
var subscriber = new AdvisingSubscriber();
|
||||
subscriber.Current["Tank.A"] = 1.0;
|
||||
subscriber.Current["Tank.B"] = 2.0;
|
||||
using var driver = NewDriver(subscriber);
|
||||
var values = new ConcurrentQueue<(string Ref, double Value)>();
|
||||
driver.OnDataChange += (_, e) => { if (e.Snapshot.Value is double d) values.Enqueue((e.FullReference, d)); };
|
||||
|
||||
await driver.SubscribeAsync(["Tank.A", "Tank.B"], TimeSpan.Zero, TestContext.Current.CancellationToken);
|
||||
var preGap = subscriber.LiveHandles.ToArray();
|
||||
preGap.Length.ShouldBe(2);
|
||||
|
||||
subscriber.EmitGap();
|
||||
|
||||
await TestWait.UntilAsync(() => subscriber.SubscribeCalls >= 2, "the replay gap must trigger a re-snapshot");
|
||||
await TestWait.UntilAsync(() => preGap.All(subscriber.Unsubscribed.Contains),
|
||||
"the re-snapshot must release the pre-gap handles — the session is the same, so they are still advised",
|
||||
() => $"unsubscribed=[{string.Join(", ", subscriber.Unsubscribed)}] preGap=[{string.Join(", ", preGap)}]");
|
||||
subscriber.LiveHandles.Count.ShouldBe(2, "exactly one advise per tag after the gap");
|
||||
|
||||
subscriber.Set("Tank.B", 9.0);
|
||||
await TestWait.UntilAsync(() => values.Contains(("Tank.B", 9.0)), "data must flow on the post-gap handles");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Behaves like the gateway + MXAccess for the parts these tests need: every SubscribeBulk issues fresh item
|
||||
/// handles and pushes each one's current value (an advise's initial value), a change is pushed on every live
|
||||
/// handle advising that reference, and UnsubscribeBulk retires handles.
|
||||
/// </summary>
|
||||
private sealed class AdvisingSubscriber : IGalaxySubscriber
|
||||
{
|
||||
private readonly Channel<MxEvent> _events = Channel.CreateUnbounded<MxEvent>();
|
||||
private readonly ConcurrentDictionary<int, string> _live = new();
|
||||
private int _nextHandle = 100;
|
||||
private int _subscribeCalls;
|
||||
|
||||
public ConcurrentDictionary<string, double> Current { get; } = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
public ConcurrentQueue<int> Unsubscribed { get; } = new();
|
||||
|
||||
public int SubscribeCalls => Volatile.Read(ref _subscribeCalls);
|
||||
|
||||
public ICollection<int> LiveHandles => _live.Keys;
|
||||
|
||||
public int[] LiveHandlesFor(string fullRef) =>
|
||||
[.. _live.Where(kv => string.Equals(kv.Value, fullRef, StringComparison.OrdinalIgnoreCase)).Select(kv => kv.Key)];
|
||||
|
||||
public void Set(string fullRef, double value)
|
||||
{
|
||||
Current[fullRef] = value;
|
||||
foreach (var handle in LiveHandlesFor(fullRef)) Emit(handle, value);
|
||||
}
|
||||
|
||||
public void EmitGap() => _events.Writer.TryWrite(new MxEvent
|
||||
{
|
||||
Family = MxEventFamily.Unspecified,
|
||||
ReplayGap = new ReplayGap { RequestedAfterSequence = 1, OldestAvailableSequence = 2 },
|
||||
}).ShouldBeTrue();
|
||||
|
||||
private void Emit(int handle, double value) => _events.Writer.TryWrite(new MxEvent
|
||||
{
|
||||
Family = MxEventFamily.OnDataChange,
|
||||
ItemHandle = handle,
|
||||
Value = new MxValue { DoubleValue = value },
|
||||
Quality = 192,
|
||||
SourceTimestamp = Timestamp.FromDateTime(DateTime.UtcNow),
|
||||
}).ShouldBeTrue();
|
||||
|
||||
public Task<IReadOnlyList<SubscribeResult>> SubscribeBulkAsync(
|
||||
IReadOnlyList<string> fullReferences, int bufferedUpdateIntervalMs, CancellationToken cancellationToken)
|
||||
{
|
||||
Interlocked.Increment(ref _subscribeCalls);
|
||||
var results = new List<SubscribeResult>(fullReferences.Count);
|
||||
foreach (var r in fullReferences)
|
||||
{
|
||||
var handle = Interlocked.Increment(ref _nextHandle);
|
||||
_live[handle] = r;
|
||||
results.Add(new SubscribeResult { TagAddress = r, ItemHandle = handle, WasSuccessful = true });
|
||||
if (Current.TryGetValue(r, out var v)) Emit(handle, v); // the advise's initial value
|
||||
}
|
||||
return Task.FromResult<IReadOnlyList<SubscribeResult>>(results);
|
||||
}
|
||||
|
||||
public Task UnsubscribeBulkAsync(IReadOnlyList<int> itemHandles, CancellationToken cancellationToken)
|
||||
{
|
||||
foreach (var h in itemHandles)
|
||||
{
|
||||
Unsubscribed.Enqueue(h);
|
||||
_live.TryRemove(h, out _);
|
||||
}
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public async IAsyncEnumerable<MxEvent> StreamEventsAsync([EnumeratorCancellation] CancellationToken cancellationToken)
|
||||
{
|
||||
await foreach (var ev in _events.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false))
|
||||
yield return ev;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading.Channels;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.Runtime;
|
||||
|
||||
/// <summary>
|
||||
/// #991 G-5 — every data-change event used to allocate, in the subscriber lookup alone, a result list, a LINQ
|
||||
/// <c>Distinct</c> iterator with its own hash set, and a boxed immutable-set enumerator, plus a new subscription
|
||||
/// handle per subscriber per event. The reverse map now stores each item handle's subscribers as a pre-built
|
||||
/// array (lookup is allocation-free) and the pump reuses one handle object per subscription.
|
||||
/// </summary>
|
||||
public sealed class FanOutAllocationTests
|
||||
{
|
||||
/// <summary>Resolving a handle's subscribers allocates nothing once the map is built.</summary>
|
||||
[Fact]
|
||||
public void ResolveSubscribers_does_not_allocate()
|
||||
{
|
||||
var registry = new SubscriptionRegistry();
|
||||
registry.Register(1, [new TagBinding("Tank.Level", 7)]);
|
||||
registry.Register(2, [new TagBinding("Tank.Level", 7), new TagBinding("Tank.Temp", 8)]);
|
||||
registry.ResolveSubscribers(7).Count.ShouldBe(2); // warm-up (JIT)
|
||||
|
||||
var before = GC.GetAllocatedBytesForCurrentThread();
|
||||
var total = 0;
|
||||
for (var i = 0; i < 1_000; i++) total += registry.ResolveSubscribers(7).Count;
|
||||
var allocated = GC.GetAllocatedBytesForCurrentThread() - before;
|
||||
|
||||
total.ShouldBe(2_000);
|
||||
allocated.ShouldBe(0L, "the per-event subscriber lookup must not allocate");
|
||||
}
|
||||
|
||||
/// <summary>Semantics kept: one entry per subscription, the subscription's own reference, removals honoured.</summary>
|
||||
[Fact]
|
||||
public void ResolveSubscribers_keeps_its_semantics()
|
||||
{
|
||||
var registry = new SubscriptionRegistry();
|
||||
registry.Register(1, [new TagBinding("A.X", 5), new TagBinding("A.X", 5)]); // a duplicate binding stays one entry
|
||||
registry.Register(2, [new TagBinding("B.X", 5)]);
|
||||
|
||||
registry.ResolveSubscribers(5).OrderBy(s => s.SubscriptionId).ShouldBe([(1L, "A.X"), (2L, "B.X")]);
|
||||
|
||||
registry.Rebind(1, [new TagBinding("A.X", 6)]);
|
||||
registry.ResolveSubscribers(5).ShouldBe([(2L, "B.X")]);
|
||||
registry.ResolveSubscribers(6).ShouldBe([(1L, "A.X")]);
|
||||
|
||||
registry.Remove(2);
|
||||
registry.ResolveSubscribers(5).ShouldBeEmpty();
|
||||
registry.TrackedItemHandleCount.ShouldBe(1);
|
||||
}
|
||||
|
||||
/// <summary>The pump hands every event of one subscription the same handle instance.</summary>
|
||||
[Fact]
|
||||
public async Task The_pump_reuses_one_handle_per_subscription()
|
||||
{
|
||||
var subscriber = new ChannelSubscriber();
|
||||
var registry = new SubscriptionRegistry();
|
||||
registry.Register(1, [new TagBinding("Tank.Level", 7)]);
|
||||
var handles = new List<ISubscriptionHandle>();
|
||||
var twoSeen = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
await using var pump = new EventPump(subscriber, registry, channelCapacity: 8, clientName: "G5");
|
||||
pump.OnDataChange += (_, e) =>
|
||||
{
|
||||
handles.Add(e.SubscriptionHandle);
|
||||
if (handles.Count == 2) twoSeen.TrySetResult();
|
||||
};
|
||||
pump.Start();
|
||||
|
||||
await subscriber.EmitAsync(7, 1.0);
|
||||
await subscriber.EmitAsync(7, 2.0);
|
||||
await TestWait.ForAsync(twoSeen.Task, "both events must be dispatched");
|
||||
|
||||
handles[1].ShouldBeSameAs(handles[0]);
|
||||
((GalaxySubscriptionHandle)handles[0]).SubscriptionId.ShouldBe(1);
|
||||
}
|
||||
|
||||
private sealed class ChannelSubscriber : IGalaxySubscriber
|
||||
{
|
||||
private readonly Channel<MxEvent> _events = Channel.CreateUnbounded<MxEvent>();
|
||||
|
||||
public Task<IReadOnlyList<SubscribeResult>> SubscribeBulkAsync(
|
||||
IReadOnlyList<string> fullReferences, int bufferedUpdateIntervalMs, CancellationToken cancellationToken)
|
||||
=> Task.FromResult<IReadOnlyList<SubscribeResult>>([]);
|
||||
|
||||
public Task UnsubscribeBulkAsync(IReadOnlyList<int> itemHandles, CancellationToken cancellationToken) => Task.CompletedTask;
|
||||
|
||||
public async IAsyncEnumerable<MxEvent> StreamEventsAsync([EnumeratorCancellation] CancellationToken cancellationToken)
|
||||
{
|
||||
await foreach (var ev in _events.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false))
|
||||
yield return ev;
|
||||
}
|
||||
|
||||
public ValueTask EmitAsync(int handle, double value) => _events.Writer.WriteAsync(new MxEvent
|
||||
{
|
||||
Family = MxEventFamily.OnDataChange,
|
||||
ItemHandle = handle,
|
||||
Value = new MxValue { DoubleValue = value },
|
||||
Quality = 192,
|
||||
});
|
||||
}
|
||||
}
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.MxGateway.Contracts.Proto.Galaxy;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Browse;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.Runtime;
|
||||
|
||||
/// <summary>
|
||||
/// #991 G-1 — <c>WriteAsync</c> picks <c>WriteSecured</c> vs the supervisory raw <c>Write</c> from a per-tag
|
||||
/// security map that ONLY <c>DiscoverAsync</c> filled — and the runtime never calls <c>DiscoverAsync</c> on the
|
||||
/// served driver (only the <c>/raw</c> picker's throwaway instance does). Every authored tag resolved
|
||||
/// <c>FreeAccess</c>, so a SecuredWrite/VerifiedWrite attribute always went down the raw path and was refused
|
||||
/// (MXAccess 1012/1013 → <c>BadUserAccessDenied</c>, pointing at permissions rather than the routing). The map is
|
||||
/// now seeded for the authored tags at initialize (and re-seeded on every redeploy) from the Galaxy repository.
|
||||
/// </summary>
|
||||
public sealed class GalaxyDriverSecurityResolutionTests
|
||||
{
|
||||
private static GalaxyDriverOptions Opts(params (string RawPath, string AttributeRef)[] tags) => new(
|
||||
new GalaxyGatewayOptions("https://mxgw.test:5001", "key"),
|
||||
new GalaxyMxAccessOptions("OtOpcUa-A"),
|
||||
new GalaxyRepositoryOptions(WatchDeployEvents: false),
|
||||
new GalaxyReconnectOptions())
|
||||
{
|
||||
RawTags = [.. tags.Select(t => new RawTagEntry(t.RawPath, $$"""{"attributeRef":"{{t.AttributeRef}}"}""", false))],
|
||||
};
|
||||
|
||||
private static GalaxyObject Obj(string tag, params (string Name, int Sec)[] attrs)
|
||||
{
|
||||
var o = new GalaxyObject { TagName = tag, ContainedName = tag };
|
||||
foreach (var (name, sec) in attrs)
|
||||
{
|
||||
o.Attributes.Add(new GalaxyAttribute
|
||||
{
|
||||
AttributeName = name,
|
||||
FullTagReference = $"{tag}.{name}",
|
||||
MxDataType = 2,
|
||||
SecurityClassification = sec,
|
||||
});
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
private sealed class FakeHierarchySource(IReadOnlyList<GalaxyObject> objects) : IGalaxyHierarchySource
|
||||
{
|
||||
public Task<IReadOnlyList<GalaxyObject>> GetHierarchyAsync(CancellationToken cancellationToken)
|
||||
=> Task.FromResult(objects);
|
||||
}
|
||||
|
||||
private sealed class FakeWriter : IGalaxyDataWriter
|
||||
{
|
||||
public List<(string FullRef, SecurityClassification Resolved)> Calls { get; } = [];
|
||||
|
||||
public Task<IReadOnlyList<WriteResult>> WriteAsync(
|
||||
IReadOnlyList<WriteRequest> writes, Func<string, SecurityClassification> securityResolver,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
foreach (var w in writes) Calls.Add((w.FullReference, securityResolver(w.FullReference)));
|
||||
return Task.FromResult<IReadOnlyList<WriteResult>>([.. writes.Select(_ => new WriteResult(StatusCodeMap.Good))]);
|
||||
}
|
||||
|
||||
public void InvalidateHandleCaches() { }
|
||||
}
|
||||
|
||||
private static async Task<SecurityClassification> ResolvedOnWriteAsync(GalaxyDriver driver, FakeWriter writer, string rawPath)
|
||||
{
|
||||
writer.Calls.Clear();
|
||||
await driver.WriteAsync([new WriteRequest(rawPath, 1.0)], TestContext.Current.CancellationToken);
|
||||
return writer.Calls.ShouldHaveSingleItem().Resolved;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The production shape: tags authored, the driver initialized, <c>DiscoverAsync</c> never called. The writer
|
||||
/// must receive the attribute's real classification (positive control: a FreeAccess sibling stays FreeAccess).
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task An_authored_secured_tag_resolves_its_classification_without_DiscoverAsync()
|
||||
{
|
||||
var hierarchy = new FakeHierarchySource([
|
||||
Obj("Tank1", ("SP", 2 /*SecuredWrite*/), ("Mode", 3 /*VerifiedWrite*/), ("Note", 0 /*FreeAccess*/)),
|
||||
]);
|
||||
var writer = new FakeWriter();
|
||||
var driver = new GalaxyDriver("g",
|
||||
Opts(("Plant/Tank1/SP", "Tank1.SP"), ("Plant/Tank1/Mode", "Tank1.Mode"), ("Plant/Tank1/Note", "Tank1.Note")),
|
||||
hierarchySource: hierarchy, dataWriter: writer);
|
||||
|
||||
await driver.InitializeAsync("{}", TestContext.Current.CancellationToken);
|
||||
|
||||
await TestWait.UntilAsync(
|
||||
() => ResolvedOnWriteAsync(driver, writer, "Plant/Tank1/SP").GetAwaiter().GetResult() == SecurityClassification.SecuredWrite,
|
||||
"a SecuredWrite attribute must route to WriteSecured without anyone calling DiscoverAsync");
|
||||
(await ResolvedOnWriteAsync(driver, writer, "Plant/Tank1/Mode")).ShouldBe(SecurityClassification.VerifiedWrite);
|
||||
(await ResolvedOnWriteAsync(driver, writer, "Plant/Tank1/Note")).ShouldBe(SecurityClassification.FreeAccess);
|
||||
writer.Calls.Single().FullRef.ShouldBe("Tank1.Note", "the writer dials the attributeRef");
|
||||
}
|
||||
|
||||
/// <summary>The dedicated seam is preferred, and only the authored objects are asked for.</summary>
|
||||
[Fact]
|
||||
public async Task The_security_seed_queries_only_the_authored_objects()
|
||||
{
|
||||
var source = new RecordingSecuritySource([Obj("Pump7", ("Speed", 4 /*Tune*/))]);
|
||||
var writer = new FakeWriter();
|
||||
var driver = new GalaxyDriver("g",
|
||||
Opts(("Plant/Pump7/Speed", "Pump7.Speed"), ("Plant/Pump7/Run", "Pump7.Run"), ("Plant/Valve2/Pos", "Valve2.Pos")),
|
||||
hierarchySource: null, dataWriter: writer, securitySource: source);
|
||||
|
||||
await driver.InitializeAsync("{}", TestContext.Current.CancellationToken);
|
||||
|
||||
await TestWait.UntilAsync(
|
||||
() => ResolvedOnWriteAsync(driver, writer, "Plant/Pump7/Speed").GetAwaiter().GetResult() == SecurityClassification.Tune,
|
||||
"the seeded classification must be used");
|
||||
source.Requested.ShouldHaveSingleItem().OrderBy(n => n).ShouldBe(["Pump7", "Valve2"]);
|
||||
(await ResolvedOnWriteAsync(driver, writer, "Plant/Valve2/Pos")).ShouldBe(SecurityClassification.FreeAccess,
|
||||
"an object the repository did not return keeps the FreeAccess default");
|
||||
}
|
||||
|
||||
private sealed class RecordingSecuritySource(IReadOnlyList<GalaxyObject> objects) : IGalaxyAttributeSecuritySource
|
||||
{
|
||||
public List<IReadOnlyCollection<string>> Requested { get; } = [];
|
||||
|
||||
public Task<IReadOnlyList<GalaxyObject>> GetObjectsAsync(
|
||||
IReadOnlyCollection<string> tagNames, CancellationToken cancellationToken)
|
||||
{
|
||||
lock (Requested) Requested.Add([.. tagNames]);
|
||||
return Task.FromResult(objects);
|
||||
}
|
||||
}
|
||||
}
|
||||
+5
@@ -319,6 +319,8 @@ public sealed class GalaxyDriverShutdownTests
|
||||
await driver.InitializeAsync("{}", CancellationToken.None);
|
||||
opens.ShouldBe(1);
|
||||
var client = driver.OwnedMxClientForTests.ShouldNotBeNull();
|
||||
// #991 G-19: the owned client runs over the driver's keep-alive channel, which the teardown must release.
|
||||
var channel = driver.OwnedMxChannelForTests.ShouldNotBeNull();
|
||||
var session = driver.OwnedMxSessionForTests.ShouldNotBeNull();
|
||||
session.IsConnected.ShouldBeTrue();
|
||||
driver.SupervisorForTests.ShouldNotBeNull();
|
||||
@@ -333,6 +335,9 @@ public sealed class GalaxyDriverShutdownTests
|
||||
await Should.ThrowAsync<ObjectDisposedException>(() => client.OpenSessionAsync(cancellationToken: CancellationToken.None),
|
||||
"the owned gateway channel must be disposed");
|
||||
driver.OwnedMxClientForTests.ShouldBeNull();
|
||||
driver.OwnedMxChannelForTests.ShouldBeNull();
|
||||
await Should.ThrowAsync<ObjectDisposedException>(() => channel.ConnectAsync(CancellationToken.None),
|
||||
"the keep-alive channel must be disposed with its client (a client over a caller-owned channel does not)");
|
||||
driver.OwnedMxSessionForTests.ShouldBeNull();
|
||||
driver.SupervisorForTests.ShouldBeNull();
|
||||
driver.ProbeWatcherForTests.ShouldBeNull();
|
||||
|
||||
+258
@@ -0,0 +1,258 @@
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Sockets;
|
||||
using Grpc.Core;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Server.Kestrel.Core;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.MxGateway.Client;
|
||||
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.Runtime;
|
||||
|
||||
/// <summary>
|
||||
/// #991 G-19 — a gateway connection that dies SILENTLY (host power loss, a firewall dropping the flow: no FIN, no
|
||||
/// RST) never faulted the driver's <c>StreamEvents</c>: a server stream sends nothing after its request, and the
|
||||
/// client library's channel has no HTTP/2 keep-alive, so the read waited forever and Galaxy stayed Healthy with
|
||||
/// stale Good values. The driver's channels now PING; an unanswered PING fails the connection and the stream.
|
||||
/// Proven here against an in-process gRPC gateway behind a TCP proxy that can be switched to a black hole.
|
||||
/// </summary>
|
||||
public sealed class GatewayChannelKeepAliveTests
|
||||
{
|
||||
/// <summary>Keep-alive pings at 1 s with a 1 s budget: a black-holed stream faults within a few seconds.</summary>
|
||||
[Fact]
|
||||
public async Task A_black_holed_stream_faults_on_the_keep_alive_channel()
|
||||
{
|
||||
await using var gateway = await FakeGateway.StartAsync();
|
||||
await using var proxy = BlackHoleProxy.Start(gateway.Port);
|
||||
var options = ClientOptions(proxy.Port);
|
||||
using var channel = GalaxyGatewayChannelFactory.CreateChannel(
|
||||
options, new GalaxyGatewayOptions(options.Endpoint.ToString(), "k", UseTls: false,
|
||||
KeepAlivePingDelaySeconds: 1, KeepAlivePingTimeoutSeconds: 1));
|
||||
await using var client = MxGatewayClient.Create(channel, options);
|
||||
|
||||
var outcome = await ReadAcrossBlackHoleAsync(client, proxy, TimeSpan.FromSeconds(15));
|
||||
|
||||
outcome.ShouldNotBeNull("the stream must fault once the pings go unanswered");
|
||||
outcome.ShouldNotBeOfType<EndOfStreamException>("a fault, not a clean end");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The control — and the defect: the client library's own channel (no keep-alive) leaves the same black-holed
|
||||
/// stream waiting. Without this the test above could pass for some other reason (e.g. the proxy closing).
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Without_keep_alive_a_black_holed_stream_waits_forever()
|
||||
{
|
||||
await using var gateway = await FakeGateway.StartAsync();
|
||||
await using var proxy = BlackHoleProxy.Start(gateway.Port);
|
||||
var options = ClientOptions(proxy.Port);
|
||||
await using var client = MxGatewayClient.Create(options);
|
||||
|
||||
var outcome = await ReadAcrossBlackHoleAsync(client, proxy, TimeSpan.FromSeconds(5));
|
||||
|
||||
outcome.ShouldBeNull("with no pings nothing ever notices the dead connection");
|
||||
}
|
||||
|
||||
/// <summary>The handler carries the pings (policy Always — a stream between events is not an "active request" gap).</summary>
|
||||
[Fact]
|
||||
public void The_handler_pings_always_and_zero_disables()
|
||||
{
|
||||
var options = ClientOptions(5001);
|
||||
using var on = GalaxyGatewayChannelFactory.CreateHttpHandler(options, TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(10));
|
||||
on.KeepAlivePingDelay.ShouldBe(TimeSpan.FromSeconds(15));
|
||||
on.KeepAlivePingTimeout.ShouldBe(TimeSpan.FromSeconds(10));
|
||||
on.KeepAlivePingPolicy.ShouldBe(HttpKeepAlivePingPolicy.Always);
|
||||
on.ConnectTimeout.ShouldBe(options.ConnectTimeout);
|
||||
|
||||
var defaults = new GalaxyGatewayOptions("http://x:1", "k");
|
||||
GalaxyGatewayChannelFactory.KeepAliveDelay(defaults).ShouldBe(TimeSpan.FromSeconds(15));
|
||||
GalaxyGatewayChannelFactory.KeepAliveTimeout(defaults).ShouldBe(TimeSpan.FromSeconds(10));
|
||||
GalaxyGatewayChannelFactory.KeepAliveDelay(defaults with { KeepAlivePingDelaySeconds = 0 })
|
||||
.ShouldBe(Timeout.InfiniteTimeSpan, "0 disables the pings");
|
||||
}
|
||||
|
||||
/// <summary>TLS options mirror the client library: no-validation only when asked for, CA pinning otherwise.</summary>
|
||||
[Fact]
|
||||
public void The_handler_mirrors_the_client_tls_settings()
|
||||
{
|
||||
var tls = new MxGatewayClientOptions
|
||||
{
|
||||
Endpoint = new Uri("https://gw:5001"), ApiKey = "k", UseTls = true, ServerNameOverride = "gw.example",
|
||||
RequireCertificateValidation = false,
|
||||
};
|
||||
using var lax = GalaxyGatewayChannelFactory.CreateHttpHandler(tls, Timeout.InfiniteTimeSpan, TimeSpan.Zero);
|
||||
lax.SslOptions.TargetHost.ShouldBe("gw.example");
|
||||
lax.SslOptions.RemoteCertificateValidationCallback.ShouldNotBeNull();
|
||||
|
||||
using var strict = GalaxyGatewayChannelFactory.CreateHttpHandler(
|
||||
new MxGatewayClientOptions
|
||||
{
|
||||
Endpoint = tls.Endpoint, ApiKey = "k", UseTls = true, RequireCertificateValidation = true,
|
||||
}, Timeout.InfiniteTimeSpan, TimeSpan.Zero);
|
||||
strict.SslOptions.RemoteCertificateValidationCallback.ShouldBeNull("platform validation applies");
|
||||
|
||||
using var plain = GalaxyGatewayChannelFactory.CreateHttpHandler(ClientOptions(5001), Timeout.InfiniteTimeSpan, TimeSpan.Zero);
|
||||
plain.SslOptions.RemoteCertificateValidationCallback.ShouldBeNull();
|
||||
}
|
||||
|
||||
private static MxGatewayClientOptions ClientOptions(int port) => new()
|
||||
{
|
||||
Endpoint = new Uri($"http://127.0.0.1:{port}"),
|
||||
ApiKey = "test-key",
|
||||
UseTls = false,
|
||||
ConnectTimeout = TimeSpan.FromSeconds(5),
|
||||
DefaultCallTimeout = TimeSpan.FromSeconds(5),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Opens StreamEvents, takes the first event (the connection is proven live), black-holes the proxy, and waits
|
||||
/// up to <paramref name="window"/> for the next read to end. Returns the exception it ended with, a sentinel
|
||||
/// exception for a clean end, or null if it was still waiting when the window closed.
|
||||
/// </summary>
|
||||
private static async Task<Exception?> ReadAcrossBlackHoleAsync(MxGatewayClient client, BlackHoleProxy proxy, TimeSpan window)
|
||||
{
|
||||
using var cts = new CancellationTokenSource();
|
||||
var enumerator = client.StreamEventsAsync(new StreamEventsRequest { SessionId = "s1" }, cts.Token)
|
||||
.GetAsyncEnumerator(cts.Token);
|
||||
try
|
||||
{
|
||||
(await enumerator.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(10))).ShouldBeTrue("the first event proves the stream is live");
|
||||
|
||||
proxy.BlackHole();
|
||||
var next = enumerator.MoveNextAsync().AsTask();
|
||||
var finished = await Task.WhenAny(next, Task.Delay(window, TestContext.Current.CancellationToken));
|
||||
if (finished != next) return null;
|
||||
try
|
||||
{
|
||||
return await next ? new InvalidOperationException("an unexpected event arrived") : new EndOfStreamException("completed");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return ex;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
await cts.CancelAsync();
|
||||
try { await enumerator.DisposeAsync(); } catch { /* the stream is dead either way */ }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A gateway whose StreamEvents sends one event and then stays open, silent, until cancelled.</summary>
|
||||
private sealed class FakeGatewayService : MxAccessGateway.MxAccessGatewayBase
|
||||
{
|
||||
public override async Task StreamEvents(
|
||||
StreamEventsRequest request, IServerStreamWriter<MxEvent> responseStream, ServerCallContext context)
|
||||
{
|
||||
await responseStream.WriteAsync(new MxEvent { Family = MxEventFamily.OnDataChange, ItemHandle = 1 });
|
||||
try { await Task.Delay(Timeout.Infinite, context.CancellationToken); }
|
||||
catch (OperationCanceledException) { }
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class FakeGateway(WebApplication app, int port) : IAsyncDisposable
|
||||
{
|
||||
public int Port => port;
|
||||
|
||||
public static async Task<FakeGateway> StartAsync()
|
||||
{
|
||||
var builder = WebApplication.CreateSlimBuilder();
|
||||
builder.Logging.ClearProviders();
|
||||
builder.WebHost.ConfigureKestrel(k => k.Listen(IPAddress.Loopback, 0, o => o.Protocols = HttpProtocols.Http2));
|
||||
builder.Services.AddGrpc();
|
||||
var app = builder.Build();
|
||||
app.MapGrpcService<FakeGatewayService>();
|
||||
await app.StartAsync();
|
||||
return new FakeGateway(app, new Uri(app.Urls.First()).Port);
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
using var stop = new CancellationTokenSource(TimeSpan.FromSeconds(2));
|
||||
try { await app.StopAsync(stop.Token); } catch { /* best effort */ }
|
||||
await app.DisposeAsync();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Forwards TCP between client and gateway until <see cref="BlackHole"/>; from then on every byte in either
|
||||
/// direction is swallowed while both sockets stay open — no FIN, no RST, exactly what a dead host or a
|
||||
/// dropping firewall looks like to the client.
|
||||
/// </summary>
|
||||
private sealed class BlackHoleProxy : IAsyncDisposable
|
||||
{
|
||||
private readonly TcpListener _listener = new(IPAddress.Loopback, 0);
|
||||
private readonly int _targetPort;
|
||||
private readonly CancellationTokenSource _cts = new();
|
||||
private readonly List<Socket> _sockets = [];
|
||||
private volatile bool _blackHoled;
|
||||
private Task? _acceptLoop;
|
||||
|
||||
private BlackHoleProxy(int targetPort) => _targetPort = targetPort;
|
||||
|
||||
public int Port => ((IPEndPoint)_listener.LocalEndpoint).Port;
|
||||
|
||||
public static BlackHoleProxy Start(int targetPort)
|
||||
{
|
||||
var proxy = new BlackHoleProxy(targetPort);
|
||||
proxy._listener.Start();
|
||||
proxy._acceptLoop = Task.Run(proxy.AcceptLoopAsync);
|
||||
return proxy;
|
||||
}
|
||||
|
||||
public void BlackHole() => _blackHoled = true;
|
||||
|
||||
private async Task AcceptLoopAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
while (!_cts.IsCancellationRequested)
|
||||
{
|
||||
var inbound = await _listener.AcceptSocketAsync(_cts.Token);
|
||||
var outbound = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
||||
await outbound.ConnectAsync(IPAddress.Loopback, _targetPort, _cts.Token);
|
||||
lock (_sockets) { _sockets.Add(inbound); _sockets.Add(outbound); }
|
||||
_ = PumpAsync(inbound, outbound);
|
||||
_ = PumpAsync(outbound, inbound);
|
||||
}
|
||||
}
|
||||
catch (Exception) when (_cts.IsCancellationRequested) { }
|
||||
catch (ObjectDisposedException) { }
|
||||
}
|
||||
|
||||
private async Task PumpAsync(Socket from, Socket to)
|
||||
{
|
||||
var buffer = new byte[16 * 1024];
|
||||
try
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
var read = await from.ReceiveAsync(buffer, SocketFlags.None, _cts.Token);
|
||||
if (read == 0) return;
|
||||
if (_blackHoled) continue; // swallowed: never delivered, never answered
|
||||
await to.SendAsync(buffer.AsMemory(0, read), SocketFlags.None, _cts.Token);
|
||||
}
|
||||
}
|
||||
catch (Exception) { /* proxy shutting down */ }
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await _cts.CancelAsync();
|
||||
_listener.Stop();
|
||||
lock (_sockets)
|
||||
{
|
||||
foreach (var s in _sockets) { try { s.Dispose(); } catch { /* best effort */ } }
|
||||
}
|
||||
if (_acceptLoop is not null) { try { await _acceptLoop; } catch { /* stopped */ } }
|
||||
_cts.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
+14
@@ -37,6 +37,20 @@ public sealed class GatewayGalaxyDataWriterFailClosedTests
|
||||
ops.RawWriteHandles.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
/// <summary>#991 G-1: WriteSecured carries the configured WriteUserId as the current user, not a hard-coded 0.</summary>
|
||||
[Fact]
|
||||
public async Task WriteOne_SecuredClassification_CarriesTheConfiguredWriteUserId()
|
||||
{
|
||||
var ops = new FakeMxWriteOps();
|
||||
var writer = new GatewayGalaxyDataWriter(
|
||||
new GalaxyMxSession(new Config.GalaxyMxAccessOptions(ClientName: "OtOpcUa-Test")), writeUserId: 42);
|
||||
|
||||
await writer.WriteOneForTestAsync(
|
||||
ops, new WriteRequest("Tag.Sec", true), SecurityClassification.SecuredWrite, CancellationToken.None);
|
||||
|
||||
ops.Invokes.Single(r => r.Command.Kind == MxCommandKind.WriteSecured).Command.WriteSecured.CurrentUserId.ShouldBe(42);
|
||||
}
|
||||
|
||||
// ---------------- T6: fail-closed on advise failure ----------------
|
||||
|
||||
/// <summary>When AdviseSupervisory fails (non-OK protocol status), the raw Write must NOT be issued and
|
||||
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading.Channels;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.Runtime;
|
||||
|
||||
/// <summary>
|
||||
/// #991 G-2 — <see cref="StatusCodeMap.FromQualityByte"/> used to log a Warning for EVERY event carrying a quality
|
||||
/// byte outside its 15-entry table, on the pump's single dispatch thread. The commonest such bytes are the listed
|
||||
/// qualities with the OPC DA limit bits set (<c>Good | LowLimited</c> = 0xC1): a few hundred limited attributes at
|
||||
/// 1 s cadence meant hundreds of Warning lines per second, slowing dispatch until the bounded channel dropped events.
|
||||
/// Now the two limit bits are masked before the lookup (they never change the category or substatus), and a byte
|
||||
/// that is still unlisted warns once per distinct value.
|
||||
/// </summary>
|
||||
public sealed class QualityByteLimitBitsTests
|
||||
{
|
||||
/// <summary>The limit bits (LL in QQSSSSLL) do not change the mapped status, and are not "unrecognised".</summary>
|
||||
/// <param name="input">A listed quality with limit bits set.</param>
|
||||
/// <param name="expected">The status the same quality maps to without them.</param>
|
||||
[Theory]
|
||||
[InlineData((byte)0xC1, StatusCodeMap.Good)] // Good | LowLimited
|
||||
[InlineData((byte)0xC2, StatusCodeMap.Good)] // Good | HighLimited
|
||||
[InlineData((byte)0xC3, StatusCodeMap.Good)] // Good | Constant
|
||||
[InlineData((byte)0xDA, StatusCodeMap.GoodLocalOverride)] // LocalOverride | HighLimited
|
||||
[InlineData((byte)0x45, StatusCodeMap.UncertainLastUsableValue)] // LastUsable | LowLimited
|
||||
[InlineData((byte)0x13, StatusCodeMap.BadSensorFailure)] // SensorFailure | Constant
|
||||
public void Limit_bits_map_like_the_unlimited_quality_without_a_warning(byte input, uint expected)
|
||||
{
|
||||
var logger = new CapturingLogger();
|
||||
|
||||
StatusCodeMap.FromQualityByte(input, logger).ShouldBe(expected);
|
||||
|
||||
logger.Entries.ShouldBeEmpty($"0x{input:X2} is a listed quality with limit bits — nothing is unrecognised");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 1,000 events carrying a genuinely unlisted byte through the pump: every one is published at its category,
|
||||
/// and the log gets ONE line, not one per event. 0xE0 is used by no other test (the guard is process-wide).
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task An_unlisted_quality_byte_warns_once_however_many_events_carry_it()
|
||||
{
|
||||
const int events = 1_000;
|
||||
var subscriber = new ChannelSubscriber();
|
||||
var registry = new SubscriptionRegistry();
|
||||
registry.Register(1, [new TagBinding("Tank01.Level", 7)]);
|
||||
var logger = new CapturingLogger();
|
||||
var statuses = new List<uint>();
|
||||
var allDelivered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
await using var pump = new EventPump(subscriber, registry, logger, channelCapacity: events + 8, clientName: "G2");
|
||||
pump.OnDataChange += (_, e) =>
|
||||
{
|
||||
statuses.Add(e.Snapshot.StatusCode);
|
||||
if (statuses.Count == events) allDelivered.TrySetResult();
|
||||
};
|
||||
pump.Start();
|
||||
|
||||
for (var i = 0; i < events; i++) await subscriber.EmitAsync(7, quality: 0xE0);
|
||||
|
||||
await TestWait.ForAsync(allDelivered.Task, "every event must be dispatched");
|
||||
statuses.ShouldAllBe(s => s == StatusCodeMap.Good, "0xE0 is in the Good category");
|
||||
logger.Entries.Count(e => e.Level == LogLevel.Warning && e.Text.Contains("0xE0"))
|
||||
.ShouldBe(1, "an unlisted byte is worth one diagnostic line, not one per event");
|
||||
}
|
||||
|
||||
private sealed class ChannelSubscriber : IGalaxySubscriber
|
||||
{
|
||||
private readonly Channel<MxEvent> _events = Channel.CreateUnbounded<MxEvent>();
|
||||
|
||||
public Task<IReadOnlyList<SubscribeResult>> SubscribeBulkAsync(
|
||||
IReadOnlyList<string> fullReferences, int bufferedUpdateIntervalMs, CancellationToken cancellationToken)
|
||||
=> Task.FromResult<IReadOnlyList<SubscribeResult>>([]);
|
||||
|
||||
public Task UnsubscribeBulkAsync(IReadOnlyList<int> itemHandles, CancellationToken cancellationToken) => Task.CompletedTask;
|
||||
|
||||
public async IAsyncEnumerable<MxEvent> StreamEventsAsync([EnumeratorCancellation] CancellationToken cancellationToken)
|
||||
{
|
||||
await foreach (var ev in _events.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false))
|
||||
yield return ev;
|
||||
}
|
||||
|
||||
public ValueTask EmitAsync(int handle, int quality) => _events.Writer.WriteAsync(new MxEvent
|
||||
{
|
||||
Family = MxEventFamily.OnDataChange,
|
||||
ItemHandle = handle,
|
||||
Value = new MxValue { DoubleValue = 1 },
|
||||
Quality = quality,
|
||||
});
|
||||
}
|
||||
}
|
||||
+7
@@ -34,6 +34,13 @@
|
||||
<!-- Client package: only the Skip-gated live alarm-feed smoke (GatewayGalaxyAlarmFeedLiveTests)
|
||||
constructs a real MxGatewayClient. Unit tests use the fake stream-factory seam. -->
|
||||
<PackageReference Include="ZB.MOM.WW.MxGateway.Client" />
|
||||
<!-- #991 G-19: an in-process gRPC gateway behind a black-holing TCP proxy proves the keep-alive channel
|
||||
faults a silently dead StreamEvents (and that the client library's own channel does not). -->
|
||||
<PackageReference Include="Grpc.AspNetCore" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
Reference in New Issue
Block a user