diff --git a/docs/Configuration.md b/docs/Configuration.md index ac86656d0..4b0d834bc 100644 --- a/docs/Configuration.md +++ b/docs/Configuration.md @@ -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. diff --git a/docs/DataConnections.md b/docs/DataConnections.md new file mode 100644 index 000000000..d003a81bb --- /dev/null +++ b/docs/DataConnections.md @@ -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. diff --git a/docs/README.md b/docs/README.md index b8ea0da2d..8e772f86a 100644 --- a/docs/README.md +++ b/docs/README.md @@ -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 | diff --git a/docs/Raw.md b/docs/Raw.md index 3a5a8152d..43e7f297b 100644 --- a/docs/Raw.md +++ b/docs/Raw.md @@ -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`), diff --git a/docs/ReadWriteOperations.md b/docs/ReadWriteOperations.md index e519f5e40..965e44534 100644 --- a/docs/ReadWriteOperations.md +++ b/docs/ReadWriteOperations.md @@ -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. diff --git a/docs/Redundancy.md b/docs/Redundancy.md index 23e09fe3d..529889204 100644 --- a/docs/Redundancy.md +++ b/docs/Redundancy.md @@ -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). diff --git a/docs/Uns.md b/docs/Uns.md index 16e36b428..5cf060ffc 100644 --- a/docs/Uns.md +++ b/docs/Uns.md @@ -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 diff --git a/docs/plans/evidence/grpc-data/README.md b/docs/plans/evidence/grpc-data/README.md index 2b1e02a7c..ecb6e25e4 100644 --- a/docs/plans/evidence/grpc-data/README.md +++ b/docs/plans/evidence/grpc-data/README.md @@ -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. diff --git a/docs/plans/evidence/grpc-data/p09-astra-review.md b/docs/plans/evidence/grpc-data/p09-astra-review.md new file mode 100644 index 000000000..2df07d0ed --- /dev/null +++ b/docs/plans/evidence/grpc-data/p09-astra-review.md @@ -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. diff --git a/docs/security.md b/docs/security.md index d9afe6eab..6483a33ba 100644 --- a/docs/security.md +++ b/docs/security.md @@ -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__`) 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: diff --git a/scripts/validation/grpc-data/unit-phases.json b/scripts/validation/grpc-data/unit-phases.json index f0d227584..7cd9627f1 100644 --- a/scripts/validation/grpc-data/unit-phases.json +++ b/scripts/validation/grpc-data/unit-phases.json @@ -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" + ] } ] } diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/DataConnectionDiagnosticsSnapshot.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/DataConnectionDiagnosticsSnapshot.cs new file mode 100644 index 000000000..c35a033f4 --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/DataConnectionDiagnosticsSnapshot.cs @@ -0,0 +1,33 @@ +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Commons.Interfaces; + +/// Bounded, secret-free evidence from one node's applied data connection. +/// Nullable measures mean that evidence is unavailable, rather than zero activity. +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); diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/NodeDiagnosticsSnapshot.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/NodeDiagnosticsSnapshot.cs index f8db2d319..f8686d205 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/NodeDiagnosticsSnapshot.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/NodeDiagnosticsSnapshot.cs @@ -48,4 +48,5 @@ public sealed record NodeDiagnosticsSnapshot( RevisionHash? CurrentRevision, IReadOnlyList Drivers, DateTime AsOfUtc, - bool RunningFromCache = false); + bool RunningFromCache = false, + IReadOnlyList? DataConnections = null); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor new file mode 100644 index 000000000..5cd0cd588 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor @@ -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 + + +Data connections · OtOpcUa +

Data connections · @ClusterId

+ +

Connections are directional. Exports grant a peer access to local data; mappings place remote data under a local Raw or UNS parent.

