Compare commits

...

14 Commits

Author SHA1 Message Date
Joseph Doherty c24abc8a97 docs(historian): mark Phase C tasks 1-6 complete (T7 live deferred)
v2-ci / build (push) Failing after 40s
v2-ci / unit-tests (tests/Core/ZB.MOM.WW.OtOpcUa.Cluster.Tests) (push) Has been skipped
v2-ci / unit-tests (tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests) (push) Has been skipped
v2-ci / unit-tests (tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests) (push) Has been skipped
v2-ci / unit-tests (tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests) (push) Has been skipped
v2-ci / unit-tests (tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests) (push) Has been skipped
v2-ci / integration (tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests) (push) Has been skipped
v2-ci / integration (tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests) (push) Has been skipped
2026-06-14 21:19:28 -04:00
Joseph Doherty 7eb8f4d054 docs(historian): Phase C HistoryRead guide + CLAUDE.md pointer 2026-06-14 20:27:17 -04:00
Joseph Doherty 83e1318425 refactor(historian): align ServerHistorianOptions with AlarmHistorian (Port default, Validate list, log context) 2026-06-14 20:23:22 -04:00
Joseph Doherty a6f1f4ef15 feat(historian): AddServerHistorian DI + Host wiring of IHistorianDataSource 2026-06-14 20:17:10 -04:00
Joseph Doherty e6ec0ad8be fix(historian): events arm sets results on bad paths + Variant.Null SourceName + test hardening
- HistoryReadEvents miss path + catch path now both set results[handle.Index] explicitly
  (new SdkHistoryReadResult { StatusCode = BadHistoryOperationUnsupported }) — don't rely on
  base pre-seeding results[i] so every path sets BOTH errors and results coherently (#1)
- ProjectEventField: SourceName null now emits Variant.Null instead of a String-typed null
  variant (evt.SourceName is null ? Variant.Null : new Variant(evt.SourceName)) (#3)
- Comment near the HistoryRead dispatcher block updated: all four arms (Raw/Processed/AtTime
  + Events/Task 4) are now overridden — "left to the base" wording was stale (#5)
- Happy-path test adds ReceiveTime to select clauses and asserts it projects ReceivedTimeUtc
  as a DateTime Variant at the correct select-order position (#4)
- Backend-throw test hardened: asserts errors[0] via ServiceResult.IsBad + explicit code,
  asserts results[0] is non-null with the Bad code (no longer relies on base seeding),
  and asserts EventsEntered to prove the override reached the bridge before the throw (#1)
- RecordingHistorianDataSource gains EventsEntered flag (set before ThrowOnRead check) (#1)
- Events_non_source_node test gains clarifying doc comment explaining the SDK base rejects
  variable nodes (EventNotifier=None) for event reads before our override runs; the
  override's source-guard is exercised by the promoted-without-source test instead (#2)
2026-06-14 20:10:16 -04:00
Joseph Doherty e3c0ef7b41 feat(historian): HistoryReadEvents over equipment-folder notifiers + event-field projection 2026-06-14 19:56:38 -04:00
Joseph Doherty 059f18bdad test(historian): multi-node HistoryRead isolation + single-lookup ServeNode + comment fix
Fix A: add Raw_multi_node_per_node_error_isolation test — two historized variables
(eqA/good→A.PV, eqB/bad→B.PV) in one Raw batch; per-tagname fake throws for B.PV,
returns a sample for A.PV; asserts errors[0]=Good+sample, errors[1]=Bad,
HistoryData[1]=null (no cross-slot leak), no exception escapes.

Fix B: collapse double ConcurrentDictionary lookup in ServeNode — TryGetHistorizedTagname
now captures `out var tagname` on the guard; the resolved tagname is threaded into the
read callback as a second parameter (Func<IHistorianDataSource, string, Task<HistorianRead>>),
removing the redundant ResolveTagname helper (deleted) and the tiny race window between
the check and the second lookup.  All three call-sites (Raw/Processed/AtTime) updated.

Fix C: rewrite the IsReadModified comment at NodeManagerHistoryReadTests.cs:102 — the
SDK's ReadRawModifiedDetails.Initialize() sets m_isReadModified=true (generated ctor body
in Opc.Ua.DataTypes.cs), so the default IS true; the test must explicitly clear it to
false for a plain raw read.  Previous comment said the same thing but imprecisely; now
cites the SDK mechanism (Initialize() call in the public ctor).
2026-06-14 19:44:56 -04:00
Joseph Doherty 13fba8f8fb feat(historian): HistoryRead override (Raw/Processed/AtTime) over IHistorianDataSource 2026-06-14 19:31:39 -04:00
Joseph Doherty 50e1141fc2 test(historian): assert Deferred sink forwards historianTagname + doc nits
I1: DeferredAddressSpaceSinkTests.RecordingSink now captures HistorianTagname
per EnsureVariable call (HistorianQueue/HistorianCalls, matching the
Phase7ApplierTests pattern); new test EnsureVariable_forwards_historianTagname_to_inner_sink
asserts the arg is forwarded unchanged through DeferredAddressSpaceSink.

M1: OtOpcUaNodeManager.EnsureVariable doc-comment notes that a changed
historize intent on an already-registered node is silently ignored until
a RebuildAddressSpace (rebuild precondition for Task 3 implementers).

N2: DeploymentArtifact.ExtractTagHistorize doc wording: "The live-edit
side" → "The live-edit composer side".
2026-06-14 19:16:23 -04:00
Joseph Doherty 6041dc202b feat(historian): materialise historized vars with Historizing + HistoryRead bit + NodeId->tagname map 2026-06-14 19:09:32 -04:00
Joseph Doherty c35c1d3734 refactor(historian): single-parse ExtractTagHistorize + review-nit tests/docs
Stop parsing TagConfig twice per tag on the deploy hot path: Phase7Composer's
equipment-tag Select lambda is now block-bodied (captures isHistorized/historianTagname
once), and DeploymentArtifact.BuildEquipmentTagPlans captures locals before result.Add.
Add wrong-type-historianTagname InlineData to ExtractTagHistorizeTests. Extend the
parity round-trip fixture with a 4th tag (isHistorized:false + JSON-null tagname)
exercising the artifact-side private guard path. Align DeploymentArtifact's
ExtractTagHistorize doc-comment with the composer-side phrasing (ExtractTagFullName /
ExtractTagAlarm cross-reference).
2026-06-14 19:02:02 -04:00
Joseph Doherty 440929c82a feat(historian): carry isHistorized + historianTagname through EquipmentTagPlan (byte-parity) 2026-06-14 18:55:04 -04:00
Joseph Doherty fb906f26ac docs(historian): Phase C HistoryRead implementation plan + tasks 2026-06-14 18:48:33 -04:00
Joseph Doherty 5e42c1bc38 docs(historian): Phase C server-side HistoryRead design 2026-06-14 18:46:43 -04:00
32 changed files with 3377 additions and 37 deletions
+4
View File
@@ -181,3 +181,7 @@ See `docs/ScriptEditor.md` for the full guide. Scripts may use the `{{equip}}` t
## Scripted Alarm Ack/Shelve
Inbound operator acknowledge/shelve for scripted alarms is fully implemented. Two surfaces converge on the `alarm-commands` DPS topic: (1) OPC UA Part 9 condition methods (Acknowledge / Confirm / AddComment / OneShotShelve / TimedShelve / Unshelve) wired in `OtOpcUaNodeManager`, gated on the `AlarmAck` LDAP role via `RoleCarryingUserIdentity`; (2) AdminUI `/alerts` per-row buttons routed through the `AdminOperationsActor` singleton (gated by `DriverOperator` policy). `ScriptedAlarmHostActor` dispatches from the topic to the engine. Client.CLI supports `ack`, `confirm`, `shelve` commands. See `docs/ScriptedAlarms.md` §"Inbound operator ack/shelve" and `docs/AlarmTracking.md`.
## Historian / HistoryRead
Server-side OPC UA HistoryRead for historized equipment tags is implemented driver-agnostically in Phase C. A tag is historized by adding `"isHistorized": true` to its `TagConfig` JSON blob (authored in the raw-JSON textarea on the `/uns` TagModal); an optional `"historianTagname"` field overrides the default historian tagname, which is the tag's driver `FullName`. The server dispatches all history reads to the registered `IHistorianDataSource` (Wonderware historian TCP client) via the `ServerHistorian` appsettings section (`Enabled` defaults to `false`; when disabled, a `NullHistorianDataSource` is used and historized nodes return `GoodNoData` rather than an error). Supported variants: Raw, Processed (Average/Minimum/Maximum/Total/Count aggregates), and AtTime over historized variable nodes; Events over alarm-owning equipment-folder event-notifier nodes. Reads are ungated (served from any redundancy node); authorization uses the standard `AccessLevels.HistoryRead` bit set at materialization. See `docs/Historian.md` for the full guide.
+212
View File
@@ -0,0 +1,212 @@
# Historian — server-side OPC UA HistoryRead (Phase C)
Phase C wires server-side OPC UA **HistoryRead** for authored equipment tags flagged
historized. The feature is driver-agnostic: any equipment tag (Galaxy, Modbus, OpcUaClient,
or any other driver) can be marked historized; the server dispatches all history reads to the
registered `IHistorianDataSource` — today, the Wonderware sidecar client
(`WonderwareHistorianClient`). No EF migration is required; the historian flag rides in the
existing schemaless `TagConfig` JSON blob alongside the Phase B `alarm` object.
Design reference: [docs/plans/2026-06-14-galaxy-phase-c-historian-design.md](plans/2026-06-14-galaxy-phase-c-historian-design.md).
---
## Historized TagConfig schema
A tag is historized by adding fields to its `TagConfig` blob on the `/uns` equipment page
Tags tab (raw-JSON textarea). No separate UI control exists — Galaxy (the primary use case)
already uses the raw-JSON editor.
### Fields
| Field | Type | Required | Description |
|---|---|---|---|
| `isHistorized` | bool | yes | Marks the tag historized. Materialises the OPC UA node with `Historizing=true` and the `HistoryRead` AccessLevel bit. |
| `historianTagname` | string | no | Explicit historian tagname to query. When absent or empty, defaults to the tag's driver `FullName` (the `TagConfig.FullName`). |
### Examples
Default historian tagname (uses `FullName` = `TestMachine_002.TestFloat`):
```json
{"FullName":"TestMachine_002.TestFloat","isHistorized":true}
```
Explicit historian tagname override:
```json
{"FullName":"TestMachine_002.TestFloat","isHistorized":true,"historianTagname":"Plant.Line1.Flow"}
```
A tag that is both historized and a native alarm:
```json
{"FullName":"TestMachine_002.HiAlarm","isHistorized":true,"alarm":{"alarmType":"OffNormalAlarm","severity":700}}
```
---
## ServerHistorian configuration
The `ServerHistorian` section in `appsettings.json` controls the historian read path.
`Enabled` defaults to `false`; when disabled, the server registers `NullHistorianDataSource`
and all HistoryRead calls on historized nodes return `GoodNoData` (empty, not an error).
```json
{
"ServerHistorian": {
"Enabled": false,
"Host": "localhost",
"Port": 32569,
"UseTls": false,
"ServerCertThumbprint": "",
"SharedSecret": ""
}
}
```
| Key | Type | Default | Description |
|---|---|---|---|
| `Enabled` | bool | `false` | Enable the live `WonderwareHistorianClient`. `false` → `NullHistorianDataSource` (empty reads). |
| `Host` | string | `localhost` | DNS name or IP of the machine running the historian sidecar. |
| `Port` | int | `32569` | TCP port the sidecar listens on (`OTOPCUA_HISTORIAN_TCP_PORT`). |
| `UseTls` | bool | `false` | Wrap the TCP connection in TLS. |
| `ServerCertThumbprint` | string | — | Optional SHA-1 thumbprint to pin the sidecar's TLS certificate. Leave empty for CA-chain validation. |
| `SharedSecret` | string | — | Shared secret token the sidecar expects on every connection. Required when `Enabled`. |
> **Do not commit `SharedSecret` to `appsettings.json`.** Set it via an environment variable,
> a secrets store, or a deployment-time overlay. The checked-in default is always empty.
The `ServerHistorian` section is independent of the `AlarmHistorian` section (the alarm
write path). They share the same Wonderware sidecar process but hold separate client
instances and separate `SharedSecret` values.
---
## HistoryRead behavior
### Read variants
The server supports all four OPC UA HistoryRead variants:
| Variant | Node type | CLI `--aggregate` |
|---|---|---|
| **Raw** | Historized variable | (omit `--aggregate`) |
| **Processed** | Historized variable | `Average`, `Minimum`, `Maximum`, `Total`, `Count` |
| **AtTime** | Historized variable | n/a (client supplies exact timestamps) |
| **Events** | Equipment folder (event notifier) | n/a |
**Variable nodes** (historized tags) serve Raw, Processed, and AtTime history.
`Historizing=true` and `AccessLevels.HistoryRead` are set at materialization so any compliant
OPC UA client can discover historized capability from the node's attributes.
**Equipment-folder event-notifier nodes** serve Event history. Every equipment folder that
owns at least one alarm condition is already an event notifier; the server registers a
`sourceName` (the equipment id) for each such folder and maps event history reads to the
Wonderware historian using that source. Event-field projection supports the standard
`BaseEventType` select clauses — `EventId`, `SourceName`, `Time`, `ReceiveTime`, `Message`,
and `Severity`; an unsupported select operand returns a null field (spec-conformant).
### Graceful degradation
| Situation | HistoryRead status |
|---|---|
| Historized node, historian configured and reachable, results found | `Good` |
| Historized node, historian configured, time range empty | `GoodNoData` |
| Historized node, historian NOT configured (`Enabled=false` / Null source) | `GoodNoData` (empty) |
| Non-historized node | `BadHistoryOperationUnsupported` |
| Backend timeout or exception | `BadHistoryOperationUnsupported` per node; other nodes in the same batch are unaffected |
A historized node with no historian configured never returns an error status — it returns
empty. This means a deployment can author and publish historized tags before the historian
sidecar is provisioned, without producing error spikes in connected clients.
### Known limitations
- **No server-managed continuation points.** Each HistoryRead call is single-shot. The server
honors the client's `NumValuesPerNode` limit but does not issue continuation points for
large result sets. Paging across multiple calls is a documented follow-up.
- **No modified-value history** (`HistoryReadModified`). Requests for modified values return
`BadHistoryOperationUnsupported`. This is a follow-up.
### Redundancy and authorization
History reads are served from any node — there is no Primary gate. Authorization is the
standard OPC UA `HistoryRead` permission enforced by the SDK through the `AccessLevels.HistoryRead`
bit set at materialization. A session without sufficient permissions receives
`BadUserAccessDenied` from the SDK before the dispatch reaches the historian.
---
## Authoring workflow
1. Open the equipment's **Tags** tab on `/uns/equipment/{id}`.
2. Create or edit the tag. Because Galaxy uses the raw-JSON editor, add `"isHistorized":true`
(and optionally `"historianTagname":"..."`) directly in the TagConfig textarea.
3. Save and publish. The server rebuilds its address space; the node materialises with
`Historizing=true` and the `HistoryRead` AccessLevel bit.
4. Confirm with Client.CLI `read` that the node's `Status` is `Good` and that the value
is updating. Then issue a `historyread` to verify the historian connection returns data.
---
## Client.CLI historyread examples
The `historyread` command reads historical data from any node. Supply start and end times in
ISO 8601 UTC form. See [docs/Client.CLI.md](Client.CLI.md) for the full flag reference.
```bash
# Raw history for a historized Galaxy tag (last 24 hours by default)
otopcua-cli historyread \
-u opc.tcp://localhost:4840/OtOpcUa \
-n "ns=2;s=EQ-55297329838d/GalaxyTestTag" \
--start "2026-06-13T00:00:00Z" --end "2026-06-14T00:00:00Z"
# Limit to 100 values
otopcua-cli historyread \
-u opc.tcp://localhost:4840/OtOpcUa \
-n "ns=2;s=EQ-55297329838d/GalaxyTestTag" \
--start "2026-06-13T00:00:00Z" --end "2026-06-14T00:00:00Z" \
--max 100
# 1-hour average aggregate
otopcua-cli historyread \
-u opc.tcp://localhost:4840/OtOpcUa \
-n "ns=2;s=EQ-55297329838d/GalaxyTestTag" \
--start "2026-06-13T00:00:00Z" --end "2026-06-14T00:00:00Z" \
--aggregate Average --interval 3600000
# Authenticated read (ReadOnly role or higher required)
otopcua-cli historyread \
-u opc.tcp://localhost:4840/OtOpcUa \
-n "ns=2;s=EQ-55297329838d/GalaxyTestTag" \
--start "2026-06-13T00:00:00Z" --end "2026-06-14T00:00:00Z" \
-U reader -P password
```
Supported `--aggregate` values: `Average`, `Minimum`, `Maximum`, `Count`, `Start`, `End`,
`StandardDeviation` (aliases: `avg`, `min`, `max`, `stddev`/`stdev`, `first`, `last`).
`--interval` is the processing interval in milliseconds (default 3600000 = 1 hour).
---
## Live /run gate
The live read gate requires the Wonderware historian sidecar running on the WW Historian VM
(`10.100.0.48`) and AVEVA Historian healthy. Set `ServerHistorian:Enabled=true` with the
correct `Host`, `Port`, and `SharedSecret` in `appsettings.json` (or via environment
variables), then deploy and publish at least one historized Galaxy tag. The gate is
operator-driven — it is not part of the local docker-dev rig.
See [AlarmHistorian.md](AlarmHistorian.md) for the historian sidecar setup and
[ServiceHosting.md](ServiceHosting.md) for the sidecar service configuration.
---
## See also
- [docs/plans/2026-06-14-galaxy-phase-c-historian-design.md](plans/2026-06-14-galaxy-phase-c-historian-design.md) — full design and implementation notes
- [AlarmHistorian.md](AlarmHistorian.md) — alarm write path; shares the same Wonderware sidecar
- [AlarmTracking.md](AlarmTracking.md) — OPC UA Part 9 alarm surface (event history source)
- [Client.CLI.md](Client.CLI.md) — full `historyread` flag reference
- [ScriptedAlarms.md](ScriptedAlarms.md) §"Native driver alarms" — the Phase B `alarm` object in `TagConfig` (parallel carrier)
@@ -0,0 +1,229 @@
# Galaxy Phase C — Server-side OPC UA HistoryRead — Design
**Date:** 2026-06-14
**Status:** Approved (brainstorming) — ready for implementation planning
**Branch:** `feat/galaxy-phase-c-historian` off master `c9a0f627`
**Parent design:** `docs/plans/2026-06-12-galaxy-standard-driver-design.md` (workstream 3 / Phase C).
**Follow-up:** `pending.md` open item #2 ("Phase C — server-side `HistoryRead` backend over the Wonderware reader").
## Goal
Make the OtOpcUa server answer OPC UA **HistoryRead** for an authored equipment tag flagged
historized — driver-agnostically — by dispatching to the already-built, already-hardened
server-side `IHistorianDataSource` (the Wonderware TCP client). No mxaccessgw history RPC; no EF
migration. A historized tag's raw / processed / at-time samples and an equipment folder's
event-history come back to any OPC UA client (e.g. `Client.CLI historyread`).
## What already exists (grounded in code, 2026-06-14)
Phase C is **mostly wiring** — the read surface is built:
- **`IHistorianDataSource`** (`src/Core/.../Core.Abstractions/Historian/IHistorianDataSource.cs`) —
the server-side read seam, with **required** `ReadRawAsync` / `ReadProcessedAsync` /
`ReadAtTimeAsync` / `ReadEventsAsync` / `GetHealthSnapshot`. Returns
`HistoryReadResult(IReadOnlyList<DataValueSnapshot> Samples, byte[]? ContinuationPoint)` and
`HistoricalEventsResult(IReadOnlyList<HistoricalEvent> Events, byte[]? ContinuationPoint)`
(both in `IHistoryProvider.cs`). `DataValueSnapshot(object? Value, uint StatusCode,
DateTime? SourceTimestampUtc, DateTime ServerTimestampUtc)` mirrors `Opc.Ua.DataValue`.
- **`WonderwareHistorianClient`** (`Driver.Historian.Wonderware.Client`, .NET 10) **implements
`IHistorianDataSource`** over a hardened TCP/TLS/shared-secret channel. The **Host is the only
project that references it** (same as the alarm-historian writer).
- **`DriverAttributeInfo.IsHistorized`** already exists; Galaxy + OpcUaClient drivers populate it
(informational — the equipment-tag path does not consume `DriverAttributeInfo`, it carries
`TagConfig`; see below).
- **The Phase B `alarm`-object-in-`TagConfig` carrier** — `EquipmentTagPlan.Alarm` parsed by
`Phase7Composer.ExtractTagAlarm` and the byte-parity `DeploymentArtifact.ExtractTagAlarm`. This is
the **exact precedent** for carrying `isHistorized` / `historianTagname`.
- **The wiring pattern** — the node manager exposes settable props (`AlarmCommandRouter`,
`NodeWriteGateway`); `OtOpcUaSdkServer.Set*` methods set them; the Host's
`OtOpcUaServerHostedService.StartAsync` wires them post-start.
- **The DI pattern** — `AddAlarmHistorian(config, writerFactory)` (Null default via
`AddOtOpcUaRuntime`'s `TryAddSingleton`, config-gated real impl), Host supplies the Wonderware
client factory in `Program.cs`.
- **`EnsureFolderIsEventNotifier`** already promotes alarm-owning equipment folders to
`EventNotifiers.SubscribeToEvents` + `AddRootNotifier` (guarded by `_notifierFolders`).
## What's missing (the Phase C work)
1. **No `HistoryRead` override.** `OtOpcUaNodeManager : CustomNodeManager2` overrides only
`CreateAddressSpace`. `Historizing` is hardcoded `false` in `EnsureVariable` (`:846`) and
`CreateVariable` (`:977`); no `AccessLevels.HistoryRead` bit, no event-notifier `HistoryRead` bit.
2. **No carrier for `isHistorized` / `historianTagname`** through `EquipmentTagPlan` → artifact →
materialization.
3. **No `IHistorianDataSource` registration / Null default / node-manager wiring / config section.**
## Locked decisions (this Phase C brainstorming)
| Decision | Choice |
|---|---|
| Read variants | **All four** — Raw, Processed, AtTime over historized **variable** nodes; **Events** over historized **equipment-folder** event-notifier nodes. (User-selected.) |
| Authoring | **Raw `TagConfig` JSON** — `"isHistorized": true` (+ optional `"historianTagname"`) rides in the existing `TagConfig` blob, mirroring the Phase B `alarm` object. **No UI control, no EF migration.** Galaxy already uses the raw-JSON tag editor. (User-selected.) |
| Tagname mapping | Default = the tag's driver **`FullName`** (already on `EquipmentTagPlan`); optional explicit override via `TagConfig.historianTagname`. |
| Async bridge | The override is **synchronous** and blocks on the async data source with its own call-timeout. **No actor** — HistoryRead is read-only and is **not** invoked under the node-manager `Lock` (unlike `OnWriteValue`), so blocking is safe and won't freeze the address space. |
| Redundancy / auth | **No Primary gate** (reads are safe from any node). Auth is the standard `NodePermissions.HistoryRead` enforced by the SDK via the `AccessLevels.HistoryRead` bit we set at materialization. |
| Graceful degrade | A **`NullHistorianDataSource`** (returns empty `Samples` / `Events`) is the default. A historized node with the Null source returns **`GoodNoData`** (empty), not an error spike (parent-design invariant). A **non-historized** node returns `BadHistoryOperationUnsupported`. |
| Continuation points | **Single-shot** read honoring the client's `NumValuesPerNode`; `results[i].ContinuationPoint = null`. `releaseContinuationPoints == true` → `Good` (we never issue one). Server-managed paging is an explicit follow-up. |
| Config | New **`ServerHistorian`** appsettings section (`Host`/`Port`/`SharedSecret`/`UseTls`/`ServerCertThumbprint`/`Enabled`) + `AddServerHistorian(config, factory)`, mirroring `AlarmHistorian`. Independent of the alarm-write path (its own enable + its own client instance to the same sidecar). |
### Rejected / out of scope
- **Server-object fleet-wide event history.** The Server object belongs to the SDK's
`CoreNodeManager`, not ours; the `MasterNodeManager` routes HistoryRead by node ownership. We expose
event history only on **our** equipment-folder event-notifiers (per-equipment `sourceName`). Clean
ownership boundary.
- **An historian read actor** (mirroring `HistorianAdapterActor`). The write path needs an actor for
fire-and-forget + redundancy gating; reads are synchronous, ungated, and ownerless — a direct
blocking bridge is simpler and correct.
- **Continuation-point paging / `HistoryUpdate` / live UI authoring control.** Follow-ups.
## Carrier seam (mirrors Phase B `alarm` exactly)
```
Tag.TagConfig JSON { "FullName":"…", "isHistorized":true, "historianTagname":"…"? , "alarm":{…}? }
→ Phase7Composer.ExtractTagHistorize(tagConfig) → (bool IsHistorized, string? HistorianTagname)
→ EquipmentTagPlan { …, IsHistorized, HistorianTagname } (+2 fields)
→ ConfigComposer snapshot → artifact JSON
→ DeploymentArtifact.ExtractTagHistorize(tagConfig) ← BYTE-PARITY copy of the composer parse
→ Phase7Applier.MaterialiseEquipmentTags
historianTagname := tag.IsHistorized ? (tag.HistorianTagname ?? tag.FullName) : null
→ IOpcUaAddressSpaceSink.EnsureVariable(…, string? historianTagname) (+1 nullable param)
→ OtOpcUaNodeManager.EnsureVariable
if historianTagname is not null:
Historizing = true
AccessLevel |= AccessLevels.HistoryRead (Read + History; ReadWrite + History)
_historizedTagnames[nodeId] = historianTagname
```
**Single nullable param.** The sink seam gains exactly one `string? historianTagname` (null ⇒ not
historized) across `IOpcUaAddressSpaceSink` / `NullOpcUaAddressSpaceSink` /
`DeferredAddressSpaceSink` / `SdkAddressSpaceSink` / `Phase7Applier.SafeEnsureVariable`. The applier
resolves default-vs-override so the node manager just consumes the final tagname.
## HistoryRead dispatch (the new override)
`OtOpcUaNodeManager` gains a settable `public IHistorianDataSource HistorianDataSource { get; set; }`
(defaults to `NullHistorianDataSource.Instance`; volatile-backed like `NodeWriteGateway`) and a
`ConcurrentDictionary<string,string> _historizedTagnames` (NodeId-string → historian tagname).
Override the `CustomNodeManager2` HistoryRead surface. **The exact override point is version-sensitive
— the implementer confirms it** against the installed `OPCFoundation.NetStandard.Opc.Ua.Server`
(use the DeepWiki MCP `OPCFoundation/UA-.NETStandard`, per CLAUDE.md). Recommended: override the
per-details protected virtuals (`HistoryReadRawModified` / `HistoryReadProcessed` /
`HistoryReadAtTime` / `HistoryReadEvents`); fallback: override the single `HistoryRead` and switch on
`details`. Per `nodesToRead[i]`:
- **Resolve.** NodeId.Identifier (string) → `_historizedTagnames`. Miss ⇒
`errors[i] = BadHistoryOperationUnsupported`, `Processed = true`. (Reading `_historizedTagnames`
needs **no `Lock`** — it's a concurrent dict.)
- **Data (variable nodes):** switch on the details type →
`HistorianDataSource.ReadRawAsync(tagname, start, end, NumValuesPerNode, ct)` /
`ReadProcessedAsync(…interval, MapAggregate(aggregateId)…)` /
`ReadAtTimeAsync(tagname, reqTimes, ct)`. Block with the data source's timeout
(`.GetAwaiter().GetResult()` inside `try`). Map each `DataValueSnapshot` →
`Opc.Ua.DataValue(new Variant(Value), new StatusCode(StatusCode), SourceTs, ServerTs)`; wrap the
list in `HistoryData { DataValues = … }`; set `results[i].HistoryData =
new ExtensionObject(historyData)`, `results[i].StatusCode = samples.Count == 0 ? GoodNoData : Good`,
`ContinuationPoint = null`, `Processed = true`.
- **Events (equipment-folder notifier nodes):** `ReadEventDetails` target folder →
`_eventNotifierSources[folderNodeId]` (`sourceName`, default = the folder's string id = equipment
id, registered when `EnsureFolderIsEventNotifier` promotes it) →
`ReadEventsAsync(sourceName, start, end, maxEvents, ct)`. Project each `HistoricalEvent` into a
`HistoryEventFieldList` per the request's `ReadEventDetails.Filter` SelectClauses — support the
standard `BaseEventType` operands (`EventId`, `SourceName`, `Time`, `Message`, `Severity`); an
unsupported operand yields a `null` field (spec-conformant). Wrap in `HistoryEvent { Events = … }`.
- **Errors never escape.** A backend throw / timeout → `errors[i] = BadHistoryOperationUnsupported`
(or `BadUnexpectedError`) + log; one node's failure never faults the batch.
`MapAggregate(NodeId aggregateId)` maps the OPC UA Part 13 aggregate NodeIds
(`ObjectIds.AggregateFunction_Average/Minimum/Maximum/Total/Count`) → `HistoryAggregateType`; an
unsupported aggregate ⇒ `BadAggregateNotSupported`.
## Materialization: Historizing + access bits
- **Variable nodes** — `EnsureVariable` sets `Historizing = historianTagname is not null` and ORs
`AccessLevels.HistoryRead` into both `AccessLevel` and `UserAccessLevel` when historized; registers
`_historizedTagnames`. `CreateVariable` (lazy, never historized) stays `Historizing = false`.
- **Event-notifier folders** — `EnsureFolderIsEventNotifier` ORs `EventNotifiers.HistoryRead` into the
promoted folder's `EventNotifier` **when a non-Null historian is wired**, and registers
`_eventNotifierSources[folder.NodeId-string] = folder.NodeId.Identifier` (the equipment id). On
`RebuildAddressSpace`, clear `_historizedTagnames` + `_eventNotifierSources` alongside the existing
guards.
## Wiring + DI
- **`NullHistorianDataSource`** (Core.Abstractions/Historian) — empty `Samples`/`Events`, disabled
health snapshot. The node-manager prop default + the DI default.
- **`ServerHistorianOptions`** (Runtime/Historian, `SectionName = "ServerHistorian"`) +
**`AddServerHistorian(this IServiceCollection, IConfiguration, Func<ServerHistorianOptions,
IServiceProvider, IHistorianDataSource> factory)`** — `Enabled=false` ⇒ no-op (Null default from
`AddOtOpcUaRuntime`'s new `TryAddSingleton<IHistorianDataSource>(NullHistorianDataSource.Instance)`);
`Enabled=true` ⇒ `AddSingleton` the factory result; `Validate()` warnings mirror `AlarmHistorian`.
- **`OtOpcUaSdkServer.SetHistorianDataSource(IHistorianDataSource?)`** — mirrors
`SetNodeWriteGateway` (null-coalesces to the Null default; returns false if NodeManager not up yet).
- **Host** — `Program.cs` adds `AddServerHistorian(config, (opts,sp) => new WonderwareHistorianClient(
new WonderwareHistorianClientOptions(opts.Host, opts.Port, opts.SharedSecret){ UseTls=…,
ServerCertThumbprint=… }, sp.GetService<ILogger<WonderwareHistorianClient>>()))`;
`OtOpcUaServerHostedService.StartAsync` resolves `IHistorianDataSource` from DI and calls
`_server.SetHistorianDataSource(...)` (right after `SetNodeWriteGateway`); `StopAsync` clears it.
## Error handling / edge cases
- **Byte-parity invariant** — `Phase7Composer.ExtractTagHistorize` and
`DeploymentArtifact.ExtractTagHistorize` must parse identically; a parity round-trip test guards it
(precedent: `DeploymentArtifactAliasParityTests`).
- **Non-historized HistoryRead** → `BadHistoryOperationUnsupported` (node not in
`_historizedTagnames`); the SDK's own `AccessLevel` check already blocks most before we see them.
- **Null / unconfigured historian** → `GoodNoData` empty (not an error).
- **Backend timeout / throw** → per-node `BadHistoryOperationUnsupported` + log; batch survives.
- **Redeploy** → `RebuildAddressSpace` clears the two new maps; re-materialization re-registers.
## Testing (no bUnit, offline xUnit + Shouldly)
- **Composer** `ExtractTagHistorize` — true / false / absent / override / malformed-JSON (never throws).
- **Artifact parity** — composer plan == artifact plan for a historized tag (incl. override) round-trip.
- **`EnsureVariable`** — historized ⇒ `Historizing==true` + `HistoryRead` access bit + registry entry;
non-historized ⇒ unchanged; default-vs-override tagname resolution in the applier.
- **HistoryRead override (data)** — fake `IHistorianDataSource`; assert Raw / Processed / AtTime
dispatch, tagname passed (default + override), `DataValueSnapshot→DataValue` mapping (value / status
/ timestamps), `GoodNoData` on empty, `BadHistoryOperationUnsupported` on non-historized,
`BadAggregateNotSupported` on an unknown aggregate.
- **HistoryRead override (events)** — fake source; assert folder→sourceName resolution + event-field
projection for the standard select clauses + empty/Null.
- **DI** — `AddServerHistorian` leaves Null when disabled, swaps the real source when enabled;
`NullHistorianDataSource` returns empty.
**Live docker-dev `/run` (user-driven; the agent does NOT sign in) — DEFERRED.** Requires the
Wonderware sidecar + AVEVA Historian (the WW Historian VM `10.100.0.48`), which is not part of the
local docker-dev rig, so this gate is inherently operator-driven. When run: author a historized Galaxy
equipment tag, set `ServerHistorian:Enabled=true` pointed at the sidecar, deploy, then
`Client.CLI historyread` → samples return.
## Hard rules (carried into implementation)
- Stage by path; never `git add .`. Never stage `sql_login.txt`,
`src/Server/ZB.MOM.WW.OtOpcUa.Host/pki/`, `pending.md`, `current.md`, or
`docker-dev/docker-compose.yml`. Never echo the gateway API key or the historian `SharedSecret` into
a tracked file. No force-push, no `--no-verify`.
- **NO EF/Configuration entity or migration change** — the flag rides in the existing `TagConfig` blob
(the Phase A `NamespaceKind` migration was a one-off already shipped; Phase C adds none).
- Build on `feat/galaxy-phase-c-historian` off master `c9a0f627`.
## Authoritative touched-code list
- `src/Server/.../OpcUaServer/Phase7Composer.cs` — `EquipmentTagPlan` +2 fields; `ExtractTagHistorize`.
- `src/Server/.../Runtime/Drivers/DeploymentArtifact.cs` — byte-parity `ExtractTagHistorize` + thread.
- `src/Core/.../Commons/OpcUa/IOpcUaAddressSpaceSink.cs` (+ `NullOpcUaAddressSpaceSink`,
`DeferredAddressSpaceSink`) — `EnsureVariable` gains `string? historianTagname`.
- `src/Server/.../OpcUaServer/SdkAddressSpaceSink.cs` — pass-through.
- `src/Server/.../OpcUaServer/Phase7Applier.cs` — resolve + thread the tagname.
- `src/Server/.../OpcUaServer/OtOpcUaNodeManager.cs` — `HistorianDataSource` prop, `_historizedTagnames`,
`_eventNotifierSources`, `EnsureVariable`/`EnsureFolderIsEventNotifier`/`RebuildAddressSpace` edits,
the HistoryRead override + mapping helpers.
- `src/Server/.../OpcUaServer/OtOpcUaSdkServer.cs` — `SetHistorianDataSource`.
- `src/Core/.../Core.Abstractions/Historian/NullHistorianDataSource.cs` (new).
- `src/Server/.../Runtime/Historian/ServerHistorianOptions.cs` (new) +
`src/Server/.../Runtime/ServiceCollectionExtensions.cs` — `AddServerHistorian` + Null default in
`AddOtOpcUaRuntime`.
- `src/Server/.../Host/Program.cs` + `Host/OpcUa/OtOpcUaServerHostedService.cs` — wire the data source.
- Docs: new `docs/Historian.md` (or a Galaxy-driver note) + a `CLAUDE.md` pointer; `appsettings.json`
`ServerHistorian` block (disabled).
@@ -0,0 +1,300 @@
# Galaxy Phase C — Server-side HistoryRead — Implementation Plan
> **For Claude:** REQUIRED SUB-SKILL: use superpowers-extended-cc:subagent-driven-development (or executing-plans) to implement this plan task-by-task.
**Goal:** Answer OPC UA HistoryRead (Raw / Processed / AtTime / Events) for historized equipment
tags by dispatching to the existing `IHistorianDataSource` (Wonderware TCP client). Authoring via a
`"isHistorized"` flag in the existing `TagConfig` blob — **no UI, no EF migration**.
**Architecture:** Carry `isHistorized`/`historianTagname` through the Phase-B `alarm`-object seam
(`TagConfig` → `EquipmentTagPlan` → byte-parity artifact → `EnsureVariable`), set `Historizing` +
`AccessLevels.HistoryRead`, register a NodeId→tagname map, and override `CustomNodeManager2`'s
HistoryRead surface to block-bridge onto the async data source. Config-gated DI mirrors
`AddAlarmHistorian`; the Host supplies the Wonderware client.
**Tech Stack:** .NET 10, OPC Foundation `Opc.Ua.Server` (`CustomNodeManager2`), Akka-free node
manager, xUnit + Shouldly.
**Design:** `docs/plans/2026-06-14-galaxy-phase-c-historian-design.md` (read for the locked decisions).
---
## Execution notes (hard rules — every task)
- **Branch:** `feat/galaxy-phase-c-historian` (already created off master `c9a0f627`). Do NOT work on
master.
- **Stage by path; never `git add .`.** Never stage `sql_login.txt`,
`src/Server/ZB.MOM.WW.OtOpcUa.Host/pki/`, `pending.md`, `current.md`, or
`docker-dev/docker-compose.yml`. Never echo the gateway API key or historian `SharedSecret` into a
tracked file. No force-push, no `--no-verify`.
- **NO EF/Configuration entity or migration change.** The flag rides in `TagConfig` JSON.
- **NO bUnit** — there is no UI in Phase C; everything here is offline-unit-testable. The live `/run`
is deferred (Task 7).
- Production projects are `TreatWarningsAsErrors` — keep the build at **0 warnings** in `src/`.
- Each task: write the failing test, see it fail, implement minimally, see it pass, then commit by path.
---
### Task 0: Feature branch (already created)
**Classification:** trivial · **Estimated implement time:** ~0 min · **Parallelizable with:** none
Precondition met — `feat/galaxy-phase-c-historian` exists off master `c9a0f627`, design committed
`5e42c1bc`. No action.
---
### Task 1: Carry `isHistorized` + `historianTagname` (composer + artifact, byte-parity)
**Classification:** standard · **Estimated implement time:** ~5 min · **Parallelizable with:** none
Mirror the Phase B `alarm`-object carrier exactly.
**Files:**
- Modify: `src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Phase7Composer.cs`
- `EquipmentTagPlan` record (`:82-91`): add `bool IsHistorized` and `string? HistorianTagname` as
the last two positional fields (update the doc-comment to mention they parse identically on the
artifact side, like `Alarm`).
- Add `internal static (bool IsHistorized, string? HistorianTagname) ExtractTagHistorize(string?
tagConfig)` next to `ExtractTagAlarm` (`:461`): parse `isHistorized` (bool; absent/non-bool ⇒
false) and `historianTagname` (string; absent/blank/non-string ⇒ null). Never throws (catch
`JsonException` ⇒ `(false, null)`). Carry the **byte-parity** comment naming
`DeploymentArtifact.ExtractTagHistorize`.
- In the `equipmentTags` `.Select(...)` (`:331-340`): set `IsHistorized` / `HistorianTagname` from
`ExtractTagHistorize(t.TagConfig)`.
- Modify: `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DeploymentArtifact.cs`
- Add a **byte-parity** `private static (bool, string?) ExtractTagHistorize(string? tagConfig)` next
to `ExtractTagAlarm` (`:658`), same parse, carrying the byte-parity comment naming the composer.
- In `BuildEquipmentTagPlans` (`:440-449`): thread the two new fields onto the `new
EquipmentTagPlan(...)`.
- Test: `tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/ExtractTagHistorizeTests.cs` (new; model on
`ExtractTagAlarmTests.cs`).
- Test: `tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DeploymentArtifactHistorizeParityTests.cs`
(new; model on `DeploymentArtifactAliasParityTests.cs`).
**Steps:**
1. Failing test `ExtractTagHistorizeTests`: `{"FullName":"T.A","isHistorized":true}` ⇒ `(true,null)`;
`+"historianTagname":"WW.Tag"` ⇒ `(true,"WW.Tag")`; absent ⇒ `(false,null)`; `"isHistorized":false`
⇒ `(false,null)`; malformed JSON / blank-tagname ⇒ `(false,null)` / `(true,null)`; never throws.
2. Run → fail (method missing). Implement `ExtractTagHistorize` + record fields + Select wiring. Run →
pass.
3. Failing test `DeploymentArtifactHistorizeParityTests`: build a snapshot with a historized tag (and
one with an override tagname), run it through `ConfigComposer`→artifact→`DeploymentArtifact`
decode, and assert the decoded `EquipmentTagPlan.IsHistorized`/`HistorianTagname` equal the
composer's for the same input (parity). Run → fail. Implement the artifact side. Run → pass.
4. `dotnet build` clean (0 warn); `dotnet test` the two projects green. Commit by path
(`Phase7Composer.cs`, `DeploymentArtifact.cs`, the two new test files).
---
### Task 2: Materialize historized — `Historizing` + `HistoryRead` bit + NodeId→tagname registry
**Classification:** standard · **Estimated implement time:** ~5 min · **Parallelizable with:** none
**Files:**
- Modify: `src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/IOpcUaAddressSpaceSink.cs` — `EnsureVariable`
signature gains a trailing `string? historianTagname` param (doc: null ⇒ not historized). Update the
`NullOpcUaAddressSpaceSink` no-op impl in the same file.
- Modify: `src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/DeferredAddressSpaceSink.cs` — pass the new param
through.
- Modify: `src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs` — pass-through.
- Modify: `src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Phase7Applier.cs` — `SafeEnsureVariable` (`:294`)
gains the param; `MaterialiseEquipmentTags` (`:200`) computes
`string? historianTagname = tag.IsHistorized ? (string.IsNullOrWhiteSpace(tag.HistorianTagname) ?
tag.FullName : tag.HistorianTagname) : null;` and passes it.
- Modify: `src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs`
- Add `private readonly ConcurrentDictionary<string,string> _historizedTagnames = new(StringComparer.Ordinal);`
- `EnsureVariable` (`:820`): take `string? historianTagname`; when non-null set `Historizing = true`,
OR `AccessLevels.HistoryRead` into both `AccessLevel`+`UserAccessLevel` (keep the writable
ReadWrite composite), and `_historizedTagnames[variableNodeId] = historianTagname`. When null,
behavior is exactly as today (`Historizing=false`).
- `RebuildAddressSpace` (`:889`): `_historizedTagnames.Clear();` alongside the other clears.
- Test: `tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/SdkAddressSpaceSinkTests.cs` (extend) — or a
new `NodeManagerHistorizeTests.cs` if cleaner. Reuse the node-manager harness in `SdkAddressSpaceSinkTests`
/ `EquipmentWriteGateTests`.
**Steps:**
1. Failing test: materialize a variable with `historianTagname:"WW.Tag"` ⇒ the node's `Historizing`
is true and `(AccessLevel & AccessLevels.HistoryRead) != 0`; a null tagname ⇒ `Historizing` false,
no History bit. (Expose a read path: the existing tests already reach `BaseDataVariableState` via
the node manager — assert on that, or add a small `TryGetVariable` test accessor if none exists.)
2. Run → fail. Thread the param through all five seam files + node manager. Run → pass.
3. Failing test (applier): a historized `EquipmentTagPlan` with no override ⇒ the sink receives
`historianTagname == FullName`; with an override ⇒ receives the override. (Use a recording fake
`IOpcUaAddressSpaceSink`.) Run → fail → implement the applier resolve → pass.
4. Build clean; the `OpcUaServer.Tests` suite green (existing `EnsureVariable` callers updated for the
new param). Commit by path.
---
### Task 3: HistoryRead override — Raw / Processed / AtTime + `NullHistorianDataSource` + wiring prop
**Classification:** high-risk · **Estimated implement time:** ~6 min · **Parallelizable with:** none
This is the load-bearing OPC UA service-level task.
**Files:**
- Create: `src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/Historian/NullHistorianDataSource.cs` —
singleton `Instance`; all reads return empty `HistoryReadResult`/`HistoricalEventsResult` (empty
list, null continuation); `GetHealthSnapshot()` returns a disabled snapshot; `Dispose()` no-op.
- Modify: `src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs`
- Add `private volatile IHistorianDataSource _historianDataSource = NullHistorianDataSource.Instance;`
+ `public IHistorianDataSource HistorianDataSource { get => _historianDataSource; set =>
_historianDataSource = value ?? NullHistorianDataSource.Instance; }` (doc mirrors `NodeWriteGateway`).
- **Confirm the override surface** of the installed `OPCFoundation.NetStandard.Opc.Ua.Server` first:
query the DeepWiki MCP (`OPCFoundation/UA-.NETStandard`, per CLAUDE.md) AND inspect the actual
base members (e.g. `grep`/decompile the referenced `Opc.Ua.Server.CustomNodeManager2` for
`HistoryRead`). RECOMMENDED: override the per-details protected virtuals
(`HistoryReadRawModified`, `HistoryReadProcessed`, `HistoryReadAtTime`); FALLBACK: override the
single public `HistoryRead(...)` and switch on `details`. Whatever the chosen surface, do **not**
invoke base for nodes we own (`_historizedTagnames` hit); mark `Processed`/fill `results[i]`.
- Per node: resolve `NodeId.Identifier` (string) in `_historizedTagnames`; miss ⇒
`BadHistoryOperationUnsupported`. On hit, dispatch to `_historianDataSource` (block with
`.GetAwaiter().GetResult()` in `try`/`catch` → per-node `BadHistoryOperationUnsupported`/
`BadUnexpectedError` + log; never fault the batch). Map `DataValueSnapshot` →
`Opc.Ua.DataValue`; wrap in `HistoryData`; `results[i].HistoryData = new ExtensionObject(data)`;
`StatusCode = samples.Count == 0 ? GoodNoData : Good`; `ContinuationPoint = null`. Handle
`releaseContinuationPoints == true` ⇒ `Good` no-op.
- `MapAggregate(NodeId)` helper → `HistoryAggregateType`; unknown ⇒ `BadAggregateNotSupported`.
- `DataValueSnapshot→DataValue` mapping helper (value Variant, StatusCode, source+server ts).
- Test: `tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/NodeManagerHistoryReadTests.cs` (new) — a
recording/fake `IHistorianDataSource`.
- Test: `tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/Historian/NullHistorianDataSourceTests.cs`
(new).
**Steps:**
1. Confirm the override surface (DeepWiki + assembly). Write `NullHistorianDataSource` + its test
(empty results). Run → pass.
2. Failing test (Raw): materialize a historized node; set a fake source returning 2 samples; invoke
the HistoryRead override with a `ReadRawModifiedDetails` + one `HistoryReadValueId` for the node;
assert the fake got `(tagname == FullName, start, end, numValues)`, the result decodes to a
`HistoryData` of 2 `DataValue`s with mapped value/status/timestamps, `StatusCode == Good`.
3. Run → fail. Add the prop + override + Raw path + mappers. Run → pass.
4. Add tests + impl for: Processed (aggregate mapping, `BadAggregateNotSupported` on unknown), AtTime
(request times passed through), default-vs-override tagname, empty ⇒ `GoodNoData`, non-historized
node ⇒ `BadHistoryOperationUnsupported`, backend-throw ⇒ per-node bad + batch survives.
5. Build clean; `OpcUaServer.Tests` + `Core.Abstractions.Tests` green. Commit by path.
---
### Task 4: HistoryRead override — Events over equipment-folder notifiers
**Classification:** high-risk · **Estimated implement time:** ~6 min · **Parallelizable with:** Task 5
**Files:**
- Modify: `src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs`
- Add `private readonly ConcurrentDictionary<string,string> _eventNotifierSources = new(StringComparer.Ordinal);`
- `EnsureFolderIsEventNotifier` (`:749`): when `_historianDataSource is not NullHistorianDataSource`,
OR `EventNotifiers.HistoryRead` into `folder.EventNotifier` (keep `SubscribeToEvents`); register
`_eventNotifierSources[folder.NodeId.Identifier?.ToString()] = folder.NodeId.Identifier?.ToString()`
(the equipment id = `sourceName`). (Reads the data-source field — fine; it's set before
materialization in the Host. If a deployment materializes before wiring, the bit is simply absent
until the next rebuild — acceptable; document it.)
- `RebuildAddressSpace`: `_eventNotifierSources.Clear();`.
- Events dispatch (the `ReadEventDetails` arm of the chosen override surface): resolve the target
folder NodeId in `_eventNotifierSources` (miss ⇒ `BadHistoryOperationUnsupported`); call
`_historianDataSource.ReadEventsAsync(sourceName, start, end, maxEvents, ct)` (block + guard);
project each `HistoricalEvent` → `HistoryEventFieldList` per `ReadEventDetails.Filter.SelectClauses`
— support `BaseEventType` operands `EventId`, `SourceName`, `Time`, `Message`, `Severity`; an
unsupported operand ⇒ `null` field; wrap in `HistoryEvent { Events = … }`; `StatusCode = Good`
(or `GoodNoData` when empty).
- `ProjectEventField(HistoricalEvent, SimpleAttributeOperand)` helper.
- Test: extend `NodeManagerHistoryReadTests.cs` — events arm.
**Steps:**
1. Failing test: promote a folder to a notifier with a wired (fake non-Null) source; invoke the
override with a `ReadEventDetails` (a select clause for EventId/SourceName/Time/Message/Severity)
on the folder; assert the fake got `(sourceName == equipmentId, …)` and each returned
`HistoryEventFieldList` carries the projected fields in select-clause order; an unsupported operand
⇒ null field; empty ⇒ `GoodNoData`; a non-notifier node ⇒ `BadHistoryOperationUnsupported`.
2. Run → fail. Implement the `_eventNotifierSources` map + folder-promotion bit + the events arm +
projector. Run → pass.
3. Build clean; `OpcUaServer.Tests` green. Commit by path.
---
### Task 5: DI + config + Host wiring (`AddServerHistorian`, `SetHistorianDataSource`)
**Classification:** standard · **Estimated implement time:** ~5 min · **Parallelizable with:** Task 4
**Files:**
- Create: `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Historian/ServerHistorianOptions.cs` — `SectionName =
"ServerHistorian"`; `Enabled`, `Host`, `Port`, `UseTls`, `ServerCertThumbprint`, `SharedSecret`;
`Validate()` warnings mirroring `AlarmHistorianOptions` (empty SharedSecret, etc.).
- Modify: `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ServiceCollectionExtensions.cs`
- `AddOtOpcUaRuntime`: `services.TryAddSingleton<IHistorianDataSource>(NullHistorianDataSource.Instance);`
- Add `AddServerHistorian(this IServiceCollection, IConfiguration, Func<ServerHistorianOptions,
IServiceProvider, IHistorianDataSource> factory)` — bind the section; `Enabled != true` ⇒ no-op
(Null stays); else log `Validate()` warnings + `AddSingleton<IHistorianDataSource>(sp =>
factory(opts, sp))`. Mirror `AddAlarmHistorian`.
- Modify: `src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaSdkServer.cs` — add
`public bool SetHistorianDataSource(IHistorianDataSource? source)` mirroring `SetNodeWriteGateway`.
- Modify: `src/Server/ZB.MOM.WW.OtOpcUa.Host/Program.cs` — after `AddAlarmHistorian` (`:94`), add
`AddServerHistorian(config, (opts,sp) => new WonderwareHistorianClient(new
WonderwareHistorianClientOptions(opts.Host, opts.Port, opts.SharedSecret){ UseTls=opts.UseTls,
ServerCertThumbprint=opts.ServerCertThumbprint }, sp.GetService<ILogger<WonderwareHistorianClient>>()))`.
- Modify: `src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs` — after
`SetNodeWriteGateway` (`:147`), resolve `IHistorianDataSource` from DI and
`_server.SetHistorianDataSource(source)`; in `StopAsync` (`:166`) `_server?.SetHistorianDataSource(null)`.
(The hosted service must be able to resolve `IHistorianDataSource` — inject it or pull from the
provider exactly as the other sinks are obtained.)
- Modify: `src/Server/ZB.MOM.WW.OtOpcUa.Host/appsettings.json` — add a disabled `ServerHistorian`
block (documented defaults). **Do not** put a real `SharedSecret` in a tracked file (leave `""`).
- Test: `tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Historian/AddServerHistorianTests.cs` (new;
model on the existing `AddAlarmHistorian` DI test) — disabled ⇒ resolves `NullHistorianDataSource`;
enabled ⇒ resolves the factory's source.
**Steps:**
1. Failing DI test: `ServerHistorian:Enabled=false` ⇒ `IHistorianDataSource` is the Null instance;
`Enabled=true` ⇒ the factory's fake. Run → fail.
2. Implement `ServerHistorianOptions` + `AddServerHistorian` + the `TryAddSingleton` default + the
`SetHistorianDataSource` setter. Run → pass.
3. Wire the Host (`Program.cs` + hosted service + appsettings). Build the **Host** project to prove
the Wonderware factory + DI compile (no unit test for the Host wiring — it's covered by the live
gate). Build clean.
4. Commit by path (do NOT stage appsettings.json secrets — the block is disabled with empty secret).
---
### Task 6: Docs + bookkeeping
**Classification:** small · **Estimated implement time:** ~4 min · **Parallelizable with:** none
**Files:**
- Create: `docs/Historian.md` — the historized-tag `TagConfig` schema (`isHistorized`,
`historianTagname` default=FullName), the `ServerHistorian` config section, HistoryRead behavior
(the four variants, graceful degrade to `GoodNoData`, the single-shot/no-continuation limitation,
events-on-equipment-folders), and a `Client.CLI historyread` example.
- Modify: `CLAUDE.md` — a short pointer under a Historian/HistoryRead note (one paragraph + the doc link).
- Modify (disk-only, **do NOT commit**): `pending.md` — mark #2 Phase C done with the merge SHA +
the deferred live gate.
- Update: the plan's `.tasks.json` statuses.
**Steps:** Write the docs; commit `docs/Historian.md` + `CLAUDE.md` by path. Update `pending.md` on
disk only (never staged).
---
### Task 7: Live docker-dev `/run` verification — DEFERRED (user-driven)
**Classification:** n/a (live) · **Parallelizable with:** none · **Depends on:** Task 5
**Deferred — the agent does NOT sign in and the local docker-dev rig has no Wonderware sidecar.** The
historian backend is the WW Historian VM (`10.100.0.48`) + AVEVA, so this gate is operator-driven.
When run: author a historized Galaxy equipment tag (`TagConfig` `"isHistorized":true`), set
`ServerHistorian:Enabled=true` pointed at the sidecar (`Host`/`Port`/`SharedSecret`/TLS), deploy on
`MAIN-galaxy-eq` (`POST http://localhost:9200/api/deployments`, `X-Api-Key: docker-dev-deploy-key`),
then `Client.CLI historyread -u opc.tcp://localhost:4840 -n "ns=2;s=<equip>/<tag>" --start … --end …`
→ samples return; a non-historized tag ⇒ `BadHistoryOperationUnsupported`.
---
## Dependency graph
`0 → 1 → 2 → 3 → (4 ∥ 5) → 6 → 7(deferred)`. Tasks 4 and 5 touch disjoint files
(node-manager events arm vs. DI/Host/SdkServer) and may be dispatched concurrently after Task 3.
## Done
Build clean (0 warnings in `src/`) + `dotnet test` green (new + existing suites) for Tasks 1–6. The
live `/run` (Task 7) is the deferred user-driven gate.
@@ -0,0 +1,14 @@
{
"planPath": "docs/plans/2026-06-14-galaxy-phase-c-historian-plan.md",
"tasks": [
{"id": 0, "subject": "Task 0: Feature branch feat/galaxy-phase-c-historian (created)", "status": "completed"},
{"id": 1, "subject": "Task 1: Carry isHistorized + historianTagname (composer + artifact byte-parity)", "status": "completed", "blockedBy": [0]},
{"id": 2, "subject": "Task 2: Materialize historized — Historizing + HistoryRead bit + NodeId->tagname registry", "status": "completed", "blockedBy": [1]},
{"id": 3, "subject": "Task 3: HistoryRead override — Raw/Processed/AtTime + NullHistorianDataSource + prop", "status": "completed", "blockedBy": [2]},
{"id": 4, "subject": "Task 4: HistoryRead override — Events over equipment-folder notifiers", "status": "completed", "blockedBy": [3]},
{"id": 5, "subject": "Task 5: DI + config + Host wiring (AddServerHistorian, SetHistorianDataSource)", "status": "completed", "blockedBy": [3]},
{"id": 6, "subject": "Task 6: Docs + bookkeeping", "status": "completed", "blockedBy": [4, 5]},
{"id": 7, "subject": "Task 7: Live docker-dev /run verification — DEFERRED (user-driven)", "status": "pending", "blockedBy": [5]}
],
"lastUpdated": "2026-06-14"
}
@@ -59,8 +59,10 @@ public sealed class DeferredAddressSpaceSink : IOpcUaAddressSpaceSink
/// <param name="displayName">The display name of the variable.</param>
/// <param name="dataType">The OPC UA data type of the variable.</param>
/// <param name="writable">When true the node is created read/write; otherwise read-only.</param>
public void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable)
=> _inner.EnsureVariable(variableNodeId, parentFolderNodeId, displayName, dataType, writable);
/// <param name="historianTagname">null ⇒ not historized; non-null ⇒ create Historizing with the
/// HistoryRead access bit and register the historian tagname.</param>
public void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable, string? historianTagname = null)
=> _inner.EnsureVariable(variableNodeId, parentFolderNodeId, displayName, dataType, writable, historianTagname);
/// <summary>Rebuilds the address space through the inner sink.</summary>
public void RebuildAddressSpace() => _inner.RebuildAddressSpace();
@@ -65,7 +65,10 @@ public interface IOpcUaAddressSpaceSink
/// <param name="writable">When true the node is created <c>CurrentReadWrite</c> (an authored
/// ReadWrite equipment tag); when false it stays <c>CurrentRead</c> (read-only). Non-equipment-tag
/// variables (folders' children, alarm placeholders) always pass <c>false</c>.</param>
void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable);
/// <param name="historianTagname">null ⇒ the variable is not historized; non-null ⇒ create it
/// Historizing with the HistoryRead access bit and register the (already default-resolved)
/// historian tagname.</param>
void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable, string? historianTagname = null);
/// <summary>
/// Tear down + repopulate the address space. Called by <c>OpcUaPublishActor</c> after a
@@ -98,7 +101,7 @@ public sealed class NullOpcUaAddressSpaceSink : IOpcUaAddressSpaceSink
public void EnsureFolder(string folderNodeId, string? parentNodeId, string displayName) { }
/// <inheritdoc />
public void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable) { }
public void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable, string? historianTagname = null) { }
/// <inheritdoc />
public void RebuildAddressSpace() { }
@@ -0,0 +1,81 @@
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions;
/// <summary>
/// A no-op <see cref="IHistorianDataSource"/> — the server's default historian backend when no
/// real historian has been registered. Every read returns an EMPTY result (no samples / events,
/// null continuation point) so the node-manager's HistoryRead override surfaces
/// <c>GoodNoData</c> for a historized node rather than faulting, and
/// <see cref="GetHealthSnapshot"/> reports a fully-disabled (zeroed, disconnected) snapshot.
/// <para>
/// A process-wide singleton via <see cref="Instance"/> (private ctor): it carries no state
/// and is immutable, so one shared instance is safe to assign as the node-manager's
/// <c>HistorianDataSource</c> default until the Host wires a real source post-start (Task 5).
/// </para>
/// </summary>
public sealed class NullHistorianDataSource : IHistorianDataSource
{
/// <summary>The shared singleton instance.</summary>
public static readonly NullHistorianDataSource Instance = new();
private static readonly HistoryReadResult EmptyRead = new(Array.Empty<DataValueSnapshot>(), null);
private static readonly HistoricalEventsResult EmptyEvents = new(Array.Empty<HistoricalEvent>(), null);
private NullHistorianDataSource()
{
}
/// <inheritdoc />
public Task<HistoryReadResult> ReadRawAsync(
string fullReference,
DateTime startUtc,
DateTime endUtc,
uint maxValuesPerNode,
CancellationToken cancellationToken) => Task.FromResult(EmptyRead);
/// <inheritdoc />
public Task<HistoryReadResult> ReadProcessedAsync(
string fullReference,
DateTime startUtc,
DateTime endUtc,
TimeSpan interval,
HistoryAggregateType aggregate,
CancellationToken cancellationToken) => Task.FromResult(EmptyRead);
/// <inheritdoc />
public Task<HistoryReadResult> ReadAtTimeAsync(
string fullReference,
IReadOnlyList<DateTime> timestampsUtc,
CancellationToken cancellationToken) => Task.FromResult(EmptyRead);
/// <inheritdoc />
public Task<HistoricalEventsResult> ReadEventsAsync(
string? sourceName,
DateTime startUtc,
DateTime endUtc,
int maxEvents,
CancellationToken cancellationToken) => Task.FromResult(EmptyEvents);
/// <summary>
/// Returns a fully-disabled snapshot — no connections open, every counter zero, every nullable
/// field null, no cluster nodes. Pure; never blocks.
/// </summary>
public HistorianHealthSnapshot GetHealthSnapshot() => new(
TotalQueries: 0,
TotalSuccesses: 0,
TotalFailures: 0,
ConsecutiveFailures: 0,
LastSuccessTime: null,
LastFailureTime: null,
LastError: null,
ProcessConnectionOpen: false,
EventConnectionOpen: false,
ActiveProcessNode: null,
ActiveEventNode: null,
Nodes: Array.Empty<HistorianClusterNodeState>());
/// <summary>No-op — the null source owns no unmanaged resources.</summary>
public void Dispose()
{
// Stateless singleton; nothing to release.
}
}
@@ -5,6 +5,7 @@ using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
using ZB.MOM.WW.OtOpcUa.Runtime;
@@ -30,6 +31,7 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
private readonly DeferredAddressSpaceSink _deferredSink;
private readonly DeferredServiceLevelPublisher _deferredServiceLevel;
private readonly IOpcUaUserAuthenticator _userAuthenticator;
private readonly IHistorianDataSource _historianDataSource;
private readonly Func<ActorSystem> _actorSystemAccessor;
private readonly ActorRegistry _actorRegistry;
private readonly ILoggerFactory _loggerFactory;
@@ -45,6 +47,11 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
/// <param name="deferredSink">The deferred address space sink that receives the real sink once the server is ready.</param>
/// <param name="deferredServiceLevel">The deferred service level publisher that receives the real publisher once the server is ready.</param>
/// <param name="userAuthenticator">The OPC UA user authenticator.</param>
/// <param name="historianDataSource">The server-side HistoryRead backend resolved from DI — the
/// <c>NullHistorianDataSource</c> default seeded by <c>AddOtOpcUaRuntime</c> (which runs on this driver
/// node, the same source the address-space sink + node-write gateway come from), or the configured
/// Wonderware read client when <c>AddServerHistorian</c> enabled it. Wired onto the node manager in
/// <see cref="StartAsync"/>.</param>
/// <param name="actorSystemAccessor">Lazy accessor for the running <see cref="ActorSystem"/>, used to
/// resolve the DistributedPubSub mediator the inbound alarm-command router publishes through. Resolved
/// lazily (mirroring <c>DpsScriptLogPublisher</c>) so construction never races Akka startup.</param>
@@ -57,6 +64,7 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
DeferredAddressSpaceSink deferredSink,
DeferredServiceLevelPublisher deferredServiceLevel,
IOpcUaUserAuthenticator userAuthenticator,
IHistorianDataSource historianDataSource,
Func<ActorSystem> actorSystemAccessor,
ActorRegistry actorRegistry,
ILoggerFactory loggerFactory)
@@ -65,6 +73,7 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
_deferredSink = deferredSink;
_deferredServiceLevel = deferredServiceLevel;
_userAuthenticator = userAuthenticator;
_historianDataSource = historianDataSource;
_actorSystemAccessor = actorSystemAccessor;
_actorRegistry = actorRegistry;
_loggerFactory = loggerFactory;
@@ -148,6 +157,11 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
resolveDriverHost: () => _actorRegistry.TryGet<DriverHostActorKey>(out var driverHost) ? driverHost : null,
logger: _loggerFactory.CreateLogger<ActorNodeWriteGateway>()));
// Wire the server-side read backend resolved from DI — the NullHistorianDataSource default (when
// the ServerHistorian section is disabled) or the configured Wonderware read client (when enabled).
// The node manager's HistoryRead overrides block-bridge to whatever source is set here.
_server.SetHistorianDataSource(_historianDataSource);
// ServiceLevel publisher needs IServerInternal — only available after Start.
if (_server.CurrentInstance is { } serverInternal)
{
@@ -171,6 +185,8 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
_deferredServiceLevel.SetInner(null);
// Restore the Null write gateway so a late client write doesn't Ask a stopping DriverHostActor.
_server?.SetNodeWriteGateway(null);
// Restore the Null historian so a late HistoryRead doesn't hit a disposed read client.
_server?.SetHistorianDataSource(null);
return Task.CompletedTask;
}
@@ -100,6 +100,20 @@ if (hasDriver)
},
sp.GetService<ILogger<WonderwareHistorianClient>>()));
// Config-gated server-side HistoryRead backend. When the ServerHistorian section is enabled this
// overrides the NullHistorianDataSource default from AddOtOpcUaRuntime (last registration wins) with
// a read-only WonderwareHistorianClient the node manager's HistoryRead overrides block-bridge to.
// The client is supplied here because the Host is the only project that references the Wonderware
// client — Runtime owns the gating, the Host supplies the concrete read downstream.
builder.Services.AddServerHistorian(
builder.Configuration,
(opts, sp) => new WonderwareHistorianClient(
new WonderwareHistorianClientOptions(opts.Host, opts.Port, opts.SharedSecret)
{
UseTls = opts.UseTls, ServerCertThumbprint = opts.ServerCertThumbprint,
},
sp.GetService<ILogger<WonderwareHistorianClient>>()));
// Bind every cross-platform driver factory before AddAkka resolves IDriverFactory — replaces
// the F7-default NullDriverFactory with a real DriverFactoryRegistryAdapter so DriverHostActor
// can materialise real IDriver instances on deploy.
@@ -22,5 +22,13 @@
"DrainIntervalSeconds": 5,
"Capacity": 1000000,
"DeadLetterRetentionDays": 30
},
"ServerHistorian": {
"Enabled": false,
"Host": "localhost",
"Port": 32569,
"UseTls": false,
"ServerCertThumbprint": null,
"SharedSecret": ""
}
}
@@ -2,7 +2,13 @@ using System.Collections.Concurrent;
using Opc.Ua;
using Opc.Ua.Server;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
// The SDK's HistoryRead service result (the value the override fills + hands back) and the historian
// data source's read DTO are both named HistoryReadResult. Alias each to keep the two unambiguous:
// the SDK result stays unqualified as the dominant name in the override; the source DTO is HistorianRead.
using HistorianRead = ZB.MOM.WW.OtOpcUa.Core.Abstractions.HistoryReadResult;
using SdkHistoryReadResult = Opc.Ua.HistoryReadResult;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
@@ -30,11 +36,25 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2
private readonly ConcurrentDictionary<string, BaseDataVariableState> _variables = new(StringComparer.Ordinal);
private readonly ConcurrentDictionary<string, FolderState> _folders = new(StringComparer.Ordinal);
private readonly ConcurrentDictionary<string, AlarmConditionState> _alarmConditions = new(StringComparer.Ordinal);
/// <summary>Phase C: NodeId → resolved historian tagname for every variable materialised
/// Historizing. Populated by <see cref="EnsureVariable"/> when a historian tagname is supplied; the
/// (later) HistoryRead override resolves a HistoryRead request's NodeId against this map. Cleared on
/// <see cref="RebuildAddressSpace"/>.</summary>
private readonly ConcurrentDictionary<string, string> _historizedTagnames = new(StringComparer.Ordinal);
/// <summary>Folders we have already promoted to event-notifiers + registered as root notifiers,
/// so repeated <see cref="MaterialiseAlarmCondition"/> calls don't double-add (idempotent guard).
/// Keyed by NodeId → the actual <see cref="FolderState"/> so <see cref="RebuildAddressSpace"/> can
/// pass the folder to <c>RemoveRootNotifier</c> on teardown.</summary>
private readonly Dictionary<NodeId, FolderState> _notifierFolders = new();
/// <summary>Phase C (Task 4): event-notifier folder NodeId-identifier → the event-history source
/// name passed to <see cref="IHistorianDataSource.ReadEventsAsync"/>. The equipment-folder NodeId
/// identifier IS the equipment id, which IS the sourceName, so key and value are the same string;
/// the map's presence (not its value) is what makes a folder an event-history source. Populated by
/// <see cref="EnsureFolderIsEventNotifier"/> only when a real historian is wired at promotion time,
/// and the <see cref="HistoryReadEvents"/> override resolves an inbound request's notifier NodeId
/// against it (a miss ⇒ <c>BadHistoryOperationUnsupported</c>). Cleared on
/// <see cref="RebuildAddressSpace"/>.</summary>
private readonly ConcurrentDictionary<string, string> _eventNotifierSources = new(StringComparer.Ordinal);
private FolderState? _root;
/// <summary>Initializes a new instance of the <see cref="OtOpcUaNodeManager"/> class with the OPC UA server and configuration.</summary>
@@ -106,6 +126,32 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2
set => _nodeWriteGateway = value ?? NullOpcUaNodeWriteGateway.Instance;
}
private volatile IHistorianDataSource _historianDataSource = NullHistorianDataSource.Instance;
/// <summary>
/// Server-side read backend for the OPC UA HistoryRead service over historized variable nodes.
/// When a client issues a HistoryRead (Raw / Processed / AtTime) against a node materialised
/// <c>Historizing</c> (a tag with <see cref="TryGetHistorizedTagname"/> registered), the
/// HistoryRead override resolves the node's NodeId to its historian tagname and dispatches to
/// this source — so a single registered historian (e.g. Wonderware) serves many drivers' nodes,
/// independent of any driver's lifecycle.
/// <para>
/// Set by the Host at <c>StartAsync</c> (Task 5). The <see cref="NullHistorianDataSource"/>
/// default (assigning <c>null</c> restores it) means "no historian wired" → every read
/// returns empty, so a historized node's HistoryRead surfaces <c>GoodNoData</c> rather than
/// faulting. Backed by a <c>volatile</c> field (auto-properties can't be volatile) to make
/// the startup-write / SDK-read-thread handoff explicit: the Host assigns it once at boot on
/// the start thread and the SDK reads it on HistoryRead request threads. Unlike
/// <see cref="NodeWriteGateway"/>, the HistoryRead override does NOT run under the
/// node-manager <c>Lock</c>, so the override may block-bridge to this (async) source.
/// </para>
/// </summary>
public IHistorianDataSource HistorianDataSource
{
get => _historianDataSource;
set => _historianDataSource = value ?? NullHistorianDataSource.Instance;
}
/// <summary>Look up a materialised Part 9 alarm-condition node by its alarm node id (the
/// ScriptedAlarmId), or null if not yet materialised. Exposed for tests + diagnostics.</summary>
/// <param name="alarmNodeId">The alarm node identifier (== ScriptedAlarmId).</param>
@@ -113,6 +159,34 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2
public AlarmConditionState? TryGetAlarmCondition(string alarmNodeId) =>
_alarmConditions.TryGetValue(alarmNodeId, out var condition) ? condition : null;
/// <summary>Phase C: look up the resolved historian tagname registered for a historized variable
/// node, or null when the node is not historized. The (later) HistoryRead override resolves an
/// inbound HistoryRead request's NodeId against this map. Exposed for tests + the override.</summary>
/// <param name="nodeId">The variable node identifier.</param>
/// <param name="tagname">The resolved historian tagname when historized; otherwise null.</param>
/// <returns>True when the node is registered as historized; otherwise false.</returns>
public bool TryGetHistorizedTagname(string nodeId, out string? tagname)
{
if (_historizedTagnames.TryGetValue(nodeId, out var t)) { tagname = t; return true; }
tagname = null;
return false;
}
/// <summary>Look up a materialised variable node by its NodeId string, or null if not present.
/// Exposed for tests so they can assert the SDK node's Historizing / AccessLevel attributes.</summary>
/// <param name="nodeId">The variable node identifier.</param>
/// <returns>The cached <see cref="BaseDataVariableState"/>, or null when none is registered.</returns>
internal BaseDataVariableState? TryGetVariable(string nodeId) =>
_variables.TryGetValue(nodeId, out var variable) ? variable : null;
/// <summary>Look up a materialised folder node by its NodeId string, or null if not present.
/// Exposed for tests so they can resolve an equipment folder's NodeId (e.g. the event-notifier
/// node a HistoryReadEvents request targets).</summary>
/// <param name="nodeId">The folder node identifier.</param>
/// <returns>The cached <see cref="FolderState"/>, or null when none is registered.</returns>
internal FolderState? TryGetFolder(string nodeId) =>
_folders.TryGetValue(nodeId, out var folder) ? folder : null;
/// <summary>
/// Apply a value write from <see cref="IOpcUaAddressSpaceSink.WriteValue"/>. Creates the
/// variable node on first call; subsequent calls update Value + StatusCode +
@@ -746,10 +820,31 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2
/// <summary>Promote <paramref name="folder"/> to <see cref="EventNotifiers.SubscribeToEvents"/> and
/// register it as a root notifier (idempotent — guarded by <see cref="_notifierFolders"/>) so the
/// alarm condition has a notifier path to the Server object for T16's event propagation.</summary>
/// <remarks>
/// Phase C (Task 4): when a real historian is wired at promotion time (the source is NOT the
/// <see cref="NullHistorianDataSource"/>), the folder ALSO gets the
/// <see cref="EventNotifiers.HistoryRead"/> bit OR-ed in (keeping SubscribeToEvents) and registers
/// its NodeId identifier as an event-history source so the <see cref="HistoryReadEvents"/> override
/// accepts it. The HistoryRead-events bit is therefore only advertised when a historian is wired at
/// the moment of promotion: the Host wires the source at <c>StartAsync</c> — BEFORE any deployment
/// materialises alarms — so the normal boot ordering promotes folders with the bit set. A folder
/// promoted while the source is still Null advertises live-event subscription but NOT event history
/// until the next <see cref="RebuildAddressSpace"/> re-promotes it (acceptable, documented). The
/// HistoryRead bit + source registration happen inside the same first-time
/// <see cref="_notifierFolders"/> block so the idempotency guard covers them too.
/// </remarks>
private void EnsureFolderIsEventNotifier(FolderState folder)
{
if (!_notifierFolders.TryAdd(folder.NodeId, folder)) return;
folder.EventNotifier = EventNotifiers.SubscribeToEvents;
if (_historianDataSource is not NullHistorianDataSource)
{
// A historian is wired: advertise event history on this notifier and register it as a source.
// The equipment-folder NodeId identifier IS the equipment id IS the ReadEventsAsync sourceName.
folder.EventNotifier = (byte)(folder.EventNotifier | EventNotifiers.HistoryRead);
var sourceName = folder.NodeId.Identifier?.ToString() ?? string.Empty;
_eventNotifierSources[sourceName] = sourceName;
}
AddRootNotifier(folder);
folder.ClearChangeMasks(SystemContext, includeChildren: false);
}
@@ -807,7 +902,10 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2
/// <paramref name="parentFolderNodeId"/> (or root when null). Initial value=null, quality=Bad,
/// timestamp=epoch — <see cref="WriteValue"/> fills these in once driver data flows.
/// Idempotent. Materialises equipment-namespace tags so they're browseable before drivers
/// issue SubscribeBulk.
/// issue SubscribeBulk. Note: because of the early <c>_variables.ContainsKey</c> return, a
/// re-apply of an EXISTING node with a changed historize intent (e.g. non-historized →
/// historized) is silently ignored — a historize-intent change only takes effect after a
/// <see cref="RebuildAddressSpace"/> (which the planner triggers on an equipment-tag delta).
/// </summary>
/// <param name="variableNodeId">The node identifier of the variable.</param>
/// <param name="parentFolderNodeId">The node identifier of the parent folder; null to use the namespace root.</param>
@@ -817,7 +915,12 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2
/// ReadWrite equipment tag) and the inbound-write handler <see cref="OnEquipmentTagWrite"/> is attached
/// to its <c>OnWriteValue</c> (Task 11) so a client write gates on the <c>WriteOperate</c> role + routes
/// to the backing driver; when false it stays <c>CurrentRead</c> (read-only) with no write handler.</param>
public void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable)
/// <param name="historianTagname">Phase C: null ⇒ the node is NOT historized (Historizing=false, no
/// HistoryRead bit, not registered). Non-null ⇒ the node is created <c>Historizing</c> with the
/// <c>HistoryRead</c> access bit OR-ed into both <c>AccessLevel</c> and <c>UserAccessLevel</c>, and the
/// (already default-resolved) tagname is registered in the NodeId→tagname map the HistoryRead override
/// resolves against.</param>
public void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable, string? historianTagname = null)
{
ArgumentException.ThrowIfNullOrEmpty(variableNodeId);
ArgumentException.ThrowIfNullOrEmpty(displayName);
@@ -830,6 +933,13 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2
if (_variables.ContainsKey(variableNodeId)) return;
var parent = ResolveParentFolder(parentFolderNodeId);
// Phase C: a non-null historian tagname makes the node Historizing and grants the HistoryRead
// access bit (on top of the writable composite) so clients can browse + HistoryRead it.
var historized = historianTagname is not null;
// The SDK exposes the flags separately (no CurrentReadWrite composite): ReadWrite is
// CurrentRead | CurrentWrite. OR-ing two byte constants promotes to int, so cast back.
byte access = writable ? (byte)(AccessLevels.CurrentRead | AccessLevels.CurrentWrite) : AccessLevels.CurrentRead;
if (historized) access = (byte)(access | AccessLevels.HistoryRead);
var variable = new BaseDataVariableState(parent)
{
NodeId = new NodeId(variableNodeId, NamespaceIndex),
@@ -839,11 +949,9 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2
ReferenceTypeId = ReferenceTypeIds.Organizes,
DataType = ResolveBuiltInDataType(dataType),
ValueRank = ValueRanks.Scalar,
// The SDK exposes the flags separately (no CurrentReadWrite composite): ReadWrite is
// CurrentRead | CurrentWrite. OR-ing two byte constants promotes to int, so cast back.
AccessLevel = writable ? (byte)(AccessLevels.CurrentRead | AccessLevels.CurrentWrite) : AccessLevels.CurrentRead,
UserAccessLevel = writable ? (byte)(AccessLevels.CurrentRead | AccessLevels.CurrentWrite) : AccessLevels.CurrentRead,
Historizing = false,
AccessLevel = access,
UserAccessLevel = access,
Historizing = historized,
Value = null,
StatusCode = StatusCodes.BadWaitingForInitialData,
Timestamp = DateTime.MinValue,
@@ -859,6 +967,9 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2
parent.AddChild(variable);
AddPredefinedNode(SystemContext, variable);
_variables[variableNodeId] = variable;
// Phase C: register the resolved historian tagname so the HistoryRead override can map this
// NodeId back to its Aveva/historian source.
if (historized) _historizedTagnames[variableNodeId] = historianTagname!;
}
}
@@ -896,6 +1007,8 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2
PredefinedNodes?.Remove(v.NodeId);
}
_variables.Clear();
// Phase C: drop the NodeId→historian-tagname registrations alongside the variables they map.
_historizedTagnames.Clear();
foreach (var alarm in _alarmConditions.Values)
{
@@ -923,6 +1036,9 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2
// Drop the notifier-folder guard so re-materialised alarms re-promote their (rebuilt)
// equipment folders to event notifiers.
_notifierFolders.Clear();
// Phase C (Task 4): drop the event-history source registrations alongside the notifier folders
// they map; re-materialised alarms re-register them (with the HistoryRead bit) on re-promotion.
_eventNotifierSources.Clear();
}
}
@@ -932,6 +1048,382 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2
return _folders.TryGetValue(parentNodeId, out var existing) ? existing : _root!;
}
// ---------------------------------------------------------------------------------------------
// Phase C — OPC UA HistoryRead over historized variable nodes.
//
// The base CustomNodeManager2.HistoryRead (public + protected dispatcher) does the heavy lifting:
// it validates handles under Lock, builds `nodesToProcess` (a NodeHandle list for nodes WE own
// that carry the HistoryRead access bit), validates the timestamp args, handles
// `releaseContinuationPoints`, and dispatches by `details` runtime type to the per-details
// protected virtuals below. We override all four arms: the three variable-history virtuals
// (Raw/Processed/AtTime) and the event-history arm (HistoryReadEvents, Task 4). Each override
// receives the pre-filtered handles and fills results[handle.Index] / errors[handle.Index] —
// handle.Index is the original index into the service-level results/errors lists, seeded by the
// base. The base pre-seeds every handle's error to BadHistoryOperationUnsupported, so a handle
// we don't recognise stays "unsupported" by default.
//
// NOTE: unlike OnWriteValue, the SDK does NOT hold the node-manager Lock while invoking these, so
// block-bridging the async data source (GetAwaiter().GetResult()) is safe — it can't freeze the
// address space. Each handle is served in isolation under try/catch so one node's failure (timeout,
// backend throw) never throws out of the batch.
// ---------------------------------------------------------------------------------------------
/// <summary>
/// Serve a HistoryRead-Raw request over the pre-filtered historized variable handles, dispatching
/// each to <see cref="IHistorianDataSource.ReadRawAsync"/>. Modified-history reads
/// (<c>IsReadModified</c>) are unsupported — we don't serve a modified-value history surface.
/// </summary>
protected override void HistoryReadRawModified(
ServerSystemContext context,
ReadRawModifiedDetails details,
TimestampsToReturn timestampsToReturn,
IList<HistoryReadValueId> nodesToRead,
IList<SdkHistoryReadResult> results,
IList<ServiceResult> errors,
List<NodeHandle> nodesToProcess,
IDictionary<NodeId, NodeState> cache)
{
foreach (var handle in nodesToProcess)
{
if (details.IsReadModified)
{
// We never serve modified-value history; mark this node unsupported and move on.
errors[handle.Index] = StatusCodes.BadHistoryOperationUnsupported;
continue;
}
ServeNode(handle, results, errors, (source, tagname) => source.ReadRawAsync(
tagname,
details.StartTime,
details.EndTime,
details.NumValuesPerNode,
CancellationToken.None));
}
}
/// <summary>
/// Serve a HistoryRead-Processed request, mapping each node's per-node aggregate NodeId (from the
/// parallel <c>AggregateType</c> collection — the base guarantees it is the same length as
/// <c>nodesToRead</c>) to a <see cref="HistoryAggregateType"/> and dispatching to
/// <see cref="IHistorianDataSource.ReadProcessedAsync"/>. An unknown aggregate yields
/// <c>BadAggregateNotSupported</c> for that node.
/// </summary>
protected override void HistoryReadProcessed(
ServerSystemContext context,
ReadProcessedDetails details,
TimestampsToReturn timestampsToReturn,
IList<HistoryReadValueId> nodesToRead,
IList<SdkHistoryReadResult> results,
IList<ServiceResult> errors,
List<NodeHandle> nodesToProcess,
IDictionary<NodeId, NodeState> cache)
{
foreach (var handle in nodesToProcess)
{
// AggregateType is a per-node parallel collection (same length as nodesToRead, enforced by
// the base dispatcher). handle.Index is the node's position in that collection.
var aggregateNodeId = details.AggregateType[handle.Index];
var aggregate = MapAggregate(aggregateNodeId);
if (aggregate is null)
{
errors[handle.Index] = StatusCodes.BadAggregateNotSupported;
continue;
}
ServeNode(handle, results, errors, (source, tagname) => source.ReadProcessedAsync(
tagname,
details.StartTime,
details.EndTime,
// OPC UA ProcessingInterval is a Duration in milliseconds.
TimeSpan.FromMilliseconds(details.ProcessingInterval),
aggregate.Value,
CancellationToken.None));
}
}
/// <summary>
/// Serve a HistoryRead-AtTime request, dispatching the requested timestamps to
/// <see cref="IHistorianDataSource.ReadAtTimeAsync"/>.
/// </summary>
protected override void HistoryReadAtTime(
ServerSystemContext context,
ReadAtTimeDetails details,
TimestampsToReturn timestampsToReturn,
IList<HistoryReadValueId> nodesToRead,
IList<SdkHistoryReadResult> results,
IList<ServiceResult> errors,
List<NodeHandle> nodesToProcess,
IDictionary<NodeId, NodeState> cache)
{
// Snapshot the requested timestamps once — the same list is read for every node.
var timestamps = details.ReqTimes?.ToList() ?? new List<DateTime>();
foreach (var handle in nodesToProcess)
{
ServeNode(handle, results, errors, (source, tagname) => source.ReadAtTimeAsync(
tagname,
timestamps,
CancellationToken.None));
}
}
/// <summary>
/// Serve a HistoryRead-Events request over the equipment-folder event-notifier nodes (the folders
/// that own alarm conditions). Each handle's NodeId identifier is resolved against
/// <see cref="_eventNotifierSources"/>: a miss ⇒ <c>BadHistoryOperationUnsupported</c> (a node we own
/// that isn't a registered event-history source — e.g. a plain folder, or one promoted while no
/// historian was wired); a hit block-bridges to <see cref="IHistorianDataSource.ReadEventsAsync"/>
/// for the folder's source name and projects each <see cref="HistoricalEvent"/> into a
/// <see cref="HistoryEventFieldList"/> per the request's event filter. Like the Raw/Processed/AtTime
/// arms this is NOT invoked under the node-manager <c>Lock</c>, so the block-bridge is safe; each
/// handle is served under try/catch so a backend throw becomes a Bad status for THAT node only and
/// never throws out of the batch.
/// </summary>
protected override void HistoryReadEvents(
ServerSystemContext context,
ReadEventDetails details,
TimestampsToReturn timestampsToReturn,
IList<HistoryReadValueId> nodesToRead,
IList<SdkHistoryReadResult> results,
IList<ServiceResult> errors,
List<NodeHandle> nodesToProcess,
IDictionary<NodeId, NodeState> cache)
{
// Snapshot the select clauses once — the same filter projects every node's events.
var selectClauses = details.Filter?.SelectClauses ?? new SimpleAttributeOperandCollection();
foreach (var handle in nodesToProcess)
{
var idString = handle.NodeId.Identifier?.ToString();
if (idString is null || !_eventNotifierSources.TryGetValue(idString, out var sourceName))
{
// Not a registered event-history source (plain folder / Null-source promotion) ⇒ unsupported.
// Set both errors and results explicitly on every bad path — don't rely on the SDK base
// pre-seeding results[i], so every path is self-contained and the contract is obvious.
errors[handle.Index] = StatusCodes.BadHistoryOperationUnsupported;
results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadHistoryOperationUnsupported };
continue;
}
try
{
// NOT under the node-manager Lock — block-bridging the async source is safe here.
var sourceResult = _historianDataSource.ReadEventsAsync(
sourceName,
details.StartTime,
details.EndTime,
// NumValuesPerNode is uint; ReadEventsAsync takes int (<=0 ⇒ backend default cap).
ClampToInt(details.NumValuesPerNode),
CancellationToken.None).GetAwaiter().GetResult();
var historyEvent = ProjectEvents(sourceResult.Events, selectClauses);
results[handle.Index] = new SdkHistoryReadResult
{
// No events ⇒ GoodNoData (the notifier is historized, the window just held no events).
StatusCode = sourceResult.Events.Count == 0 ? StatusCodes.GoodNoData : StatusCodes.Good,
HistoryData = new ExtensionObject(historyEvent),
// We never issue continuation points — every read returns the full window in one shot.
ContinuationPoint = null,
};
errors[handle.Index] = ServiceResult.Good;
}
catch (Exception ex)
{
// One node's backend failure must not throw out of the batch — surface Bad for THIS node
// only. This manager carries no ILogger, so log via the SDK's static trace (see ServeNode).
#pragma warning disable CS0618 // Type or member is obsolete
Utils.LogError(ex, "OtOpcUaNodeManager: HistoryReadEvents failed for node {0}", handle.NodeId);
#pragma warning restore CS0618
errors[handle.Index] = StatusCodes.BadHistoryOperationUnsupported;
results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadHistoryOperationUnsupported };
}
}
}
/// <summary>Clamp a <see cref="uint"/> request cap to a non-negative <see cref="int"/> for the
/// event-read surface (whose <c>maxEvents</c> is signed): values above <see cref="int.MaxValue"/>
/// saturate to <see cref="int.MaxValue"/>.</summary>
/// <param name="value">The uint cap from the request (<c>NumValuesPerNode</c>).</param>
/// <returns>The clamped non-negative int.</returns>
private static int ClampToInt(uint value) => value > int.MaxValue ? int.MaxValue : (int)value;
/// <summary>
/// Project a sequence of <see cref="HistoricalEvent"/>s into an SDK <see cref="HistoryEvent"/> —
/// one <see cref="HistoryEventFieldList"/> per event, each carrying the requested
/// <paramref name="selectClauses"/>' fields in select-clause order (see
/// <see cref="ProjectEventField"/>).
/// </summary>
/// <param name="events">The historian's event rows.</param>
/// <param name="selectClauses">The request's event-filter select clauses (the fields to emit, in order).</param>
/// <returns>The populated SDK <see cref="HistoryEvent"/>.</returns>
private static HistoryEvent ProjectEvents(
IReadOnlyList<HistoricalEvent> events, SimpleAttributeOperandCollection selectClauses)
{
var fieldLists = new HistoryEventFieldListCollection(events.Count);
foreach (var evt in events)
{
var fields = new VariantCollection(selectClauses.Count);
foreach (var operand in selectClauses)
{
fields.Add(ProjectEventField(evt, operand));
}
fieldLists.Add(new HistoryEventFieldList { EventFields = fields });
}
return new HistoryEvent { Events = fieldLists };
}
/// <summary>
/// Project one <see cref="HistoricalEvent"/> field requested by a select <paramref name="operand"/>
/// into a <see cref="Variant"/>. Mapping is by the operand's BrowsePath LEAF QualifiedName name
/// (case-sensitive, per the OPC UA BaseEventType field names) against the
/// <see cref="HistoricalEvent"/> shape:
/// <c>EventId</c>→ByteString, <c>SourceName</c>→String, <c>Time</c>→DateTime,
/// <c>ReceiveTime</c>→DateTime, <c>Message</c>→LocalizedText, <c>Severity</c>→UInt16. Any other
/// leaf (EventType / SourceNode / ConditionName / an unrecognised name) and an empty BrowsePath ⇒
/// <see cref="Variant.Null"/> — spec-conformant: a field the server can't supply is null.
/// </summary>
/// <param name="evt">The source event row.</param>
/// <param name="operand">The select-clause operand naming the field to project.</param>
/// <returns>The projected variant, or <see cref="Variant.Null"/> for an unsupported field.</returns>
private static Variant ProjectEventField(HistoricalEvent evt, SimpleAttributeOperand operand)
{
var leaf = LeafFieldName(operand);
return leaf switch
{
// BaseEventType/EventId is a ByteString — encode the driver-specific string id as UTF-8 bytes.
"EventId" => new Variant(System.Text.Encoding.UTF8.GetBytes(evt.EventId ?? string.Empty)),
"SourceName" => evt.SourceName is null ? Variant.Null : new Variant(evt.SourceName),
"Time" => new Variant(evt.EventTimeUtc),
"ReceiveTime" => new Variant(evt.ReceivedTimeUtc),
"Message" => new Variant(new LocalizedText(evt.Message ?? string.Empty)),
"Severity" => new Variant(evt.Severity), // UInt16
// EventType / SourceNode / ConditionName / empty path / unrecognised leaf ⇒ null (spec-conformant).
_ => Variant.Null,
};
}
/// <summary>Extract the leaf (last) <see cref="QualifiedName.Name"/> from a select operand's BrowsePath,
/// or <c>null</c> when the BrowsePath is null/empty.</summary>
/// <param name="operand">The select-clause operand.</param>
/// <returns>The leaf field name, or null for an empty BrowsePath.</returns>
private static string? LeafFieldName(SimpleAttributeOperand operand)
{
var path = operand.BrowsePath;
if (path is null || path.Count == 0) return null;
return path[^1].Name;
}
/// <summary>
/// Block-bridge to the historian source for one node handle and project the result onto the
/// service-level results/errors slots. Resolves the node's registered historian tagname first —
/// a single <see cref="TryGetHistorizedTagname"/> lookup; the resolved tagname is passed directly
/// to <paramref name="read"/>, removing any risk of a second concurrent lookup on the same key.
/// A node we don't recognise as historized maps to <c>BadHistoryOperationUnsupported</c>
/// (shouldn't normally reach us, since the base only hands us nodes with the HistoryRead access
/// bit, but we guard explicitly). The <paramref name="read"/> callback receives the resolved
/// tagname and is wrapped in try/catch so a backend throw / timeout becomes a Bad status for
/// THIS node without throwing out of the batch.
/// </summary>
/// <param name="handle">The pre-filtered node handle to serve; <c>handle.Index</c> indexes results/errors.</param>
/// <param name="results">The service-level results list to fill at <c>handle.Index</c>.</param>
/// <param name="errors">The service-level errors list to fill at <c>handle.Index</c>.</param>
/// <param name="read">Invokes the resolved data-source read with the resolved tagname; only called
/// once the tagname is confirmed present.</param>
private void ServeNode(
NodeHandle handle,
IList<SdkHistoryReadResult> results,
IList<ServiceResult> errors,
Func<IHistorianDataSource, string, Task<HistorianRead>> read)
{
var idString = handle.NodeId.Identifier?.ToString();
if (idString is null || !TryGetHistorizedTagname(idString, out var tagname))
{
// Not a historized node we own a tagname for — unsupported. (The base pre-seeds this same
// status, but set it explicitly so the contract is local + obvious.)
errors[handle.Index] = StatusCodes.BadHistoryOperationUnsupported;
return;
}
try
{
// HistoryRead is NOT invoked under the node-manager Lock (unlike OnWriteValue), so blocking
// on the async source here is safe and won't freeze the address space.
var sourceResult = read(HistorianDataSource, tagname!).GetAwaiter().GetResult();
var historyData = ToHistoryData(sourceResult);
results[handle.Index] = new SdkHistoryReadResult
{
// No source samples ⇒ GoodNoData (the node is historized, the window just held no data).
StatusCode = historyData.DataValues.Count == 0 ? StatusCodes.GoodNoData : StatusCodes.Good,
HistoryData = new ExtensionObject(historyData),
// We never issue continuation points — every read returns the full window in one shot.
ContinuationPoint = null,
};
errors[handle.Index] = ServiceResult.Good;
}
catch (Exception ex)
{
// One node's backend failure (throw / timeout / cancellation) must not throw out of the
// batch — surface a Bad status for THIS node only. This CustomNodeManager2 carries no
// ILogger (see ReportConditionEvent), so log through the SDK's static trace rather than
// swallowing silently. Utils.LogError is [Obsolete] in 1.5.378 (favours an ITelemetryContext
// this manager doesn't wire) — suppress the deprecation, matching the existing pattern.
#pragma warning disable CS0618 // Type or member is obsolete
Utils.LogError(ex, "OtOpcUaNodeManager: HistoryRead failed for node {0}", handle.NodeId);
#pragma warning restore CS0618
errors[handle.Index] = StatusCodes.BadHistoryOperationUnsupported;
}
}
/// <summary>
/// Map an OPC UA Part 13 standard-aggregate function NodeId to our
/// <see cref="HistoryAggregateType"/>. Returns <c>null</c> for any aggregate we don't serve so
/// the caller can surface <c>BadAggregateNotSupported</c>.
/// </summary>
/// <param name="aggregateNodeId">The per-node aggregate-function NodeId from the request.</param>
/// <returns>The mapped aggregate, or <c>null</c> when unsupported.</returns>
private static HistoryAggregateType? MapAggregate(NodeId aggregateNodeId)
{
if (aggregateNodeId == ObjectIds.AggregateFunction_Average) return HistoryAggregateType.Average;
if (aggregateNodeId == ObjectIds.AggregateFunction_Minimum) return HistoryAggregateType.Minimum;
if (aggregateNodeId == ObjectIds.AggregateFunction_Maximum) return HistoryAggregateType.Maximum;
if (aggregateNodeId == ObjectIds.AggregateFunction_Total) return HistoryAggregateType.Total;
if (aggregateNodeId == ObjectIds.AggregateFunction_Count) return HistoryAggregateType.Count;
return null;
}
/// <summary>
/// Project the historian source's <see cref="HistorianRead"/> (Core.Abstractions DTO) into an
/// SDK <see cref="HistoryData"/> — one <see cref="DataValue"/> per <see cref="DataValueSnapshot"/>,
/// carrying value / status / source+server timestamps. A null SourceTimestamp maps to
/// <c>DateTime.MinValue</c> (the SDK's "unset" sentinel for that field).
/// </summary>
/// <param name="sourceResult">The data source's read result.</param>
/// <returns>The populated SDK <see cref="HistoryData"/>.</returns>
private static HistoryData ToHistoryData(HistorianRead sourceResult)
{
var values = new DataValueCollection(sourceResult.Samples.Count);
foreach (var sample in sourceResult.Samples)
{
values.Add(ToSdkDataValue(sample));
}
return new HistoryData { DataValues = values };
}
/// <summary>Convert one driver-agnostic <see cref="DataValueSnapshot"/> to an SDK
/// <see cref="DataValue"/>, mirroring value / status code / source + server timestamps.</summary>
/// <param name="snapshot">The source sample.</param>
/// <returns>The equivalent SDK data value.</returns>
private static DataValue ToSdkDataValue(DataValueSnapshot snapshot) => new()
{
WrappedValue = new Variant(snapshot.Value),
StatusCode = new StatusCode(snapshot.StatusCode),
SourceTimestamp = snapshot.SourceTimestampUtc ?? DateTime.MinValue,
ServerTimestamp = snapshot.ServerTimestampUtc,
};
/// <inheritdoc />
public override void CreateAddressSpace(IDictionary<NodeId, IList<IReference>> externalReferences)
{
@@ -1,6 +1,7 @@
using Opc.Ua;
using Opc.Ua.Server;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
@@ -59,6 +60,28 @@ public sealed class OtOpcUaSdkServer : StandardServer
return true;
}
/// <summary>
/// Wire the server-side HistoryRead backend (the <see cref="IHistorianDataSource"/> the node
/// manager's HistoryRead overrides block-bridge to) onto the created
/// <see cref="OtOpcUaNodeManager"/>. The host calls this after start with the DI-resolved source —
/// the <c>NullHistorianDataSource</c> default (GoodNoData-empty reads) or the configured Wonderware
/// read client. Passing <c>null</c> restores the Null default (the property setter null-coalesces),
/// i.e. "no historian". No-op (returns <c>false</c>) when the node manager has not been created yet,
/// so the caller can detect a too-early call (mirrors <see cref="SetNodeWriteGateway"/>).
/// </summary>
/// <param name="source">The read backend invoked by the node manager's HistoryRead overrides; may be
/// <c>null</c> to restore the Null default (GoodNoData-empty reads).</param>
/// <returns><c>true</c> when the source was set on a live node manager; <c>false</c> when no node
/// manager exists yet.</returns>
public bool SetHistorianDataSource(IHistorianDataSource? source)
{
if (_otOpcUaNodeManager is null) return false;
// The HistorianDataSource setter null-coalesces to the Null default, so a null source is intentional
// (restores GoodNoData-empty reads); forgive the nullable-in here.
_otOpcUaNodeManager.HistorianDataSource = source!;
return true;
}
/// <inheritdoc />
protected override MasterNodeManager CreateMasterNodeManager(
IServerInternal server, ApplicationConfiguration configuration)
@@ -197,7 +197,13 @@ public sealed class Phase7Applier
}
else
{
SafeEnsureVariable(nodeId, parent, tag.Name, tag.DataType, tag.Writable);
// Phase C: a historized tag materialises Historizing + HistoryRead. Resolve the effective
// historian tagname HERE (default-vs-override): a null/blank override falls back to the
// driver-side FullName; null means the tag is not historized at all.
string? historianTagname = tag.IsHistorized
? (string.IsNullOrWhiteSpace(tag.HistorianTagname) ? tag.FullName : tag.HistorianTagname)
: null;
SafeEnsureVariable(nodeId, parent, tag.Name, tag.DataType, tag.Writable, historianTagname);
}
}
@@ -291,9 +297,9 @@ public sealed class Phase7Applier
catch (Exception ex) { _logger.LogWarning(ex, "Phase7Applier: EnsureFolder threw for {Node}", nodeId); }
}
private void SafeEnsureVariable(string nodeId, string? parentNodeId, string displayName, string dataType, bool writable)
private void SafeEnsureVariable(string nodeId, string? parentNodeId, string displayName, string dataType, bool writable, string? historianTagname = null)
{
try { _sink.EnsureVariable(nodeId, parentNodeId, displayName, dataType, writable); }
try { _sink.EnsureVariable(nodeId, parentNodeId, displayName, dataType, writable, historianTagname); }
catch (Exception ex) { _logger.LogWarning(ex, "Phase7Applier: EnsureVariable threw for {Node}", nodeId); }
}
@@ -78,6 +78,11 @@ public sealed record ScriptedAlarmPlan(string ScriptedAlarmId, string EquipmentI
/// (<c>DeploymentArtifact.BuildEquipmentTagPlans</c>) for byte-parity. <see cref="Alarm"/> carries
/// the optional native-alarm intent parsed from <c>Tag.TagConfig</c>'s <c>alarm</c> object (null ⇒
/// a plain value variable); it too is parsed identically on the artifact-decode side for byte-parity.
/// <see cref="IsHistorized"/> / <see cref="HistorianTagname"/> carry the optional server-side
/// HistoryRead intent parsed from <c>Tag.TagConfig</c>'s <c>isHistorized</c> bool +
/// <c>historianTagname</c> string (Phase C); a null <see cref="HistorianTagname"/> means the historian
/// tagname defaults to <see cref="FullName"/> (resolved later, not here). Both are parsed identically
/// on the artifact-decode side for byte-parity.
/// </summary>
public sealed record EquipmentTagPlan(
string TagId,
@@ -88,7 +93,9 @@ public sealed record EquipmentTagPlan(
string DataType,
string FullName,
bool Writable,
EquipmentTagAlarmInfo? Alarm);
EquipmentTagAlarmInfo? Alarm,
bool IsHistorized = false,
string? HistorianTagname = null);
/// <summary>Native-alarm intent parsed from an equipment tag's <c>TagConfig.alarm</c> object. Null ⇒
/// the tag is a plain value variable. <see cref="AlarmType"/> is an OPC UA Part 9 subtype string
@@ -328,16 +335,22 @@ public static class Phase7Composer
.OrderBy(t => t.EquipmentId, StringComparer.Ordinal)
.ThenBy(t => t.FolderPath ?? string.Empty, StringComparer.Ordinal) // coalesce so the sort matches the artifact-decode side exactly
.ThenBy(t => t.Name, StringComparer.Ordinal)
.Select(t => new EquipmentTagPlan(
TagId: t.TagId,
EquipmentId: t.EquipmentId!,
DriverInstanceId: t.DriverInstanceId,
FolderPath: t.FolderPath ?? string.Empty,
Name: t.Name,
DataType: t.DataType,
FullName: ExtractTagFullName(t.TagConfig),
Writable: t.AccessLevel == TagAccessLevel.ReadWrite,
Alarm: ExtractTagAlarm(t.TagConfig)))
.Select(t =>
{
var (isHistorized, historianTagname) = ExtractTagHistorize(t.TagConfig);
return new EquipmentTagPlan(
TagId: t.TagId,
EquipmentId: t.EquipmentId!,
DriverInstanceId: t.DriverInstanceId,
FolderPath: t.FolderPath ?? string.Empty,
Name: t.Name,
DataType: t.DataType,
FullName: ExtractTagFullName(t.TagConfig),
Writable: t.AccessLevel == TagAccessLevel.ReadWrite,
Alarm: ExtractTagAlarm(t.TagConfig),
IsHistorized: isHistorized,
HistorianTagname: historianTagname);
})
.ToList();
// Per-equipment tag base = the shared substring-before-first-dot across each equipment's
@@ -474,4 +487,33 @@ public static class Phase7Composer
}
catch (JsonException) { return null; }
}
/// <summary>Parses the optional server-side HistoryRead intent from a tag's <c>TagConfig</c> JSON:
/// the <c>isHistorized</c> bool (absent / not a bool / non-object root / blank / malformed ⇒
/// <c>false</c>) and the optional <c>historianTagname</c> string override (absent / not a string /
/// whitespace-or-empty ⇒ <c>null</c>, meaning the historian tagname defaults to the tag's FullName,
/// resolved later). The raw string value is used — not trimmed — matching <c>ExtractTagFullName</c> /
/// <c>ExtractTagAlarm</c>. Never throws. The artifact-decode side
/// (<c>DeploymentArtifact.ExtractTagHistorize</c>) MUST parse identically (byte-parity).</summary>
internal static (bool IsHistorized, string? HistorianTagname) ExtractTagHistorize(string? tagConfig)
{
if (string.IsNullOrWhiteSpace(tagConfig)) return (false, null);
try
{
using var doc = JsonDocument.Parse(tagConfig);
if (doc.RootElement.ValueKind != JsonValueKind.Object) return (false, null);
var isHistorized = doc.RootElement.TryGetProperty("isHistorized", out var hEl)
&& (hEl.ValueKind == JsonValueKind.True || hEl.ValueKind == JsonValueKind.False)
&& hEl.GetBoolean();
string? tagname = null;
if (doc.RootElement.TryGetProperty("historianTagname", out var nEl)
&& nEl.ValueKind == JsonValueKind.String)
{
var raw = nEl.GetString();
if (!string.IsNullOrWhiteSpace(raw)) tagname = raw;
}
return (isHistorized, tagname);
}
catch (JsonException) { return (false, null); }
}
}
@@ -57,8 +57,10 @@ public sealed class SdkAddressSpaceSink : IOpcUaAddressSpaceSink
/// <param name="displayName">The display name for the variable.</param>
/// <param name="dataType">The OPC UA data type.</param>
/// <param name="writable">When true the node is created read/write; otherwise read-only.</param>
public void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable)
=> _nodeManager.EnsureVariable(variableNodeId, parentFolderNodeId, displayName, dataType, writable);
/// <param name="historianTagname">null ⇒ not historized; non-null ⇒ create Historizing with the
/// HistoryRead access bit and register the historian tagname.</param>
public void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable, string? historianTagname = null)
=> _nodeManager.EnsureVariable(variableNodeId, parentFolderNodeId, displayName, dataType, writable, historianTagname);
/// <summary>Rebuilds the entire OPC UA address space.</summary>
public void RebuildAddressSpace() => _nodeManager.RebuildAddressSpace();
@@ -437,6 +437,7 @@ public static class DeploymentArtifact
// ordinary equipment tags now (GalaxyMxGateway is a standard Equipment-kind driver).
if (!equipmentNamespaces.Contains(nsId)) continue;
var (isHistorized, historianTagname) = ExtractTagHistorize(tagConfig);
result.Add(new EquipmentTagPlan(
TagId: tagId!,
EquipmentId: equipmentId!,
@@ -446,7 +447,9 @@ public static class DeploymentArtifact
DataType: dataType ?? "BaseDataType",
FullName: ExtractTagFullName(tagConfig),
Writable: writable,
Alarm: ExtractTagAlarm(tagConfig)));
Alarm: ExtractTagAlarm(tagConfig),
IsHistorized: isHistorized,
HistorianTagname: historianTagname));
}
result.Sort((a, b) =>
@@ -672,6 +675,35 @@ public static class DeploymentArtifact
catch (JsonException) { return null; }
}
/// <summary>Parses the optional server-side HistoryRead intent from a tag's <c>TagConfig</c> JSON:
/// the <c>isHistorized</c> bool (absent / not a bool / non-object root / blank / malformed ⇒
/// <c>false</c>) and the optional <c>historianTagname</c> string override (absent / not a string /
/// whitespace-or-empty ⇒ <c>null</c>, meaning the historian tagname defaults to the tag's FullName,
/// resolved later). The raw string value is used — not trimmed — matching <c>ExtractTagFullName</c> /
/// <c>ExtractTagAlarm</c>. Never throws. The live-edit composer side
/// (<c>Phase7Composer.ExtractTagHistorize</c>) MUST parse identically (byte-parity).</summary>
private static (bool IsHistorized, string? HistorianTagname) ExtractTagHistorize(string? tagConfig)
{
if (string.IsNullOrWhiteSpace(tagConfig)) return (false, null);
try
{
using var doc = JsonDocument.Parse(tagConfig);
if (doc.RootElement.ValueKind != JsonValueKind.Object) return (false, null);
var isHistorized = doc.RootElement.TryGetProperty("isHistorized", out var hEl)
&& (hEl.ValueKind == JsonValueKind.True || hEl.ValueKind == JsonValueKind.False)
&& hEl.GetBoolean();
string? tagname = null;
if (doc.RootElement.TryGetProperty("historianTagname", out var nEl)
&& nEl.ValueKind == JsonValueKind.String)
{
var raw = nEl.GetString();
if (!string.IsNullOrWhiteSpace(raw)) tagname = raw;
}
return (isHistorized, tagname);
}
catch (JsonException) { return (false, null); }
}
private static IReadOnlyList<T> ReadArray<T>(JsonElement root, string propertyName, Func<JsonElement, T?> reader)
where T : class
{
@@ -0,0 +1,57 @@
using System.Collections.Generic;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Historian;
/// <summary>
/// Binds the <c>ServerHistorian</c> configuration section that gates the server-side
/// HistoryRead backend. When <see cref="Enabled"/> is <c>true</c>, <c>AddServerHistorian</c>
/// registers a read-only <c>WonderwareHistorianClient</c> (supplied by the Host) as the
/// <c>IHistorianDataSource</c> in place of the <c>NullHistorianDataSource</c> default;
/// otherwise the Null default survives and HistoryRead returns <c>GoodNoData</c>-empty.
/// <para>
/// This is the READ path only — there are no DatabasePath / drain / capacity / retention
/// knobs (those belong to the write-side <c>AlarmHistorian</c> store-and-forward sink). The
/// client's own <c>CallTimeout</c> bounds each read; the node manager adds no extra timeout.
/// </para>
/// </summary>
public sealed class ServerHistorianOptions
{
/// <summary>The configuration section name this options class binds.</summary>
public const string SectionName = "ServerHistorian";
/// <summary>
/// When <c>true</c>, the Wonderware read client is registered as the
/// <c>IHistorianDataSource</c>; when <c>false</c> (the default) the no-op
/// <c>NullHistorianDataSource</c> stays in place and HistoryRead returns empty.
/// </summary>
public bool Enabled { get; init; }
/// <summary>TCP hostname or IP address the Wonderware historian sidecar listens on.</summary>
public string Host { get; init; } = "localhost";
/// <summary>TCP port the Wonderware historian sidecar listens on.</summary>
public int Port { get; init; } = 32569;
/// <summary>When <c>true</c>, the client connects over TLS.</summary>
public bool UseTls { get; init; }
/// <summary>Expected TLS server certificate thumbprint (hex, no spaces). Null or empty disables pinning.</summary>
public string? ServerCertThumbprint { get; init; }
/// <summary>Per-process shared secret the sidecar verifies in the Hello frame.</summary>
public string SharedSecret { get; init; } = "";
/// <summary>Returns operator-facing misconfiguration warnings for an <c>Enabled</c> historian
/// (empty when disabled or correctly configured). Pure — the registration logs each entry.</summary>
/// <returns>Zero or more human-readable warning messages.</returns>
public IReadOnlyList<string> Validate()
{
var warnings = new List<string>();
if (!Enabled) return warnings;
if (string.IsNullOrWhiteSpace(SharedSecret))
warnings.Add("ServerHistorian:SharedSecret is empty while the historian is enabled — the Wonderware sidecar Hello frame will carry an empty secret.");
if (Port <= 0)
warnings.Add($"ServerHistorian:Port is {Port} — must be > 0; the read client cannot dial the sidecar.");
return warnings;
}
}
@@ -42,6 +42,7 @@ public static class ServiceCollectionExtensions
public static IServiceCollection AddOtOpcUaRuntime(this IServiceCollection services)
{
services.TryAddSingleton<IAlarmHistorianSink>(NullAlarmHistorianSink.Instance);
services.TryAddSingleton<IHistorianDataSource>(NullHistorianDataSource.Instance);
services.TryAddSingleton<IDriverFactory>(NullDriverFactory.Instance);
services.TryAddSingleton<IOpcUaAddressSpaceSink>(NullOpcUaAddressSpaceSink.Instance);
services.TryAddSingleton<IServiceLevelPublisher>(NullServiceLevelPublisher.Instance);
@@ -93,6 +94,38 @@ public static class ServiceCollectionExtensions
return services;
}
/// <summary>
/// Config-gated server-side HistoryRead backend. When the <c>ServerHistorian</c> section has
/// <c>Enabled=true</c>, registers the <paramref name="dataSourceFactory"/>-supplied
/// <see cref="IHistorianDataSource"/> (the read-only Wonderware client) overriding the
/// <see cref="NullHistorianDataSource"/> default from <see cref="AddOtOpcUaRuntime"/>. Otherwise
/// a no-op (the Null default stays and the node manager's HistoryRead returns
/// <c>GoodNoData</c>-empty). The data source is injected so the Wonderware client can be supplied
/// by the Host, which is the only project that references it.
/// </summary>
/// <param name="services">The service collection to register with.</param>
/// <param name="configuration">The configuration carrying the <c>ServerHistorian</c> section.</param>
/// <param name="dataSourceFactory">
/// Factory the Host supplies to build the concrete read <see cref="IHistorianDataSource"/>
/// (the Wonderware client) from the bound options + the resolving provider.
/// </param>
/// <returns>The same <paramref name="services"/> instance for chaining.</returns>
public static IServiceCollection AddServerHistorian(
this IServiceCollection services,
IConfiguration configuration,
Func<ServerHistorianOptions, IServiceProvider, IHistorianDataSource> dataSourceFactory)
{
var opts = configuration.GetSection(ServerHistorianOptions.SectionName).Get<ServerHistorianOptions>();
if (opts is not { Enabled: true }) return services; // leave the Null default from AddOtOpcUaRuntime
foreach (var warning in opts.Validate())
Serilog.Log.Logger.ForContext<IHistorianDataSource>().Warning("ServerHistorian config: {ServerHistorianConfigWarning}", warning);
// Last-registration-wins over the TryAddSingleton Null default seeded by AddOtOpcUaRuntime.
services.AddSingleton<IHistorianDataSource>(sp => dataSourceFactory(opts, sp));
return services;
}
/// <summary>
/// Spawns the per-node driver-role actors on the host's <see cref="ActorSystem"/>:
/// <see cref="DriverHostActor"/> (one per node), <see cref="DbHealthProbeActor"/>
@@ -0,0 +1,100 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests.Historian;
/// <summary>
/// The default no-op historian source. Every read returns an empty result with a null
/// continuation point; <see cref="NullHistorianDataSource.GetHealthSnapshot"/> reports a fully
/// disabled shape; and <see cref="NullHistorianDataSource.Instance"/> is the shared singleton.
/// </summary>
public sealed class NullHistorianDataSourceTests
{
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private static readonly NullHistorianDataSource Source = NullHistorianDataSource.Instance;
/// <summary><see cref="NullHistorianDataSource.Instance"/> is a single shared instance.</summary>
[Fact]
public void Instance_is_a_singleton()
{
NullHistorianDataSource.Instance.ShouldBeSameAs(NullHistorianDataSource.Instance);
}
/// <summary>ReadRawAsync returns no samples and a null continuation point.</summary>
[Fact]
public async Task ReadRawAsync_returns_empty()
{
var result = await Source.ReadRawAsync(
"WW.Tag", DateTime.UtcNow.AddHours(-1), DateTime.UtcNow, maxValuesPerNode: 100, Ct);
result.Samples.ShouldBeEmpty();
result.ContinuationPoint.ShouldBeNull();
}
/// <summary>ReadProcessedAsync returns no samples and a null continuation point.</summary>
[Fact]
public async Task ReadProcessedAsync_returns_empty()
{
var result = await Source.ReadProcessedAsync(
"WW.Tag", DateTime.UtcNow.AddHours(-1), DateTime.UtcNow,
TimeSpan.FromSeconds(10), HistoryAggregateType.Average, Ct);
result.Samples.ShouldBeEmpty();
result.ContinuationPoint.ShouldBeNull();
}
/// <summary>ReadAtTimeAsync returns no samples and a null continuation point.</summary>
[Fact]
public async Task ReadAtTimeAsync_returns_empty()
{
var result = await Source.ReadAtTimeAsync(
"WW.Tag", new[] { DateTime.UtcNow }, Ct);
result.Samples.ShouldBeEmpty();
result.ContinuationPoint.ShouldBeNull();
}
/// <summary>ReadEventsAsync returns no events and a null continuation point.</summary>
[Fact]
public async Task ReadEventsAsync_returns_empty()
{
var result = await Source.ReadEventsAsync(
sourceName: null, DateTime.UtcNow.AddHours(-1), DateTime.UtcNow, maxEvents: 0, Ct);
result.Events.ShouldBeEmpty();
result.ContinuationPoint.ShouldBeNull();
}
/// <summary>GetHealthSnapshot reports a fully-disabled (zeroed, disconnected, no-node) shape.</summary>
[Fact]
public void GetHealthSnapshot_is_disabled()
{
var snapshot = Source.GetHealthSnapshot();
snapshot.TotalQueries.ShouldBe(0);
snapshot.TotalSuccesses.ShouldBe(0);
snapshot.TotalFailures.ShouldBe(0);
snapshot.ConsecutiveFailures.ShouldBe(0);
snapshot.LastSuccessTime.ShouldBeNull();
snapshot.LastFailureTime.ShouldBeNull();
snapshot.LastError.ShouldBeNull();
snapshot.ProcessConnectionOpen.ShouldBeFalse();
snapshot.EventConnectionOpen.ShouldBeFalse();
snapshot.ActiveProcessNode.ShouldBeNull();
snapshot.ActiveEventNode.ShouldBeNull();
snapshot.Nodes.ShouldBeEmpty();
}
/// <summary>Dispose is a safe no-op (idempotent).</summary>
[Fact]
public void Dispose_is_a_noop()
{
Should.NotThrow(() =>
{
Source.Dispose();
Source.Dispose();
});
}
}
@@ -67,6 +67,22 @@ public sealed class DeferredAddressSpaceSinkTests
second.Calls.Single().ShouldBe("WV:b");
}
/// <summary>Verifies that <see cref="DeferredAddressSpaceSink.EnsureVariable"/> forwards the
/// <c>historianTagname</c> argument to the inner sink unchanged.</summary>
[Fact]
public void EnsureVariable_forwards_historianTagname_to_inner_sink()
{
var deferred = new DeferredAddressSpaceSink();
var inner = new RecordingSink();
deferred.SetSink(inner);
deferred.EnsureVariable("v-1", null, "MyVar", "Float", writable: false, historianTagname: "MyTag.PV");
var call = inner.HistorianCalls.ShouldHaveSingleItem();
call.NodeId.ShouldBe("v-1");
call.HistorianTagname.ShouldBe("MyTag.PV");
}
/// <summary>Builds a minimal <see cref="AlarmConditionSnapshot"/> for the forwarding tests (the
/// inner sink only records the node id, so the exact state values don't matter here).</summary>
private static AlarmConditionSnapshot Snapshot(bool active = false) =>
@@ -80,6 +96,12 @@ public sealed class DeferredAddressSpaceSinkTests
/// <summary>Gets the list of recorded calls.</summary>
public List<string> Calls => CallQueue.ToList();
/// <summary>Gets the queue of (NodeId, HistorianTagname) pairs captured per
/// <c>EnsureVariable</c> call, in call order.</summary>
public ConcurrentQueue<(string NodeId, string? HistorianTagname)> HistorianQueue { get; } = new();
/// <summary>Gets the list of (NodeId, HistorianTagname) pairs captured per EnsureVariable call.</summary>
public List<(string NodeId, string? HistorianTagname)> HistorianCalls => HistorianQueue.ToList();
/// <inheritdoc />
public void WriteValue(string nodeId, object? value, OpcUaQuality quality, DateTime sourceTimestampUtc)
=> CallQueue.Enqueue($"WV:{nodeId}");
@@ -93,8 +115,11 @@ public sealed class DeferredAddressSpaceSinkTests
public void EnsureFolder(string folderNodeId, string? parentNodeId, string displayName)
=> CallQueue.Enqueue($"EF:{folderNodeId}");
/// <inheritdoc />
public void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable)
=> CallQueue.Enqueue($"EV:{variableNodeId}");
public void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable, string? historianTagname = null)
{
CallQueue.Enqueue($"EV:{variableNodeId}");
HistorianQueue.Enqueue((variableNodeId, historianTagname));
}
/// <inheritdoc />
public void RebuildAddressSpace() => CallQueue.Enqueue("RB");
}
@@ -0,0 +1,35 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests;
public class ExtractTagHistorizeTests
{
[Theory]
// isHistorized true, no explicit tagname ⇒ tagname null (defaults to FullName later).
[InlineData("{\"FullName\":\"T.A\",\"isHistorized\":true}", true, null)]
// isHistorized true with an explicit historian-tagname override.
[InlineData("{\"FullName\":\"T.A\",\"isHistorized\":true,\"historianTagname\":\"WW.Tag\"}", true, "WW.Tag")]
// Absent isHistorized ⇒ false.
[InlineData("{\"FullName\":\"T.A\"}", false, null)]
// historianTagname parses independently of the flag.
[InlineData("{\"FullName\":\"T.A\",\"isHistorized\":false,\"historianTagname\":\"WW.Tag\"}", false, "WW.Tag")]
// Blank/whitespace tagname ⇒ null.
[InlineData("{\"FullName\":\"T.A\",\"isHistorized\":true,\"historianTagname\":\" \"}", true, null)]
// null / empty / malformed-JSON / array-root ⇒ (false, null), never throws.
[InlineData(null, false, null)]
[InlineData("", false, null)]
[InlineData("not json {", false, null)]
[InlineData("[1,2]", false, null)]
// Wrong type for isHistorized (string, not bool) ⇒ false.
[InlineData("{\"isHistorized\":\"yes\"}", false, null)]
// Wrong type for historianTagname (number, not string) ⇒ tagname null, flag still honoured.
[InlineData("{\"isHistorized\":true,\"historianTagname\":123}", true, null)]
public void ExtractTagHistorize_parses_or_returns_defaults(string? cfg, bool expectedHistorized, string? expectedTagname)
{
var (isHistorized, historianTagname) = Phase7Composer.ExtractTagHistorize(cfg);
isHistorized.ShouldBe(expectedHistorized);
historianTagname.ShouldBe(expectedTagname);
}
}
@@ -0,0 +1,159 @@
using Microsoft.Extensions.Logging.Abstractions;
using Opc.Ua;
using Shouldly;
using Xunit;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests;
/// <summary>
/// Phase C Task 2 — node-manager materialisation honours the historize intent. Boot a real
/// <see cref="OtOpcUaSdkServer"/> through <see cref="OpcUaApplicationHost"/> (the same harness
/// <see cref="SdkAddressSpaceSinkTests"/> uses), drive <see cref="OtOpcUaNodeManager.EnsureVariable"/>
/// with / without a historian tagname, and assert the created <see cref="BaseDataVariableState"/>'s
/// <c>Historizing</c> flag + <c>HistoryRead</c> access bit + the NodeId→tagname registration.
/// </summary>
public sealed class NodeManagerHistorizeTests : IDisposable
{
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private readonly string _pkiRoot = Path.Combine(
Path.GetTempPath(),
$"otopcua-historize-{Guid.NewGuid():N}");
/// <summary>A historized variable is created Historizing, gains the HistoryRead access bit in BOTH
/// AccessLevel and UserAccessLevel, and its NodeId→tagname registration is queryable.</summary>
[Fact]
public async Task EnsureVariable_with_historian_tagname_sets_historizing_and_history_read_bit()
{
var (host, server) = await BootAsync();
var nm = server.NodeManager!;
nm.EnsureVariable("eq-1/temp", parentFolderNodeId: null, displayName: "Temp", dataType: "Float",
writable: false, historianTagname: "WW.Tag");
var variable = nm.TryGetVariable("eq-1/temp");
variable.ShouldNotBeNull();
variable!.Historizing.ShouldBeTrue();
(variable.AccessLevel & AccessLevels.HistoryRead).ShouldNotBe((byte)0);
(variable.UserAccessLevel & AccessLevels.HistoryRead).ShouldNotBe((byte)0);
// Read-only historized node still grants CurrentRead.
(variable.AccessLevel & AccessLevels.CurrentRead).ShouldNotBe((byte)0);
// The NodeId→resolved-tagname registration is queryable for the (later) HistoryRead override.
nm.TryGetHistorizedTagname("eq-1/temp", out var tagname).ShouldBeTrue();
tagname.ShouldBe("WW.Tag");
await host.DisposeAsync();
}
/// <summary>A non-historized variable (tagname null / omitted) stays Historizing=false, has no
/// HistoryRead bit, and is NOT registered in the NodeId→tagname map.</summary>
[Fact]
public async Task EnsureVariable_without_historian_tagname_is_not_historized()
{
var (host, server) = await BootAsync();
var nm = server.NodeManager!;
// Explicit null and the defaulted-param form both mean "not historized".
nm.EnsureVariable("eq-1/plain", parentFolderNodeId: null, displayName: "Plain", dataType: "Int32",
writable: false, historianTagname: null);
nm.EnsureVariable("eq-1/plain2", parentFolderNodeId: null, displayName: "Plain2", dataType: "Int32",
writable: false);
foreach (var nodeId in new[] { "eq-1/plain", "eq-1/plain2" })
{
var variable = nm.TryGetVariable(nodeId);
variable.ShouldNotBeNull();
variable!.Historizing.ShouldBeFalse();
(variable.AccessLevel & AccessLevels.HistoryRead).ShouldBe((byte)0);
(variable.UserAccessLevel & AccessLevels.HistoryRead).ShouldBe((byte)0);
nm.TryGetHistorizedTagname(nodeId, out var tagname).ShouldBeFalse();
tagname.ShouldBeNull();
}
await host.DisposeAsync();
}
/// <summary>A historized AND writable node keeps the CurrentRead|CurrentWrite composite AND gains the
/// HistoryRead bit (the three bits are OR-ed, not replaced).</summary>
[Fact]
public async Task EnsureVariable_historized_and_writable_keeps_read_write_and_adds_history_read()
{
var (host, server) = await BootAsync();
var nm = server.NodeManager!;
nm.EnsureVariable("eq-1/setpoint", parentFolderNodeId: null, displayName: "Setpoint", dataType: "Float",
writable: true, historianTagname: "WW.Setpoint");
var variable = nm.TryGetVariable("eq-1/setpoint");
variable.ShouldNotBeNull();
variable!.Historizing.ShouldBeTrue();
(variable.AccessLevel & AccessLevels.CurrentRead).ShouldNotBe((byte)0);
(variable.AccessLevel & AccessLevels.CurrentWrite).ShouldNotBe((byte)0);
(variable.AccessLevel & AccessLevels.HistoryRead).ShouldNotBe((byte)0);
// The composite is exactly CurrentRead | CurrentWrite | HistoryRead.
variable.AccessLevel.ShouldBe((byte)(AccessLevels.CurrentRead | AccessLevels.CurrentWrite | AccessLevels.HistoryRead));
variable.UserAccessLevel.ShouldBe(variable.AccessLevel);
nm.TryGetHistorizedTagname("eq-1/setpoint", out var tagname).ShouldBeTrue();
tagname.ShouldBe("WW.Setpoint");
await host.DisposeAsync();
}
/// <summary>RebuildAddressSpace drops the NodeId→tagname registrations alongside the variables.</summary>
[Fact]
public async Task RebuildAddressSpace_clears_historized_tagname_registrations()
{
var (host, server) = await BootAsync();
var nm = server.NodeManager!;
nm.EnsureVariable("eq-1/temp", parentFolderNodeId: null, displayName: "Temp", dataType: "Float",
writable: false, historianTagname: "WW.Tag");
nm.TryGetHistorizedTagname("eq-1/temp", out _).ShouldBeTrue();
nm.RebuildAddressSpace();
nm.TryGetHistorizedTagname("eq-1/temp", out var tagname).ShouldBeFalse();
tagname.ShouldBeNull();
await host.DisposeAsync();
}
private async Task<(OpcUaApplicationHost Host, OtOpcUaSdkServer Server)> BootAsync()
{
var host = new OpcUaApplicationHost(
new OpcUaApplicationHostOptions
{
ApplicationName = "OtOpcUa.HistorizeTest",
ApplicationUri = $"urn:OtOpcUa.HistorizeTest:{Guid.NewGuid():N}",
OpcUaPort = AllocateFreePort(),
PublicHostname = "localhost",
PkiStoreRoot = _pkiRoot,
},
NullLogger<OpcUaApplicationHost>.Instance);
var server = new OtOpcUaSdkServer();
await host.StartAsync(server, Ct);
return (host, server);
}
private static int AllocateFreePort()
{
using var listener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 0);
listener.Start();
var port = ((System.Net.IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();
return port;
}
/// <summary>Cleans up the PKI root directory.</summary>
public void Dispose()
{
if (Directory.Exists(_pkiRoot))
{
try { Directory.Delete(_pkiRoot, recursive: true); }
catch { /* best-effort cleanup */ }
}
}
}
@@ -0,0 +1,427 @@
using Microsoft.Extensions.Logging.Abstractions;
using Opc.Ua;
using Opc.Ua.Server;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using HistorianRead = ZB.MOM.WW.OtOpcUa.Core.Abstractions.HistoryReadResult;
using SdkHistoryReadResult = Opc.Ua.HistoryReadResult;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests;
/// <summary>
/// Phase C Task 4 — the node-manager's OPC UA HistoryReadEvents override over equipment-folder
/// event-notifier nodes. Boots a real <see cref="OtOpcUaSdkServer"/> (the same harness Task 3 uses),
/// wires a recording fake <see cref="IHistorianDataSource"/> BEFORE materialising an alarm condition
/// (so the alarm-owning equipment folder is promoted to an event notifier WITH the HistoryRead bit),
/// then invokes the node manager's PUBLIC <c>HistoryRead(OperationContext, …)</c> with a
/// <see cref="ReadEventDetails"/>. The base CustomNodeManager2 builds the node handles + dispatches to
/// the protected <c>HistoryReadEvents</c> override, so this exercises the real dispatch path
/// in-process — fast + deterministic, no client socket.
/// </summary>
public sealed class NodeManagerHistoryReadEventsTests : IDisposable
{
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private readonly string _pkiRoot = Path.Combine(
Path.GetTempPath(),
$"otopcua-historyreadevents-{Guid.NewGuid():N}");
/// <summary>Happy path: the fake receives (sourceName == the equipment-folder id, StartTime, EndTime,
/// maxEvents), and each returned event decodes to a HistoryEventFieldList whose EventFields are in
/// SelectClause ORDER with correctly-typed Variants (EventId ByteString, SourceName string, Time
/// DateTime, ReceiveTime DateTime, Message LocalizedText, Severity UInt16). StatusCode is Good when
/// events are present.</summary>
[Fact]
public async Task Events_dispatches_to_source_and_projects_fields_in_select_order()
{
var (host, server) = await BootAsync();
var nm = server.NodeManager!;
var fake = new RecordingHistorianDataSource();
// Wire the source BEFORE materialising the alarm so the folder gets the HistoryRead bit.
nm.HistorianDataSource = fake;
const string equipmentId = "eq-evt";
nm.EnsureFolder(equipmentId, parentNodeId: null, displayName: "Equipment");
nm.MaterialiseAlarmCondition("alarm-1", equipmentId, "HighTemp", "OffNormalAlarm", severity: 700);
var notifierNodeId = nm.TryGetFolder(equipmentId)!.NodeId;
var evtTime = new DateTime(2026, 6, 14, 10, 0, 0, DateTimeKind.Utc);
var rcvTime = new DateTime(2026, 6, 14, 10, 0, 1, DateTimeKind.Utc);
fake.EventsResult = new HistoricalEventsResult(
new[] { new HistoricalEvent("evt-42", "Pump_001", evtTime, rcvTime, "Pump tripped", 700) }, null);
var start = DateTime.UtcNow.AddHours(-1);
var end = DateTime.UtcNow;
var details = new ReadEventDetails
{
StartTime = start,
EndTime = end,
NumValuesPerNode = 50,
// ReceiveTime is included to verify it projects evt.ReceivedTimeUtc at index 3.
Filter = SelectFilter("EventId", "SourceName", "Time", "ReceiveTime", "Message", "Severity"),
};
var (results, errors) = InvokeHistoryRead(server, nm, details, notifierNodeId);
// The source saw the equipment/folder id as the sourceName + the request window + cap.
fake.LastSourceName.ShouldBe(equipmentId);
fake.LastStart.ShouldBe(start);
fake.LastEnd.ShouldBe(end);
fake.LastMaxEvents.ShouldBe(50);
errors[0].StatusCode.Code.ShouldBe(StatusCodes.Good);
results[0].StatusCode.Code.ShouldBe(StatusCodes.Good);
var history = (HistoryEvent)ExtensionObject.ToEncodeable(results[0].HistoryData);
history.Events.Count.ShouldBe(1);
var fields = history.Events[0].EventFields;
fields.Count.ShouldBe(6);
// EventId ⇒ ByteString (UTF-8 of "evt-42").
fields[0].Value.ShouldBeOfType<byte[]>().ShouldBe(System.Text.Encoding.UTF8.GetBytes("evt-42"));
// SourceName ⇒ string.
fields[1].Value.ShouldBe("Pump_001");
// Time ⇒ DateTime (event occurrence time).
fields[2].Value.ShouldBe(evtTime);
// ReceiveTime ⇒ DateTime (server receipt time = ReceivedTimeUtc).
fields[3].Value.ShouldBe(rcvTime);
// Message ⇒ LocalizedText.
fields[4].Value.ShouldBeOfType<LocalizedText>().Text.ShouldBe("Pump tripped");
// Severity ⇒ UInt16.
fields[5].Value.ShouldBe((ushort)700);
await host.DisposeAsync();
}
/// <summary>An unsupported select operand (BrowsePath ["EventType"]) projects to Variant.Null — a field
/// the server can't supply is null (spec-conformant) — while supported siblings still project.</summary>
[Fact]
public async Task Events_unsupported_select_field_projects_null()
{
var (host, server) = await BootAsync();
var nm = server.NodeManager!;
var fake = new RecordingHistorianDataSource();
nm.HistorianDataSource = fake;
const string equipmentId = "eq-unsupported";
nm.EnsureFolder(equipmentId, parentNodeId: null, displayName: "Equipment");
nm.MaterialiseAlarmCondition("alarm-2", equipmentId, "Cond", "OffNormalAlarm", severity: 500);
var notifierNodeId = nm.TryGetFolder(equipmentId)!.NodeId;
fake.EventsResult = new HistoricalEventsResult(
new[] { new HistoricalEvent("evt-1", "Src", DateTime.UtcNow, DateTime.UtcNow, "msg", 500) }, null);
var details = new ReadEventDetails
{
StartTime = DateTime.UtcNow.AddHours(-1),
EndTime = DateTime.UtcNow,
NumValuesPerNode = 10,
// EventType is a real BaseEventType field we cannot supply from a HistoricalEvent; EventId is.
Filter = SelectFilter("EventType", "EventId"),
};
var (results, errors) = InvokeHistoryRead(server, nm, details, notifierNodeId);
errors[0].StatusCode.Code.ShouldBe(StatusCodes.Good);
var history = (HistoryEvent)ExtensionObject.ToEncodeable(results[0].HistoryData);
var fields = history.Events[0].EventFields;
fields.Count.ShouldBe(2);
// EventType ⇒ Variant.Null.
fields[0].Value.ShouldBeNull();
// EventId still projects to a ByteString.
fields[1].Value.ShouldBeOfType<byte[]>().ShouldBe(System.Text.Encoding.UTF8.GetBytes("evt-1"));
await host.DisposeAsync();
}
/// <summary>Empty events ⇒ the notifier's StatusCode is GoodNoData (the source is wired, the window
/// just held no events).</summary>
[Fact]
public async Task Events_empty_yields_GoodNoData()
{
var (host, server) = await BootAsync();
var nm = server.NodeManager!;
var fake = new RecordingHistorianDataSource
{
EventsResult = new HistoricalEventsResult(Array.Empty<HistoricalEvent>(), null),
};
nm.HistorianDataSource = fake;
const string equipmentId = "eq-empty";
nm.EnsureFolder(equipmentId, parentNodeId: null, displayName: "Equipment");
nm.MaterialiseAlarmCondition("alarm-3", equipmentId, "Cond", "OffNormalAlarm", severity: 300);
var notifierNodeId = nm.TryGetFolder(equipmentId)!.NodeId;
var details = new ReadEventDetails
{
StartTime = DateTime.UtcNow.AddHours(-1),
EndTime = DateTime.UtcNow,
NumValuesPerNode = 10,
Filter = SelectFilter("EventId"),
};
var (results, errors) = InvokeHistoryRead(server, nm, details, notifierNodeId);
errors[0].StatusCode.Code.ShouldBe(StatusCodes.Good);
results[0].StatusCode.Code.ShouldBe(StatusCodes.GoodNoData);
var history = (HistoryEvent)ExtensionObject.ToEncodeable(results[0].HistoryData);
history.Events.ShouldBeEmpty();
await host.DisposeAsync();
}
/// <summary>A folder promoted to an event notifier while NO historian was wired (Null source at
/// materialise time) is NOT registered as an event-history source ⇒ a HistoryReadEvents over it yields
/// BadHistoryOperationUnsupported, and the (later-wired) source is never invoked.</summary>
[Fact]
public async Task Events_folder_promoted_without_source_yields_BadHistoryOperationUnsupported()
{
var (host, server) = await BootAsync();
var nm = server.NodeManager!;
// Materialise the alarm while the source is still the Null default — the folder is promoted to
// SubscribeToEvents but DOES NOT get the HistoryRead bit / source registration.
const string equipmentId = "eq-nosrc";
nm.EnsureFolder(equipmentId, parentNodeId: null, displayName: "Equipment");
nm.MaterialiseAlarmCondition("alarm-4", equipmentId, "Cond", "OffNormalAlarm", severity: 200);
var notifierNodeId = nm.TryGetFolder(equipmentId)!.NodeId;
// Wire a real source AFTER promotion — it must NOT retroactively make the folder a source.
var fake = new RecordingHistorianDataSource();
nm.HistorianDataSource = fake;
var details = new ReadEventDetails
{
StartTime = DateTime.UtcNow.AddHours(-1),
EndTime = DateTime.UtcNow,
NumValuesPerNode = 10,
Filter = SelectFilter("EventId"),
};
var (_, errors) = InvokeHistoryRead(server, nm, details, notifierNodeId);
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadHistoryOperationUnsupported);
fake.LastSourceName.ShouldBeNull(); // source never reached
fake.EventsCalled.ShouldBeFalse();
await host.DisposeAsync();
}
/// <summary>A variable node targeted by a HistoryReadEvents request ⇒ BadHistoryOperationUnsupported;
/// the source is never invoked.
/// <para>
/// NOTE — what this test actually pins: the SDK base (CustomNodeManager2.HistoryRead) filters
/// event-history reads by the <c>EventNotifier.HistoryRead</c> bit, NOT by
/// <c>AccessLevel.HistoryRead</c>. A variable node carries <c>AccessLevel.HistoryRead</c> (for
/// variable-history reads) but <c>EventNotifier = None</c> (no event-notifier bits at all). The
/// SDK base therefore rejects it and does NOT pass it to our <c>HistoryReadEvents</c> override;
/// the Bad result comes from the base's pre-seeding, not from our source-guard. This test pins
/// that base-level rejection of variable nodes for event reads.
/// The override's own source-guard (miss in <c>_eventNotifierSources</c>) is exercised by the
/// <c>Events_folder_promoted_without_source_yields_BadHistoryOperationUnsupported</c> test instead.
/// </para>
/// </summary>
[Fact]
public async Task Events_non_source_node_yields_BadHistoryOperationUnsupported()
{
var (host, server) = await BootAsync();
var nm = server.NodeManager!;
var fake = new RecordingHistorianDataSource();
nm.HistorianDataSource = fake;
// A historized variable node — has AccessLevel.HistoryRead (variable-history reads) but
// EventNotifier=None (no event-notifier bit). The SDK base rejects it before our override runs.
nm.EnsureVariable("eq-1/temp", parentFolderNodeId: null, displayName: "Temp", dataType: "Float",
writable: false, historianTagname: "WW.Temp");
var nodeId = nm.TryGetVariable("eq-1/temp")!.NodeId;
var details = new ReadEventDetails
{
StartTime = DateTime.UtcNow.AddHours(-1),
EndTime = DateTime.UtcNow,
NumValuesPerNode = 10,
Filter = SelectFilter("EventId"),
};
var (_, errors) = InvokeHistoryRead(server, nm, details, nodeId);
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadHistoryOperationUnsupported);
fake.EventsCalled.ShouldBeFalse();
await host.DisposeAsync();
}
/// <summary>A backend that throws ⇒ that node's error is Bad and no exception escapes the
/// HistoryRead call. The fake source MUST be invoked (proving we reached the bridge) and threw;
/// the production catch now sets BOTH errors and results explicitly, so both are asserted here
/// rather than relying on the SDK base pre-seeding results[i].</summary>
[Fact]
public async Task Events_backend_throw_yields_bad_status_and_does_not_escape()
{
var (host, server) = await BootAsync();
var nm = server.NodeManager!;
var fake = new RecordingHistorianDataSource { ThrowOnRead = true };
nm.HistorianDataSource = fake;
const string equipmentId = "eq-boom";
nm.EnsureFolder(equipmentId, parentNodeId: null, displayName: "Equipment");
nm.MaterialiseAlarmCondition("alarm-5", equipmentId, "Cond", "OffNormalAlarm", severity: 900);
var notifierNodeId = nm.TryGetFolder(equipmentId)!.NodeId;
var details = new ReadEventDetails
{
StartTime = DateTime.UtcNow.AddHours(-1),
EndTime = DateTime.UtcNow,
NumValuesPerNode = 10,
Filter = SelectFilter("EventId"),
};
// The call must not throw even though the backend does.
var (results, errors) = InvokeHistoryRead(server, nm, details, notifierNodeId);
// Authoritative per-node signal: errors[0] must be Bad.
ServiceResult.IsBad(errors[0]).ShouldBeTrue();
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadHistoryOperationUnsupported);
// The production catch now sets results[0] explicitly — assert it directly (not relying on base seeding).
results[0].ShouldNotBeNull();
results[0].StatusCode.Code.ShouldBe(StatusCodes.BadHistoryOperationUnsupported);
// The source WAS entered (proving the override reached the bridge and the throw was swallowed).
fake.EventsEntered.ShouldBeTrue();
// ThrowOnRead fires before EventsCalled/LastSourceName are set — that's the throw path.
fake.EventsCalled.ShouldBeFalse();
await host.DisposeAsync();
}
/// <summary>Build a HistoryReadEvents-style event filter whose select clauses are single-element
/// BrowsePaths over the supplied BaseEventType leaf field names, in order.</summary>
private static EventFilter SelectFilter(params string[] leafFieldNames)
{
var filter = new EventFilter();
foreach (var name in leafFieldNames)
{
filter.SelectClauses.Add(
new SimpleAttributeOperand(ObjectTypeIds.BaseEventType, new QualifiedName(name))
{
AttributeId = Attributes.Value,
});
}
return filter;
}
/// <summary>Invoke the node manager's public HistoryRead with a single node, returning the filled
/// results + errors — same session-less <see cref="OperationContext"/> pattern as Task 3's tests.</summary>
private static (IList<SdkHistoryReadResult> Results, IList<ServiceResult> Errors) InvokeHistoryRead(
OtOpcUaSdkServer server, OtOpcUaNodeManager nm, HistoryReadDetails details, NodeId nodeId)
{
var context = new OperationContext(
new RequestHeader(), secureChannelContext: null, RequestType.HistoryRead, identity: null);
var nodesToRead = new List<HistoryReadValueId> { new() { NodeId = nodeId } };
var results = new List<SdkHistoryReadResult> { null! };
var errors = new List<ServiceResult> { null! };
nm.HistoryRead(
context,
details,
TimestampsToReturn.Both,
releaseContinuationPoints: false,
nodesToRead,
results,
errors);
return (results, errors);
}
/// <summary>A recording fake historian source — captures the last ReadEventsAsync call's arguments and
/// returns a configured result (or throws when <see cref="ThrowOnRead"/> is set). The Raw/Processed/
/// AtTime reads delegate to the Null source (unused by these tests).</summary>
private sealed class RecordingHistorianDataSource : IHistorianDataSource
{
public bool ThrowOnRead { get; init; }
public HistoricalEventsResult EventsResult { get; set; } =
new(Array.Empty<HistoricalEvent>(), null);
/// <summary>Set on every ReadEventsAsync entry, even when ThrowOnRead causes it to throw
/// before EventsCalled is set — proves the override reached the bridge.</summary>
public bool EventsEntered { get; private set; }
public bool EventsCalled { get; private set; }
public string? LastSourceName { get; private set; }
public DateTime LastStart { get; private set; }
public DateTime LastEnd { get; private set; }
public int LastMaxEvents { get; private set; }
public Task<HistorianRead> ReadRawAsync(
string fullReference, DateTime startUtc, DateTime endUtc, uint maxValuesPerNode,
CancellationToken cancellationToken) =>
NullHistorianDataSource.Instance.ReadRawAsync(fullReference, startUtc, endUtc, maxValuesPerNode, cancellationToken);
public Task<HistorianRead> ReadProcessedAsync(
string fullReference, DateTime startUtc, DateTime endUtc, TimeSpan interval,
HistoryAggregateType aggregate, CancellationToken cancellationToken) =>
NullHistorianDataSource.Instance.ReadProcessedAsync(fullReference, startUtc, endUtc, interval, aggregate, cancellationToken);
public Task<HistorianRead> ReadAtTimeAsync(
string fullReference, IReadOnlyList<DateTime> timestampsUtc, CancellationToken cancellationToken) =>
NullHistorianDataSource.Instance.ReadAtTimeAsync(fullReference, timestampsUtc, cancellationToken);
public Task<HistoricalEventsResult> ReadEventsAsync(
string? sourceName, DateTime startUtc, DateTime endUtc, int maxEvents,
CancellationToken cancellationToken)
{
EventsEntered = true;
if (ThrowOnRead) throw new InvalidOperationException("backend boom for events");
EventsCalled = true;
LastSourceName = sourceName;
LastStart = startUtc;
LastEnd = endUtc;
LastMaxEvents = maxEvents;
return Task.FromResult(EventsResult);
}
public HistorianHealthSnapshot GetHealthSnapshot() => NullHistorianDataSource.Instance.GetHealthSnapshot();
public void Dispose()
{
}
}
private async Task<(OpcUaApplicationHost Host, OtOpcUaSdkServer Server)> BootAsync()
{
var host = new OpcUaApplicationHost(
new OpcUaApplicationHostOptions
{
ApplicationName = "OtOpcUa.HistoryReadEventsTest",
ApplicationUri = $"urn:OtOpcUa.HistoryReadEventsTest:{Guid.NewGuid():N}",
OpcUaPort = AllocateFreePort(),
PublicHostname = "localhost",
PkiStoreRoot = _pkiRoot,
},
NullLogger<OpcUaApplicationHost>.Instance);
var server = new OtOpcUaSdkServer();
await host.StartAsync(server, Ct);
return (host, server);
}
private static int AllocateFreePort()
{
using var listener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 0);
listener.Start();
var port = ((System.Net.IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();
return port;
}
/// <summary>Cleans up the PKI root directory.</summary>
public void Dispose()
{
if (Directory.Exists(_pkiRoot))
{
try { Directory.Delete(_pkiRoot, recursive: true); }
catch { /* best-effort cleanup */ }
}
}
}
@@ -0,0 +1,560 @@
using Microsoft.Extensions.Logging.Abstractions;
using Opc.Ua;
using Opc.Ua.Server;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using HistorianRead = ZB.MOM.WW.OtOpcUa.Core.Abstractions.HistoryReadResult;
using SdkHistoryReadResult = Opc.Ua.HistoryReadResult;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests;
/// <summary>
/// Phase C Task 3 — the node-manager's OPC UA HistoryRead override (Raw / Processed / AtTime) over
/// historized variable nodes. Boots a real <see cref="OtOpcUaSdkServer"/> (the same harness
/// <see cref="NodeManagerHistorizeTests"/> uses), materialises a historized variable via
/// <see cref="OtOpcUaNodeManager.EnsureVariable"/>, wires a recording fake
/// <see cref="IHistorianDataSource"/>, then invokes the node manager's PUBLIC
/// <c>HistoryRead(OperationContext, …)</c> directly. The base CustomNodeManager2 builds the node
/// handles + dispatches to the protected per-details overrides, so this exercises the real dispatch
/// path in-process — fast + deterministic, no client socket.
/// </summary>
public sealed class NodeManagerHistoryReadTests : IDisposable
{
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private readonly string _pkiRoot = Path.Combine(
Path.GetTempPath(),
$"otopcua-historyread-{Guid.NewGuid():N}");
/// <summary>Raw read: the fake receives the resolved tagname + StartTime/EndTime/NumValuesPerNode,
/// and the returned samples decode to a HistoryData whose DataValues mirror value/status/source+server
/// timestamps. StatusCode is Good when samples are present.</summary>
[Fact]
public async Task Raw_dispatches_to_source_and_maps_samples()
{
var (host, server) = await BootAsync();
var nm = server.NodeManager!;
var fake = new RecordingHistorianDataSource();
nm.HistorianDataSource = fake;
nm.EnsureVariable("eq-1/temp", parentFolderNodeId: null, displayName: "Temp", dataType: "Float",
writable: false, historianTagname: "WW.Temp");
var nodeId = nm.TryGetVariable("eq-1/temp")!.NodeId;
var src = DateTime.UtcNow.AddSeconds(-5);
var srv = DateTime.UtcNow;
fake.RawResult = new HistorianRead(
new[] { new DataValueSnapshot(42.5f, StatusCodes.Good, src, srv) }, null);
var start = DateTime.UtcNow.AddHours(-1);
var end = DateTime.UtcNow;
var details = new ReadRawModifiedDetails
{
StartTime = start,
EndTime = end,
NumValuesPerNode = 100,
IsReadModified = false,
};
var (results, errors) = InvokeHistoryRead(server, nm, details, nodeId);
// The source saw the resolved tagname + the request window + cap.
fake.LastCall.ShouldBe("Raw");
fake.LastTagname.ShouldBe("WW.Temp");
fake.LastStart.ShouldBe(start);
fake.LastEnd.ShouldBe(end);
fake.LastMaxValues.ShouldBe(100u);
errors[0].StatusCode.Code.ShouldBe(StatusCodes.Good);
results[0].StatusCode.Code.ShouldBe(StatusCodes.Good);
var data = (HistoryData)ExtensionObject.ToEncodeable(results[0].HistoryData);
data.DataValues.Count.ShouldBe(1);
var dv = data.DataValues[0];
dv.Value.ShouldBe(42.5f);
dv.StatusCode.Code.ShouldBe(StatusCodes.Good);
dv.SourceTimestamp.ShouldBe(src);
dv.ServerTimestamp.ShouldBe(srv);
await host.DisposeAsync();
}
/// <summary>The resolved tagname that reaches the source is the OVERRIDE tagname (distinct from the
/// NodeId / FullName) — the override resolves the NodeId→tagname map, not the bare NodeId.</summary>
[Fact]
public async Task Raw_resolves_override_tagname_not_node_id()
{
var (host, server) = await BootAsync();
var nm = server.NodeManager!;
var fake = new RecordingHistorianDataSource { RawResult = Empty() };
nm.HistorianDataSource = fake;
// Node id "eq-9/flow" but a DISTINCT historian tagname "Plant.Flow.PV".
nm.EnsureVariable("eq-9/flow", parentFolderNodeId: null, displayName: "Flow", dataType: "Double",
writable: false, historianTagname: "Plant.Flow.PV");
var nodeId = nm.TryGetVariable("eq-9/flow")!.NodeId;
var details = new ReadRawModifiedDetails
{
StartTime = DateTime.UtcNow.AddHours(-1),
EndTime = DateTime.UtcNow,
NumValuesPerNode = 10,
// ReadRawModifiedDetails.Initialize() sets m_isReadModified=true (SDK-generated ctor body),
// so the default from new ReadRawModifiedDetails() is TRUE. A plain raw read must explicitly
// clear it to false to avoid hitting the IsReadModified=true early-return in the override.
IsReadModified = false,
};
InvokeHistoryRead(server, nm, details, nodeId);
fake.LastTagname.ShouldBe("Plant.Flow.PV");
await host.DisposeAsync();
}
/// <summary>Empty samples ⇒ the node's StatusCode is GoodNoData (the node is historized, the window
/// just held no data).</summary>
[Fact]
public async Task Raw_empty_samples_yields_GoodNoData()
{
var (host, server) = await BootAsync();
var nm = server.NodeManager!;
var fake = new RecordingHistorianDataSource { RawResult = Empty() };
nm.HistorianDataSource = fake;
nm.EnsureVariable("eq-1/empty", parentFolderNodeId: null, displayName: "Empty", dataType: "Float",
writable: false, historianTagname: "WW.Empty");
var nodeId = nm.TryGetVariable("eq-1/empty")!.NodeId;
var details = new ReadRawModifiedDetails
{
StartTime = DateTime.UtcNow.AddHours(-1),
EndTime = DateTime.UtcNow,
NumValuesPerNode = 10,
IsReadModified = false,
};
var (results, errors) = InvokeHistoryRead(server, nm, details, nodeId);
errors[0].StatusCode.Code.ShouldBe(StatusCodes.Good);
results[0].StatusCode.Code.ShouldBe(StatusCodes.GoodNoData);
var data = (HistoryData)ExtensionObject.ToEncodeable(results[0].HistoryData);
data.DataValues.ShouldBeEmpty();
await host.DisposeAsync();
}
/// <summary>A non-historized node (plain variable, no HistoryRead bit) reaching HistoryRead yields
/// BadHistoryOperationUnsupported — the source is never invoked.</summary>
[Fact]
public async Task Non_historized_node_yields_BadHistoryOperationUnsupported()
{
var (host, server) = await BootAsync();
var nm = server.NodeManager!;
var fake = new RecordingHistorianDataSource { RawResult = Empty() };
nm.HistorianDataSource = fake;
// Plain (non-historized) variable — no HistoryRead access bit.
nm.EnsureVariable("eq-1/plain", parentFolderNodeId: null, displayName: "Plain", dataType: "Int32",
writable: false, historianTagname: null);
var nodeId = nm.TryGetVariable("eq-1/plain")!.NodeId;
var details = new ReadRawModifiedDetails
{
StartTime = DateTime.UtcNow.AddHours(-1),
EndTime = DateTime.UtcNow,
NumValuesPerNode = 10,
};
var (_, errors) = InvokeHistoryRead(server, nm, details, nodeId);
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadHistoryOperationUnsupported);
fake.LastCall.ShouldBeNull(); // source never reached
await host.DisposeAsync();
}
/// <summary>Raw with IsReadModified=true ⇒ BadHistoryOperationUnsupported (we don't serve modified
/// history); the source is never invoked.</summary>
[Fact]
public async Task Raw_read_modified_yields_BadHistoryOperationUnsupported()
{
var (host, server) = await BootAsync();
var nm = server.NodeManager!;
var fake = new RecordingHistorianDataSource { RawResult = Empty() };
nm.HistorianDataSource = fake;
nm.EnsureVariable("eq-1/mod", parentFolderNodeId: null, displayName: "Mod", dataType: "Float",
writable: false, historianTagname: "WW.Mod");
var nodeId = nm.TryGetVariable("eq-1/mod")!.NodeId;
var details = new ReadRawModifiedDetails
{
StartTime = DateTime.UtcNow.AddHours(-1),
EndTime = DateTime.UtcNow,
NumValuesPerNode = 10,
IsReadModified = true,
};
var (_, errors) = InvokeHistoryRead(server, nm, details, nodeId);
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadHistoryOperationUnsupported);
fake.LastCall.ShouldBeNull();
await host.DisposeAsync();
}
/// <summary>Processed read with a known aggregate (Average) reaches the source as
/// HistoryAggregateType.Average + the ProcessingInterval as a TimeSpan.</summary>
[Fact]
public async Task Processed_known_aggregate_dispatches_with_interval()
{
var (host, server) = await BootAsync();
var nm = server.NodeManager!;
var fake = new RecordingHistorianDataSource { ProcessedResult = Empty() };
nm.HistorianDataSource = fake;
nm.EnsureVariable("eq-1/avg", parentFolderNodeId: null, displayName: "Avg", dataType: "Float",
writable: false, historianTagname: "WW.Avg");
var nodeId = nm.TryGetVariable("eq-1/avg")!.NodeId;
var details = new ReadProcessedDetails
{
StartTime = DateTime.UtcNow.AddHours(-1),
EndTime = DateTime.UtcNow,
ProcessingInterval = 10_000.0, // ms
AggregateType = new NodeIdCollection { ObjectIds.AggregateFunction_Average },
};
InvokeHistoryRead(server, nm, details, nodeId);
fake.LastCall.ShouldBe("Processed");
fake.LastTagname.ShouldBe("WW.Avg");
fake.LastAggregate.ShouldBe(HistoryAggregateType.Average);
fake.LastInterval.ShouldBe(TimeSpan.FromMilliseconds(10_000.0));
await host.DisposeAsync();
}
/// <summary>Processed read with an UNKNOWN aggregate NodeId ⇒ BadAggregateNotSupported; the source
/// is never invoked.</summary>
[Fact]
public async Task Processed_unknown_aggregate_yields_BadAggregateNotSupported()
{
var (host, server) = await BootAsync();
var nm = server.NodeManager!;
var fake = new RecordingHistorianDataSource { ProcessedResult = Empty() };
nm.HistorianDataSource = fake;
nm.EnsureVariable("eq-1/sd", parentFolderNodeId: null, displayName: "Sd", dataType: "Float",
writable: false, historianTagname: "WW.Sd");
var nodeId = nm.TryGetVariable("eq-1/sd")!.NodeId;
var details = new ReadProcessedDetails
{
StartTime = DateTime.UtcNow.AddHours(-1),
EndTime = DateTime.UtcNow,
ProcessingInterval = 10_000.0,
// StandardDeviationSample is a real OPC UA aggregate we do not serve.
AggregateType = new NodeIdCollection { ObjectIds.AggregateFunction_StandardDeviationSample },
};
var (_, errors) = InvokeHistoryRead(server, nm, details, nodeId);
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadAggregateNotSupported);
fake.LastCall.ShouldBeNull();
await host.DisposeAsync();
}
/// <summary>AtTime read: the requested timestamps reach ReadAtTimeAsync in order.</summary>
[Fact]
public async Task AtTime_dispatches_requested_timestamps()
{
var (host, server) = await BootAsync();
var nm = server.NodeManager!;
var fake = new RecordingHistorianDataSource { AtTimeResult = Empty() };
nm.HistorianDataSource = fake;
nm.EnsureVariable("eq-1/at", parentFolderNodeId: null, displayName: "At", dataType: "Float",
writable: false, historianTagname: "WW.At");
var nodeId = nm.TryGetVariable("eq-1/at")!.NodeId;
var t1 = DateTime.UtcNow.AddMinutes(-2);
var t2 = DateTime.UtcNow.AddMinutes(-1);
var details = new ReadAtTimeDetails
{
ReqTimes = new DateTimeCollection { t1, t2 },
};
InvokeHistoryRead(server, nm, details, nodeId);
fake.LastCall.ShouldBe("AtTime");
fake.LastTagname.ShouldBe("WW.At");
fake.LastTimestamps.ShouldBe(new[] { t1, t2 });
await host.DisposeAsync();
}
/// <summary>
/// Two nodes in a single Raw HistoryRead batch — one backend succeeds, one throws. Proves that
/// per-node error isolation is enforced across handle indices: the good node's slot is
/// Good+samples, the bad node's slot is Bad, and neither status leaks into the other.
/// </summary>
[Fact]
public async Task Raw_multi_node_per_node_error_isolation()
{
var (host, server) = await BootAsync();
var nm = server.NodeManager!;
// Materialise two distinct historized variables under separate equipment folders.
nm.EnsureVariable("eqA/good", parentFolderNodeId: null, displayName: "Good", dataType: "Float",
writable: false, historianTagname: "A.PV");
nm.EnsureVariable("eqB/bad", parentFolderNodeId: null, displayName: "Bad", dataType: "Float",
writable: false, historianTagname: "B.PV");
var goodNodeId = nm.TryGetVariable("eqA/good")!.NodeId;
var badNodeId = nm.TryGetVariable("eqB/bad")!.NodeId;
var src = DateTime.UtcNow.AddSeconds(-5);
var srv = DateTime.UtcNow;
// Per-tagname fake: A.PV returns one sample; B.PV throws.
var perTagFake = new PerTagnameHistorianDataSource(tagname =>
tagname == "A.PV"
? Task.FromResult(new HistorianRead(new[] { new DataValueSnapshot(1.0f, StatusCodes.Good, src, srv) }, null))
: throw new InvalidOperationException("backend boom for B.PV"));
nm.HistorianDataSource = perTagFake;
var details = new ReadRawModifiedDetails
{
StartTime = DateTime.UtcNow.AddHours(-1),
EndTime = DateTime.UtcNow,
NumValuesPerNode = 10,
IsReadModified = false,
};
// Single batch listing BOTH nodes in order [goodNodeId, badNodeId].
// handle.Index maps by position: good=0, bad=1.
var (results, errors) = InvokeHistoryRead(server, nm, details, goodNodeId, badNodeId);
// Good node (index 0): should have a Good status + one sample.
errors[0].StatusCode.Code.ShouldBe(StatusCodes.Good);
results[0].StatusCode.Code.ShouldBe(StatusCodes.Good);
var data = (HistoryData)ExtensionObject.ToEncodeable(results[0].HistoryData);
data.DataValues.Count.ShouldBe(1);
data.DataValues[0].Value.ShouldBe(1.0f);
// Bad node (index 1): errors slot must be Bad; results slot must NOT carry any HistoryData
// (no data was projected into it). The base may pre-seed results[i] to a default-constructed
// SdkHistoryReadResult whose StatusCode is 0 (Good) — that's fine for the result field, but the
// distinguishing signal is the error slot AND the absence of HistoryData from the good node.
StatusCode.IsBad(errors[1].StatusCode).ShouldBeTrue();
errors[1].StatusCode.Code.ShouldBe(StatusCodes.BadHistoryOperationUnsupported);
// HistoryData must be null/empty — the good node's sample MUST NOT have leaked into slot 1.
(results[1].HistoryData == null || ExtensionObject.IsNull(results[1].HistoryData)).ShouldBeTrue();
await host.DisposeAsync();
}
/// <summary>A backend that throws ⇒ that node's error is Bad (not GoodNoData) and no exception
/// escapes the HistoryRead call.</summary>
[Fact]
public async Task Backend_throw_yields_bad_status_and_does_not_escape()
{
var (host, server) = await BootAsync();
var nm = server.NodeManager!;
var fake = new RecordingHistorianDataSource { ThrowOnRead = true };
nm.HistorianDataSource = fake;
nm.EnsureVariable("eq-1/boom", parentFolderNodeId: null, displayName: "Boom", dataType: "Float",
writable: false, historianTagname: "WW.Boom");
var nodeId = nm.TryGetVariable("eq-1/boom")!.NodeId;
var details = new ReadRawModifiedDetails
{
StartTime = DateTime.UtcNow.AddHours(-1),
EndTime = DateTime.UtcNow,
NumValuesPerNode = 10,
IsReadModified = false,
};
// The call must not throw even though the backend does.
var (results, errors) = InvokeHistoryRead(server, nm, details, nodeId);
StatusCode.IsBad(errors[0].StatusCode).ShouldBeTrue();
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadHistoryOperationUnsupported);
// The result slot was never filled with a GoodNoData success.
(results[0].StatusCode.Code == StatusCodes.GoodNoData).ShouldBeFalse();
await host.DisposeAsync();
}
/// <summary>Invoke the node manager's public HistoryRead with a single node, returning the filled
/// results + errors. Uses a session-less <see cref="OperationContext"/> (the
/// (RequestHeader, SecureChannelContext, RequestType, IUserIdentity) ctor) — HistoryRead's
/// handle-building only needs the NodeId + namespace, not a session.</summary>
private static (IList<SdkHistoryReadResult> Results, IList<ServiceResult> Errors) InvokeHistoryRead(
OtOpcUaSdkServer server, OtOpcUaNodeManager nm, HistoryReadDetails details, NodeId nodeId)
=> InvokeHistoryRead(server, nm, details, new[] { nodeId });
/// <summary>Multi-node overload — issues one HistoryRead batch for all supplied node ids in order.
/// Results and errors are returned in the same order as <paramref name="nodeIds"/>.</summary>
private static (IList<SdkHistoryReadResult> Results, IList<ServiceResult> Errors) InvokeHistoryRead(
OtOpcUaSdkServer server, OtOpcUaNodeManager nm, HistoryReadDetails details, params NodeId[] nodeIds)
{
var context = new OperationContext(
new RequestHeader(), secureChannelContext: null, RequestType.HistoryRead, identity: null);
var nodesToRead = nodeIds.Select(id => new HistoryReadValueId { NodeId = id }).ToList();
var results = Enumerable.Repeat<SdkHistoryReadResult>(null!, nodeIds.Length).ToList();
var errors = Enumerable.Repeat<ServiceResult>(null!, nodeIds.Length).ToList();
nm.HistoryRead(
context,
details,
TimestampsToReturn.Both,
releaseContinuationPoints: false,
nodesToRead,
results,
errors);
return (results, errors);
}
private static HistorianRead Empty() => new(Array.Empty<DataValueSnapshot>(), null);
/// <summary>A recording fake historian source — captures the last call's kind + arguments and returns
/// a configured result (or throws when <see cref="ThrowOnRead"/> is set).</summary>
private sealed class RecordingHistorianDataSource : IHistorianDataSource
{
public bool ThrowOnRead { get; init; }
public HistorianRead RawResult { get; set; } = new(Array.Empty<DataValueSnapshot>(), null);
public HistorianRead ProcessedResult { get; set; } = new(Array.Empty<DataValueSnapshot>(), null);
public HistorianRead AtTimeResult { get; set; } = new(Array.Empty<DataValueSnapshot>(), null);
public string? LastCall { get; private set; }
public string? LastTagname { get; private set; }
public DateTime LastStart { get; private set; }
public DateTime LastEnd { get; private set; }
public uint LastMaxValues { get; private set; }
public TimeSpan LastInterval { get; private set; }
public HistoryAggregateType LastAggregate { get; private set; }
public IReadOnlyList<DateTime>? LastTimestamps { get; private set; }
public Task<HistorianRead> ReadRawAsync(
string fullReference, DateTime startUtc, DateTime endUtc, uint maxValuesPerNode,
CancellationToken cancellationToken)
{
if (ThrowOnRead) throw new InvalidOperationException("backend boom");
LastCall = "Raw";
LastTagname = fullReference;
LastStart = startUtc;
LastEnd = endUtc;
LastMaxValues = maxValuesPerNode;
return Task.FromResult(RawResult);
}
public Task<HistorianRead> ReadProcessedAsync(
string fullReference, DateTime startUtc, DateTime endUtc, TimeSpan interval,
HistoryAggregateType aggregate, CancellationToken cancellationToken)
{
if (ThrowOnRead) throw new InvalidOperationException("backend boom");
LastCall = "Processed";
LastTagname = fullReference;
LastStart = startUtc;
LastEnd = endUtc;
LastInterval = interval;
LastAggregate = aggregate;
return Task.FromResult(ProcessedResult);
}
public Task<HistorianRead> ReadAtTimeAsync(
string fullReference, IReadOnlyList<DateTime> timestampsUtc, CancellationToken cancellationToken)
{
if (ThrowOnRead) throw new InvalidOperationException("backend boom");
LastCall = "AtTime";
LastTagname = fullReference;
LastTimestamps = timestampsUtc;
return Task.FromResult(AtTimeResult);
}
public Task<HistoricalEventsResult> ReadEventsAsync(
string? sourceName, DateTime startUtc, DateTime endUtc, int maxEvents,
CancellationToken cancellationToken) =>
Task.FromResult(new HistoricalEventsResult(Array.Empty<HistoricalEvent>(), null));
public HistorianHealthSnapshot GetHealthSnapshot() => NullHistorianDataSource.Instance.GetHealthSnapshot();
public void Dispose()
{
}
}
/// <summary>A per-tagname historian source that delegates each raw read to a caller-supplied
/// <see cref="Func{T, TResult}"/>. The func may throw to simulate a backend failure for a
/// specific tagname while returning results for others — enabling per-node isolation tests.
/// Processed / AtTime / Events are not wired (they delegate to the null source).</summary>
private sealed class PerTagnameHistorianDataSource(Func<string, Task<HistorianRead>> rawHandler)
: IHistorianDataSource
{
public Task<HistorianRead> ReadRawAsync(
string fullReference, DateTime startUtc, DateTime endUtc, uint maxValuesPerNode,
CancellationToken cancellationToken) => rawHandler(fullReference);
public Task<HistorianRead> ReadProcessedAsync(
string fullReference, DateTime startUtc, DateTime endUtc, TimeSpan interval,
HistoryAggregateType aggregate, CancellationToken cancellationToken) =>
NullHistorianDataSource.Instance.ReadProcessedAsync(fullReference, startUtc, endUtc, interval, aggregate, cancellationToken);
public Task<HistorianRead> ReadAtTimeAsync(
string fullReference, IReadOnlyList<DateTime> timestampsUtc, CancellationToken cancellationToken) =>
NullHistorianDataSource.Instance.ReadAtTimeAsync(fullReference, timestampsUtc, cancellationToken);
public Task<HistoricalEventsResult> ReadEventsAsync(
string? sourceName, DateTime startUtc, DateTime endUtc, int maxEvents,
CancellationToken cancellationToken) =>
NullHistorianDataSource.Instance.ReadEventsAsync(sourceName, startUtc, endUtc, maxEvents, cancellationToken);
public HistorianHealthSnapshot GetHealthSnapshot() => NullHistorianDataSource.Instance.GetHealthSnapshot();
public void Dispose() { }
}
private async Task<(OpcUaApplicationHost Host, OtOpcUaSdkServer Server)> BootAsync()
{
var host = new OpcUaApplicationHost(
new OpcUaApplicationHostOptions
{
ApplicationName = "OtOpcUa.HistoryReadTest",
ApplicationUri = $"urn:OtOpcUa.HistoryReadTest:{Guid.NewGuid():N}",
OpcUaPort = AllocateFreePort(),
PublicHostname = "localhost",
PkiStoreRoot = _pkiRoot,
},
NullLogger<OpcUaApplicationHost>.Instance);
var server = new OtOpcUaSdkServer();
await host.StartAsync(server, Ct);
return (host, server);
}
private static int AllocateFreePort()
{
using var listener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 0);
listener.Start();
var port = ((System.Net.IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();
return port;
}
/// <summary>Cleans up the PKI root directory.</summary>
public void Dispose()
{
if (Directory.Exists(_pkiRoot))
{
try { Directory.Delete(_pkiRoot, recursive: true); }
catch { /* best-effort cleanup */ }
}
}
}
@@ -265,7 +265,8 @@ public sealed class Phase7ApplierHierarchyTests : IDisposable
/// <param name="displayName">The display name of the variable.</param>
/// <param name="dataType">The OPC UA built-in type name.</param>
/// <param name="writable">Whether the node is created read/write.</param>
public void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable) { }
/// <param name="historianTagname">The resolved historian tagname (null ⇒ not historized).</param>
public void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable, string? historianTagname = null) { }
/// <summary>Rebuilds the address space (stub implementation for testing).</summary>
public void RebuildAddressSpace() { }
}
@@ -262,6 +262,65 @@ public sealed class Phase7ApplierTests
sink.VariableCalls.ShouldBeEmpty();
}
/// <summary>Phase C Task 2 — the applier resolves the historian tagname per value tag and threads it
/// to <c>EnsureVariable</c>: a historized tag with NO override falls back to its <c>FullName</c>; a
/// historized tag WITH an override passes the override verbatim; a non-historized tag passes null.</summary>
[Fact]
public void MaterialiseEquipmentTags_resolves_historian_tagname_default_override_and_null()
{
var sink = new RecordingSink();
var applier = new Phase7Applier(sink, NullLogger<Phase7Applier>.Instance);
var composition = new Phase7CompositionResult(
Array.Empty<EquipmentNode>(), Array.Empty<DriverInstancePlan>(), Array.Empty<ScriptedAlarmPlan>())
{
EquipmentTags = new[]
{
// Historized, no override ⇒ tagname defaults to FullName ("T.A").
new EquipmentTagPlan("tag-def", "eq-1", "drv", FolderPath: "", Name: "ADefault", DataType: "Float",
FullName: "T.A", Writable: false, Alarm: null, IsHistorized: true, HistorianTagname: null),
// Historized, override ⇒ tagname is the override ("WW.Override"), NOT FullName.
new EquipmentTagPlan("tag-ovr", "eq-1", "drv", FolderPath: "", Name: "BOverride", DataType: "Float",
FullName: "T.B", Writable: false, Alarm: null, IsHistorized: true, HistorianTagname: "WW.Override"),
// Not historized ⇒ tagname is null.
new EquipmentTagPlan("tag-no", "eq-1", "drv", FolderPath: "", Name: "CPlain", DataType: "Float",
FullName: "T.C", Writable: false, Alarm: null, IsHistorized: false, HistorianTagname: null),
},
};
applier.MaterialiseEquipmentTags(composition);
var byNode = sink.HistorianCalls.ToDictionary(c => c.NodeId, c => c.HistorianTagname);
byNode[EquipmentNodeIds.Variable("eq-1", "", "ADefault")].ShouldBe("T.A"); // default ⇒ FullName
byNode[EquipmentNodeIds.Variable("eq-1", "", "BOverride")].ShouldBe("WW.Override"); // override verbatim
byNode[EquipmentNodeIds.Variable("eq-1", "", "CPlain")].ShouldBeNull(); // not historized ⇒ null
}
/// <summary>Phase C Task 2 — a historized tag whose override is blank/whitespace still falls back to
/// <c>FullName</c> (the resolve uses <c>string.IsNullOrWhiteSpace</c>, not just null).</summary>
[Fact]
public void MaterialiseEquipmentTags_blank_override_falls_back_to_full_name()
{
var sink = new RecordingSink();
var applier = new Phase7Applier(sink, NullLogger<Phase7Applier>.Instance);
var composition = new Phase7CompositionResult(
Array.Empty<EquipmentNode>(), Array.Empty<DriverInstancePlan>(), Array.Empty<ScriptedAlarmPlan>())
{
EquipmentTags = new[]
{
new EquipmentTagPlan("tag-blank", "eq-1", "drv", FolderPath: "", Name: "Speed", DataType: "Float",
FullName: "40001", Writable: false, Alarm: null, IsHistorized: true, HistorianTagname: " "),
},
};
applier.MaterialiseEquipmentTags(composition);
var call = sink.HistorianCalls.ShouldHaveSingleItem();
call.NodeId.ShouldBe(EquipmentNodeIds.Variable("eq-1", "", "Speed"));
call.HistorianTagname.ShouldBe("40001");
}
/// <summary>Verifies MaterialiseEquipmentVirtualTags creates one Variable per VirtualTag directly
/// under its existing equipment folder, with a folder-scoped NodeId (EquipmentId/Name — NOT the
/// VirtualTagId or Expression), parent == EquipmentId, displayName == Name, and does NOT re-create
@@ -463,6 +522,9 @@ public sealed class Phase7ApplierTests
public ConcurrentQueue<(string NodeId, string? Parent, string DisplayName)> FolderQueue { get; } = new();
/// <summary>Gets the queue of variable creation calls.</summary>
public ConcurrentQueue<(string NodeId, string? Parent, string DisplayName, string DataType, bool Writable)> VariableQueue { get; } = new();
/// <summary>Gets the queue of the historian-tagname arg captured per <c>EnsureVariable</c> call,
/// keyed by NodeId (null ⇒ that call passed not-historized).</summary>
public ConcurrentQueue<(string NodeId, string? HistorianTagname)> HistorianQueue { get; } = new();
/// <summary>Gets the queue of alarm-condition materialise calls.</summary>
public ConcurrentQueue<(string AlarmNodeId, string EquipmentNodeId, string DisplayName, string AlarmType, int Severity)> AlarmConditionQueue { get; } = new();
/// <summary>Gets the number of rebuild calls made on this sink.</summary>
@@ -474,6 +536,8 @@ public sealed class Phase7ApplierTests
public List<(string NodeId, string? Parent, string DisplayName)> FolderCalls => FolderQueue.ToList();
/// <summary>Gets the list of recorded variable creation calls.</summary>
public List<(string NodeId, string? Parent, string DisplayName, string DataType, bool Writable)> VariableCalls => VariableQueue.ToList();
/// <summary>Gets the list of recorded (NodeId, historian-tagname) pairs captured per EnsureVariable call.</summary>
public List<(string NodeId, string? HistorianTagname)> HistorianCalls => HistorianQueue.ToList();
/// <summary>Gets the list of recorded alarm-condition materialise calls.</summary>
public List<(string AlarmNodeId, string EquipmentNodeId, string DisplayName, string AlarmType, int Severity)> AlarmConditionCalls => AlarmConditionQueue.ToList();
@@ -509,8 +573,12 @@ public sealed class Phase7ApplierTests
/// <param name="displayName">The display name for the variable.</param>
/// <param name="dataType">The OPC UA built-in type name.</param>
/// <param name="writable">Whether the node is created read/write.</param>
public void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable)
=> VariableQueue.Enqueue((variableNodeId, parentFolderNodeId, displayName, dataType, writable));
/// <param name="historianTagname">The resolved historian tagname (null ⇒ not historized).</param>
public void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable, string? historianTagname = null)
{
VariableQueue.Enqueue((variableNodeId, parentFolderNodeId, displayName, dataType, writable));
HistorianQueue.Enqueue((variableNodeId, historianTagname));
}
/// <summary>Records a rebuild address space call.</summary>
public void RebuildAddressSpace() => Interlocked.Increment(ref RebuildCalls);
}
@@ -555,7 +623,8 @@ public sealed class Phase7ApplierTests
/// <param name="displayName">The display name for the variable.</param>
/// <param name="dataType">The OPC UA built-in type name.</param>
/// <param name="writable">Whether the node is created read/write.</param>
public void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable) { }
/// <param name="historianTagname">The resolved historian tagname (null ⇒ not historized).</param>
public void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable, string? historianTagname = null) { }
/// <summary>No-op rebuild address space call.</summary>
public void RebuildAddressSpace() { }
}
@@ -0,0 +1,194 @@
using System.Linq;
using System.Text.Json;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
/// <summary>
/// Proves the Phase C HistoryRead intent (<c>isHistorized</c> + optional <c>historianTagname</c>),
/// which rides inside the raw <c>TagConfig</c> JSON blob, round-trips with byte-parity through both
/// equipment-tag producers: the live-edit composer (<see cref="Phase7Composer.Compose"/>) and the
/// artifact decoder (<see cref="DeploymentArtifact.ParseComposition(System.ReadOnlySpan{byte})"/>).
/// The artifact serializer re-parses the SAME <c>TagConfig</c> string both sides emit, so no
/// ConfigComposer change is needed — the flags are already carried in the blob.
/// </summary>
public sealed class DeploymentArtifactHistorizeParityTests
{
/// <summary>
/// One draft consumed by both producers: a historized equipment tag with no explicit historian
/// tagname (defaults to FullName later, so <c>HistorianTagname</c> is null on both sides), plus a
/// historized equipment tag WITH an explicit <c>historianTagname</c> override, plus a plain
/// non-historized tag. The decoded <c>EquipmentTags</c> must equal the composer's element-wise
/// (positional-record value equality) and in the same order, proving <c>IsHistorized</c> /
/// <c>HistorianTagname</c> are derived byte-identically on both seams.
/// </summary>
[Fact]
public void Composer_and_artifact_agree_on_historized_equipment_tags()
{
var ns = new Namespace
{
NamespaceId = "ns-eq",
ClusterId = "c1",
Kind = NamespaceKind.Equipment,
NamespaceUri = "urn:eq",
};
var driver = new DriverInstance
{
DriverInstanceId = "drv-modbus",
ClusterId = "c1",
NamespaceId = "ns-eq",
Name = "Modbus1",
DriverType = "Modbus",
DriverConfig = "{}",
};
var area = new UnsArea { UnsAreaId = "area-1", ClusterId = "c1", Name = "filling" };
var line = new UnsLine { UnsLineId = "line-1", UnsAreaId = "area-1", Name = "line-1" };
var equip = new Equipment
{
EquipmentId = "eq-1",
DriverInstanceId = "drv-modbus",
UnsLineId = "line-1",
Name = "FillingPump",
MachineCode = "FILLINGPUMP",
};
// Historized, no explicit tagname → HistorianTagname null (defaults to FullName later).
var histDefaultTag = new Tag
{
TagId = "tag-hist-default",
DriverInstanceId = "drv-modbus",
EquipmentId = "eq-1",
FolderPath = null,
Name = "Flow",
DataType = "Float",
AccessLevel = TagAccessLevel.Read,
TagConfig = "{\"FullName\":\"40001\",\"isHistorized\":true}",
};
// Historized WITH an explicit historian-tagname override.
var histOverrideTag = new Tag
{
TagId = "tag-hist-override",
DriverInstanceId = "drv-modbus",
EquipmentId = "eq-1",
FolderPath = null,
Name = "Pressure",
DataType = "Float",
AccessLevel = TagAccessLevel.Read,
TagConfig = "{\"FullName\":\"40002\",\"isHistorized\":true,\"historianTagname\":\"Plant.Line1.Pressure\"}",
};
// Plain tag — not historized.
var plainTag = new Tag
{
TagId = "tag-plain",
DriverInstanceId = "drv-modbus",
EquipmentId = "eq-1",
FolderPath = null,
Name = "Speed",
DataType = "Float",
AccessLevel = TagAccessLevel.ReadWrite,
TagConfig = "{\"FullName\":\"40003\"}",
};
// Well-formed but non-historized: explicit isHistorized:false + a JSON-null historianTagname
// (not a string token → falls through the ValueKind==String guard → tagname null).
// This exercises the artifact-side private ExtractTagHistorize through the real round-trip
// (it can't be unit-tested directly because it's private). A truly malformed TagConfig string
// would cause ExtractTagFullName to return "" and break the SequenceEqual on other fields, so
// we use a well-formed blob and note that the malformed/throws path is already covered by
// the composer unit test in ExtractTagHistorizeTests.
var notHistorizedNullNameTag = new Tag
{
TagId = "tag-not-hist-nullname",
DriverInstanceId = "drv-modbus",
EquipmentId = "eq-1",
FolderPath = null,
Name = "Temp",
DataType = "Float",
AccessLevel = TagAccessLevel.Read,
TagConfig = "{\"FullName\":\"40004\",\"isHistorized\":false,\"historianTagname\":null}",
};
var areas = new[] { area };
var lines = new[] { line };
var equipment = new[] { equip };
var drivers = new[] { driver };
var tags = new[] { histDefaultTag, histOverrideTag, plainTag, notHistorizedNullNameTag };
var namespaces = new[] { ns };
// ---- Side 1: the live-edit composer ----
var composed = Phase7Composer.Compose(
areas, lines, equipment, drivers, Array.Empty<ScriptedAlarm>(), tags, namespaces);
// ---- Side 2: serialise the SAME draft to the artifact blob shape, then decode it ----
var blob = JsonSerializer.SerializeToUtf8Bytes(new
{
Namespaces = new[]
{
new { ns.NamespaceId, ns.ClusterId, Kind = (int)ns.Kind },
},
DriverInstances = new[]
{
new { driver.DriverInstanceId, driver.DriverType, driver.DriverConfig, driver.NamespaceId, driver.ClusterId },
},
Tags = new[]
{
ToSnapshot(histDefaultTag),
ToSnapshot(histOverrideTag),
ToSnapshot(plainTag),
ToSnapshot(notHistorizedNullNameTag),
},
});
var decoded = DeploymentArtifact.ParseComposition(blob);
// ---- Full byte-parity: every field, same order (positional-record value equality) ----
decoded.EquipmentTags.Count.ShouldBe(4);
decoded.EquipmentTags.SequenceEqual(composed.EquipmentTags).ShouldBeTrue();
// Spell out the Phase C fields per-tag so a divergence names the offending tag.
var histDefault = decoded.EquipmentTags.Single(t => t.TagId == "tag-hist-default");
histDefault.IsHistorized.ShouldBeTrue();
histDefault.HistorianTagname.ShouldBeNull();
composed.EquipmentTags.Single(t => t.TagId == "tag-hist-default").IsHistorized.ShouldBeTrue();
composed.EquipmentTags.Single(t => t.TagId == "tag-hist-default").HistorianTagname.ShouldBeNull();
var histOverride = decoded.EquipmentTags.Single(t => t.TagId == "tag-hist-override");
histOverride.IsHistorized.ShouldBeTrue();
histOverride.HistorianTagname.ShouldBe("Plant.Line1.Pressure");
composed.EquipmentTags.Single(t => t.TagId == "tag-hist-override").IsHistorized.ShouldBeTrue();
composed.EquipmentTags.Single(t => t.TagId == "tag-hist-override").HistorianTagname.ShouldBe("Plant.Line1.Pressure");
var plain = decoded.EquipmentTags.Single(t => t.TagId == "tag-plain");
plain.IsHistorized.ShouldBeFalse();
plain.HistorianTagname.ShouldBeNull();
composed.EquipmentTags.Single(t => t.TagId == "tag-plain").IsHistorized.ShouldBeFalse();
composed.EquipmentTags.Single(t => t.TagId == "tag-plain").HistorianTagname.ShouldBeNull();
// 4th tag: explicit isHistorized:false + JSON-null historianTagname ⇒ (false, null) on both sides.
// Exercises the artifact-side private ExtractTagHistorize's null-JSON-token guard path.
var notHistorizedNullName = decoded.EquipmentTags.Single(t => t.TagId == "tag-not-hist-nullname");
notHistorizedNullName.IsHistorized.ShouldBeFalse();
notHistorizedNullName.HistorianTagname.ShouldBeNull();
composed.EquipmentTags.Single(t => t.TagId == "tag-not-hist-nullname").IsHistorized.ShouldBeFalse();
composed.EquipmentTags.Single(t => t.TagId == "tag-not-hist-nullname").HistorianTagname.ShouldBeNull();
}
/// <summary>The Pascal-case snapshot a <see cref="Tag"/> EF entity serialises to in the artifact
/// (matches ConfigComposer); the equipment-tag decoder re-parses these fields — including the raw
/// <c>TagConfig</c> blob the Phase C flags ride inside.</summary>
private static object ToSnapshot(Tag t) => new
{
t.TagId,
t.DriverInstanceId,
t.EquipmentId,
t.Name,
t.FolderPath,
t.DataType,
AccessLevel = (int)t.AccessLevel,
t.TagConfig,
};
}
@@ -0,0 +1,197 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Runtime;
using ZB.MOM.WW.OtOpcUa.Runtime.Historian;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Historian;
/// <summary>
/// Verifies the config-gated <c>AddServerHistorian</c> registration: when the
/// <c>ServerHistorian</c> section is absent or disabled the <see cref="NullHistorianDataSource"/>
/// default seeded by <c>AddOtOpcUaRuntime</c> survives (the factory is never invoked); when it is
/// enabled the factory's returned <see cref="IHistorianDataSource"/> wins
/// (last-registration-wins over the <c>TryAddSingleton</c> Null default).
/// </summary>
public sealed class AddServerHistorianTests
{
/// <summary>A trivial read source the factory hands back when enabled; never actually invoked.</summary>
private sealed class FakeHistorianDataSource : IHistorianDataSource
{
private static readonly HistoryReadResult EmptyRead = new(Array.Empty<DataValueSnapshot>(), null);
private static readonly HistoricalEventsResult EmptyEvents = new(Array.Empty<HistoricalEvent>(), null);
public Task<HistoryReadResult> ReadRawAsync(
string fullReference, DateTime startUtc, DateTime endUtc, uint maxValuesPerNode,
CancellationToken cancellationToken) => Task.FromResult(EmptyRead);
public Task<HistoryReadResult> ReadProcessedAsync(
string fullReference, DateTime startUtc, DateTime endUtc, TimeSpan interval,
HistoryAggregateType aggregate, CancellationToken cancellationToken) => Task.FromResult(EmptyRead);
public Task<HistoryReadResult> ReadAtTimeAsync(
string fullReference, IReadOnlyList<DateTime> timestampsUtc,
CancellationToken cancellationToken) => Task.FromResult(EmptyRead);
public Task<HistoricalEventsResult> ReadEventsAsync(
string? sourceName, DateTime startUtc, DateTime endUtc, int maxEvents,
CancellationToken cancellationToken) => Task.FromResult(EmptyEvents);
public HistorianHealthSnapshot GetHealthSnapshot() => new(
TotalQueries: 0, TotalSuccesses: 0, TotalFailures: 0, ConsecutiveFailures: 0,
LastSuccessTime: null, LastFailureTime: null, LastError: null,
ProcessConnectionOpen: false, EventConnectionOpen: false,
ActiveProcessNode: null, ActiveEventNode: null,
Nodes: Array.Empty<HistorianClusterNodeState>());
public void Dispose()
{
// Stateless fake; nothing to release.
}
}
private static IConfiguration ConfigFrom(Dictionary<string, string?> values)
=> new ConfigurationBuilder().AddInMemoryCollection(values).Build();
[Fact]
public void Section_absent_keeps_null_source_and_factory_not_invoked()
{
var factoryInvoked = false;
var services = new ServiceCollection();
services.AddOtOpcUaRuntime();
var config = ConfigFrom(new Dictionary<string, string?>());
services.AddServerHistorian(config, (_, _) =>
{
factoryInvoked = true;
return new FakeHistorianDataSource();
});
using var provider = services.BuildServiceProvider();
provider.GetRequiredService<IHistorianDataSource>().ShouldBeSameAs(NullHistorianDataSource.Instance);
factoryInvoked.ShouldBeFalse();
}
[Fact]
public void Section_disabled_keeps_null_source_and_factory_not_invoked()
{
var factoryInvoked = false;
var services = new ServiceCollection();
services.AddOtOpcUaRuntime();
var config = ConfigFrom(new Dictionary<string, string?>
{
["ServerHistorian:Enabled"] = "false",
});
services.AddServerHistorian(config, (_, _) =>
{
factoryInvoked = true;
return new FakeHistorianDataSource();
});
using var provider = services.BuildServiceProvider();
provider.GetRequiredService<IHistorianDataSource>().ShouldBeSameAs(NullHistorianDataSource.Instance);
factoryInvoked.ShouldBeFalse();
}
[Fact]
public void Section_enabled_registers_factory_source()
{
var services = new ServiceCollection();
services.AddOtOpcUaRuntime();
var config = ConfigFrom(new Dictionary<string, string?>
{
["ServerHistorian:Enabled"] = "true",
["ServerHistorian:Host"] = "historian.example.com",
["ServerHistorian:Port"] = "32569",
["ServerHistorian:SharedSecret"] = "s",
});
services.AddServerHistorian(config, (_, _) => new FakeHistorianDataSource());
using var provider = services.BuildServiceProvider();
var resolved = provider.GetRequiredService<IHistorianDataSource>();
resolved.ShouldBeOfType<FakeHistorianDataSource>();
resolved.ShouldNotBeSameAs(NullHistorianDataSource.Instance);
}
[Fact]
public void Section_enabled_passes_bound_options_to_factory()
{
ServerHistorianOptions? seen = null;
var services = new ServiceCollection();
services.AddOtOpcUaRuntime();
var config = ConfigFrom(new Dictionary<string, string?>
{
["ServerHistorian:Enabled"] = "true",
["ServerHistorian:Host"] = "historian.example.com",
["ServerHistorian:Port"] = "12345",
["ServerHistorian:UseTls"] = "true",
["ServerHistorian:ServerCertThumbprint"] = "AABBCCDDEEFF",
["ServerHistorian:SharedSecret"] = "s",
});
services.AddServerHistorian(config, (opts, _) =>
{
seen = opts;
return new FakeHistorianDataSource();
});
using var provider = services.BuildServiceProvider();
_ = provider.GetRequiredService<IHistorianDataSource>();
seen.ShouldNotBeNull();
seen.Host.ShouldBe("historian.example.com");
seen.Port.ShouldBe(12345);
seen.UseTls.ShouldBeTrue();
seen.ServerCertThumbprint.ShouldBe("AABBCCDDEEFF");
}
[Fact]
public void Validate_warns_on_empty_shared_secret_when_enabled()
{
var opts = new ServerHistorianOptions { Enabled = true, SharedSecret = "", Port = 32569 };
opts.Validate().ShouldContain(w => w.Contains("SharedSecret"));
}
[Fact]
public void Validate_warns_on_non_positive_port_when_enabled()
{
var opts = new ServerHistorianOptions { Enabled = true, SharedSecret = "s", Port = 0 };
opts.Validate().ShouldContain(w => w.Contains("Port"));
}
[Fact]
public void Validate_is_silent_when_correctly_configured()
{
new ServerHistorianOptions { Enabled = true, SharedSecret = "s", Port = 32569 }.Validate().ShouldBeEmpty();
}
[Fact]
public void Validate_is_silent_when_disabled()
{
new ServerHistorianOptions { Enabled = false, SharedSecret = "", Port = 0 }.Validate().ShouldBeEmpty();
}
[Fact]
public void Section_binds_host_port_tls_fields()
{
var config = ConfigFrom(new Dictionary<string, string?>
{
["ServerHistorian:Host"] = "historian.example.com",
["ServerHistorian:Port"] = "12345",
["ServerHistorian:UseTls"] = "true",
["ServerHistorian:ServerCertThumbprint"] = "AABBCCDDEEFF",
});
var opts = config.GetSection(ServerHistorianOptions.SectionName).Get<ServerHistorianOptions>();
opts.ShouldNotBeNull();
opts.Host.ShouldBe("historian.example.com");
opts.Port.ShouldBe(12345);
opts.UseTls.ShouldBeTrue();
opts.ServerCertThumbprint.ShouldBe("AABBCCDDEEFF");
}
}
@@ -218,7 +218,8 @@ public sealed class OtOpcUaTelemetryHookTests : RuntimeActorTestBase
/// <param name="displayName">The display name for the variable.</param>
/// <param name="dataType">The OPC UA built-in type name.</param>
/// <param name="writable">Whether the node is created read/write.</param>
public void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable) { }
/// <param name="historianTagname">The resolved historian tagname (null ⇒ not historized).</param>
public void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable, string? historianTagname = null) { }
/// <summary>Rebuilds address space (recorded via span).</summary>
public void RebuildAddressSpace() { /* recorded via span */ }
}
@@ -288,7 +288,8 @@ public sealed class OpcUaPublishActorRebuildTests : RuntimeActorTestBase
/// <param name="displayName">The display name of the variable.</param>
/// <param name="dataType">The OPC UA built-in type name.</param>
/// <param name="writable">Whether the node is created read/write.</param>
public void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable)
/// <param name="historianTagname">The resolved historian tagname (null ⇒ not historized).</param>
public void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable, string? historianTagname = null)
=> Calls.Enqueue($"EV:{variableNodeId}");
/// <summary>Records a rebuild address space call.</summary>
public void RebuildAddressSpace() => Interlocked.Increment(ref RebuildCalls);
@@ -209,7 +209,8 @@ public sealed class OpcUaPublishActorTests : RuntimeActorTestBase
/// <param name="displayName">The display name of the variable.</param>
/// <param name="dataType">The OPC UA built-in type name.</param>
/// <param name="writable">Whether the node is created read/write.</param>
public void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable) { }
/// <param name="historianTagname">The resolved historian tagname (null ⇒ not historized).</param>
public void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable, string? historianTagname = null) { }
/// <summary>Records a rebuild call.</summary>
public void RebuildAddressSpace() => Interlocked.Increment(ref RebuildCalls);