feat: author and inspect grpc data connections

This commit is contained in:
Joseph Doherty
2026-11-16 20:58:43 -05:00
parent 8ad03e9c5d
commit 1df29a3124
31 changed files with 1246 additions and 141 deletions
+36
View File
@@ -246,6 +246,42 @@ See the [ClusterClient→gRPC migration design](plans/2026-08-06-clusterclient-t
**On an admin-role node, `NodeCommandService` and `CentralCommandService` are `AllowAnonymous` by design** — the AdminUI cookie `FallbackPolicy` would otherwise 401/redirect a correctly-PSK'd call before the interceptor above ever ran (archreview 03/S14). See [`security.md` § Mesh gRPC ingress is `AllowAnonymous` by design](security.md#mesh-grpc-ingress-is-allowanonymous-by-design).
### `DataConnections`
This is the dedicated current-data gRPC listener, separate from `MeshTransport`, telemetry,
artifact fetch and LocalDb sync. See [Data connections](DataConnections.md) for deployment,
consumer scope, exports, mappings, credential provisioning and recovery.
| Key | Default | Purpose |
|---|---|---|
| `Enabled` | `false` | Bind the dedicated data listener when enabled. |
| `ListenPort` / `ListenAddress` | `0` / `0.0.0.0` | Dedicated port (required when enabled) and IP literal bind address. |
| `AllowedHosts` | `[]` | Explicit permitted endpoint host names; required when enabled. |
| `CertificatePath` / `CertificateKeyPath` | unset | Server TLS certificate and optional separate PEM key. Production requires TLS. |
| `AllowDevelopmentCleartext` | `false` | Allowed only in Development with a literal loopback listener. |
| `MaxMessageBytes` / `MaxConcurrentCalls` | `1048576` / `64` | Message-size and concurrent unary-call admission. |
| `MaxStreams` / `MaxStreamsPerPrincipal` | `256` / `8` | Global and per-principal stream bounds. |
| `MaxMonitoredItems` | `10000` | Listener monitored-item bound. |
| `MaxTransportBytes` / `MaxPendingBytes` | `67108864` / `1048576` | Retained transport and pending-work byte bounds. |
| `MaxSessionLifetime` | `01:00:00` | Finite stream-session lifetime. |
| `UnaryTimeout` / `StreamCommandTimeout` | `00:00:30` / `00:00:05` | Finite ingress unary and stream-command deadlines. |
| `CredentialBundlePath` / `TrustBundlePath` | unset | Independent node-local credential and trust provisioning mounts. |
| `BundleRefreshInterval` | `00:00:01` | Local mount refresh interval (validated range: 100 ms to one minute). |
| `Hub` | `DataResourceLimits` defaults | Finite Runtime hub admission, retained-work and recovery limits. |
The authoritative settings and validation are `Host/Configuration/DataConnectionOptions.cs` and
`DataConnectionOptionsValidator.cs`. Options use normal .NET configuration layering; environment
keys use `DataConnections__...`. Host validation rejects insecure production transport and invalid
finite limits. These values are resource bounds, not measured capacity claims. Connection rows,
export grants and mappings add their own batch/page, stream/item, message/byte, depth/node,
metadata-lease and stale-timeout limits; effective admission must satisfy every applicable bound.
Listener configuration does not itself create an import. Deploy `DataConnection`, `DataExport`
and `RemoteNamespaceMapping` records through the existing configuration flow. Keep credentials out
of artifacts and resolve their canonical `secret:data/...` references on the listed consumer nodes.
New records and write-through default disabled. Production data endpoints use `https://`; existing
h2c mesh settings do not opt this listener into cleartext.
### `ConfigSource` / `ConfigServe` (config fetch-and-cache)
- **Purpose:** [per-cluster mesh](plans/2026-07-21-per-cluster-mesh-design.md) **Phase 3**. `ConfigSource:Mode` selects where a **driver** node reads its deployed configuration: `Direct` (read `Deployment.ArtifactBlob` from central SQL, today's behaviour) or `FetchAndCache` (fetch the artifact bytes from central over a gRPC stream, verify SHA-256, cache in LocalDb, and read **only** the cache — no central-SQL config read). `ConfigServe` is the **central** (admin-role) serve side that a `FetchAndCache` node dials.
+98
View File
@@ -0,0 +1,98 @@
# gRPC data connections
Data connections expose current Raw and UNS data between explicitly configured nodes or clusters.
The contract supports capabilities, browse, metadata, cached reads, writes and data-change
subscriptions. It is independent of the existing mesh command, telemetry, configuration and
pair-sync planes. An Akka pair continues to own its local field-device drivers; importing a peer's
data does not start another device driver or join the peer's gossip ring.
## Configuration and deployment
A connection is directional. Configure each direction separately when both sides need imports.
The deployed configuration uses three entities:
| Entity | Operator choices |
|---|---|
| `DataConnection` | Owning cluster, explicit consumer nodes, expected remote cluster/node, Node or Cluster target, endpoint set, consistency, secret reference, operation subset and finite call limits. |
| `DataExport` | Origin-owned Raw or UNS root, authenticated peer principal, operation grants and export limits. |
| `RemoteNamespaceMapping` | Connection, consumer subset, local parent and branch name, same-realm remote root/address, operations, optional write-through, projection limits and freshness settings. |
New connections, exports and mappings are disabled by default; write-through also defaults off.
A saved draft is not a live import. Use the existing cluster deployment flow to validate and apply
changes, and inspect applied state before enabling dependent consumers. The server-side schema
validator remains authoritative: consumers must belong to the owning cluster, mapping consumers
must be a subset of the connection's consumers, local parents must be valid containers, and branch
collisions, invalid self-routes and unsupported type expectations are rejected.
Raw maps to Raw and UNS maps to UNS. A remote root is a branch, so descendants can be discovered
without authoring one import row per leaf. The local mapping owns a distinct view with remote origin
provenance. Remote projected branches cannot be re-exported as locally owned data. Stable addresses
use cluster, namespace URI, identifier kind and identifier; numeric OPC UA namespace indexes are
process-local.
## Listener, credentials and trust
Enable the dedicated listener with `DataConnections` host settings; see
[Configuration](Configuration.md#dataconnections). Production requires TLS, a dedicated port,
explicit allowed hosts and authenticated target identity. The listener certificate must have a
current private key and SANs covering every allowed host; server-certificate rotation requires a
rolling restart. Outbound trust validates the hostname and configured custom roots. The development cleartext exception is
limited to Development on a literal loopback listener.
The consuming node must have its target bearer credential provisioned locally under the configured
canonical `secret:data/...` reference and scoped to that connection. An origin export names the
principal authenticated by that credential. Deployment artifacts carry references and scope,
never raw target credentials. `CredentialBundlePath` and `TrustBundlePath` support independently
versioned local provisioning. Trust roots are provisioned independently of credentials; rotating
one does not implicitly authorize the other. Protect mounted files and replace them atomically.
Missing or unreadable mounts are retried rather than treated as credential deletion; explicit
versioned deletion/removal and deployed scope retirement revoke authority. Do not reuse the
existing mesh PSKs for this data plane.
## Routing and availability
Node targets pin the expected node. Cluster targets select an authenticated, ready primary from
the configured eligible endpoints; an endpoint's claimed cluster and serving incarnation must match
policy. An explicit Node target may allow `ReadyReplica` for reads/subscriptions; writes still
require primary authority. A secondary is not a write proxy to its partner. Same-cluster peer
connections and cross-cluster connections use the same explicit routing rules.
Role changes, deployment changes, metadata lease expiry and credential/trust changes invalidate
stale authority. Recovery discovers the current catalog and starts a new subscription epoch with
a fresh snapshot. Transitions during a disconnect can be lost. A peer outage must be treated as
unavailable/pending remote data rather than a successfully browsed empty branch. Local device data
continues independently. [Read/write operations](ReadWriteOperations.md) describes asynchronous
projected cache refresh, freshness checks and mutation outcomes.
## Rollout and diagnosis
1. Provision TLS trust and connection-scoped target credentials on each consumer; configure the
origin export and local mapping grants.
2. Deploy with writes disabled. Confirm applied consumer scope, endpoint identity and role, then
expand a remote branch and verify metadata and current-value quality.
3. Verify subscription snapshot recovery and freshness for the intended consumer workload.
4. Enable write-through only where the application can handle confirmed, unconfirmed and unknown
outcomes. Never replay an ambiguous write after reconnect or failover.
5. To disable imports, disable the connection/mapping through the existing deployment flow. Retired
authority makes imported data unavailable; disabling does not replay pending writes.
For an unavailable import, check enabled versus deployed state, consumer membership, endpoint and
allowed-host identity, target role/readiness, credential scope/version, trust roots, export/mapping
operation intersection, metadata lease and sample age. Inspect stream resets/overflow, admitted
retained import views, acknowledged registrations and distinct write outcomes where diagnostics expose them.
The age upper bound is measured by the reporting node at the observation, independent of the admin
server clock. Coalescing notices and resets have separate counts; unavailable overflow evidence is
shown as unavailable. Ready describes the last verified handshake, whose timestamp is shown. Saving configuration is not evidence
of a ready connection, and a live transport alone is not evidence of current metadata authority.
Listener, connection, export and projection limits bound messages, streams, monitored items,
retained bytes, metadata and call lifetimes. Tune them together for measured workload demand;
defaults are admission bounds, not a throughput or capacity guarantee. Overload can reject work or
reset a stream, requiring a fresh snapshot. Do not interpret that recovery as lossless replay.
## Feature boundary
Remote history, alarm/event forwarding and relay operations are future work. Authorized imported
current values can feed local derived engines, including calculations, scripts, historization and
alarm evaluation. Such local processing does not add a remote history/alarm API or permit re-export
of an imported branch.
+5
View File
@@ -44,6 +44,11 @@ One Core subsystem is shipped without a dedicated top-level doc; see the section
|---------|-----|
| `Analyzers` (Roslyn OTOPCUA0001) | [security.md](security.md) § OTOPCUA0001 Analyzer |
Current-data federation is documented in [DataConnections.md](DataConnections.md): directional
node/cluster connections, Raw/UNS branch projection, dedicated TLS and scoped credentials,
primary routing, finite admission limits and recovery. Remote history, alarms and relays remain
outside that contract; imported current values may feed authorized local derived engines.
### Drivers
| Doc | Covers |
+14
View File
@@ -39,6 +39,20 @@ on any `DriverConfig` change, so the driver rebuilds against the new RawPaths an
⚠️ The flip side is that **a rename reconnects the driver** — briefly dropping every tag on it, not
just the renamed one. That is the accepted cost #516 documents; it is not specific to renames.
## Remote Raw branches
A deployed `RemoteNamespaceMapping` can mount an expandable remote Raw branch beneath a local
Raw container. Its directional data connection explicitly names the consumer nodes and expected
remote cluster/node, and the origin must export the same-realm root to the authenticated principal.
This supports peer-node imports within one cluster and imports across independent clusters.
Branch discovery does not create locally owned raw tags or a second field-device driver. Browse,
read and data-change subscribe use the mapped view's current grants, catalog authority and freshness;
write-through additionally requires an explicit write-enabled mapping and origin authorization.
Remote descendants retain origin provenance and cannot be re-exported as local data. A saved draft
is not an applied branch, and a pending/unavailable peer is not an empty folder. See
[Data connections](DataConnections.md) and [Read/write operations](ReadWriteOperations.md).
## Endpoint → DeviceConfig (the channel/device split)
v3 moves the **connection endpoint** off the driver and onto the **Device** (`DeviceConfig`),
+83 -120
View File
@@ -1,139 +1,102 @@
# Read/Write Operations
> **Rewritten 2026-07-27** against `src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs`.
> The previous revision described a v2-era `DriverNodeManager` with per-variable `OnReadValue` hooks,
> an `AuthorizationGate`/`WriteAuthzPolicy` ACL pair and a `NodeSourceKind` dispatch switch. **None of
> those exist** — `OnReadValue`, `WriteAuthzPolicy`, `_sourceByFullRef`, `_writeIdempotentByFullRef`
> and `IRoleBearer` all have zero occurrences in `src/`. The read path in particular worked nothing
> like the way it was documented. See `deferment.md` §3.1 and §7.
This page describes `OtOpcUaNodeManager` and the Runtime data-connection services. Namespace
indexes are assigned by the running server: resolve namespace URIs through `NamespaceArray`
instead of assuming numeric Raw or UNS indexes. Projected Raw/UNS nodes have separate namespace
URIs and retain remote origin and serving provenance.
## The shape of it: push for reads, pull for writes
## Local reads and authorization
The live server is `OtOpcUaNodeManager`, a **push-model** `CustomNodeManager2`. This asymmetry is the
single most important thing on this page:
Local driver values use a push model. `DriverInstanceActor` polls or subscribes and
`DriverHostActor` fans samples to Raw and referencing UNS nodes. An OPC UA Read returns the
cached value, source timestamp and full OPC UA status code, including its sub-code. It does
not initiate device I/O. A cached bad device quality therefore remains visible to readers.
- **Reads never reach a driver.** There is no `Read` override and no `OnReadValue` / `OnSimpleReadValue`
handler anywhere in the node manager. Driver values are *pushed in* from the Akka actor layer
(`DriverInstanceActor` polls or subscribes, `DriverHostActor` fans the value to the raw NodeId and
every referencing UNS NodeId), and a client Read is served by the OPC UA SDK straight from the
cached node value. A client read therefore costs nothing on the wire to the device, and cannot fail
with a device error — it returns whatever quality was last pushed.
- **Writes are synchronous pull-through.** A client write runs `OnWriteValue` → role gate → driver.
`OtOpcUaNodeManager.Read` does have an override. With `Security:Acl:Enabled=true`,
`DataPlaneAuthorizer` and the shared `DataOperationPolicy` enforce scoped grants on Read,
Browse, TranslateBrowsePaths, subscription admission, writes, alarm commands and HistoryRead.
Browse checks the source and filters returned references; browse transit exposes the ancestor
names needed to reach a granted descendant. Active monitored items are revalidated as authority
changes. These are production consumers of the permission evaluator.
Everything the old page said about `CapabilityInvoker` wrapping OPC UA reads was misplaced: the
invoker is real, but it lives on the **driver-actor** side wrapping the poll/subscribe calls. The
`OpcUaServer` project does not reference it at all.
With the flag off, local Read/Browse/Subscribe/HistoryRead retain their legacy permissive
posture for admitted sessions. Local Value writes use the server-wide `WriteOperate` role;
alarm methods use `AlarmAck`. Mutations also recheck API-key usability. See
[Security](security.md#data-plane-authorization) for HistoryUpdate and the detailed operation gates.
The flag does not bypass mapped-data authorization or remote export authorization.
## Read path
## Projected reads, browse and subscriptions
1. The SDK resolves the NodeId in the Raw (`ns=2`) or UNS (`ns=3`) namespace.
2. It returns the cached `DataValue` — value, `StatusCode` and source timestamp as last pushed.
A [data connection](DataConnections.md) projects an explicitly mapped same-realm remote branch
beneath a local Raw or UNS parent. Browse schedules bounded metadata discovery asynchronously;
a visible local branch anchor does not mean its remote children are ready. Pending discovery
returns `BadWaitingForInitialData`, unavailable discovery returns `BadNoCommunication`, and
continuations must still match current authority, catalog and serving generations.
### Status codes reach the client intact (Gitea #519)
A projected Value Read first acquires a current scoped demand. A cached sample can be returned
only when its proof, serving identity, projection generation and age satisfy the request.
`maxAge=0`, a missing sample or an unsuitable sample schedules an asynchronous bounded remote
read and returns `BadWaitingForInitialData`; it does not block the SDK callback on the network.
The response refreshes the local cache for a later Read. The origin's own local Read remains a
cached read rather than a device poll.
The driver's OPC UA status code — **sub-code included** — is what a client reads. A driver that maps
an unreachable device to `BadNoCommunication` surfaces exactly that, distinguishable from
`BadTypeMismatch` or `BadNotSupported`.
Projected data-change monitored items acquire live demands and share compatible upstream
acquisition. Delivery checks current authority and freshness through the publish path, including
queued delivery; admission alone is insufficient. Reconnect/reset uses a fresh snapshot and new
stream epoch. There is no durable event replay or seamless subscription transfer guarantee.
Browsing metadata alone does not acquire value subscriptions. Configured imported dependencies
can acquire values for local derived engines under their deployed authority.
This was not always true. Until #519 the publish path projected the driver's `uint` onto a 3-state
`Good`/`Uncertain`/`Bad` enum in `DriverInstanceActor`, and `OtOpcUaNodeManager` re-expanded `Bad` to
a bare `StatusCodes.Bad` (`0x80000000`). Every driver's diagnostic intent survived in logs only —
including the 16 status constants #497 had just corrected across six drivers. The value path now
carries the raw `uint` end to end (`AttributeValueBatchPublished` → `AttributeValueBatchUpdate` →
`IOpcUaAddressSpaceSink.WriteValues`), and severity classification is a helper
(`OpcUaStatus.IsGood`/`IsUncertain`/`IsBad`) rather than a lossy projection.
## Local Value writes
**Writing a status code in engine code:** use a named constant on
`ZB.MOM.WW.OtOpcUa.Commons.OpcUa.OpcUaStatus`, never an inline literal. Commons and Runtime are
deliberately SDK-free, so nothing but `StatusCodeParityTests` checks a literal against the name it is
commented with — and that guard works by reflection, so it can only see a **named** constant.
3. **No authorization check runs.** Not a per-node ACL, not a role check, nothing. Any admitted
session — including an Anonymous one — can read every node in the address space. The only gating is
the `AccessLevels` bitmask set at materialization, which is a per-node *capability* declaration, not
a per-user decision.
Writable local variables attach `OnEquipmentTagWrite`; non-writable variables are rejected by
the SDK. The handler applies the local ACL decision, or the legacy role/key gate when ACL is off,
and dispatches through the realm-qualified node write gateway to the backing driver. Raw and UNS
aliases resolve to the same device point. Primary-role admission is checked on the dispatch path.
Authored `NodeAcl` deny rules have **no effect on reads** (or on anything else — see
[docs/security.md](security.md) § Data-Plane Authorization).
The SDK invokes the callback while holding the node-manager lock. Asynchronous work is dispatched
without waiting under that lock. Local optimistic values are corrected through shared fan-out on
a confirmed failure. A driver with fire-and-forget semantics cannot provide device confirmation.
`WriteTune` and `WriteConfigure` are not separate tag-classification gates on this Value-write path.
## Write path — `OnEquipmentTagWrite`
## Remote write outcomes
The handler is attached in `EnsureVariable` **only when the tag was materialized `writable`**, and
re-attached or cleared by `UpdateTagAttributes` on an in-place edit. A non-writable node has no
handler, so the SDK rejects the write before any of this runs.
Projected write-through is opt-in. It requires an enabled deployed connection and mapping,
`WriteThrough`, a writable remote target, compatible local and remote grants, current metadata and
serving authority, and primary-role admission. Mapping a value does not grant write access.
The mapped completion path preserves these outcomes:
1. **Role gate.** `EvaluateEquipmentWriteGate(identity, gatewayWired)` requires the session identity to
be a `RoleCarryingUserIdentity` carrying the `WriteOperate` role. No identity or no role ⇒
`BadUserAccessDenied`, fail-closed. Gate passed but no write gateway wired (admin-only node,
pre-boot) ⇒ `BadNotWritable`.
- This is a **server-wide** check. It takes no node and no realm: a session that may write one tag
may write every writable tag on that node.
- `WriteTune` and `WriteConfigure` are **never checked**. `OpcUaDataPlaneRoles` declares only
`WriteOperate` and `AlarmAck`; the classification tiers exist in the permission vocabulary but no
code path reads them.
2. **Optimistic local apply.** The new value is written to the node so subscribers see it immediately.
3. **Realm-qualified dispatch.** `RealmOf(node.NodeId)` selects Raw or UNS, and the value routes to the
backing driver ref through the node write gateway. Both NodeIds for a fanned value resolve to the
same driver ref, so a write via either one reaches the same device point.
4. **Write-outcome self-correction.** If the device write fails, the optimistic value is **reverted**
on the raw NodeId and every referencing UNS NodeId through the shared fan-out, so a failed write
cannot leave a phantom Good value behind. (Galaxy is the exception: its write is fire-and-forget, so
it can never surface a write failure.)
`OnWriteValue` is invoked by the SDK **while holding the node-manager `Lock`**, so the handler must not
block. Anything asynchronous is dispatched fire-and-forget with the revert wired as a continuation.
## Alarm method calls
Part 9 condition methods (Acknowledge / Confirm / AddComment / OneShotShelve / TimedShelve / Unshelve)
are gated by a second role check requiring `AlarmAck` — one role covering all five methods; the
`operation` argument is passed to the router but the gate does not consult it. Scripted alarms go
through `HandleAlarmCommand`, driver-fed native alarms through `HandleNativeAlarmAck`; both fail closed
with `BadUserAccessDenied`.
## HistoryRead
Four overrides — `HistoryReadRawModified`, `HistoryReadProcessed`, `HistoryReadAtTime`,
`HistoryReadEvents` — route to the **server-wide** `IHistorianDataSource` (the HistorianGateway-backed
reader, or `NullHistorianDataSource` when `ServerHistorian:Enabled=false`, which returns `GoodNoData`).
Drivers carry no history capability.
**No authorization check runs on any of the four.** Unlike `OnWriteValue`, the SDK does *not* hold the
node-manager `Lock` while invoking them, so these paths may await.
See [docs/Historian.md](Historian.md).
## Failure isolation
Exceptions in a driver capability call are logged and converted to a per-node bad status rather than
unwinding into the master node manager, so one driver's outage cannot disrupt sibling drivers in the
same process.
## What is *not* enforced anywhere
Collected here because the previous revision of this page claimed several of these:
| Surface | Check |
| Outcome | Meaning |
|---|---|
| Read, Browse, TranslateBrowsePaths | none |
| CreateMonitoredItems / Subscribe / TransferSubscriptions | none |
| HistoryRead (all four variants) | none |
| Non-Value attribute writes | none (the handler is on `OnWriteValue`) |
| Value write | `WriteOperate` role, server-wide |
| Alarm methods | `AlarmAck` role, server-wide |
| Per-node ACLs (`NodeAcl` / `PermissionTrie`) | **authored and deployed, never evaluated** |
| `RejectedBeforeDispatch` | Execution was proven not to have reached the driver. |
| `DriverConfirmedSuccess` | The driver reported success with its actual completion guarantee. |
| `DriverConfirmedFailure` | The driver reported failure. |
| `AcceptedUnconfirmed` | The driver accepted work but cannot confirm the device outcome. |
| `OutcomeUnknown` | Submission may have executed; the caller cannot establish the outcome. |
## Key source files
Cancellation or a lost response after dispatch cannot undo a device operation. Unknown and
unconfirmed outcomes must not be collapsed into a success Boolean or a fabricated failure/revert.
There is no automatic mutation retry, hedging, offline queue or failover replay. Reconcile an
ambiguous operation with the application's procedure; readback alone does not prove whether a
non-idempotent action executed. Duplicate protection is bounded by the request registry's retention
and serving incarnation and is not exactly-once delivery. A late result may refine the retained
outcome but never starts a replacement write.
- `src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs` — the live node manager;
`EnsureVariable` / `WriteValue` / `OnEquipmentTagWrite` / `EvaluateEquipmentWriteGate` and the four
HistoryRead overrides
- `src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/RoleCarryingUserIdentity.cs`,
`Security/OpcUaDataPlaneRoles.cs` — how roles reach the gates
- `src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/AddressSpaceApplier.cs` — materialization; where the write
handler is attached per realm
- `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs` — the push side: value fan-out to
raw + UNS NodeIds
- `src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/CapabilityInvoker.cs` — driver-side resilience pipeline
(**not** on the OPC UA read path)
- `src/Core/ZB.MOM.WW.OtOpcUa.Core/Authorization/` — the permission trie + evaluator, built and
unit-tested but with **zero production consumers**
## Local alarms and history
Local Part 9 alarm methods go through the scoped ACL gate when enabled and the `AlarmAck` role/key
gate otherwise. Local HistoryRead overrides route to `IHistorianDataSource` and enforce scoped
HistoryRead permission when ACL is enabled. Drivers do not supply a remote history capability.
See [Historian](Historian.md) for the configured backend and HistoryUpdate behavior.
Remote HistoryRead/HistoryUpdate, alarm/event forwarding and relay operations are outside the data
connection contract. Imported current values may feed authorized local calculations, scripts,
historization or alarm evaluation; those outputs belong to the local engines.
## Source references
- `src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs` — SDK gates and cached/projected reads.
- `src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/DataPlaneAuthorizer.cs` — local and mapped authorization.
- `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs` — scoped asynchronous access.
- `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataWriteExecutor.cs` — bounded mutation execution.
- `src/Core/ZB.MOM.WW.OtOpcUa.Core/Authorization/DataOperationPolicy.cs` — shared authorization policy.
+20
View File
@@ -907,6 +907,26 @@ Full detail: the enablement runbook at
[`docs/operations/2026-07-20-localdb-pair-replication.md`](operations/2026-07-20-localdb-pair-replication.md)
and the `LocalDb` section of [`docs/Configuration.md`](Configuration.md).
## Data-connection routing across independent pairs
The current-data gRPC plane uses deployed endpoint sets and authenticated capabilities, independently
of Akka pair membership, mesh command routing and OPC UA client failover. A logical Cluster target
selects a ready primary of the expected application cluster. A Node target pins the expected node;
`ReadyReplica` is an explicit read/subscription policy, while writes require primary authority.
Neither a secondary nor an import mapping forwards a rejected pinned write to its partner.
A role or serving-incarnation change invalidates old projected authority. Read/subscription recovery
rediscovers the eligible server and starts a new epoch and fresh snapshot; transitions in the gap
can be lost. A write already submitted with an unknown outcome is never automatically replayed on
the new primary. Only proven pre-dispatch rejection establishes that a write did not execute;
driver confirmation, acceptance without confirmation and outcome unknown remain distinct.
Same-cluster peer imports and cross-cluster imports use explicit directional connections and
consumer scopes. They do not merge gossip rings, alter local driver ownership or start a second
device connection. Dedicated TLS and target credentials are independent of the existing h2c mesh
planes. See [Data connections](DataConnections.md) for operational controls and
[Read/write operations](ReadWriteOperations.md) for completion semantics.
## Client-side failover
The OtOpcUa Client CLI at `src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI` supports `-F` / `--failover-urls` for automatic client-side failover; for long-running subscriptions the CLI monitors session KeepAlive and reconnects to the next available server, recreating the subscription on the new endpoint. See [`Client.CLI.md`](Client.CLI.md).
+19
View File
@@ -204,6 +204,25 @@ the tag **Name**, **DataType**, and **AccessLevel** (default: read-only). There
is no alias concept, no `SystemPlatform`-kind namespace, and no relay→alias
converter.
## Remote UNS branches
An enabled, deployed `RemoteNamespaceMapping` mounts an expandable remote UNS branch beneath a
local UNS container. It references a directional data connection, explicit consumer nodes and a
same-realm exported remote root. Both same-cluster peer-node and cross-cluster imports are supported;
the existing invariant that locally driver-bound equipment belongs to its own cluster still applies.
Remote descendants are projected views with origin provenance, rather than one authored local
`UnsTagReference` per imported leaf. Browse discovers metadata; reads refresh a local projected cache
asynchronously when needed, and subscriptions acquire current values under live authority. Writes
require explicit write-through and the intersection of connection, mapping, local and origin grants.
The legacy local ACL switch does not bypass mapped authorization. A branch anchor can be visible
while its remote children are pending or unavailable.
Authorized imported values can feed local calculations, scripts, historization and alarm evaluation.
Remote history, alarm/event forwarding and relays remain future work. See
[Data connections](DataConnections.md) for provisioning, deployment, limits and recovery, and
[Read/write operations](ReadWriteOperations.md) for freshness and ambiguous write outcomes.
## Typed TagConfig editors
The **Tag modal** dispatches a driver-typed config editor for the following
+6
View File
@@ -275,3 +275,9 @@ The final P08 deltas add the affected local monitored-item revalidation classes:
Astra's final source pass found invalidation control IDs accumulating without owned sources and a mapping-lock/publication-lock cycle. The bounded-queue regression reproduced **10001 pending instead of 1** (`20261117T013439.745777Z-6bc9df4d4d69`); a further attachment-race regression reproduced stranded pins (`20261117T013827.442802Z-e086385c96cd`). The final Runtime gate validates a separate nonblocking retirement gate, membership bounded to owned source buckets, exact generation filtering, correct disposal synchronization and attach-before-final-validation cleanup. These are actual behavioral REDs and repairs; the intermediate `013618` run failed test-analyzer compilation and is not behavioral evidence.
Final composed wire confirmation `20261117T014136.461398Z-final-p08-composed-wire` passed **6/6**, no skips, using the exact Runtime/SDK graph built by the final Runtime unit run. It verifies nested Raw pages/array metadata, UNS projection, local denied-sibling filtering, mapped root-leaf headless/read/monitor composition, deployment capability expiry/reuse and configured lifecycle acquisition. P10 six-process Docker/CLI scenarios, P11 workloads and P12 full-suite verification remain outstanding.
## P09 — authoring and diagnostics
P08 was committed as `9fb46212f` after Astra approved its final 566 applicable units and 34 wire cases. P09 adds disabled-by-default connection/export/mapping authoring through the existing ConfigEditor/deployment flow, service-side identity/concurrency/validator checks and an explicit union of draft/applied/runtime rows. Node diagnostics report verified endpoint/role/protocol/handshake time, monotonic age bounds at observation, last browse lease expiry, streams/calls/acknowledged registrations, retained import views, separate resets/coalescing and exact write outcome categories. Unknown overflow evidence remains unavailable. Seven reference documents and the new DataConnections guide describe this boundary.
The first successful P09 checkpoint was 232/232 (`20261117T014816.979075Z-576c591f151a`); Astra identified deleted draft rows hiding active state, cross-machine sample-age arithmetic and coalescing mislabeled as overflow. The final applicable P09 gate `20261117T015615.974000Z-9a05695752a4` passed **235/235**, none failed/skipped: AdminUI165 and affected Runtime70, including those regressions. The initial `014455` run failed xUnit token analyzers, not runtime behavior. [Astra approved P09](p09-astra-review.md). Browser layout verification will use the actual local rig; no rendered UI claim is made at this checkpoint. No P10 integration, P11 workload or P12 whole-solution result is implied.
@@ -0,0 +1,28 @@
# P09 Astra phase review
**Disposition: P09 approved, 2026-11-17.** Astra (`gpt-6-astra`, xhigh) reviewed the frozen authoring, diagnostics and documentation changes. No material findings remain open in this phase. This does not approve P10 integration, P11 performance work or the P12 final implementation gate.
## Reviewed behavior
- Connection, export and mapping mutations enforce `ConfigEditor` inside the service as well as in the UI. Disabled defaults, immutable row identity, revision/RowVersion checks and the authoritative server-side validator preserve the distinction between editable drafts and deployment. Read-only users cannot create, delete or enable write-through through this service.
- The cluster page exposes directional connections, scoped consumer selections, realm-specific parent/root choices, operation grants and optional write-through. It uses the existing deployment flow and never claims that saving a draft starts or stops an import. Secret editing accepts references; displayed endpoints omit credentials, path, query and fragment.
- Diagnostics originate in the node's deployed connection runtime and actual verified transport observations. Local credential activation alone reports connecting. Acknowledged registrations, streams/calls, retained import views and individual write outcome states have distinct meanings. Missing measurements remain unavailable rather than becoming zero or successful activity.
- The documentation preserves independent TLS/trust/credential requirements, pinned-node and cluster-primary routing, ambiguous-write/no-replay semantics and the future-only remote history/alarm/relay boundary. Imported current values feeding local derived engines do not imply remote forwarding support.
## Findings closed
1. **P2 — Applied connections disappeared after draft deletion.** The display now uses the union of draft, applied and observed connection IDs. A removed draft remains visible with its applied/runtime evidence until that evidence is absent. `Deleted_draft_remains_visible_while_applied_or_observed` covers removal and case-insensitive identity matching.
2. **P2 — Cross-machine UTC subtraction falsely represented a sample-age upper bound.** The producer now sends a duration advanced on its own monotonic clock. The UI displays it as an upper bound at observation, without subtracting the reporting timestamp from the AdminUI clock. The skewed-node-clock regression verifies this boundary.
3. **P2 — Coalescing was labeled as overflow.** Typed coalescing notices now populate `CoalescedCount`; unobserved overflow remains null. The framed-stream regression verifies an acknowledged registration plus a coalescing notice without inventing an overflow.
The earlier receipt-time/sample-age ambiguity and unique-source labeling were also corrected: the UI identifies retained import views and reports verified sample-age evidence, not field-acquisition counts or receipt time as freshness.
## Evidence and limits
The reviewer independently read `artifacts/grpc-data/20261117T015615.974000Z-9a05695752a4/unit/P09/run.json` and its TRX files: **235/235 passed, zero failed or skipped** (AdminUI165, Runtime70). This includes the required ACL/browse-authoring regressions and affected remote-client, deployment and DriverHost diagnostics tests.
The manifest identifies HEAD `9fb46212f7c775b55d51885addf87ea7ad1190e8` with dirty-diff SHA-256 `c2cf23cfaebc043613d9ce8daa369029bdd532aacf6ead00ccf77ec5e8cca5b4`. Recorded hashes matched all seven new reviewed UI/service/diagnostics source files. Concurrent P10 harness work is outside this approval.
The Impeccable skill was applied to the bounded source-level UI review. Its context loader used the incumbent component system, and its mechanical detector returned no findings for the page and cluster navigation. No rendered-browser, responsive-layout or accessibility conformance claim is made. The reviewer ran no builds or tests and changed only this review note.
P10 actual Docker/TLS/SQL/CLI integration, P11 workload and fairness evidence, and P12 full-solution verification and final Astra review remain required.
+39 -10
View File
@@ -27,7 +27,7 @@ OtOpcUa has four independent security concerns. This document covers all four:
1. **Transport security** — OPC UA secure channel (signing, encryption, X.509 trust).
2. **OPC UA authentication** — Anonymous / UserName / X.509 session identities. A UserName token is an **API key** (username literally `apikey`, password `otua_<keyId>_<secret>`) verified by peppered HMAC — **LDAP backs Admin UI login only** since #520 (2026-08-01).
3. **Data-plane authorization** — who can do what on an OtOpcUa endpoint. ⚠️ Governed by **one flag** (#520 stages 5–6, 2026-08-01). With `Security:Acl:Enabled` **false — the default** — the only enforcement is two coarse, server-wide role gates (`WriteOperate` on Value writes, `AlarmAck` on the alarm methods), and Read, Browse, Subscribe and HistoryRead are **ungated** for any admitted session. With it **true**, scoped `NodeAcl` grants (the `PermissionTrie` subsystem) decide **every** data-plane operation — read, browse, subscribe, write, alarm commands and HistoryRead — *replacing* the server-wide roles. See [Data-Plane Authorization](#data-plane-authorization).
3. **Data-plane authorization** — who can do what on an OtOpcUa endpoint. ⚠️ Governed by **one flag** (#520 stages 5–6, 2026-08-01). For locally owned nodes with `Security:Acl:Enabled` **false — the default**, write/alarm enforcement uses coarse, server-wide role gates (`WriteOperate` on Value writes, `AlarmAck` on the alarm methods), and Read, Browse, Subscribe and HistoryRead are **ungated** for any admitted session. With it **true**, scoped `NodeAcl` grants (the `PermissionTrie` subsystem) decide **every** data-plane operation — read, browse, subscribe, write, alarm commands and HistoryRead — *replacing* the server-wide roles. Mapped data and gRPC exports always require scoped authorization independently of that flag; HistoryUpdate has its own mutation gate. See [Data-Plane Authorization](#data-plane-authorization).
4. **Control-plane authorization** — who can view or edit fleet configuration in the Admin UI. Gated by the `AdminRole` (`Viewer` / `Designer` / `Administrator`) claim resolved from `LdapGroupRoleMapping`.
Transport security and OPC UA authentication are per-node concerns configured in the Server's bootstrap `appsettings.json`. Data-plane ACLs and Admin role grants live in the Config DB.
@@ -144,7 +144,7 @@ The Admin UI `Certificates.razor` page (`src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Co
### Internal gRPC planes (h2c) — accepted cleartext posture
Everything above concerns the **OPC UA** endpoint — the surface external clients bind to. OtOpcUa
also runs **five internal gRPC planes** between its own processes (central ↔ driver node, and node ↔
also runs **five legacy internal gRPC planes** between its own processes (central ↔ driver node, and node ↔
pair partner). Those are a separate transport story, recorded here so it is written down once rather
than rediscovered per plane.
@@ -192,7 +192,7 @@ assumption is wrong:
fleet-wide key with extra steps. The three literal `dev-mesh-psk-*` keys exist only on the
docker-dev rig.
**Future work.** The recorded alternative is a `UseTls`/scheme option on these planes (dial `https://`,
**Future work for these five legacy planes.** The recorded alternative is a `UseTls`/scheme option on these planes (dial `https://`,
bind the listener with a certificate). If it is ever built it **must cover all five planes together**
— a mixed posture, where some internal links are encrypted and others are not, is harder to reason
about than either uniform answer, and invites exactly the "which one was it again?" mistake this note
@@ -200,6 +200,34 @@ exists to prevent. See issue #545.
---
## Data-connection transport and mapped authority
The current-data gRPC service is a separate plane with a dedicated HTTP/2 listener. Production
requires TLS, an explicit allowed-host list and authenticated target cluster/node policy. Its
Development-only cleartext exception requires a literal loopback listener. The accepted h2c posture
of the five legacy mesh planes above does not apply to data connections and does not change them.
See [Configuration](Configuration.md#dataconnections).
Origin exports grant named authenticated principals access to explicit Raw/UNS roots. Consumer
connections use independently provisioned target credentials, canonical `secret:data/...`
references and independently versioned trust roots. Applied artifacts carry references and explicit
consumer scopes rather than credential values. Credential and trust bundle mounts are node-local;
scope/version validation, explicit deletion and retirement prevent an old bundle from restoring
retired authority. Missing mounts are retried and are not themselves deletion requests.
Mapped access is always authorized, including when `Security:Acl:Enabled=false`. It requires the
intersection of local mapped-view grants, connection/mapping operations and origin export grants,
plus current identity, metadata lease and serving provenance. Mapped descendants are resolved from
the trusted live catalog; their opaque identifiers must not fall back to local path-based grants.
Read/browse/subscription admission and final value delivery retain current authority checks. Writable
metadata alone does not confer write-through, and secondary/read-replica access never confers writes.
The flag-off descriptions below concern locally owned nodes. They are not a bypass for gRPC export
or mapped nodes. Remote projected branches cannot be re-exported as locally owned data, and remote
history, alarm/event and relay operations are not part of this contract. Authorized imported current
values can feed local derived engines. See [Data connections](DataConnections.md) and
[Read/write operations](ReadWriteOperations.md).
## OPC UA Authentication
The Server accepts three OPC UA identity-token types:
@@ -582,8 +610,9 @@ the one request making it. One key remains:
### What is enforced with the flag off
There are exactly **three** authorization checks in the whole OPC UA server layer. All three are
coarse, **server-wide role string checks** with no per-node component.
For locally owned nodes, the legacy write/alarm gates below are coarse, server-wide role checks.
HistoryUpdate also has its own mutation gate. Mapped nodes always use scoped authority, as described
[above](#data-connection-transport-and-mapped-authority).
| Operation | Gate | Requires |
|---|---|---|
@@ -620,10 +649,10 @@ write and each Part 9 method call first asks `DataPlaneAuthorizer.AuthorizeKeyUs
check reads the deployed snapshot, which is also what the flag-on path has always done. Deploy after
minting a key.
**What has no authorization check at all:**
**Local operations left permissive with the flag off:**
- **Read, Browse, TranslateBrowsePaths** — no override, no handler. Any admitted session, including
an Anonymous one, sees and reads the entire address space.
- **Read, Browse, TranslateBrowsePaths** — local-node ACL filtering is bypassed; admitted sessions,
including Anonymous, can access locally owned nodes. The overrides still enforce mapped authority.
- **HistoryRead** — all four overrides (`HistoryReadRawModified`, `HistoryReadProcessed`,
`HistoryReadAtTime`, `HistoryReadEvents`) run without an identity check.
- **CreateMonitoredItems / subscriptions / TransferSubscriptions**.
@@ -1331,8 +1360,8 @@ HistoryUpdate rewrites recorded history, so unlike HistoryRead it is gated **wha
(`src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/DataPlaneAuthorizer.cs`, registered in
`Host/Program.cs`, consulted by `OtOpcUaNodeManager`) calls `Authorize` at every data-plane seam —
read, browse, subscribe, write, alarm commands and HistoryRead — **when `Security:Acl:Enabled` is
true**. With the flag **off (the default)** the authorizer is constructed but not consulted, and the
effective posture for Read/Browse/Subscribe/HistoryRead is default-ALLOW (see
true**. With the flag **off (the default)** local Read/Browse/Subscribe/HistoryRead remain permissive;
mutation key-usability checks and mapped-data authorization still consult the authorizer/policy (see
[What is enforced with the flag off](#what-is-enforced-with-the-flag-off)).
Properties of the wired path:
@@ -599,6 +599,16 @@
"RawBrowseCommitMapperTests",
"RawBrowseCommitMapperParityTests"
]
},
{
"project": "tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ZB.MOM.WW.OtOpcUa.Runtime.Tests.csproj",
"filter": "(Feature=GrpcData&Phase=P09)|FullyQualifiedName~.GrpcDataConnectionClientTests.|FullyQualifiedName~.GrpcDataDeploymentActivationTests.|FullyQualifiedName~.DriverHostActorDiagnosticsTests.",
"new_classes": [],
"existing_classes": [
"GrpcDataConnectionClientTests",
"GrpcDataDeploymentActivationTests",
"DriverHostActorDiagnosticsTests"
]
}
]
}
@@ -0,0 +1,33 @@
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Commons.Interfaces;
/// <summary>Bounded, secret-free evidence from one node's applied data connection.</summary>
/// <remarks>Nullable measures mean that evidence is unavailable, rather than zero activity.</remarks>
public sealed record DataConnectionDiagnosticsSnapshot(
string ConnectionId,
long Revision,
string State,
string? SelectedEndpoint,
ServingIdentity? Serving,
int ActiveStreams,
int ActiveCalls,
long ScopeVersion,
string ArtifactRevision,
DateTime AsOfUtc,
DateTime? LastSampleAtUtc = null,
DateTime? MetadataLeaseExpiresAtUtc = null,
int? SourceCount = null,
int? RegistrationCount = null,
long? ResetCount = null,
long? OverflowCount = null,
long? WriteSucceededCount = null,
long? WriteRejectedCount = null,
long? WriteUnknownCount = null,
int? ProtocolMajor = null,
int? ProtocolMinor = null,
DateTime? LastVerifiedAtUtc = null,
long? WriteFailedCount = null,
long? WriteUnconfirmedCount = null,
TimeSpan? SampleAgeUpperBound = null,
long? CoalescedCount = null);
@@ -48,4 +48,5 @@ public sealed record NodeDiagnosticsSnapshot(
RevisionHash? CurrentRevision,
IReadOnlyList<DriverInstanceDiagnostics> Drivers,
DateTime AsOfUtc,
bool RunningFromCache = false);
bool RunningFromCache = false,
IReadOnlyList<DataConnectionDiagnosticsSnapshot>? DataConnections = null);
@@ -0,0 +1,246 @@
@page "/clusters/{ClusterId}/data-connections"
@attribute [Authorize(Policy = AdminUiPolicies.AuthenticatedRead)]
@rendermode RenderMode.InteractiveServer
@using ZB.MOM.WW.OtOpcUa.AdminUI.DataConnections
@using ZB.MOM.WW.OtOpcUa.Configuration.Entities
@using ZB.MOM.WW.OtOpcUa.Configuration.Validation
@using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections
@using ZB.MOM.WW.OtOpcUa.Commons.OpcUa
@using ZB.MOM.WW.OtOpcUa.Commons.Interfaces
@using ZB.MOM.WW.OtOpcUa.Commons.Types
@inject DataConnectionAdminService Service
@inject IFleetDiagnosticsClient Diagnostics
<PageErrorBoundary>
<PageTitle>Data connections · OtOpcUa</PageTitle>
<div class="page-head"><h1>Data connections · <span class="mono">@ClusterId</span></h1></div>
<ClusterNav ClusterId="@ClusterId" ActiveTab="data" />
<p>Connections are directional. Exports grant a peer access to local data; mappings place remote data under a local Raw or UNS parent.</p>
<section class="panel notice">Changes are saved as drafts. Deploy them from <a href="/deployments">Deployments</a>; saving alone does not start or stop an import. Runtime status is unavailable until reported by a node.</section>
@if (_snapshot is null) { <p>Loading…</p> }
else
{
@if (_error is not null) { <div class="alert alert-danger" role="alert">@_error</div> }
@if (_message is not null) { <div class="alert alert-success" role="status">@_message</div> }
<section class="panel mt-3">
<h2 class="panel-head">Connections</h2>
<div class="p-3">
@if (!ConnectionRows.Any()) { <p class="text-muted">No draft, applied, or observed connections.</p> }
@foreach (var row in ConnectionRows)
{
<div class="d-flex flex-wrap gap-2 align-items-center mb-2"><strong>@row.Id</strong>@if (row.Draft is { } draft) { <span class="chip chip-idle">Draft: @(draft.Enabled ? "enabled" : "disabled")</span> } else { <span class="chip chip-warn">Removed from draft</span> }@if (!_live.Any(x => Same(x.Row.ConnectionId, row.Id))) { <span>Runtime: unavailable</span> }
@foreach (var live in _live.Where(x => Same(x.Row.ConnectionId, row.Id)))
{
<div class="w-100 small"><strong>@live.NodeId: @DataConnectionDiagnostics.State(live.Row.State)</strong> · revision @live.Row.Revision · endpoint @DataConnectionDiagnostics.Endpoint(live.Row.SelectedEndpoint)
@if (live.Row.Serving is { } serving) { <span> · serving @serving.NodeId · role @serving.Role · incarnation @serving.Incarnation</span> }
<div>Streams @live.Row.ActiveStreams · calls @live.Row.ActiveCalls · retained import views @Measure(live.Row.SourceCount) · registrations @Measure(live.Row.RegistrationCount) · resets @Measure(live.Row.ResetCount) · coalesced notices @Measure(live.Row.CoalescedCount) · overflows @Measure(live.Row.OverflowCount)</div>
<div>Writes succeeded @Measure(live.Row.WriteSucceededCount) · rejected @Measure(live.Row.WriteRejectedCount) · failed @Measure(live.Row.WriteFailedCount) · unconfirmed @Measure(live.Row.WriteUnconfirmedCount) · unknown @Measure(live.Row.WriteUnknownCount)</div>
<div>Last observed sample bound @Time(live.Row.LastSampleAtUtc) (age upper bound @DataConnectionDiagnostics.SampleAge(live.Row)) · metadata lease expires @Time(live.Row.MetadataLeaseExpiresAtUtc) · last handshake @Time(live.Row.LastVerifiedAtUtc) · observed @live.Row.AsOfUtc.ToString("u") · artifact @live.Row.ArtifactRevision · protocol @Measure(live.Row.ProtocolMajor).@Measure(live.Row.ProtocolMinor)</div></div>
}
@foreach (var applied in _applied.Where(x => Same(x.ConnectionId, row.Id))) { <span class="small">@applied.NodeId: last applied revision @applied.Revision (@(applied.Enabled ? "enabled" : "disabled"))</span> }
@if (row.Draft is { } editable) { <AuthorizeView Policy="@AdminUiPolicies.ConfigEditor"><button class="btn btn-sm btn-outline-primary" @onclick="() => Edit(editable)">Edit</button></AuthorizeView> }</div>
}
<AuthorizeView Policy="@AdminUiPolicies.ConfigEditor"><button class="btn btn-sm btn-primary" @onclick="NewConnection">New connection</button></AuthorizeView>
</div>
</section>
<section class="panel mt-3">
<h2 class="panel-head">Exports</h2><div class="p-3">
@if (!Exports.Any()) { <p class="text-muted">No export grants have been authored.</p> }
@foreach (var e in Exports) { <div class="d-flex flex-wrap gap-2 align-items-center mb-2"><strong>@e.DataExportId</strong><span>@e.Realm · @e.RootKind · @e.PrincipalId</span><span class="chip chip-idle">Draft: @(e.Enabled ? "enabled" : "disabled")</span><AuthorizeView Policy="@AdminUiPolicies.ConfigEditor"><button class="btn btn-sm btn-outline-primary" @onclick="() => Edit(e)">Edit</button></AuthorizeView></div> }
<AuthorizeView Policy="@AdminUiPolicies.ConfigEditor"><button class="btn btn-sm btn-primary" @onclick="NewExport">New export</button></AuthorizeView></div>
</section>
<section class="panel mt-3"><h2 class="panel-head">Mappings</h2><div class="p-3">
@if (!Mappings.Any()) { <p class="text-muted">No remote branches have been mapped.</p> }
@foreach (var m in Mappings) { <div class="d-flex flex-wrap gap-2 align-items-center mb-2"><strong>@m.RemoteNamespaceMappingId</strong><span>@m.Realm · @m.BranchName via @m.DataConnectionId</span><span class="chip chip-idle">Draft: @(m.Enabled ? "enabled" : "disabled")</span><AuthorizeView Policy="@AdminUiPolicies.ConfigEditor"><button class="btn btn-sm btn-outline-primary" @onclick="() => Edit(m)">Edit</button></AuthorizeView></div> }
<AuthorizeView Policy="@AdminUiPolicies.ConfigEditor"><button class="btn btn-sm btn-primary" @onclick="NewMapping">New mapping</button></AuthorizeView></div>
</section>
<AuthorizeView Policy="@AdminUiPolicies.ConfigEditor">
@if (_deleteCandidate is not null)
{
<section class="panel notice mt-3" role="alert"><p>Delete this draft? The change takes effect only after deployment.</p><button class="btn btn-danger btn-sm me-2" @onclick="() => Delete(_deleteCandidate)">Confirm delete</button><button class="btn btn-outline-secondary btn-sm" @onclick="() => _deleteCandidate = null">Keep draft</button></section>
}
@if (_connection is not null)
{
var c = _connection.Value;
<section class="panel mt-3"><h2 class="panel-head">Connection draft</h2><div class="p-3">
<label class="form-label" for="connection-id">Connection ID</label><input id="connection-id" class="form-control mb-2" @bind="c.DataConnectionId" disabled="@(c.DataConnectionRowId != Guid.Empty)" />
<label class="form-label" for="target-cluster">Expected cluster ID</label><input id="target-cluster" class="form-control mb-2" @bind="c.ExpectedClusterId" />
<label class="form-label" for="target-mode">Target</label><select id="target-mode" class="form-select mb-2" @bind="c.TargetMode" @bind:after="() => TargetChanged(c)"><option value="@DataTargetMode.Node">Node</option><option value="@DataTargetMode.Cluster">Cluster</option></select>
@if (c.TargetMode == DataTargetMode.Node) { <label class="form-label" for="target-node">Expected node ID</label><input id="target-node" class="form-control mb-2" @bind="c.ExpectedNodeId" /> }
else { <label class="form-label" for="eligible">Eligible target node IDs, one per line</label><textarea id="eligible" class="form-control mb-2" @bind="_connection.EligibleNodes"></textarea> }
<label class="form-label" for="consistency">Consistency</label><select id="consistency" class="form-select mb-2" @bind="c.Consistency"><option value="@DataConsistency.Primary">Primary</option><option value="@DataConsistency.ReadyReplica">Ready replica</option></select>
<label class="form-label" for="endpoints">HTTPS endpoints, one per line</label><textarea id="endpoints" class="form-control mb-2" @bind="_connection.Endpoints"></textarea>
<label class="form-label" for="secret-ref">Secret reference</label><input id="secret-ref" class="form-control mb-2" placeholder="secret:data/…" @bind="c.SecretReference" /><div class="form-text">Reference only; never enter a key or secret value.</div>
<fieldset><legend class="fs-6">Consumer nodes</legend>@foreach (var n in Nodes) { <label class="me-3"><input type="checkbox" checked="@c.ConsumerNodeIds.Contains(n.NodeId)" @onchange="e => Toggle(c.ConsumerNodeIds, n.NodeId, (bool)e.Value!)" /> @n.NodeId</label> }</fieldset>
@Operations(c.AllowedOperations, v => c.AllowedOperations = v)
<label><input type="checkbox" @bind="c.Enabled" /> Enabled in next deployment</label>
@Actions(c, c.DataConnectionRowId != Guid.Empty)
</div></section>
}
@if (_export is not null)
{
var e = _export;
<section class="panel mt-3"><h2 class="panel-head">Export draft</h2><div class="p-3">
<label class="form-label" for="export-id">Export ID</label><input id="export-id" class="form-control mb-2" @bind="e.DataExportId" disabled="@(e.DataExportRowId != Guid.Empty)" />
<label class="form-label" for="principal">Peer principal</label><input id="principal" class="form-control mb-2" @bind="e.PrincipalId" />
<label class="form-label" for="export-realm">Realm</label><select id="export-realm" class="form-select mb-2" @bind="e.Realm"><option value="@DataRealm.Raw">Raw</option><option value="@DataRealm.Uns">UNS</option></select>
<label class="form-label" for="export-root">Local export root</label><select id="export-root" class="form-select mb-2" value="@(e.RootKind + "|" + e.RootEntityId)" @onchange="args => SetExportRoot(e, args.Value?.ToString())"><option value="">Choose a root</option>@foreach (var p in ExportRoots(e.Realm)) { <option value="@p.Value">@p.Label</option> }</select>
@Operations(e.AllowedOperations, v => e.AllowedOperations = v)
<label><input type="checkbox" @bind="e.Enabled" /> Enabled in next deployment</label>@Actions(e, e.DataExportRowId != Guid.Empty)
</div></section>
}
@if (_mapping is not null)
{
var m = _mapping.Value;
<section class="panel mt-3"><h2 class="panel-head">Mapping draft</h2><div class="p-3">
<label class="form-label" for="mapping-id">Mapping ID</label><input id="mapping-id" class="form-control mb-2" @bind="m.RemoteNamespaceMappingId" disabled="@(m.RemoteNamespaceMappingRowId != Guid.Empty)" />
<label class="form-label" for="mapping-connection">Connection</label><select id="mapping-connection" class="form-select mb-2" @bind="m.DataConnectionId"><option value="">Choose a connection</option>@foreach (var c in Connections) { <option value="@c.DataConnectionId">@c.DataConnectionId</option> }</select>
<label class="form-label" for="mapping-realm">Realm</label><select id="mapping-realm" class="form-select mb-2" @bind="m.Realm" @bind:after="() => SetRealm(m)"><option value="@DataRealm.Raw">Raw</option><option value="@DataRealm.Uns">UNS</option></select>
<label class="form-label" for="mapping-parent">Local parent</label><select id="mapping-parent" class="form-select mb-2" value="@(m.LocalParentKind + "|" + m.LocalParentId)" @onchange="args => SetParent(m, args.Value?.ToString())"><option value="">Choose a parent</option>@foreach (var p in Parents(m.Realm)) { <option value="@p.Value">@p.Label</option> }</select>
<label class="form-label" for="branch">Branch name</label><input id="branch" class="form-control mb-2" @bind="m.BranchName" />
<label class="form-label" for="remote-root">Remote root entity</label><select id="remote-root" class="form-select mb-2" @bind="m.RemoteRootEntityId"><option value="">Choose a root</option>@foreach (var p in RemoteRoots(m)) { <option value="@p.Id">@p.Label</option> }</select><div class="form-text">The picker uses the configured target cluster. For a separately managed cluster, enter its root ID below.</div><label class="form-label" for="remote-root-id">Remote root ID</label><input id="remote-root-id" class="form-control mb-2" @bind="m.RemoteRootEntityId" />
<label class="form-label" for="identifier-kind">Remote canonical identifier kind</label><input id="identifier-kind" class="form-control mb-2" @bind="m.RemoteIdentifierKind" />
<label class="form-label" for="identifier">Remote canonical identifier</label><input id="identifier" class="form-control mb-2" @bind="m.RemoteIdentifier" />
<fieldset><legend class="fs-6">Consumer nodes</legend>@foreach (var n in Nodes) { <label class="me-3"><input type="checkbox" checked="@m.ConsumerNodeIds.Contains(n.NodeId)" @onchange="e => Toggle(m.ConsumerNodeIds, n.NodeId, (bool)e.Value!)" /> @n.NodeId</label> }</fieldset>
@Operations(m.AllowedOperations, v => m.AllowedOperations = v)
<div><label><input type="checkbox" @bind="m.WriteThrough" /> Allow write-through</label></div><label><input type="checkbox" @bind="m.Enabled" /> Enabled in next deployment</label>@Actions(m, m.RemoteNamespaceMappingRowId != Guid.Empty)
</div></section>
}
</AuthorizeView>
}
</PageErrorBoundary>
@code {
[Parameter] public string ClusterId { get; set; } = "";
private DraftSnapshot? _snapshot;
private DataConnectionEditorModel? _connection;
private DataExport? _export;
private RemoteMappingEditorModel? _mapping;
private string? _error, _message;
private object? _deleteCandidate;
private IReadOnlyList<AppliedConnection> _applied = [];
private List<(string NodeId, DataConnectionDiagnosticsSnapshot Row)> _live = [];
private IReadOnlyList<ConnectionDisplayRow> ConnectionRows => DataConnectionDiagnostics.Rows(Connections, _applied.Select(x => x.ConnectionId), _live.Select(x => x.Row.ConnectionId));
private IEnumerable<DataConnection> Connections => _snapshot!.DataConnections.Where(x => Same(x.ClusterId, ClusterId));
private IEnumerable<DataExport> Exports => _snapshot!.DataExports.Where(x => Same(x.ClusterId, ClusterId));
private IEnumerable<RemoteNamespaceMapping> Mappings => _snapshot!.RemoteNamespaceMappings.Where(x => Same(x.ClusterId, ClusterId));
private IEnumerable<ClusterNode> Nodes => _snapshot!.ClusterNodes.Where(x => Same(x.ClusterId, ClusterId) && x.Enabled);
protected override async Task OnInitializedAsync() => await Reload();
private async Task Reload()
{
_snapshot = await Service.LoadAsync(); _applied = await Service.LoadAppliedAsync(ClusterId);
var observations = await Task.WhenAll(Nodes.Select(async node =>
{
try { return (node.NodeId, Snapshot: (NodeDiagnosticsSnapshot?)await Diagnostics.GetDiagnosticsAsync(NodeId.Parse($"{node.Host}:{node.AkkaPort}"), CancellationToken.None)); }
catch (Exception) { return (node.NodeId, Snapshot: (NodeDiagnosticsSnapshot?)null); }
}));
_live = observations.Where(x => x.Snapshot?.DataConnections is not null)
.SelectMany(x => x.Snapshot!.DataConnections!.Select(row => (x.NodeId, row))).ToList();
}
private static string Measure<T>(T? value) where T : struct => value?.ToString() ?? "unavailable";
private static string Time(DateTime? value) => value?.ToString("u") ?? "unavailable";
private static bool Same(string? a, string? b) => string.Equals(a, b, StringComparison.OrdinalIgnoreCase);
private static T Clone<T>(T value) => System.Text.Json.JsonSerializer.Deserialize<T>(System.Text.Json.JsonSerializer.Serialize(value))!;
private void Clear() { _connection = null; _export = null; _mapping = null; _deleteCandidate = null; _error = null; _message = null; }
private void NewConnection() { Clear(); _connection = new(); _connection.Value.ClusterId = ClusterId; _connection.Value.SecretScopeClusterId = ClusterId; }
private void NewExport() { Clear(); _export = new() { ClusterId = ClusterId, Realm = DataRealm.Raw, AllowedOperations = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Subscribe }; }
private void NewMapping() { Clear(); _mapping = new(); _mapping.Value.ClusterId = ClusterId; SetRealm(_mapping.Value); }
private void Edit(DataConnection c) { Clear(); _connection = new() { Value = Clone(c) }; }
private void Edit(DataExport e) { Clear(); _export = Clone(e); }
private void Edit(RemoteNamespaceMapping m) { Clear(); _mapping = new() { Value = Clone(m) }; }
private static void Toggle(List<string> ids, string id, bool on) { if (on && !ids.Contains(id)) ids.Add(id); else if (!on) ids.Remove(id); }
private static void TargetChanged(DataConnection c) { if (c.TargetMode == DataTargetMode.Cluster) c.ExpectedNodeId = null; else c.EligibleTargetNodeIds.Clear(); }
private static void SetRealm(RemoteNamespaceMapping m) { m.RemoteRealm = m.Realm; m.RemoteNamespaceUri = m.Realm == DataRealm.Raw ? V3NodeIds.RawNamespaceUri : V3NodeIds.UnsNamespaceUri; }
private static void SetParent(RemoteNamespaceMapping m, string? value) { var p = (value ?? "").Split('|', 2); m.LocalParentKind = p[0]; m.LocalParentId = p.Length > 1 ? p[1] : ""; }
private static void SetExportRoot(DataExport e, string? value) { var p = (value ?? "").Split('|', 2); e.RootKind = p[0]; e.RootEntityId = p.Length > 1 ? p[1] : ""; }
private IEnumerable<(string Value, string Label)> Parents(DataRealm realm)
{
yield return ($"Cluster|{ClusterId}", "Cluster root");
if (realm == DataRealm.Raw)
{
foreach (var x in _snapshot!.RawFolders.Where(x => Same(x.ClusterId, ClusterId))) yield return ($"RawFolder|{x.RawFolderId}", $"Folder: {x.Name} ({x.RawFolderId})");
foreach (var x in _snapshot.DriverInstances.Where(x => Same(x.ClusterId, ClusterId))) yield return ($"RawDriver|{x.DriverInstanceId}", $"Driver: {x.Name} ({x.DriverInstanceId})");
var drivers = _snapshot.DriverInstances.Where(x => Same(x.ClusterId, ClusterId)).Select(x => x.DriverInstanceId).ToHashSet(StringComparer.OrdinalIgnoreCase);
var devices = _snapshot.Devices.Where(x => drivers.Contains(x.DriverInstanceId)).ToList();
foreach (var x in devices) yield return ($"RawDevice|{x.DeviceId}", $"Device: {x.Name} ({x.DeviceId})");
var ids = devices.Select(x => x.DeviceId).ToHashSet(StringComparer.OrdinalIgnoreCase);
foreach (var x in _snapshot.TagGroups.Where(x => ids.Contains(x.DeviceId))) yield return ($"RawTagGroup|{x.TagGroupId}", $"Tag group: {x.Name} ({x.TagGroupId})");
}
else if (realm == DataRealm.Uns)
{
var areas = _snapshot!.UnsAreas.Where(x => Same(x.ClusterId, ClusterId)).ToList();
foreach (var x in areas) yield return ($"UnsArea|{x.UnsAreaId}", $"Area: {x.Name} ({x.UnsAreaId})");
var areaIds = areas.Select(x => x.UnsAreaId).ToHashSet(StringComparer.OrdinalIgnoreCase);
var lines = _snapshot.UnsLines.Where(x => areaIds.Contains(x.UnsAreaId)).ToList();
foreach (var x in lines) yield return ($"UnsLine|{x.UnsLineId}", $"Line: {x.Name} ({x.UnsLineId})");
var lineIds = lines.Select(x => x.UnsLineId).ToHashSet(StringComparer.OrdinalIgnoreCase);
foreach (var x in _snapshot.Equipment.Where(x => lineIds.Contains(x.UnsLineId))) yield return ($"Equipment|{x.EquipmentId}", $"Equipment: {x.Name} ({x.EquipmentId})");
}
}
private IEnumerable<(string Value, string Label)> ExportRoots(DataRealm realm)
{
foreach (var parent in Parents(realm)) yield return parent;
if (realm == DataRealm.Raw)
{
var drivers = _snapshot!.DriverInstances.Where(x => Same(x.ClusterId, ClusterId)).Select(x => x.DriverInstanceId).ToHashSet(StringComparer.OrdinalIgnoreCase);
var devices = _snapshot.Devices.Where(x => drivers.Contains(x.DriverInstanceId)).Select(x => x.DeviceId).ToHashSet(StringComparer.OrdinalIgnoreCase);
foreach (var tag in _snapshot.Tags.Where(x => devices.Contains(x.DeviceId))) yield return ($"RawTag|{tag.TagId}", $"Tag: {tag.Name} ({tag.TagId})");
}
else if (realm == DataRealm.Uns)
{
var areas = _snapshot!.UnsAreas.Where(x => Same(x.ClusterId, ClusterId)).Select(x => x.UnsAreaId).ToHashSet(StringComparer.OrdinalIgnoreCase);
var lines = _snapshot.UnsLines.Where(x => areas.Contains(x.UnsAreaId)).Select(x => x.UnsLineId).ToHashSet(StringComparer.OrdinalIgnoreCase);
var equipment = _snapshot.Equipment.Where(x => lines.Contains(x.UnsLineId)).Select(x => x.EquipmentId).ToHashSet(StringComparer.OrdinalIgnoreCase);
foreach (var tag in _snapshot.VirtualTags.Where(x => equipment.Contains(x.EquipmentId))) yield return ($"VirtualTag|{tag.VirtualTagId}", $"Virtual tag: {tag.Name} ({tag.VirtualTagId})");
foreach (var tag in _snapshot.UnsTagReferences.Where(x => equipment.Contains(x.EquipmentId))) yield return ($"UnsTagReference|{tag.UnsTagReferenceId}", $"Tag reference: {tag.UnsTagReferenceId}");
}
}
private IEnumerable<(string Id, string Label)> RemoteRoots(RemoteNamespaceMapping mapping)
{
var target = Connections.FirstOrDefault(x => Same(x.DataConnectionId, mapping.DataConnectionId))?.ExpectedClusterId;
if (string.IsNullOrEmpty(target)) yield break;
yield return (target, "Cluster root: " + target);
if (mapping.Realm == DataRealm.Raw)
{
foreach (var x in _snapshot!.RawFolders.Where(x => Same(x.ClusterId, target))) yield return (x.RawFolderId, $"Folder: {x.Name} ({x.RawFolderId})");
var drivers = _snapshot.DriverInstances.Where(x => Same(x.ClusterId, target)).ToList();
foreach (var x in drivers) yield return (x.DriverInstanceId, $"Driver: {x.Name} ({x.DriverInstanceId})");
var driverIds = drivers.Select(x => x.DriverInstanceId).ToHashSet(StringComparer.OrdinalIgnoreCase);
var devices = _snapshot.Devices.Where(x => driverIds.Contains(x.DriverInstanceId)).ToList();
foreach (var x in devices) yield return (x.DeviceId, $"Device: {x.Name} ({x.DeviceId})");
var deviceIds = devices.Select(x => x.DeviceId).ToHashSet(StringComparer.OrdinalIgnoreCase);
foreach (var x in _snapshot.TagGroups.Where(x => deviceIds.Contains(x.DeviceId))) yield return (x.TagGroupId, $"Tag group: {x.Name} ({x.TagGroupId})");
foreach (var x in _snapshot.Tags.Where(x => deviceIds.Contains(x.DeviceId))) yield return (x.TagId, $"Tag: {x.Name} ({x.TagId})");
}
else
{
var areas = _snapshot!.UnsAreas.Where(x => Same(x.ClusterId, target)).ToList();
foreach (var x in areas) yield return (x.UnsAreaId, $"Area: {x.Name} ({x.UnsAreaId})");
var areaIds = areas.Select(x => x.UnsAreaId).ToHashSet(StringComparer.OrdinalIgnoreCase);
var lines = _snapshot.UnsLines.Where(x => areaIds.Contains(x.UnsAreaId)).ToList();
foreach (var x in lines) yield return (x.UnsLineId, $"Line: {x.Name} ({x.UnsLineId})");
var lineIds = lines.Select(x => x.UnsLineId).ToHashSet(StringComparer.OrdinalIgnoreCase);
foreach (var x in _snapshot.Equipment.Where(x => lineIds.Contains(x.UnsLineId))) yield return (x.EquipmentId, $"Equipment: {x.Name} ({x.EquipmentId})");
}
}
private RenderFragment Operations(DataOperations current, Action<DataOperations> set) => builder =>
{
builder.OpenElement(0, "fieldset"); builder.OpenElement(1, "legend"); builder.AddAttribute(2, "class", "fs-6"); builder.AddContent(3, "Allowed operations"); builder.CloseElement();
foreach (var bit in new[] { DataOperations.Browse, DataOperations.Metadata, DataOperations.Read, DataOperations.Subscribe, DataOperations.Write })
{
builder.OpenElement(4, "label"); builder.AddAttribute(5, "class", "me-3"); builder.OpenElement(6, "input"); builder.AddAttribute(7, "type", "checkbox"); builder.AddAttribute(8, "checked", current.HasFlag(bit));
builder.AddAttribute(9, "onchange", EventCallback.Factory.Create<ChangeEventArgs>(this, args => set((bool)args.Value! ? current | bit : current & ~bit))); builder.CloseElement(); builder.AddContent(10, " " + bit); builder.CloseElement();
}
builder.CloseElement();
};
private RenderFragment Actions(object row, bool existing) => builder =>
{
builder.OpenElement(0, "div"); builder.AddAttribute(1, "class", "d-flex gap-2 mt-3");
builder.OpenElement(2, "button"); builder.AddAttribute(3, "class", "btn btn-primary"); builder.AddAttribute(4, "onclick", EventCallback.Factory.Create(this, () => Save(row))); builder.AddContent(5, "Save draft"); builder.CloseElement();
builder.OpenElement(6, "button"); builder.AddAttribute(7, "class", "btn btn-outline-secondary"); builder.AddAttribute(8, "onclick", EventCallback.Factory.Create(this, Clear)); builder.AddContent(9, "Cancel"); builder.CloseElement();
if (existing) { builder.OpenElement(10, "button"); builder.AddAttribute(11, "class", "btn btn-outline-danger"); builder.AddAttribute(12, "onclick", EventCallback.Factory.Create(this, () => _deleteCandidate = row)); builder.AddContent(13, "Delete draft"); builder.CloseElement(); }
builder.CloseElement();
};
private async Task Save(object row) { try { await Service.SaveAsync(ClusterId, row); Clear(); await Reload(); _message = "Draft saved. Deploy to apply it."; } catch (Exception ex) { _error = ex is UnauthorizedAccessException or InvalidOperationException ? ex.Message : "Could not save the draft. It may have changed; reload and try again."; } }
private async Task Delete(object? row) { try { if (row is null) return; await Service.DeleteAsync(ClusterId, row); Clear(); await Reload(); _message = "Draft deleted. Deploy to apply the change."; } catch (Exception ex) { _error = ex is UnauthorizedAccessException or InvalidOperationException ? ex.Message : "Could not delete the draft. Reload and try again."; } }
}
@@ -10,6 +10,7 @@
<ul class="nav nav-tabs mb-3">
<li class="nav-item"><a class="nav-link @Active("overview")" aria-current='@(ActiveTab == "overview" ? "page" : null)' href="/clusters/@ClusterId">Overview</a></li>
<li class="nav-item"><a class="nav-link @Active("data")" aria-current='@(ActiveTab == "data" ? "page" : null)' href="/clusters/@ClusterId/data-connections">Data connections</a></li>
<li class="nav-item"><a class="nav-link @Active("acls")" aria-current='@(ActiveTab == "acls" ? "page" : null)' href="/clusters/@ClusterId/acls">ACLs</a></li>
<li class="nav-item"><a class="nav-link @Active("audit")" aria-current='@(ActiveTab == "audit" ? "page" : null)' href="/clusters/@ClusterId/audit">Audit</a></li>
<li class="nav-item"><a class="nav-link @Active("redundancy")" aria-current='@(ActiveTab == "redundancy" ? "page" : null)' href="/clusters/@ClusterId/redundancy">Redundancy</a></li>
@@ -0,0 +1,160 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
using ZB.MOM.WW.OtOpcUa.Security.Auth;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.DataConnections;
/// <summary>Authorizes and validates data-connection draft mutations. Deployment remains a separate operation.</summary>
public sealed class DataConnectionAdminService(IDbContextFactory<OtOpcUaConfigDbContext> factory,
IAuthorizationService authorization, AuthenticationStateProvider authentication)
{
public async Task<DraftSnapshot> LoadAsync(CancellationToken ct = default)
{
await using var db = await factory.CreateDbContextAsync(ct);
return await DraftSnapshotFactory.FromConfigDbAsync(db, ct);
}
/// <summary>Returns the last successfully applied artifact's connection revision per node, when available.</summary>
public async Task<IReadOnlyList<AppliedConnection>> LoadAppliedAsync(string clusterId, CancellationToken ct = default)
{
await using var db = await factory.CreateDbContextAsync(ct);
var nodes = await db.ClusterNodes.AsNoTracking().Where(n => n.ClusterId == clusterId).Select(n => n.NodeId).ToListAsync(ct);
var result = new List<AppliedConnection>();
foreach (var node in nodes)
{
var deployment = await db.NodeDeploymentStates.AsNoTracking().Where(s => s.NodeId == node && s.Status == NodeDeploymentStatus.Applied)
.OrderByDescending(s => s.StartedAtUtc).Select(s => (Guid?)s.DeploymentId).FirstOrDefaultAsync(ct);
if (deployment is null) continue;
var blob = await db.Deployments.AsNoTracking().Where(d => d.DeploymentId == deployment).Select(d => d.ArtifactBlob).FirstOrDefaultAsync(ct);
if (blob is not { Length: > 0 }) continue;
try
{
result.AddRange(DeploymentArtifact.ParseDataConnections(blob, node)
.Select(c => new AppliedConnection(node, c.DataConnectionId, c.Revision, c.Enabled)));
}
catch (Exception ex) when (ex is InvalidDataException or InvalidOperationException or System.Text.Json.JsonException)
{
// An unreadable artifact is unknown, not evidence of an empty deployment.
}
}
return result;
}
public async Task SaveAsync(string clusterId, object row, CancellationToken ct = default)
{
await RequireEditorAsync();
await using var db = await factory.CreateDbContextAsync(ct);
var snapshot = await DraftSnapshotFactory.FromConfigDbAsync(db, ct);
switch (row)
{
case DataConnection c:
CheckIdentity(clusterId, c.ClusterId, c.DataConnectionId);
await SaveRow(db, snapshot.DataConnections, c, x => x.DataConnectionRowId, x => x.DataConnectionId, ct);
break;
case DataExport e:
CheckIdentity(clusterId, e.ClusterId, e.DataExportId);
await SaveRow(db, snapshot.DataExports, e, x => x.DataExportRowId, x => x.DataExportId, ct);
break;
case RemoteNamespaceMapping m:
CheckIdentity(clusterId, m.ClusterId, m.RemoteNamespaceMappingId);
await SaveRow(db, snapshot.RemoteNamespaceMappings, m, x => x.RemoteNamespaceMappingRowId, x => x.RemoteNamespaceMappingId, ct);
break;
default: throw new ArgumentException("Unsupported draft row.", nameof(row));
}
var errors = DataConnectionValidator.Validate(snapshot);
if (errors.Count != 0) throw new InvalidOperationException(string.Join(" ", errors.Select(e => e.Message)));
await db.SaveChangesAsync(ct);
}
public async Task DeleteAsync(string clusterId, object row, CancellationToken ct = default)
{
await RequireEditorAsync();
await using var db = await factory.CreateDbContextAsync(ct);
var snapshot = await DraftSnapshotFactory.FromConfigDbAsync(db, ct);
switch (row)
{
case DataConnection c:
CheckIdentity(clusterId, c.ClusterId, c.DataConnectionId);
await DeleteRow(db, snapshot.DataConnections, c, x => x.DataConnectionRowId, x => x.DataConnectionId, ct); break;
case DataExport e:
CheckIdentity(clusterId, e.ClusterId, e.DataExportId);
await DeleteRow(db, snapshot.DataExports, e, x => x.DataExportRowId, x => x.DataExportId, ct); break;
case RemoteNamespaceMapping m:
CheckIdentity(clusterId, m.ClusterId, m.RemoteNamespaceMappingId);
await DeleteRow(db, snapshot.RemoteNamespaceMappings, m, x => x.RemoteNamespaceMappingRowId, x => x.RemoteNamespaceMappingId, ct); break;
default: throw new ArgumentException("Unsupported draft row.", nameof(row));
}
var errors = DataConnectionValidator.Validate(snapshot);
if (errors.Count != 0) throw new InvalidOperationException(string.Join(" ", errors.Select(e => e.Message)));
await db.SaveChangesAsync(ct);
}
private async Task RequireEditorAsync()
{
var user = (await authentication.GetAuthenticationStateAsync()).User;
if (!(await authorization.AuthorizeAsync(user, AdminUiPolicies.ConfigEditor)).Succeeded)
throw new UnauthorizedAccessException("Configuration editor access is required.");
}
private static void CheckIdentity(string cluster, string owner, string id)
{
if (string.IsNullOrWhiteSpace(id) || !string.Equals(cluster, owner, StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException("A row ID and matching cluster are required.");
}
private static async Task SaveRow<T>(OtOpcUaConfigDbContext db, IReadOnlyList<T> rows, T row,
Func<T, Guid> key, Func<T, string> id, CancellationToken ct) where T : class
{
var list = (List<T>)rows;
var existing = list.FirstOrDefault(x => key(x) == key(row) && key(row) != Guid.Empty);
if (existing is null)
{
if (key(row) != Guid.Empty || list.Any(x => string.Equals(id(x), id(row), StringComparison.OrdinalIgnoreCase)))
throw new InvalidOperationException("The row no longer exists or its ID is already in use.");
db.Set<T>().Add(row); list.Add(row);
}
else
{
if (!string.Equals(id(existing), id(row), StringComparison.OrdinalIgnoreCase) ||
!string.Equals(Owner(existing), Owner(row), StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException("The row ID cannot be changed.");
if (Revision(existing) != Revision(row)) throw new DbUpdateConcurrencyException("This draft has changed. Reload it before saving.");
var tracked = await db.Set<T>().FindAsync([key(row)], ct) ?? throw new InvalidOperationException("The row no longer exists.");
db.Entry(tracked).CurrentValues.SetValues(row);
db.Entry(tracked).Property("RowVersion").OriginalValue = db.Entry(row).Property("RowVersion").CurrentValue;
var revision = db.Entry(tracked).Property<long>("Revision");
revision.CurrentValue = checked(revision.OriginalValue + 1);
list[list.IndexOf(existing)] = tracked;
}
}
private static string Owner<T>(T row) => row switch
{
DataConnection c => c.ClusterId, DataExport e => e.ClusterId, RemoteNamespaceMapping m => m.ClusterId,
_ => throw new ArgumentException("Unsupported draft row.")
};
private static long Revision<T>(T row) => row switch
{
DataConnection c => c.Revision, DataExport e => e.Revision, RemoteNamespaceMapping m => m.Revision,
_ => throw new ArgumentException("Unsupported draft row.")
};
private static async Task DeleteRow<T>(OtOpcUaConfigDbContext db, IReadOnlyList<T> rows, T row,
Func<T, Guid> getKey, Func<T, string> getId, CancellationToken ct) where T : class
{
var list = (List<T>)rows;
var key = getKey(row);
var existing = list.FirstOrDefault(x => getKey(x) == key && string.Equals(Owner(x), Owner(row), StringComparison.OrdinalIgnoreCase)) ?? throw new InvalidOperationException("The row no longer exists.");
if (!string.Equals(getId(existing), getId(row), StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException("The row ID cannot be changed.");
if (Revision(existing) != Revision(row)) throw new DbUpdateConcurrencyException("This draft has changed. Reload it before deleting.");
var tracked = await db.Set<T>().FindAsync([key], ct) ?? throw new InvalidOperationException("The row no longer exists.");
db.Entry(tracked).Property("RowVersion").OriginalValue = db.Entry(row).Property("RowVersion").CurrentValue;
db.Remove(tracked); list.Remove(existing);
}
}
/// <summary>Connection configuration in a node’s last successfully applied artifact.</summary>
public sealed record AppliedConnection(string NodeId, string ConnectionId, long Revision, bool Enabled);
@@ -0,0 +1,31 @@
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.DataConnections;
/// <summary>Display helpers that never equate an authored draft with a running connection.</summary>
public static class DataConnectionDiagnostics
{
/// <summary>Includes evidence for connections removed from the draft until it is no longer reported.</summary>
public static IReadOnlyList<ConnectionDisplayRow> Rows(
IEnumerable<DataConnection> drafts, IEnumerable<string> appliedIds, IEnumerable<string> observedIds)
{
var result = new Dictionary<string, ConnectionDisplayRow>(StringComparer.OrdinalIgnoreCase);
foreach (var draft in drafts) result[draft.DataConnectionId] = new(draft.DataConnectionId, draft);
foreach (var id in appliedIds.Concat(observedIds))
if (!string.IsNullOrWhiteSpace(id) && !result.ContainsKey(id)) result.Add(id, new(id, null));
return result.Values.OrderBy(x => x.Id, StringComparer.OrdinalIgnoreCase).ToArray();
}
/// <summary>Uses the reporting node's measured duration, independent of the admin clock.</summary>
public static string SampleAge(ZB.MOM.WW.OtOpcUa.Commons.Interfaces.DataConnectionDiagnosticsSnapshot row) =>
row.SampleAgeUpperBound is { } age ? $"{age.TotalSeconds:F0}s at observation" : "unavailable";
public static string State(string? state) => state?.ToLowerInvariant() switch
{
"disabled" => "Disabled", "connecting" => "Connecting", "ready" => "Ready", "degraded" => "Degraded",
"auth-failed" => "Authentication failed", "backoff" => "Backoff", _ => "Unavailable"
};
public static string Endpoint(string? value) => Uri.TryCreate(value, UriKind.Absolute, out var uri)
&& uri.Scheme == Uri.UriSchemeHttps ? (uri.HostNameType == UriHostNameType.IPv6 ? $"https://[{uri.Host}]{(uri.IsDefaultPort ? "" : $":{uri.Port}")}" : $"https://{uri.IdnHost}{(uri.IsDefaultPort ? "" : $":{uri.Port}")}") : "Unavailable";
}
/// <summary>A connection identity and its optional current draft.</summary>
public sealed record ConnectionDisplayRow(string Id, DataConnection? Draft);
@@ -0,0 +1,13 @@
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.DataConnections;
/// <summary>Safe defaults and list editing helpers for a directional connection.</summary>
public sealed class DataConnectionEditorModel
{
public DataConnection Value { get; set; } = new() { TargetMode = DataTargetMode.Node, AllowedOperations = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Subscribe };
public string Endpoints { get => string.Join("\n", Value.Endpoints); set => Value.Endpoints = Lines(value); }
public string EligibleNodes { get => string.Join("\n", Value.EligibleTargetNodeIds); set => Value.EligibleTargetNodeIds = Lines(value); }
public static List<string> Lines(string? value) => (value ?? "").Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToList();
}
@@ -0,0 +1,10 @@
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.DataConnections;
/// <summary>Creates disabled mapping drafts with read-only operation defaults.</summary>
public sealed class RemoteMappingEditorModel
{
public RemoteNamespaceMapping Value { get; set; } = new() { Realm = DataRealm.Raw, RemoteRealm = DataRealm.Raw, AllowedOperations = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Subscribe };
}
@@ -87,6 +87,7 @@ public static class EndpointRouteBuilderExtensions
// mirror the deploy gate's NodeAclScope* rules. Scoped, because it composes the two scoped tree
// services above.
services.AddScoped<Acls.IAclScopeService, Acls.AclScopeService>();
services.AddScoped<DataConnections.DataConnectionAdminService>();
// lmxopcua#749: per-API-key Galaxy alarm-ack identity, held in the Secrets store (never the DB).
services.AddScoped<ApiKeyAck.IApiKeyGalaxyAckIdentityService>(sp => new ApiKeyAck.ApiKeyGalaxyAckIdentityService(
sp.GetRequiredService<ZB.MOM.WW.Secrets.Abstractions.ISecretStore>(),
@@ -51,6 +51,14 @@ public sealed class ActorProjectedValuePublisher : IProjectedValuePublisher, IDi
}
public long PendingBytes { get { lock (_sync) return _pendingBytes; } }
public long RetainedControlBytes { get { lock (_sync) return _controlBytes; } }
/// <summary>Counts retained import routes by configured connection, without exposing node or secret labels.</summary>
public IReadOnlyDictionary<string, int> CaptureSourceCounts()
{
lock (_sync)
return _bindings.Values.Where(x => x.Route.DriverInstanceId.StartsWith("grpc-data:", StringComparison.Ordinal))
.GroupBy(x => x.Route.DriverInstanceId[10..], StringComparer.OrdinalIgnoreCase)
.ToDictionary(x => x.Key, x => x.Count(), StringComparer.OrdinalIgnoreCase);
}
private static (DataRealm, string) Key(ProjectedValueRoute route) => (route.Realm, route.LocalIdentifier);
private bool Authorized(ProjectedValueRoute route)
{
@@ -72,6 +72,24 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
/// <summary>Configured redundancy mode from the current validated artifact.</summary>
public RedundancyMode CurrentConsumerMode { get { lock (_sync) return _desired?.ConsumerMode ?? RedundancyMode.None; } }
/// <summary>Captures only this node's applied scope and current transport evidence.</summary>
public IReadOnlyList<ZB.MOM.WW.OtOpcUa.Commons.Interfaces.DataConnectionDiagnosticsSnapshot> CaptureDiagnostics(IReadOnlyDictionary<string, int>? retainedSourceCounts = null)
{
lock (_sync)
{
if (_disposed || _desired is not { } desired) return [];
return desired.Specs.Values.Select(spec =>
{
if (!_attemptPending && _scopeReady && _entries.TryGetValue(spec.Id, out var entry) && entry.Ready)
return entry.Connection.CaptureDiagnostics(spec.Revision, desired.ScopeVersion, desired.ArtifactRevision) with
{ SourceCount = retainedSourceCounts is null ? null : retainedSourceCounts.TryGetValue(spec.Id, out var count) ? count : 0 };
return new ZB.MOM.WW.OtOpcUa.Commons.Interfaces.DataConnectionDiagnosticsSnapshot(spec.Id, spec.Revision,
_attemptPending ? "connecting" : _retryNotBefore > _clock.GetTimestamp() ? "backoff" : "connecting",
null, null, 0, 0, desired.ScopeVersion, desired.ArtifactRevision, _clock.GetUtcNow().UtcDateTime);
}).ToArray();
}
}
/// <summary>Withdraws current routes before parsing or staging a different artifact.</summary>
public void BeginAttempt(string artifactRevision)
{
@@ -0,0 +1,78 @@
using ZB.MOM.WW.OtOpcUa.Commons.Interfaces;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using Grpc.Core;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
public sealed partial class GrpcDataConnection
{
private string? _diagnosticEndpoint;
private ServingIdentity? _diagnosticServing;
private int? _diagnosticMajor, _diagnosticMinor;
private string _diagnosticState = "connecting";
private DateTime? _lastSampleAtUtc, _metadataLeaseExpiresAtUtc, _lastVerifiedAtUtc;
private TimeSpan? _sampleAgeUpper;
private long _sampleReceivedTimestamp;
private long _resetCount, _coalescedCount, _writeSucceededCount, _writeRejectedCount, _writeUnknownCount, _writeFailedCount, _writeUnconfirmedCount;
internal DataConnectionDiagnosticsSnapshot CaptureDiagnostics(long revision, long scopeVersion, string artifactRevision)
{
lock (_sync)
return new(_id, revision, _disposed || _scope.CancellationToken.IsCancellationRequested ? "disabled" :
_nextProbeTimestamp > Clock.GetTimestamp() && _diagnosticState != "auth-failed" ? "backoff" : _diagnosticState,
_diagnosticEndpoint, _diagnosticServing, _activeStreams, _activeWork, scopeVersion, artifactRevision,
Clock.GetUtcNow().UtcDateTime, _lastSampleAtUtc, _metadataLeaseExpiresAtUtc,
RegistrationCount: _streams.Sum(x => Volatile.Read(ref x.DiagnosticRegistrationCount)),
ResetCount: Interlocked.Read(ref _resetCount),
WriteSucceededCount: Interlocked.Read(ref _writeSucceededCount), WriteRejectedCount: Interlocked.Read(ref _writeRejectedCount),
WriteUnknownCount: Interlocked.Read(ref _writeUnknownCount), ProtocolMajor: _diagnosticMajor, ProtocolMinor: _diagnosticMinor, LastVerifiedAtUtc: _lastVerifiedAtUtc,
WriteFailedCount: Interlocked.Read(ref _writeFailedCount), WriteUnconfirmedCount: Interlocked.Read(ref _writeUnconfirmedCount),
SampleAgeUpperBound: ObservedUpperAge(),
CoalescedCount: Interlocked.Read(ref _coalescedCount));
}
private TimeSpan? ObservedUpperAge()
{
if (_sampleAgeUpper is not { } upper) return null;
var elapsed = Clock.GetElapsedTime(_sampleReceivedTimestamp);
if (upper < TimeSpan.Zero || elapsed < TimeSpan.Zero) return null;
return TimeSpan.FromTicks(upper.Ticks > long.MaxValue - elapsed.Ticks ? long.MaxValue : upper.Ticks + elapsed.Ticks);
}
private void RecordSelected(Uri endpoint, DataCapabilities capabilities)
{
lock (_sync)
{
_diagnosticEndpoint = new UriBuilder(endpoint.Scheme, endpoint.Host, endpoint.Port).Uri.GetLeftPart(UriPartial.Authority);
_diagnosticServing = capabilities.Serving; _lastVerifiedAtUtc = Clock.GetUtcNow().UtcDateTime;
_diagnosticMajor = capabilities.ProtocolMajor; _diagnosticMinor = capabilities.ProtocolMinor;
_diagnosticState = capabilities.Readiness == DataReadiness.Ready ? "ready" : "degraded";
}
}
private void RecordSampleAge(DataAgeBounds age)
{
lock (_sync)
{
_sampleAgeUpper = age.Upper; _sampleReceivedTimestamp = Clock.GetTimestamp();
_lastSampleAtUtc = age.Upper is { } upper && upper >= TimeSpan.Zero && upper.Ticks <= Clock.GetUtcNow().UtcDateTime.Ticks
? Clock.GetUtcNow().UtcDateTime - upper : null;
}
}
private void RecordFailure(Exception failure)
{
lock (_sync) _diagnosticState = failure is UnauthorizedAccessException or RpcException { StatusCode: StatusCode.Unauthenticated or StatusCode.PermissionDenied }
? "auth-failed" : "degraded";
}
private void RecordWrites(IReadOnlyList<WriteItemResult> results)
{
foreach (var item in results)
switch (item.Outcome.State)
{
case DataWriteState.DriverConfirmedSuccess: Interlocked.Increment(ref _writeSucceededCount); break;
case DataWriteState.DriverConfirmedFailure: Interlocked.Increment(ref _writeFailedCount); break;
case DataWriteState.RejectedBeforeDispatch: Interlocked.Increment(ref _writeRejectedCount); break;
case DataWriteState.AcceptedUnconfirmed: Interlocked.Increment(ref _writeUnconfirmedCount); break;
case DataWriteState.OutcomeUnknown: Interlocked.Increment(ref _writeUnknownCount); break;
}
}
}
@@ -23,7 +23,7 @@ public interface IDataConnectionSecurityProvider
public sealed record DataConnectionChannelIdentity(string ConnectionId, Uri Endpoint, string CredentialVersion, string TrustFingerprint);
/// <summary>Caller-bound remote facade. All channels and requests are bounded by configured local limits.</summary>
public sealed class GrpcDataConnection : IDataConnection
public sealed partial class GrpcDataConnection : IDataConnection
{
private sealed class ChannelEntry(DataConnectionChannelIdentity identity, GrpcChannel channel, string bearer)
{
@@ -141,6 +141,8 @@ public sealed class GrpcDataConnection : IDataConnection
lock (_sync)
{
_securityGeneration++;
_diagnosticState = "connecting"; _diagnosticEndpoint = null; _diagnosticServing = null;
_lastSampleAtUtc = null; _metadataLeaseExpiresAtUtc = null; _lastVerifiedAtUtc = null; _sampleAgeUpper = null;
foreach (var item in _channels.Values)
{
_retiringChannels++;
@@ -232,6 +234,7 @@ public sealed class GrpcDataConnection : IDataConnection
Target.Mode == DataTargetMode.Cluster && !_eligibleNodeIds!.Contains(caps.Serving.NodeId))
throw new InvalidOperationException("Endpoint is not an authenticated ready target.");
linked.Token.ThrowIfCancellationRequested();
RecordSelected(endpoint, caps);
return new(channel, caps);
}
private static void Verify(W.Serving? serving, Selected selected)
@@ -265,7 +268,7 @@ public sealed class GrpcDataConnection : IDataConnection
catch { if (result is IEnumerable<ReadResult> reads) foreach (var item in reads) item.Dispose(); throw; }
}
catch (Exception ex) when (ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException)
{ failure = ex; }
{ failure = ex; RecordFailure(ex); }
}
ProbeFailed();
throw new InvalidOperationException("No ready authenticated data endpoint.", failure);
@@ -282,6 +285,7 @@ public sealed class GrpcDataConnection : IDataConnection
public Task<DataBrowseBranch> BrowseAsync(BrowseRequest request, CancellationToken cancellationToken) =>
QueryAsync(request.Budget, async (selected, budget, options) =>
{
var browseStarted = Clock.GetTimestamp();
var wire = await selected.Channel.Client.BrowseAsync(DataProtoMapper.EncodeBrowseRequest(request with { Budget = budget }), options).ResponseAsync.ConfigureAwait(false);
Verify(wire.Serving, selected); var result = DataProtoMapper.DecodeBrowseResponse(wire, Limits(budget, selected.Capabilities));
if (result.Lease is { } lease && (lease.CatalogEpoch != selected.Capabilities.Serving.CatalogEpoch ||
@@ -290,6 +294,8 @@ public sealed class GrpcDataConnection : IDataConnection
if (result.Parent != request.Parent || result.Items.Any(x => x.CatalogRevision != selected.Capabilities.Serving.CatalogEpoch || !string.Equals(x.View.Address.OriginClusterId, selected.Capabilities.ClusterId, StringComparison.OrdinalIgnoreCase)))
throw new InvalidOperationException("Browse response has unexpected provenance.");
Verify(wire.Serving, selected);
lock (_sync) _metadataLeaseExpiresAtUtc = result.Lease is { } observed
? Clock.GetUtcNow().UtcDateTime + TimeSpan.FromTicks(Math.Max(0, (observed.Duration - Clock.GetElapsedTime(browseStarted)).Ticks)) : null;
var serving = DataProtoMapper.DecodeServing(wire.Serving);
return result with { Serving = serving, Items = result.Items.Select(x => ExposeMetadata(x, serving, selected.Capabilities)).ToArray() };
}, cancellationToken);
@@ -318,7 +324,9 @@ public sealed class GrpcDataConnection : IDataConnection
if (result.Count != request.Items.Count || !result.Select(x => x.CorrelationId).SequenceEqual(request.Items.Select(x => x.CorrelationId)) ||
result.Any(x => x.Sample is not null && x.Sample.Serving != selected.Capabilities.Serving))
throw new InvalidOperationException("Read response has unexpected items or serving identity.");
Verify(wire.Serving, selected); return result;
Verify(wire.Serving, selected);
if (result.LastOrDefault(x => x.Sample is not null) is { } observed) RecordSampleAge(observed.AgeBounds);
return result;
}
catch { foreach (var item in result) item.Dispose(); throw; }
}, cancellationToken);
@@ -333,13 +341,18 @@ public sealed class GrpcDataConnection : IDataConnection
{
using var admission = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _scope.CancellationToken, _shutdown.Token);
admitted = await _unaryCapacity.WaitAsync(0, admission.Token).ConfigureAwait(false);
if (!admitted) return request.Items.Select(x => new WriteItemResult(x.CorrelationId,
new(DataWriteState.RejectedBeforeDispatch, 0x80310000u, "Unary capacity exhausted."))).ToArray();
if (!admitted)
{
var rejected = request.Items.Select(x => new WriteItemResult(x.CorrelationId,
new(DataWriteState.RejectedBeforeDispatch, 0x80310000u, "Unary capacity exhausted."))).ToArray();
RecordWrites(rejected); return rejected;
}
var elapsed = Clock.GetElapsedTime(admissionStart);
var remaining = Remaining(admissionStart, request.Budget);
var reduced = request with { Budget = request.Budget with { Timeout = remaining },
Items = request.Items.Select(x => x with { RemainingBudget = x.RemainingBudget - elapsed }).ToArray() };
return await WriteCoreAsync(reduced, cancellationToken).ConfigureAwait(false);
var outcomes = await WriteCoreAsync(reduced, cancellationToken).ConfigureAwait(false);
RecordWrites(outcomes); return outcomes;
}
finally { if (admitted) _unaryCapacity.Release(); ExitWork(); }
}
@@ -500,7 +513,7 @@ public sealed class GrpcDataConnection : IDataConnection
try
{
var call = selected.Channel.Client.Subscribe(Headers(selected.Channel), cancellationToken: lifetime.Token);
subscription = new RemoteSubscription(call, selected, lifetime, _maxMessageBytes,
subscription = new RemoteSubscription(this, call, selected, lifetime, _maxMessageBytes,
Math.Min(_maxMonitoredItems, selected.Capabilities.Limits.MaxMonitoredItems), _maxPendingCommands,
_maxCommandTimeout, _commandBudget, ClaimStreamEpoch, PendingIdentityObserverForTests, AfterTimerCancelledForTests, () => { lock (_sync) { _streams.Remove(subscription!); Interlocked.Decrement(ref _activeStreams); CheckDrainedLocked(); } });
if (BeforeStreamInstallForTests is { } pause) await pause().ConfigureAwait(false);
@@ -529,7 +542,7 @@ public sealed class GrpcDataConnection : IDataConnection
}
}
catch (Exception ex) when (ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException)
{ failure = ex; }
{ failure = ex; RecordFailure(ex); }
}
ProbeFailed();
throw new InvalidOperationException("No ready subscription endpoint.", failure);
@@ -541,7 +554,7 @@ public sealed class GrpcDataConnection : IDataConnection
}
}
private sealed class RemoteSubscription(
private sealed class RemoteSubscription(GrpcDataConnection owner,
AsyncDuplexStreamingCall<W.SubscriptionCommand, W.SubscriptionFrame> call, Selected selected,
CancellationTokenSource lifetime, int maxBytes, int maxItems, int maxPendingCommands,
TimeSpan maxCommandTimeout, CommandStateBudget commandBudget, Func<string, long, bool> claimEpoch, Action<WeakReference>? observePending,
@@ -667,6 +680,7 @@ public sealed class GrpcDataConnection : IDataConnection
catch (OperationCanceledException) { if (afterTimerCancelled is not null) await afterTimerCancelled().ConfigureAwait(false); }
catch (ObjectDisposedException) { }
}
internal int DiagnosticRegistrationCount;
public async IAsyncEnumerable<DataSubscriptionFrame> ReadAllAsync([EnumeratorCancellation] CancellationToken cancellationToken)
{
if (Interlocked.Exchange(ref _reading, 1) != 0) throw new InvalidOperationException("A stream has one reader.");
@@ -748,6 +762,7 @@ public sealed class GrpcDataConnection : IDataConnection
_pendingBytes -= pending.Bytes; commandBudget.Release(pending.Bytes);
pending.Timer.Cancel(); pending.Timer.Dispose();
_handles = next; _clientHandles = nextClients; _usedHandles = nextUsed; _versions = nextVersions;
Volatile.Write(ref DiagnosticRegistrationCount, next.Count);
}
}
if (frame is DataSubscriptionValues values)
@@ -765,6 +780,9 @@ public sealed class GrpcDataConnection : IDataConnection
_sequence = wire.Sequence;
}
catch { if (frame is IDisposable owned) owned.Dispose(); throw; }
if (frame is DataSubscriptionValues { Items.Count: > 0 } observedValues) owner.RecordSampleAge(observedValues.Items[^1].AgeBounds);
if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.Reset }) Interlocked.Increment(ref owner._resetCount);
if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.Coalesced }) Interlocked.Increment(ref owner._coalescedCount);
yield return frame;
if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.Reset })
{ await lifetime.CancelAsync().ConfigureAwait(false); yield break; }
@@ -2980,7 +2980,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
CurrentRevision: _currentRevision,
Drivers: drivers,
AsOfUtc: DateTime.UtcNow,
RunningFromCache: _isRunningFromCache);
RunningFromCache: _isRunningFromCache,
DataConnections: _dataConnections?.CaptureDiagnostics(_projectedPublisher?.CaptureSourceCounts()));
Sender.Tell(snapshot);
}
@@ -0,0 +1,117 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.EntityFrameworkCore;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.AdminUI.DataConnections;
using ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Acls;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.DataConnections;
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P09")]
public sealed class GrpcDataAuthoringTests
{
[Fact]
public async Task Editor_saves_a_disabled_draft_and_read_only_user_cannot_modify_it()
{
var factory = AclScopeTestDb.Factory(Guid.NewGuid().ToString());
var editor = new DataConnectionAdminService(factory, new Auth(true), new User());
var row = new DataConnection { ClusterId = "MAIN", DataConnectionId = "peer" };
await editor.SaveAsync("MAIN", row, TestContext.Current.CancellationToken);
var loaded = (await editor.LoadAsync(TestContext.Current.CancellationToken)).DataConnections.ShouldHaveSingleItem();
loaded.Enabled.ShouldBeFalse();
var reader = new DataConnectionAdminService(factory, new Auth(false), new User());
await Should.ThrowAsync<UnauthorizedAccessException>(() => reader.DeleteAsync("MAIN", loaded, TestContext.Current.CancellationToken));
(await editor.LoadAsync(TestContext.Current.CancellationToken)).DataConnections.Count.ShouldBe(1);
}
[Fact]
public async Task A_secret_value_is_rejected_by_the_authoritative_validator()
{
var service = new DataConnectionAdminService(AclScopeTestDb.Factory(Guid.NewGuid().ToString()), new Auth(true), new User());
await Should.ThrowAsync<InvalidOperationException>(() => service.SaveAsync("MAIN", new DataConnection { ClusterId = "MAIN", DataConnectionId = "peer", SecretReference = "raw-key" }, TestContext.Current.CancellationToken));
(await service.LoadAsync(TestContext.Current.CancellationToken)).DataConnections.ShouldBeEmpty();
}
[Fact]
public async Task Edits_advance_revision_and_stale_edits_or_deletes_are_refused()
{
var ct = TestContext.Current.CancellationToken;
var service = new DataConnectionAdminService(AclScopeTestDb.Factory(Guid.NewGuid().ToString()), new Auth(true), new User());
await service.SaveAsync("MAIN", new DataConnection { ClusterId = "MAIN", DataConnectionId = "peer" }, ct);
var original = (await service.LoadAsync(ct)).DataConnections.ShouldHaveSingleItem();
var stale = (await service.LoadAsync(ct)).DataConnections.ShouldHaveSingleItem();
original.ExpectedClusterId = "OTHER";
await service.SaveAsync("MAIN", original, ct);
(await service.LoadAsync(ct)).DataConnections.ShouldHaveSingleItem().Revision.ShouldBe(2);
await Should.ThrowAsync<DbUpdateConcurrencyException>(() => service.SaveAsync("MAIN", stale, ct));
await Should.ThrowAsync<DbUpdateConcurrencyException>(() => service.DeleteAsync("MAIN", stale, ct));
var current = (await service.LoadAsync(ct)).DataConnections.ShouldHaveSingleItem();
await service.DeleteAsync("MAIN", current, ct);
(await service.LoadAsync(ct)).DataConnections.ShouldBeEmpty();
}
[Fact]
public async Task Row_identity_cannot_be_moved_renamed_or_deleted_by_a_forged_id()
{
var ct = TestContext.Current.CancellationToken;
var service = new DataConnectionAdminService(AclScopeTestDb.Factory(Guid.NewGuid().ToString()), new Auth(true), new User());
await service.SaveAsync("MAIN", new DataConnection { ClusterId = "MAIN", DataConnectionId = "peer" }, ct);
var row = (await service.LoadAsync(ct)).DataConnections.ShouldHaveSingleItem();
row.DataConnectionId = "other";
await Should.ThrowAsync<InvalidOperationException>(() => service.SaveAsync("MAIN", row, ct));
await Should.ThrowAsync<InvalidOperationException>(() => service.DeleteAsync("MAIN", row, ct));
row.ClusterId = "OTHER";
await Should.ThrowAsync<InvalidOperationException>(() => service.SaveAsync("OTHER", row, ct));
await Should.ThrowAsync<InvalidOperationException>(() => service.DeleteAsync("OTHER", row, ct));
(await service.LoadAsync(ct)).DataConnections.ShouldHaveSingleItem().DataConnectionId.ShouldBe("peer");
}
[Fact]
public async Task Read_only_cannot_create_or_enable_write()
{
var ct = TestContext.Current.CancellationToken;
var factory = AclScopeTestDb.Factory(Guid.NewGuid().ToString());
var reader = new DataConnectionAdminService(factory, new Auth(false), new User());
var row = new DataConnection { ClusterId = "MAIN", DataConnectionId = "peer", Enabled = true,
AllowedOperations = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataOperations.Write };
await Should.ThrowAsync<UnauthorizedAccessException>(() => reader.SaveAsync("MAIN", row, ct));
(await reader.LoadAsync(ct)).DataConnections.ShouldBeEmpty();
}
[Fact]
public async Task Connection_with_enabled_mapping_cannot_be_deleted()
{
var ct = TestContext.Current.CancellationToken;
var name = Guid.NewGuid().ToString();
var factory = AclScopeTestDb.Factory(name);
await using (var db = await factory.CreateDbContextAsync(ct))
{
AclScopeTestDb.Seed(db);
db.ClusterNodes.Add(new ClusterNode { NodeId = "A", ClusterId = "MAIN", Host = "a", ApplicationUri = "urn:a", CreatedBy = "test" });
db.DataConnections.Add(new DataConnection { DataConnectionId = "peer", ClusterId = "MAIN", Enabled = true,
ConsumerNodeIds = ["A"], TargetMode = DataTargetMode.Node, ExpectedClusterId = "REMOTE", ExpectedNodeId = "B",
Endpoints = ["https://peer.example"], SecretReference = "secret:data/peer", SecretScopeClusterId = "MAIN",
AllowedOperations = DataOperations.Read });
db.RemoteNamespaceMappings.Add(new RemoteNamespaceMapping { RemoteNamespaceMappingId = "mount", ClusterId = "MAIN", Enabled = true,
DataConnectionId = "peer", ConsumerNodeIds = ["A"], Realm = DataRealm.Raw, RemoteRealm = DataRealm.Raw,
LocalParentKind = "Cluster", LocalParentId = "MAIN", BranchName = "remote", RemoteRootEntityId = "root",
RemoteNamespaceUri = V3NodeIds.RawNamespaceUri, RemoteIdentifierKind = "String", RemoteIdentifier = "root", AllowedOperations = DataOperations.Read });
await db.SaveChangesAsync(ct);
}
var service = new DataConnectionAdminService(factory, new Auth(true), new User());
var snapshot = await service.LoadAsync(ct);
DataConnectionValidator.Validate(snapshot).ShouldBeEmpty();
await Should.ThrowAsync<InvalidOperationException>(() => service.DeleteAsync("MAIN", snapshot.DataConnections.ShouldHaveSingleItem(), ct));
(await service.LoadAsync(ct)).DataConnections.Count.ShouldBe(1);
}
private sealed class User : AuthenticationStateProvider
{
public override Task<AuthenticationState> GetAuthenticationStateAsync() => Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity("test"))));
}
private sealed class Auth(bool allowed) : IAuthorizationService
{
public Task<AuthorizationResult> AuthorizeAsync(ClaimsPrincipal user, object? resource, IEnumerable<IAuthorizationRequirement> requirements) => Task.FromResult(allowed ? AuthorizationResult.Success() : AuthorizationResult.Failed());
public Task<AuthorizationResult> AuthorizeAsync(ClaimsPrincipal user, object? resource, string policyName) => Task.FromResult(allowed ? AuthorizationResult.Success() : AuthorizationResult.Failed());
}
}
@@ -0,0 +1,38 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.AdminUI.DataConnections;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.DataConnections;
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P09")]
public sealed class GrpcDataDiagnosticsTests
{
[Fact]
public void Sample_age_uses_the_node_observation_even_when_the_node_clock_is_ahead()
{
var consumerUtc = DateTime.UtcNow.AddSeconds(30);
var row = new ZB.MOM.WW.OtOpcUa.Commons.Interfaces.DataConnectionDiagnosticsSnapshot("link", 1, "ready", null, null,
0, 0, 1, "artifact", consumerUtc, LastSampleAtUtc: consumerUtc.AddSeconds(-20), SampleAgeUpperBound: TimeSpan.FromSeconds(20));
DataConnectionDiagnostics.SampleAge(row).ShouldBe("20s at observation");
}
[Fact]
public void Deleted_draft_remains_visible_while_applied_or_observed()
{
var draft = new DataConnection { DataConnectionId = "Peer", ClusterId = "MAIN" };
var before = DataConnectionDiagnostics.Rows([draft], ["peer"], ["PEER"]);
before.ShouldHaveSingleItem().Draft.ShouldBe(draft);
var after = DataConnectionDiagnostics.Rows([], ["peer"], ["PEER"]);
var retained = after.ShouldHaveSingleItem();
retained.Id.ShouldBe("peer");
retained.Draft.ShouldBeNull();
DataConnectionDiagnostics.Rows([], [], ["peer"]).ShouldHaveSingleItem();
DataConnectionDiagnostics.Rows([], [], []).ShouldBeEmpty();
}
[Fact]
public void Unknown_runtime_status_is_not_reported_as_ready() => DataConnectionDiagnostics.State(null).ShouldBe("Unavailable");
[Fact]
public void Endpoint_display_never_includes_credentials_or_query() =>
DataConnectionDiagnostics.Endpoint("https://user:password@example.com:8443/path?token=secret").ShouldBe("https://example.com:8443");
}
@@ -0,0 +1,41 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.AdminUI.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.DataConnections;
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P09")]
public sealed class GrpcDataEditorValidationTests
{
[Fact]
public void New_drafts_are_disabled_and_do_not_grant_write()
{
var connection = new DataConnectionEditorModel().Value;
var mapping = new RemoteMappingEditorModel().Value;
connection.Enabled.ShouldBeFalse(); mapping.Enabled.ShouldBeFalse();
connection.AllowedOperations.HasFlag(DataOperations.Write).ShouldBeFalse();
mapping.AllowedOperations.HasFlag(DataOperations.Write).ShouldBeFalse();
mapping.WriteThrough.ShouldBeFalse();
}
[Fact]
public void Enabled_mapping_must_use_the_connection_consumer_scope_and_require_write_through()
{
var connection = new DataConnection { DataConnectionId = "peer", ClusterId = "MAIN", Enabled = true,
ConsumerNodeIds = ["A"], TargetMode = DataTargetMode.Node, ExpectedClusterId = "REMOTE", ExpectedNodeId = "B",
Endpoints = ["https://peer.example"], SecretReference = "secret:data/peer", SecretScopeClusterId = "MAIN",
AllowedOperations = DataOperations.Read | DataOperations.Write };
var mapping = new RemoteNamespaceMapping { RemoteNamespaceMappingId = "mount", ClusterId = "MAIN", Enabled = true,
DataConnectionId = "peer", ConsumerNodeIds = ["B"], AllowedOperations = DataOperations.Write, WriteThrough = false };
var snapshot = new DraftSnapshot { GenerationId = 0, ClusterId = "MAIN", DataConnections = [connection],
RemoteNamespaceMappings = [mapping], ClusterNodes = [new ClusterNode { NodeId = "A", ClusterId = "MAIN", Host = "a", ApplicationUri = "urn:a", CreatedBy = "test" }] };
var errors = DataConnectionValidator.Validate(snapshot);
errors.ShouldContain(x => x.Code == "DataMappingConsumerScopeInvalid");
errors.ShouldContain(x => x.Code == "DataMappingOperationsInvalid");
}
[Fact]
public void List_editor_trims_lines_without_changing_order() =>
DataConnectionEditorModel.Lines(" a \r\n\n b ").ShouldBe(new[] { "a", "b" });
}
@@ -3,6 +3,7 @@ using Xunit;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.DataConnections;
[CollectionDefinition(nameof(GrpcDataDiscoveryEnvironmentCollection), DisableParallelization = true)]
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P09")]
public sealed class GrpcDataDiscoveryEnvironmentCollection
{
}
@@ -10,6 +11,7 @@ public sealed class GrpcDataDiscoveryEnvironmentCollection
[Collection(nameof(GrpcDataDiscoveryEnvironmentCollection))]
[Trait("Feature", "GrpcData")]
[Trait("Phase", "P00")]
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P09")]
public sealed class GrpcDataUnitDiscoveryIsolationTests
{
private const string Switch = "OTOPCUA_UNIT_ONLY_DISCOVERY";
@@ -19,6 +19,48 @@ public sealed class GrpcDataConnectionClientTests
private static readonly DataView View = new(new("c", "urn:test", "string", "x"), DataRealm.Raw, null, 0, "x");
private static readonly DataBudget Budget = new(TimeSpan.FromSeconds(5), 16, 65536);
[Fact, Trait("Phase", "P09")]
public async Task Coalesced_notice_is_reported_separately_from_unknown_overflow()
{
var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null);
var handle = new DataItemHandle("s", 1, 1, 1);
var ack = DataProtoMapper.EncodeControlOrAck(new DataSubscriptionAck("s", 1, 1, "open", [new("item", DataItemStatus.Good, handle, settings, null)]));
var control = DataProtoMapper.EncodeControlOrAck(new DataSubscriptionControl("s", 1, 2, DataStreamControlKind.Coalesced, [], 1, 1, null));
ack.Serving = control.Serving = DataProtoMapper.EncodeServing(Serving);
using var manager = new DataConnectionManager("consumer", 1);
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"),
[new Uri("https://example.test")], new Security(new StreamWireHandler([ack, control])), manager.Acquire("link"), 65536, 1);
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), [new("item", View, settings)], false,
TimeSpan.FromMinutes(1), Budget), TestContext.Current.CancellationToken);
await using var frames = subscription.ReadAllAsync(TestContext.Current.CancellationToken).GetAsyncEnumerator(TestContext.Current.CancellationToken);
(await frames.MoveNextAsync()).ShouldBeTrue(); (await frames.MoveNextAsync()).ShouldBeTrue();
var diagnostics = connection.CaptureDiagnostics(1, 1, "artifact");
diagnostics.CoalescedCount.ShouldBe(1); diagnostics.OverflowCount.ShouldBeNull(); diagnostics.RegistrationCount.ShouldBe(1);
}
[Fact, Trait("Phase", "P09")]
public async Task Transport_diagnostics_report_verified_endpoint_and_ambiguous_write_without_secrets()
{
using var manager = new DataConnectionManager("consumer", 1);
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"),
[new Uri("https://user:secret@example.test:8443/private?token=secret")], new Security(new WireHandler { LoseWrite = true }), manager.Acquire("link"), 65536, 1);
connection.CaptureDiagnostics(2, 3, "artifact").State.ShouldBe("connecting");
await connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken);
var live = connection.CaptureDiagnostics(2, 3, "artifact");
live.State.ShouldBe("ready"); live.SelectedEndpoint.ShouldBe("https://example.test:8443");
live.Serving.ShouldBe(Serving); live.ActiveCalls.ShouldBe(0); live.ScopeVersion.ShouldBe(3);
live.ProtocolMinor.ShouldBe(3); live.LastSampleAtUtc.ShouldBeNull();
using var value = DataValue.FromScalar(DataValueKind.Int32, 1);
var outcome = await connection.WriteAsync(new([new("item", "one", View, value, 1, "boot", TimeSpan.FromSeconds(4), 1)], Budget), TestContext.Current.CancellationToken);
outcome.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.OutcomeUnknown);
connection.CaptureDiagnostics(2, 3, "artifact").WriteUnknownCount.ShouldBe(1);
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>>());
connection.CaptureDiagnostics(2, 3, "artifact").State.ShouldBe("disabled");
}
[Fact]
public void Security_material_does_not_render_the_presented_bearer()
{
@@ -33,6 +33,24 @@ public sealed class GrpcDataDeploymentActivationTests
throw new TimeoutException("Expected deployment state did not arrive.");
}
[Fact, Trait("Phase", "P09")]
public async Task Diagnostics_never_report_a_saved_or_unaccepted_scope_as_ready()
{
var activator = new PausedActivator();
await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4);
runtime.CaptureDiagnostics().ShouldBeEmpty();
runtime.Apply(Snapshot(1, Definition("link", "secret-reference")));
await activator.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
var pending = runtime.CaptureDiagnostics().ShouldHaveSingleItem();
pending.State.ShouldBe("connecting"); pending.SelectedEndpoint.ShouldBeNull();
pending.ArtifactRevision.ShouldBe("artifact-1"); pending.ScopeVersion.ShouldBe(1);
activator.Release.TrySetResult();
await EventuallyAsync(() => runtime.CurrentScopeReady && runtime.TryAcquire("link", out var candidate) && DisposeAndTrue(candidate!));
runtime.CaptureDiagnostics().ShouldHaveSingleItem().State.ShouldBe("connecting", "local credential activation is not a remote capability handshake");
runtime.BeginAttempt("artifact-2");
runtime.CaptureDiagnostics().ShouldHaveSingleItem().State.ShouldBe("connecting");
}
[Fact]
public async Task Transient_security_resolution_exception_retries_without_a_change_event()
{