+
Changes are saved as drafts. Deploy them from Deployments; saving alone does not start or stop an import. Runtime status is unavailable until reported by a node.
+@if (_snapshot is null) {

Loading…

} +else +{ + @if (_error is not null) { } + @if (_message is not null) {
@_message
} +
+

Connections

+
+ @if (!ConnectionRows.Any()) {

No draft, applied, or observed connections.

} + @foreach (var row in ConnectionRows) + { +
@row.Id@if (row.Draft is { } draft) { Draft: @(draft.Enabled ? "enabled" : "disabled") } else { Removed from draft }@if (!_live.Any(x => Same(x.Row.ConnectionId, row.Id))) { Runtime: unavailable } + @foreach (var live in _live.Where(x => Same(x.Row.ConnectionId, row.Id))) + { +
@live.NodeId: @DataConnectionDiagnostics.State(live.Row.State) · revision @live.Row.Revision · endpoint @DataConnectionDiagnostics.Endpoint(live.Row.SelectedEndpoint) + @if (live.Row.Serving is { } serving) { · serving @serving.NodeId · role @serving.Role · incarnation @serving.Incarnation } +
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)
+
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)
+
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)
+ } + @foreach (var applied in _applied.Where(x => Same(x.ConnectionId, row.Id))) { @applied.NodeId: last applied revision @applied.Revision (@(applied.Enabled ? "enabled" : "disabled")) } + @if (row.Draft is { } editable) { }
+ } + +
+
+
+

Exports

+ @if (!Exports.Any()) {

No export grants have been authored.

} + @foreach (var e in Exports) {
@e.DataExportId@e.Realm · @e.RootKind · @e.PrincipalIdDraft: @(e.Enabled ? "enabled" : "disabled")
} +
+
+

Mappings

+ @if (!Mappings.Any()) {

No remote branches have been mapped.

} + @foreach (var m in Mappings) {
@m.RemoteNamespaceMappingId@m.Realm · @m.BranchName via @m.DataConnectionIdDraft: @(m.Enabled ? "enabled" : "disabled")
} +
+
+ + @if (_deleteCandidate is not null) + { + + } + @if (_connection is not null) + { + var c = _connection.Value; +

Connection draft

+ + + + @if (c.TargetMode == DataTargetMode.Node) { } + else { } + + +
Reference only; never enter a key or secret value.
+
Consumer nodes@foreach (var n in Nodes) { }
+ @Operations(c.AllowedOperations, v => c.AllowedOperations = v) + + @Actions(c, c.DataConnectionRowId != Guid.Empty) +
+ } + @if (_export is not null) + { + var e = _export; +

Export draft

+ + + + + @Operations(e.AllowedOperations, v => e.AllowedOperations = v) + @Actions(e, e.DataExportRowId != Guid.Empty) +
+ } + @if (_mapping is not null) + { + var m = _mapping.Value; +

Mapping draft

+ + + + + +
The picker uses the configured target cluster. For a separately managed cluster, enter its root ID below.
+ + +
Consumer nodes@foreach (var n in Nodes) { }
+ @Operations(m.AllowedOperations, v => m.AllowedOperations = v) +
@Actions(m, m.RemoteNamespaceMappingRowId != Guid.Empty) +
+ } +
+} +
+ +@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 _applied = []; + private List<(string NodeId, DataConnectionDiagnosticsSnapshot Row)> _live = []; + private IReadOnlyList ConnectionRows => DataConnectionDiagnostics.Rows(Connections, _applied.Select(x => x.ConnectionId), _live.Select(x => x.Row.ConnectionId)); + private IEnumerable Connections => _snapshot!.DataConnections.Where(x => Same(x.ClusterId, ClusterId)); + private IEnumerable Exports => _snapshot!.DataExports.Where(x => Same(x.ClusterId, ClusterId)); + private IEnumerable Mappings => _snapshot!.RemoteNamespaceMappings.Where(x => Same(x.ClusterId, ClusterId)); + private IEnumerable 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? 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 value) => System.Text.Json.JsonSerializer.Deserialize(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 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 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(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."; } } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/ClusterNav.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/ClusterNav.razor index 7c0cf941c..b5598aaec 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/ClusterNav.razor +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/ClusterNav.razor @@ -10,6 +10,7 @@