Compare commits
18 Commits
c6edef0efb
...
1be06502c7
| Author | SHA1 | Date | |
|---|---|---|---|
| 1be06502c7 | |||
| fcf84adbad | |||
| d4ecc9138f | |||
| 6d5fc35747 | |||
| ce25581596 | |||
| e2960515cf | |||
| 72f32045a4 | |||
| 6104eaba60 | |||
| ac12633087 | |||
| 706077f02f | |||
| 999e58c605 | |||
| fd4d05534e | |||
| 6e152047eb | |||
| 7ce7505a36 | |||
| 3528702185 | |||
| 35ac0b8c4e | |||
| eb6a71abf2 | |||
| 3d3f8a47a9 |
+12
-2
@@ -176,9 +176,16 @@ When `Enabled` is `false` (the default), `AddAlarmHistorian` registers
|
||||
"AlarmHistorian": {
|
||||
"Enabled": true,
|
||||
"DatabasePath": "C:\\ProgramData\\OtOpcUa\\alarmhistorian.db",
|
||||
"PipeName": "\\\\.\\pipe\\wonderware-historian",
|
||||
"SharedSecret": "<token from historian sidecar config>",
|
||||
"BatchSize": 100
|
||||
},
|
||||
"Historian": {
|
||||
"Wonderware": {
|
||||
"Host": "localhost",
|
||||
"Port": 32569,
|
||||
"UseTls": false,
|
||||
"ServerCertThumbprint": ""
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -187,9 +194,12 @@ When `Enabled` is `false` (the default), `AddAlarmHistorian` registers
|
||||
|---|---|---|---|
|
||||
| `Enabled` | bool | `false` | Enable the real SQLite + Wonderware sink. `false` → `NullAlarmHistorianSink`. |
|
||||
| `DatabasePath` | string | — | Absolute path to the SQLite queue file. Created on first use (WAL mode). Required when `Enabled`. |
|
||||
| `PipeName` | string | — | Named-pipe path for the Wonderware Historian sidecar IPC channel. Required when `Enabled`. |
|
||||
| `SharedSecret` | string | — | Shared secret token the sidecar expects on every connection. Required when `Enabled`. |
|
||||
| `BatchSize` | int | `100` | Max rows per drain cycle handed to `IAlarmHistorianWriter.WriteBatchAsync`. |
|
||||
| `AlarmHistorian:Host` | string | `localhost` | DNS name or IP of the machine running the historian sidecar. |
|
||||
| `AlarmHistorian:Port` | int | `32569` | TCP port the sidecar listens on (`OTOPCUA_HISTORIAN_TCP_PORT`). |
|
||||
| `AlarmHistorian:UseTls` | bool | `false` | Wrap the TCP stream in TLS before the Hello handshake. |
|
||||
| `AlarmHistorian:ServerCertThumbprint` | string | — | Optional SHA-1 thumbprint to pin the sidecar's TLS server certificate. Leave empty to use normal CA-chain validation. |
|
||||
|
||||
> Dev and docker-dev deployments leave `Enabled` unset (defaults to `false`) so alarm transitions historize to nowhere unless a historian sidecar is present.
|
||||
|
||||
|
||||
+10
-5
@@ -119,9 +119,11 @@ The Galaxy/MxAccess connection settings are **not an `appsettings` section.** Th
|
||||
|
||||
> The `OTOPCUA_GALAXY_*` environment variables that v1's in-process `Galaxy.Host` consumed **no longer live in this repo** — they moved into the separately-installed mxaccessgw gateway's own config (see the v1 archive pointer in `docs/README.md` and the Galaxy overview at [`docs/drivers/Galaxy.md`](drivers/Galaxy.md)). The only Galaxy connection secret this repo touches is the gateway API key via `ApiKeySecretRef` above.
|
||||
|
||||
### Historian config (env-driven sidecar)
|
||||
### Historian config (TCP sidecar)
|
||||
|
||||
The Wonderware Historian runs as a supervised sidecar process whose configuration arrives **entirely through environment variables**, not an `appsettings` section. The sidecar entry point (`src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware/Program.cs`) reads them at spawn time. See the `OTOPCUA_HISTORIAN_*` rows in the environment-variable table below. The in-process client-side options POCO is `WonderwareHistorianClientOptions` (`src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Client.Contracts/WonderwareHistorianClientOptions.cs`): `PipeName`, `SharedSecret`, `PeerName` (`OtOpcUa`), `ConnectTimeout` (default 10s), `CallTimeout` (default 30s), `ProbeTimeoutSeconds` (`15`).
|
||||
The Wonderware Historian sidecar (`OtOpcUaWonderwareHistorian`) is an independent Windows service that the OtOpcUa host connects to over TCP. It is **not** spawned as a child process by the host — the two services are started independently (e.g. by NSSM / `sc.exe`). The sidecar entry point (`src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware/Program.cs`) reads its configuration from environment variables; the OtOpcUa host side reads the `AlarmHistorian` appsettings section. See the `OTOPCUA_HISTORIAN_*` rows in the environment-variable table below.
|
||||
|
||||
The in-process **client-side** options POCO is `WonderwareHistorianClientOptions` (`src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Client.Contracts/WonderwareHistorianClientOptions.cs`), bound from the `AlarmHistorian` section: `Host`, `Port`, `UseTls`, `ServerCertThumbprint`, `SharedSecret`, `ConnectTimeout` (default 10s), `CallTimeout` (default 30s), `ProbeTimeoutSeconds` (`15`).
|
||||
|
||||
---
|
||||
|
||||
@@ -135,7 +137,6 @@ All names are read in this repo's source via `Environment.GetEnvironmentVariable
|
||||
|---|---|---|
|
||||
| `OTOPCUA_ROLES` | `src/Server/ZB.MOM.WW.OtOpcUa.Host/Program.cs` (`RoleParser.Parse`) | Comma-separated cluster roles for the node (`admin`, `driver`, `dev`). Drives the conditional wiring and the per-role appsettings overlay. Used when `Cluster:Roles` is empty. |
|
||||
| `OTOPCUA_CONFIG_CONNECTION` | `src/Core/ZB.MOM.WW.OtOpcUa.Configuration/DesignTimeDbContextFactory.cs` (design-time / `dotnet ef` only) | Read at **design time** by `DesignTimeDbContextFactory.cs` for `dotnet ef` migrations. At **runtime** the server resolves the connection string from `ConnectionStrings:ConfigDb` (env form: `ConnectionStrings__ConfigDb`) via `configuration.GetConnectionString("ConfigDb")` in `ServiceCollectionExtensions.cs` — `OTOPCUA_CONFIG_CONNECTION` appears there only as a hint in an error message, not via `GetEnvironmentVariable`. No credential is embedded in source. |
|
||||
| `OTOPCUA_ALLOWED_SID` | `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware/Program.cs` | SID of the server principal allowed to connect to the historian sidecar's named pipe (passed by the supervisor at spawn). Required — sidecar throws if unset. |
|
||||
| `ASPNETCORE_ENVIRONMENT` | ASP.NET host builder (framework) | Selects `appsettings.{Environment}.json` (e.g. `Development`). |
|
||||
|
||||
### Historian sidecar (`OTOPCUA_HISTORIAN_*`)
|
||||
@@ -144,8 +145,12 @@ All read in `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware/Program.c
|
||||
|
||||
| Variable | Effect / default |
|
||||
|---|---|
|
||||
| `OTOPCUA_HISTORIAN_PIPE` | Named-pipe name the sidecar listens on. Required (throws if unset). |
|
||||
| `OTOPCUA_HISTORIAN_SECRET` | Per-process shared secret verified in the pipe Hello frame. Required (throws if unset). |
|
||||
| `OTOPCUA_HISTORIAN_TCP_PORT` | TCP port the sidecar listens on. Default `32569`. Corresponds to `AlarmHistorian:Port` on the host side. |
|
||||
| `OTOPCUA_HISTORIAN_BIND` | TCP bind address for the sidecar. Default `0.0.0.0`. |
|
||||
| `OTOPCUA_HISTORIAN_TLS_ENABLED` | `true` enables TLS on the sidecar's TCP listener. Default `false`. Corresponds to `AlarmHistorian:UseTls` on the host side. |
|
||||
| `OTOPCUA_HISTORIAN_TLS_CERT` | PFX file path **or** `LocalMachine\My\<thumbprint>` to load the sidecar TLS server certificate from the machine store. |
|
||||
| `OTOPCUA_HISTORIAN_TLS_CERT_PASSWORD` | Password for a PFX-file certificate. Omit when using a machine-store cert. Never commit a value. |
|
||||
| `OTOPCUA_HISTORIAN_SECRET` | Per-process shared secret verified in the TCP Hello frame. Required (throws if unset). Corresponds to `AlarmHistorian:SharedSecret` on the host side. |
|
||||
| `OTOPCUA_HISTORIAN_ENABLED` | `true` opens the real Wonderware SDK connection; anything else → pipe-only mode (smoke/IPC tests). Default: not-true → pipe-only. |
|
||||
| `OTOPCUA_HISTORIAN_ALARM_WRITE_ENABLED` | `false` disables the alarm-event writer (sidecar rejects `WriteAlarmEvents`). Default `true` (when `ENABLED=true`). |
|
||||
| `OTOPCUA_HISTORIAN_INTEGRATED` | `false` → SQL auth (use `USER`/`PASS`); any other value → integrated security. Default: integrated. |
|
||||
|
||||
@@ -234,8 +234,8 @@ Implementations:
|
||||
|
||||
- `WonderwareHistorianClient`
|
||||
([`Driver.Historian.Wonderware.Client/WonderwareHistorianClient.cs`](../src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Client/WonderwareHistorianClient.cs))
|
||||
— the .NET 10 client that talks to the Wonderware historian sidecar over a
|
||||
named pipe. It implements both `IHistorianDataSource` (read paths) and
|
||||
— the .NET 10 client that talks to the Wonderware historian sidecar over
|
||||
TCP (optional TLS). It implements both `IHistorianDataSource` (read paths) and
|
||||
`IAlarmHistorianWriter` (the alarm-event drain target; see
|
||||
[AlarmHistorian.md](AlarmHistorian.md)).
|
||||
- `HistorianDataSource`
|
||||
|
||||
@@ -7,7 +7,7 @@ A production OtOpcUa deployment runs **one binary per node**, plus the optional
|
||||
| Process | Project | Runtime | Platform | Responsibility |
|
||||
|---|---|---|---|---|
|
||||
| **OtOpcUa Host** | `src/Server/ZB.MOM.WW.OtOpcUa.Host` | .NET 10 | AnyCPU | Single fused binary. `OTOPCUA_ROLES` env decides what to mount: `admin` (Blazor + auth + control-plane singletons), `driver` (OPC UA endpoint + per-driver actors), or both. |
|
||||
| **OtOpcUa Wonderware Historian** *(optional)* | `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware` | .NET Framework 4.8 | x64 (64-bit) | Out-of-process sidecar exposing the Wonderware Historian SDK over a named pipe. Required only when `Historian:Wonderware:Enabled=true`. |
|
||||
| **OtOpcUa Wonderware Historian** *(optional)* | `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware` | .NET Framework 4.8 | x64 (64-bit) | Out-of-process sidecar exposing the Wonderware Historian SDK over TCP (optional TLS). Required only when `AlarmHistorian:Enabled=true`. May run on the same machine or a remote host. |
|
||||
|
||||
Galaxy access still uses the separately-installed **mxaccessgw** sidecar (see `docs/v2/Galaxy.ParityRig.md`); the gateway owns the MXAccess COM bitness constraint (its worker is x86 net48). Nothing in the OtOpcUa repo carries that constraint anymore.
|
||||
|
||||
@@ -70,7 +70,7 @@ Used by Traefik for the active-leader-only routing pattern (see [Architecture-v2
|
||||
|
||||
## OtOpcUa Wonderware Historian (optional)
|
||||
|
||||
Unchanged from v1. IPC contract types live in `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Client.Contracts/`; sidecar pipe handler in `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware/Ipc/`. Install via `scripts/install/Install-Services.ps1 -InstallWonderwareHistorian`.
|
||||
IPC contract types live in `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Client.Contracts/`; sidecar TCP server in `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware/Ipc/`. The sidecar listens on TCP port 32569 by default; `Install-Services.ps1 -InstallWonderwareHistorian` adds the Windows Firewall inbound rule. The host and sidecar may run on different machines — configure `AlarmHistorian:Host` + `AlarmHistorian:Port` (and optionally `AlarmHistorian:UseTls`) on the OtOpcUa host side. See [Historian.Wonderware.md](drivers/Historian.Wonderware.md) for the full transport and security reference.
|
||||
|
||||
## Install / Uninstall
|
||||
|
||||
|
||||
@@ -4,7 +4,11 @@ The Wonderware Historian backend is **not a tag driver** — it has no address
|
||||
space, no `IDriver` lifecycle, and exposes no PLC. It is a **server-side
|
||||
historian sink**: an optional sidecar that gives OtOpcUa read access to AVEVA
|
||||
System Platform (Wonderware) Historian history and a write-back path for alarm
|
||||
events. It runs only when `Historian:Wonderware:Enabled=true`.
|
||||
events. It runs only when `AlarmHistorian:Enabled=true`.
|
||||
|
||||
The host connects to the sidecar over **TCP** (plaintext in dev, optional TLS
|
||||
in prod), so the OtOpcUa host no longer needs to be on the same machine as the
|
||||
sidecar — a remote host on a different VM is fully supported.
|
||||
|
||||
For the sidecar's place in a deployment, see
|
||||
[ServiceHosting.md](../ServiceHosting.md). For the alarm-history store-and-forward
|
||||
@@ -20,13 +24,13 @@ flow that drains into it, see [AlarmHistorian.md](../AlarmHistorian.md).
|
||||
| AndForwardSink --write----+--+
|
||||
| WonderwareHistorianClient (.NET 10) | |
|
||||
+-------------------------------------------+ |
|
||||
| named pipe
|
||||
MessagePack frames | (shared secret + allowed-SID)
|
||||
| TCP (optional TLS)
|
||||
MessagePack frames | shared-secret Hello auth
|
||||
v
|
||||
+-------------------------------------------+
|
||||
| OtOpcUaWonderwareHistorian (sidecar) |
|
||||
| net48 / x64 |
|
||||
| PipeServer + HistorianFrameHandler |
|
||||
| TcpFrameServer + HistorianFrameHandler |
|
||||
| HistorianDataSource (reads) |
|
||||
| SdkAlarmHistorianWriteBackend (writes) |
|
||||
| aahClientManaged / HistorianAccess |
|
||||
@@ -36,15 +40,45 @@ flow that drains into it, see [AlarmHistorian.md](../AlarmHistorian.md).
|
||||
The split exists because the AVEVA Historian SDK (`aahClientManaged` +
|
||||
native `aahClient.dll`) is .NET Framework 4.8 / x64 — so it lives out-of-process
|
||||
in the sidecar, and everything in the OtOpcUa host stays .NET 10 AnyCPU. The
|
||||
host never references the SDK; it speaks the pipe contract only.
|
||||
host never references the SDK; it speaks the TCP contract only. Because the
|
||||
transport is TCP, the host and sidecar can run on different machines.
|
||||
|
||||
### Transport & security
|
||||
|
||||
The sidecar listens on a configurable TCP port (`OTOPCUA_HISTORIAN_TCP_PORT`,
|
||||
default **32569**) and bind address (`OTOPCUA_HISTORIAN_BIND`, default `0.0.0.0`).
|
||||
`Install-Services.ps1` adds a Windows Firewall inbound rule for the port
|
||||
automatically.
|
||||
|
||||
**TLS (optional, recommended for cross-machine deployments):**
|
||||
Set `OTOPCUA_HISTORIAN_TLS_ENABLED=true` on the sidecar and supply the server
|
||||
certificate via `OTOPCUA_HISTORIAN_TLS_CERT` (PFX file path, or
|
||||
`LocalMachine\My\<thumbprint>` for a cert already in the machine store) and
|
||||
`OTOPCUA_HISTORIAN_TLS_CERT_PASSWORD` if the PFX is password-protected. On the
|
||||
client/host side set `AlarmHistorian:UseTls=true`; optionally set
|
||||
`ServerCertThumbprint` to pin the server certificate's SHA-1 thumbprint instead
|
||||
of relying on normal CA-chain validation.
|
||||
|
||||
**Shared secret (required in all modes):**
|
||||
Regardless of whether TLS is on, the client always sends a `Hello` frame
|
||||
carrying the `SharedSecret`; the sidecar rejects connections where the secret
|
||||
does not match. The Windows-SID pipe ACL from the previous named-pipe transport
|
||||
is replaced by this combination of TLS + shared secret.
|
||||
|
||||
**TLS troubleshooting note:** If TLS fails on every connection attempt, the
|
||||
most likely cause is a missing private key or an ACL on the key file — the
|
||||
sidecar loads the certificate with `MachineKeySet` (required for service
|
||||
accounts with no loaded user profile), and `SslStream` defers private-key
|
||||
access to the first handshake, so a bad key surfaces as repeated connection
|
||||
failures (→ exit 2 → NSSM restart), not a startup error.
|
||||
|
||||
## Project split
|
||||
|
||||
| Project | Target | Role |
|
||||
|---------|--------|------|
|
||||
| `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware/` | net48 / x64 | The **sidecar** (`OutputType=Exe`). Hosts the named-pipe server, the historian reader, and the alarm-write backend bound to the AVEVA SDK |
|
||||
| `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Client/` | net10.0 | `WonderwareHistorianClient` — the in-host pipe client consumed by the history router and the alarm sink |
|
||||
| `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Client.Contracts/` | net10.0 | `WonderwareHistorianClientOptions` (pipe name, shared secret, timeouts) |
|
||||
| `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware/` | net48 / x64 | The **sidecar** (`OutputType=Exe`). Hosts the TCP server, the historian reader, and the alarm-write backend bound to the AVEVA SDK |
|
||||
| `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Client/` | net10.0 | `WonderwareHistorianClient` — the in-host TCP client consumed by the history router and the alarm sink |
|
||||
| `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Client.Contracts/` | net10.0 | `WonderwareHistorianClientOptions` (host, port, TLS, shared secret, timeouts) |
|
||||
|
||||
> The csproj targets **net48 / x64** (`PlatformTarget=x64`) — the AVEVA Historian
|
||||
> 2020 SDK ships an x64 `aahClientManaged` build; the earlier x86 default was an
|
||||
@@ -52,7 +86,7 @@ host never references the SDK; it speaks the pipe contract only.
|
||||
|
||||
## What it does
|
||||
|
||||
The sidecar exposes two surfaces, both over the same named pipe:
|
||||
The sidecar exposes two surfaces, both over the same TCP connection:
|
||||
|
||||
### Read path — `IHistorianDataSource`
|
||||
|
||||
@@ -87,29 +121,32 @@ The alarm write path can be disabled independently of reads by setting
|
||||
|
||||
- **Process**: `OtOpcUaWonderwareHistorian`, installed/managed by
|
||||
`scripts/install/` (`Install-Services.ps1 -InstallWonderwareHistorian`).
|
||||
- **Spawn config**: the supervisor passes the pipe name, the allowed server
|
||||
principal SID, and a per-process shared secret via environment
|
||||
(`OTOPCUA_HISTORIAN_PIPE`, `OTOPCUA_ALLOWED_SID`, `OTOPCUA_HISTORIAN_SECRET`);
|
||||
Historian connection settings come from `OTOPCUA_HISTORIAN_SERVER` /
|
||||
`_PORT` / `_INTEGRATED` / `_USER` / `_PASS` etc. (see
|
||||
- **Spawn config**: TCP port and bind address are set via
|
||||
`OTOPCUA_HISTORIAN_TCP_PORT` (default 32569) and `OTOPCUA_HISTORIAN_BIND`
|
||||
(default `0.0.0.0`). TLS is controlled by `OTOPCUA_HISTORIAN_TLS_ENABLED` /
|
||||
`OTOPCUA_HISTORIAN_TLS_CERT` / `OTOPCUA_HISTORIAN_TLS_CERT_PASSWORD`. The
|
||||
shared secret is passed via `OTOPCUA_HISTORIAN_SECRET`. Historian connection
|
||||
settings come from `OTOPCUA_HISTORIAN_SERVER` / `_PORT` / `_INTEGRATED` /
|
||||
`_USER` / `_PASS` etc. (see
|
||||
`src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware/Program.cs`).
|
||||
- **Pipe-only mode**: with `OTOPCUA_HISTORIAN_ENABLED!=true` the sidecar boots
|
||||
- **TCP-only mode**: with `OTOPCUA_HISTORIAN_ENABLED!=true` the sidecar boots
|
||||
without loading the SDK at all — used for smoke and IPC tests.
|
||||
- **Wire**: MessagePack-framed request/reply; the named-pipe ACL restricts the
|
||||
pipe to the allowed SID and the client proves the shared secret in a Hello
|
||||
frame. The client owns a single channel with one in-flight call at a time and
|
||||
retries a transport failure once before propagating — broader backoff is the
|
||||
caller's responsibility.
|
||||
- **Wire**: MessagePack-framed request/reply over TCP (optionally TLS). The
|
||||
client proves the shared secret in a `Hello` frame before any history calls.
|
||||
The client owns a single channel with one in-flight call at a time and retries
|
||||
a transport failure once before propagating — broader backoff is the caller's
|
||||
responsibility.
|
||||
|
||||
## Testing
|
||||
|
||||
- **Sidecar unit tests** —
|
||||
`tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Tests/` cover the
|
||||
reader, the alarm-write backend outcome classification, and the pipe-frame
|
||||
handler with a faked SDK seam.
|
||||
reader, the alarm-write backend outcome classification, and the TCP frame
|
||||
handler with a faked SDK seam; `TcpRoundTripTests` exercises the plaintext +
|
||||
TLS paths including the bad-secret rejection case.
|
||||
- **Client unit tests** —
|
||||
`tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Client.Tests/`
|
||||
cover the pipe client + framing against an in-process duplex pipe pair.
|
||||
cover the TCP client + framing against loopback `TcpListener` fixtures.
|
||||
|
||||
## Further reading
|
||||
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
# Wonderware Historian Sidecar — TCP Transport Design
|
||||
|
||||
**Date:** 2026-06-12
|
||||
**Status:** Approved (design); implementation plan to follow.
|
||||
|
||||
## Goal
|
||||
|
||||
Replace the Wonderware Historian sidecar's **local named-pipe IPC** with a
|
||||
**TCP transport** so a remote OtOpcUa host (e.g. the dev server running in
|
||||
Linux Docker on a MacBook) can reach the net48 sidecar on the Windows
|
||||
Historian VM. Today the IPC is a local, Windows-SID-gated named pipe, so the
|
||||
only possible consumer is a Windows OtOpcUa process on the same machine; once
|
||||
the host moves off the VM the sidecar is orphaned.
|
||||
|
||||
## Why not gRPC (the "like mxaccessgw" question)
|
||||
|
||||
mxaccessgw uses gRPC/HTTP2, but it can do so only because it is split into a
|
||||
**net10 Server** (Kestrel/`Grpc.AspNetCore`) + a **net48 Worker**. The
|
||||
Historian sidecar must stay **net48** (the AVEVA `aahClientManaged` + native
|
||||
`aahClient.dll` SDK is .NET Framework 4.8), and **net48 cannot host
|
||||
Kestrel/`Grpc.AspNetCore`**. The only gRPC-on-net48 option is the **EOL
|
||||
`Grpc.Core` C-core** library, or adding a second net10 front process.
|
||||
|
||||
Decision: **plain TCP reusing the existing MessagePack frame protocol.** The
|
||||
protocol is 5 unary request/reply ops (`ReadRaw`, `ReadProcessed`,
|
||||
`ReadAtTime`, `ReadEvents`, `WriteAlarmEvents`) + a `Hello` handshake — no
|
||||
streaming — and is already abstracted behind a `Stream` on both ends, so a TCP
|
||||
swap is small, native to net48, depends on no EOL libraries, and reuses every
|
||||
contract.
|
||||
|
||||
## Locked decisions
|
||||
|
||||
| Decision | Choice |
|
||||
|---|---|
|
||||
| Transport | **TCP only** — named pipe fully removed |
|
||||
| Concurrency | **Single active connection, serial accept** (mirrors today's pipe `maxInstances:1`) |
|
||||
| Caller auth | **Shared-secret `Hello`**, required in every mode (replaces the SID ACL) |
|
||||
| Transport security | **TLS optional** — plaintext in dev, TLS in prod (config-driven) |
|
||||
| mTLS / client-cert | Out of scope now; future hardening follow-up |
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
Before: After:
|
||||
OtOpcUa host (same VM, Windows) OtOpcUa host (anywhere, .NET 10)
|
||||
| named pipe (local, SID-gated) | TCP (+ optional TLS), MessagePack frames
|
||||
v v
|
||||
Sidecar (net48) PipeServer Sidecar (net48) TcpFrameServer
|
||||
```
|
||||
|
||||
Everything above the socket is unchanged: `Hello`/`HelloAck` handshake,
|
||||
length-prefixed `MessageKind` framing, MessagePack DTOs, `FrameReader`/
|
||||
`FrameWriter` (they operate on `Stream`; `NetworkStream`/`SslStream` are
|
||||
`Stream`s), `HistorianFrameHandler` dispatch, and the AVEVA SDK backends
|
||||
(`HistorianDataSource` reads, `SdkAlarmHistorianWriteBackend` writes).
|
||||
|
||||
## Detailed design
|
||||
|
||||
### Server (net48 sidecar — `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware/`)
|
||||
|
||||
- **New `Ipc/TcpFrameServer.cs`** replaces `Ipc/PipeServer.cs`:
|
||||
- `TcpListener` bound to `<bind>:<port>`; single-active **serial** accept
|
||||
loop (accept the next connection only after the current disconnects).
|
||||
- Per connection: if TLS enabled, wrap `NetworkStream` in `SslStream` and
|
||||
`AuthenticateAsServer(cert)`; else use the raw `NetworkStream`.
|
||||
- Run the **existing** `Hello` handshake (verify shared secret; reject with a
|
||||
`HelloAck{Accepted=false}` on mismatch / major-version mismatch) → then the
|
||||
existing `reader.ReadFrameAsync` → `handler.HandleAsync` → `writer.WriteAsync`
|
||||
loop.
|
||||
- Keep the `RunAsync` backoff (`250ms…8s`) + `MaxConsecutiveFailures=20`→throw
|
||||
behavior so `Program.Main`'s exit-2 + NSSM restart semantics are identical.
|
||||
- **Remove:** `PipeServer`, `PipeAcl`, `VerifyCaller`/`CallerVerifier`
|
||||
(Windows-pipe-only), the `OTOPCUA_ALLOWED_SID` env + `SecurityIdentifier`.
|
||||
- **`Program.cs`:** swap `new PipeServer(pipeName, allowedSid, sharedSecret, …)`
|
||||
(line ~62) for `new TcpFrameServer(bind, port, sharedSecret, tlsCert?, …)`;
|
||||
drop the SID read; keep `OTOPCUA_HISTORIAN_ENABLED` (pipe-only-idle behavior
|
||||
becomes "tcp-only-idle" / listen-but-SDK-disabled, semantics preserved).
|
||||
- **New env vars:** `OTOPCUA_HISTORIAN_TCP_PORT` (default e.g. 32569),
|
||||
`OTOPCUA_HISTORIAN_BIND` (default `0.0.0.0`), `OTOPCUA_HISTORIAN_TLS_ENABLED`
|
||||
(default `false`), `OTOPCUA_HISTORIAN_TLS_CERT` (pfx path or cert-store
|
||||
thumbprint), `OTOPCUA_HISTORIAN_TLS_CERT_PASSWORD`. Keep
|
||||
`OTOPCUA_HISTORIAN_SECRET`, `OTOPCUA_HISTORIAN_ENABLED`, and the SDK vars
|
||||
(`OTOPCUA_HISTORIAN_SERVER`/`PORT`/…).
|
||||
|
||||
### Client (.NET 10 — `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Client/`)
|
||||
|
||||
- **`Internal/PipeChannel.cs` → `Internal/FrameChannel.cs`** (cosmetic rename;
|
||||
already transport-agnostic). Add **`DefaultTcpConnectFactory`**:
|
||||
`TcpClient.ConnectAsync(host, port, ct)` → if TLS,
|
||||
`SslStream.AuthenticateAsClientAsync` (validate server cert: thumbprint-pin
|
||||
*or* CA-chain per config; skip in plaintext mode) → return the stream. The
|
||||
`FrameReader`/`FrameWriter`/`Hello`/MessagePack layer is reused unchanged.
|
||||
- **`WonderwareHistorianClient.cs`:** default ctor switches to the TCP factory;
|
||||
the injectable `connect`-func ctor stays (used by tests).
|
||||
|
||||
### Options + host wiring
|
||||
|
||||
- **`…Client.Contracts/WonderwareHistorianClientOptions.cs`:** replace
|
||||
`PipeName` with `Host` + `Port`; add `UseTls` and `ServerCertThumbprint`
|
||||
(optional pin) / validation mode. Keep `SharedSecret`, `PeerName`,
|
||||
`ConnectTimeout`, `CallTimeout`, `ProbeTimeoutSeconds`.
|
||||
- **`Historian:Wonderware` appsettings:** `Host`/`Port`/`UseTls`/
|
||||
`ServerCertThumbprint` replace `PipeName`. Bound where the client is built:
|
||||
`src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ServiceCollectionExtensions.cs`,
|
||||
`src/Server/ZB.MOM.WW.OtOpcUa.Host/Drivers/DriverFactoryBootstrap.cs`,
|
||||
`src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Historian/AlarmHistorianOptions.cs`.
|
||||
- **AdminUI Test-Connect probe:**
|
||||
`src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/Drivers/Pickers/HistorianWonderwareAddressBuilder.cs`
|
||||
+ the probe path updated to host/port/TLS.
|
||||
|
||||
## Security model
|
||||
|
||||
- **Caller auth:** shared-secret `Hello`, required in all modes — this is the
|
||||
replacement for the named pipe's Windows-SID ACL.
|
||||
- **Transport:** TLS optional, config-driven. Dev = plaintext (`UseTls=false`).
|
||||
Prod = server cert; client pins the thumbprint *or* validates the CA chain
|
||||
(both supported). Server cert can live in the existing
|
||||
`C:\ProgramData\OtOpcUa\pki`.
|
||||
- **Network exposure:** a new inbound port requires a **Windows Firewall rule**
|
||||
on the VM. Bind to a specific management NIC instead of `0.0.0.0` to scope
|
||||
exposure.
|
||||
- **mTLS** (client-cert auth) is a future follow-up; the shared secret covers
|
||||
caller authentication for now.
|
||||
|
||||
## Deployment
|
||||
|
||||
- `scripts/install/Install-Services.ps1` / `Refresh-Services.ps1`: swap the
|
||||
historian service env block (drop `OTOPCUA_ALLOWED_SID`, add
|
||||
`OTOPCUA_HISTORIAN_TCP_PORT` + `OTOPCUA_HISTORIAN_TLS_*`), add an inbound
|
||||
firewall rule for the port, and provision the server cert (prod). The Step 4b
|
||||
deploy-completeness assertion stays as-is.
|
||||
|
||||
## Testing (no live sign-in by the agent)
|
||||
|
||||
- **Reuse** the existing byte-parity / round-trip contract tests (contracts
|
||||
unchanged).
|
||||
- **New unit/integration (xUnit + Shouldly):** TCP connect factory; self-signed
|
||||
TLS loopback handshake; **end-to-end loopback** (`TcpFrameServer` + client
|
||||
over `127.0.0.1`, both plaintext and TLS); `Hello`-reject on bad shared
|
||||
secret over TCP; single-active-connection serial-accept behavior.
|
||||
- **Live (user-driven):** MacBook OtOpcUa → VM sidecar over TCP — dev plaintext
|
||||
first: `ReadRaw` returns live samples + a `WriteAlarmEvents` round-trips; then
|
||||
flip `UseTls=true` and re-verify. Open the VM firewall port. Done = build
|
||||
clean + `dotnet test` green + live read/write pass.
|
||||
|
||||
## Rollout / migration
|
||||
|
||||
- The pipe is fully replaced, so **both ends move together** (no mixed
|
||||
pipe/TCP). The protocol above the socket is byte-identical, so this is a
|
||||
transport swap, not a contract change. Sequence: deploy the TCP sidecar
|
||||
(+firewall +env), then the TCP-client host, with the same shared secret.
|
||||
|
||||
## Open items / follow-ups (not blockers)
|
||||
|
||||
- mTLS / client-cert auth (hardening).
|
||||
- Optional: bind-NIC scoping vs `0.0.0.0`.
|
||||
- Same-machine deploys now use loopback TCP (`127.0.0.1:<port>`) instead of a
|
||||
pipe — expected given full replacement.
|
||||
|
||||
## Touched code (authoritative file list)
|
||||
|
||||
- Sidecar: `Ipc/TcpFrameServer.cs` (new, replaces `Ipc/PipeServer.cs`), remove
|
||||
`Ipc/PipeAcl.cs`, `Program.cs`.
|
||||
- Client: `Internal/FrameChannel.cs` (rename of `PipeChannel.cs` + TCP factory),
|
||||
`WonderwareHistorianClient.cs`.
|
||||
- Contracts: `WonderwareHistorianClientOptions.cs`.
|
||||
- Host: `Runtime/ServiceCollectionExtensions.cs`,
|
||||
`Host/Drivers/DriverFactoryBootstrap.cs`,
|
||||
`Runtime/Historian/AlarmHistorianOptions.cs`,
|
||||
`AdminUI/.../Pickers/HistorianWonderwareAddressBuilder.cs`.
|
||||
- Deploy: `scripts/install/Install-Services.ps1`,
|
||||
`scripts/install/Refresh-Services.ps1`.
|
||||
- Docs: `docs/drivers/Historian.Wonderware.md`, `docs/ServiceHosting.md`,
|
||||
`docs/AlarmHistorian.md`.
|
||||
- Unchanged (reused): both `Ipc/Contracts.cs`, `Ipc/Framing.cs`,
|
||||
`Ipc/FrameReader.cs`, `Ipc/HistorianFrameHandler.cs`, the AVEVA SDK backends.
|
||||
@@ -0,0 +1,477 @@
|
||||
# Wonderware Historian Sidecar — TCP Transport Implementation Plan
|
||||
|
||||
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers-extended-cc:executing-plans to implement this plan task-by-task.
|
||||
|
||||
**Goal:** Replace the Wonderware Historian sidecar's local Windows named-pipe IPC with a TCP transport (plaintext dev / optional TLS prod, shared-secret `Hello` auth) so a remote off-VM OtOpcUa host can reach the net48 sidecar.
|
||||
|
||||
**Architecture:** Everything above the socket is reused verbatim (`Hello`/`HelloAck`, length-prefixed `MessageKind` framing, both `Contracts.cs` MessagePack DTOs, `FrameReader`/`FrameWriter` — they operate on `Stream`, and `NetworkStream`/`SslStream` *are* `Stream`s — `HistorianFrameHandler` dispatch, the AVEVA SDK backends). The work is: swap the server's `PipeServer` for a `TcpFrameServer` (TcpListener + optional `SslStream`), swap the client's pipe connect-factory for a TCP one, thread host/port/TLS through options + config, and update deploy scripts + docs. Single active connection, serial accept (mirrors today's pipe `maxNumberOfServerInstances:1`).
|
||||
|
||||
**Tech Stack:** C# .NET 10 (client/host) + .NET Framework 4.8 x64 (sidecar — forced by AVEVA `aahClientManaged`), MessagePack, `System.Net.Sockets`/`System.Net.Security`, xUnit + Shouldly. **Design doc:** `docs/plans/2026-06-12-historian-tcp-transport-design.md` (master `3d3f8a47`).
|
||||
|
||||
**Green-at-each-step strategy:** Because the named pipe is fully replaced, several files change shape. To keep the build green per commit we go **additive then cleanup**: add the TCP path alongside the pipe path, switch the defaults, then delete the dead pipe code in one final cleanup task. The client side (Tasks 1–4, 7-cleanup) and the sidecar side (Tasks 5–6) touch disjoint projects and can proceed in parallel.
|
||||
|
||||
**net48 caveats (sidecar only — bake into Task 5):**
|
||||
- `TcpListener.AcceptTcpClientAsync(CancellationToken)` does **not** exist on net48. Use the no-arg `AcceptTcpClientAsync()` and tie cancellation to the listener: `ct.Register(() => _listener.Stop())` (a `Stop()` makes the pending accept throw, which the loop treats as cancellation).
|
||||
- `SslStream.AuthenticateAsServerAsync` on net48: use `SslProtocols.Tls12` (Tls13 isn't available). `checkCertificateRevocation: false` for self-signed dev certs.
|
||||
|
||||
**Hard rules:** stage by path (never `git add .`); never stage `sql_login.txt` / `src/Server/ZB.MOM.WW.OtOpcUa.Host/pki/` / `pending.md`; never echo the gateway API key or the historian `SharedSecret` into a tracked file; no force-push / no `--no-verify`; NO Configuration entity / EF migration change.
|
||||
|
||||
---
|
||||
|
||||
### Task 0: Create the feature branch
|
||||
|
||||
**Classification:** trivial
|
||||
**Estimated implement time:** ~1 min
|
||||
**Parallelizable with:** none
|
||||
|
||||
**Files:** none (git only)
|
||||
|
||||
**Step 1:** From master (HEAD `3d3f8a47`, design doc already committed):
|
||||
```bash
|
||||
git checkout master && git pull --ff-only
|
||||
git checkout -b feat/historian-tcp-transport
|
||||
```
|
||||
**Step 2:** Confirm `git status` clean (except untracked `pending.md`, which is left alone) and `git rev-parse --abbrev-ref HEAD` → `feat/historian-tcp-transport`.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Add TCP/TLS fields to the client options
|
||||
|
||||
**Classification:** small
|
||||
**Estimated implement time:** ~3 min
|
||||
**Parallelizable with:** Task 5
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Client.Contracts/WonderwareHistorianClientOptions.cs`
|
||||
- Test: `tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Client.Tests/WonderwareHistorianClientOptionsTests.cs` (new)
|
||||
|
||||
**Additive** — keep `PipeName` for now (removed in Task 7) so the build stays green. Add init-only properties:
|
||||
|
||||
```csharp
|
||||
/// <summary>Sidecar TCP host (DNS name or IP). Required for the TCP transport.</summary>
|
||||
public string? Host { get; init; }
|
||||
|
||||
/// <summary>Sidecar TCP port (matches the sidecar's OTOPCUA_HISTORIAN_TCP_PORT).</summary>
|
||||
public int Port { get; init; }
|
||||
|
||||
/// <summary>When true, the client wraps the TCP stream in TLS before the Hello handshake.</summary>
|
||||
public bool UseTls { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Optional SHA-1 thumbprint (hex, no spaces) the client pins the sidecar's TLS
|
||||
/// server cert against. When null/empty and <see cref="UseTls"/> is true, the client
|
||||
/// validates the cert chain normally (CA-issued cert).
|
||||
/// </summary>
|
||||
public string? ServerCertThumbprint { get; init; }
|
||||
```
|
||||
|
||||
**Step 1 (test, TDD):** assert an options instance carries the new fields and that defaults are `Port=0`, `UseTls=false`, `Host/ServerCertThumbprint=null`.
|
||||
**Step 2:** run `dotnet test tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Client.Tests --filter WonderwareHistorianClientOptionsTests` → fail (no fields).
|
||||
**Step 3:** add the properties.
|
||||
**Step 4:** test passes. `dotnet build` on the Contracts project is green.
|
||||
**Step 5:** commit (`git add` the two files by path) — `feat(historian-client): add TCP/TLS options fields`.
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Client TCP connect factory + FrameChannel rename
|
||||
|
||||
**Classification:** standard
|
||||
**Estimated implement time:** ~5 min
|
||||
**Parallelizable with:** Task 5
|
||||
|
||||
**Files:**
|
||||
- Rename: `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Client/Internal/PipeChannel.cs` → `Internal/FrameChannel.cs` (rename the class `PipeChannel` → `FrameChannel`; it is already transport-agnostic — it only touches `Stream`/`FrameReader`/`FrameWriter`). Update the one reference in `WonderwareHistorianClient.cs` (`private readonly PipeChannel _channel;` and `new PipeChannel(...)`).
|
||||
- Modify (same file): keep `DefaultNamedPipeConnectFactory` for now (deleted in Task 7); **add** `DefaultTcpConnectFactory`.
|
||||
- Test: `tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Client.Tests/TcpConnectFactoryTests.cs` (new)
|
||||
|
||||
Add to `FrameChannel` (needs `using System.Net.Sockets; using System.Net.Security; using System.Security.Authentication;`):
|
||||
|
||||
```csharp
|
||||
/// <summary>
|
||||
/// Default TCP factory: connects to the sidecar over TCP, optionally wrapping the
|
||||
/// stream in TLS (server-auth; pinned-thumbprint or CA-chain validation). The Hello
|
||||
/// handshake + shared secret still authenticate the caller on top of this.
|
||||
/// </summary>
|
||||
public static Func<WonderwareHistorianClientOptions, CancellationToken, Task<Stream>> DefaultTcpConnectFactory =
|
||||
async (opts, ct) =>
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(opts.Host))
|
||||
throw new InvalidOperationException("WonderwareHistorianClientOptions.Host is required for the TCP transport.");
|
||||
|
||||
var tcp = new TcpClient();
|
||||
using (var connectCts = CancellationTokenSource.CreateLinkedTokenSource(ct))
|
||||
{
|
||||
connectCts.CancelAfter(opts.EffectiveConnectTimeout);
|
||||
await tcp.ConnectAsync(opts.Host!, opts.Port, connectCts.Token).ConfigureAwait(false);
|
||||
}
|
||||
tcp.NoDelay = true;
|
||||
|
||||
Stream stream = tcp.GetStream();
|
||||
if (!opts.UseTls) return stream;
|
||||
|
||||
var ssl = new SslStream(stream, leaveInnerStreamOpen: false, (_, cert, _, errors) =>
|
||||
{
|
||||
if (!string.IsNullOrEmpty(opts.ServerCertThumbprint))
|
||||
return string.Equals(cert?.GetCertHashString(), opts.ServerCertThumbprint, StringComparison.OrdinalIgnoreCase);
|
||||
return errors == SslPolicyErrors.None;
|
||||
});
|
||||
await ssl.AuthenticateAsClientAsync(opts.Host!).ConfigureAwait(false);
|
||||
return ssl;
|
||||
};
|
||||
```
|
||||
|
||||
**Step 1 (test, TDD):** stand up a loopback `TcpListener` on `127.0.0.1:0`, accept in a background task and (a) for plaintext: read the first byte to prove a stream arrived; (b) for TLS: `AuthenticateAsServerAsync` a self-signed cert (build one with `CertificateRequest` / `X509Certificate2.CreateSelfSigned`-style helper, EKU serverAuth) and assert the client factory with the matching `ServerCertThumbprint` connects, and with a wrong thumbprint throws `AuthenticationException`.
|
||||
**Step 2:** run the new test → fail (no `DefaultTcpConnectFactory`).
|
||||
**Step 3:** add the factory + do the rename.
|
||||
**Step 4:** `dotnet test …Client.Tests --filter TcpConnectFactory` → pass; whole Client project builds.
|
||||
**Step 5:** commit by path — `feat(historian-client): TCP connect factory + FrameChannel rename`.
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Switch the client default ctor to TCP
|
||||
|
||||
**Classification:** small
|
||||
**Estimated implement time:** ~2 min
|
||||
**Parallelizable with:** none (needs Task 2)
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Client/WonderwareHistorianClient.cs:42`
|
||||
- Test: `tests/.../Client.Tests/WonderwareHistorianClientTests.cs` (extend)
|
||||
|
||||
Change the public ctor delegation from the pipe factory to TCP:
|
||||
```csharp
|
||||
public WonderwareHistorianClient(WonderwareHistorianClientOptions options, ILogger<WonderwareHistorianClient>? logger = null)
|
||||
: this(options, ct => FrameChannel.DefaultTcpConnectFactory(options, ct), logger)
|
||||
{
|
||||
}
|
||||
```
|
||||
**Step 1:** add a test that constructs the client with `Host=127.0.0.1, Port=<loopback>` against a loopback `TcpListener` running the real `Hello`/`HelloAck` exchange (reuse/extend `FakeSidecarServer` to accept a `Stream` from a TCP socket) and assert a `ReadRawAsync` round-trips. **Step 2:** fail. **Step 3:** flip the ctor. **Step 4:** pass. **Step 5:** commit by path — `feat(historian-client): default ctor dials TCP`.
|
||||
|
||||
---
|
||||
|
||||
### Task 4: Host config binding (Host/Port/TLS)
|
||||
|
||||
**Classification:** small
|
||||
**Estimated implement time:** ~3 min
|
||||
**Parallelizable with:** Task 5
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Historian/AlarmHistorianOptions.cs:29` (add fields next to `PipeName`)
|
||||
- Modify: `src/Server/ZB.MOM.WW.OtOpcUa.Host/Program.cs:96-97`
|
||||
- Test: `tests/Server/…Runtime.Tests/…` (extend an options-binding test if present; else add a small bind test)
|
||||
|
||||
`AlarmHistorianOptions`: add
|
||||
```csharp
|
||||
public string Host { get; init; } = "localhost";
|
||||
public int Port { get; init; } = 32569;
|
||||
public bool UseTls { get; init; }
|
||||
public string? ServerCertThumbprint { get; init; }
|
||||
```
|
||||
`Host/Program.cs:97` — pass them through:
|
||||
```csharp
|
||||
new WonderwareHistorianClientOptions(opts.PipeName, opts.SharedSecret)
|
||||
{
|
||||
Host = opts.Host, Port = opts.Port, UseTls = opts.UseTls, ServerCertThumbprint = opts.ServerCertThumbprint,
|
||||
}
|
||||
```
|
||||
(`PipeName` still passes through positionally until Task 7 reshapes the record; harmless.)
|
||||
Add the keys to the Host `appsettings.json` `Historian:Wonderware` section (Host/Port/UseTls/ServerCertThumbprint).
|
||||
**Steps:** TDD the binding (config → options carries Host/Port/UseTls) → green → commit by path — `feat(historian-host): bind TCP host/port/tls config`.
|
||||
|
||||
---
|
||||
|
||||
### Task 5: Sidecar `TcpFrameServer`
|
||||
|
||||
**Classification:** high-risk (transport + security + concurrency, net48)
|
||||
**Estimated implement time:** ~5 min
|
||||
**Parallelizable with:** Task 1, Task 2, Task 4 (disjoint project)
|
||||
|
||||
**Files:**
|
||||
- Create: `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware/Ipc/TcpFrameServer.cs`
|
||||
- Test: `tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Tests/Ipc/TcpRoundTripTests.cs` (new; model on the existing `Ipc/PipeRoundTripTests.cs`)
|
||||
|
||||
Mirror `PipeServer`'s shape (same `IFrameHandler`, same `Hello` verify minus SID, same `RunAsync` backoff + `MaxConsecutiveFailures=20`→throw so `Program.Main`'s exit-2/NSSM semantics are identical). Keep `PipeServer.cs` for now (deleted Task 7).
|
||||
|
||||
```csharp
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Security;
|
||||
using System.Net.Sockets;
|
||||
using System.Security.Authentication;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MessagePack;
|
||||
using Serilog;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Ipc;
|
||||
|
||||
/// <summary>
|
||||
/// Accepts one TCP client at a time, optionally over TLS, verifies the shared-secret
|
||||
/// Hello, then dispatches frames to <see cref="IFrameHandler"/>. The TCP replacement for
|
||||
/// <c>PipeServer</c>; the Windows-SID ACL is replaced by TLS + the shared secret.
|
||||
/// </summary>
|
||||
public sealed class TcpFrameServer : IDisposable
|
||||
{
|
||||
private readonly IPAddress _bind;
|
||||
private readonly int _port;
|
||||
private readonly string _sharedSecret;
|
||||
private readonly X509Certificate2? _tlsCert; // null = plaintext
|
||||
private readonly ILogger _logger;
|
||||
private readonly CancellationTokenSource _cts = new();
|
||||
private TcpListener? _listener;
|
||||
|
||||
public TcpFrameServer(IPAddress bind, int port, string sharedSecret, X509Certificate2? tlsCert, ILogger logger)
|
||||
{
|
||||
_bind = bind ?? throw new ArgumentNullException(nameof(bind));
|
||||
_port = port;
|
||||
_sharedSecret = sharedSecret ?? throw new ArgumentNullException(nameof(sharedSecret));
|
||||
_tlsCert = tlsCert;
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
}
|
||||
|
||||
/// <summary>The port the listener actually bound (useful when constructed with port 0 in tests).</summary>
|
||||
public int BoundPort => ((IPEndPoint)_listener!.LocalEndpoint).Port;
|
||||
|
||||
private void EnsureListening()
|
||||
{
|
||||
if (_listener is not null) return;
|
||||
_listener = new TcpListener(_bind, _port);
|
||||
_listener.Start();
|
||||
}
|
||||
|
||||
public async Task RunOneConnectionAsync(IFrameHandler handler, CancellationToken ct)
|
||||
{
|
||||
using var linked = CancellationTokenSource.CreateLinkedTokenSource(_cts.Token, ct);
|
||||
EnsureListening();
|
||||
|
||||
// net48 has no AcceptTcpClientAsync(CancellationToken); Stop() unblocks a pending accept.
|
||||
using var reg = linked.Token.Register(() => { try { _listener!.Stop(); } catch { /* ignore */ } });
|
||||
TcpClient client;
|
||||
try { client = await _listener!.AcceptTcpClientAsync().ConfigureAwait(false); }
|
||||
catch (ObjectDisposedException) when (linked.Token.IsCancellationRequested) { throw new OperationCanceledException(linked.Token); }
|
||||
catch (InvalidOperationException) when (linked.Token.IsCancellationRequested) { throw new OperationCanceledException(linked.Token); }
|
||||
|
||||
using (client)
|
||||
{
|
||||
client.NoDelay = true;
|
||||
Stream stream = client.GetStream();
|
||||
SslStream? ssl = null;
|
||||
try
|
||||
{
|
||||
if (_tlsCert is not null)
|
||||
{
|
||||
ssl = new SslStream(stream, leaveInnerStreamOpen: false);
|
||||
await ssl.AuthenticateAsServerAsync(_tlsCert, clientCertificateRequired: false,
|
||||
enabledSslProtocols: SslProtocols.Tls12, checkCertificateRevocation: false).ConfigureAwait(false);
|
||||
stream = ssl;
|
||||
}
|
||||
|
||||
using var reader = new FrameReader(stream, leaveOpen: true);
|
||||
using var writer = new FrameWriter(stream, leaveOpen: true);
|
||||
|
||||
var first = await reader.ReadFrameAsync(linked.Token).ConfigureAwait(false);
|
||||
if (first is null || first.Value.Kind != MessageKind.Hello)
|
||||
{
|
||||
_logger.Warning("Sidecar TCP first frame was not Hello; dropping");
|
||||
return;
|
||||
}
|
||||
var hello = MessagePackSerializer.Deserialize<Hello>(first.Value.Body);
|
||||
if (!string.Equals(hello.SharedSecret, _sharedSecret, StringComparison.Ordinal))
|
||||
{
|
||||
await writer.WriteAsync(MessageKind.HelloAck,
|
||||
new HelloAck { Accepted = false, RejectReason = "shared-secret-mismatch" }, linked.Token).ConfigureAwait(false);
|
||||
_logger.Warning("Sidecar TCP Hello rejected: shared-secret-mismatch");
|
||||
return;
|
||||
}
|
||||
if (hello.ProtocolMajor != Hello.CurrentMajor)
|
||||
{
|
||||
await writer.WriteAsync(MessageKind.HelloAck,
|
||||
new HelloAck { Accepted = false, RejectReason = $"major-version-mismatch-peer={hello.ProtocolMajor}-server={Hello.CurrentMajor}" },
|
||||
linked.Token).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
await writer.WriteAsync(MessageKind.HelloAck,
|
||||
new HelloAck { Accepted = true, HostName = Environment.MachineName }, linked.Token).ConfigureAwait(false);
|
||||
|
||||
while (!linked.Token.IsCancellationRequested)
|
||||
{
|
||||
var frame = await reader.ReadFrameAsync(linked.Token).ConfigureAwait(false);
|
||||
if (frame is null) break;
|
||||
await handler.HandleAsync(frame.Value.Kind, frame.Value.Body, writer, linked.Token).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
finally { ssl?.Dispose(); }
|
||||
}
|
||||
}
|
||||
|
||||
// ---- identical backoff/give-up policy to PipeServer (copy verbatim) ----
|
||||
private static readonly TimeSpan[] BackoffSteps =
|
||||
{
|
||||
TimeSpan.FromMilliseconds(250), TimeSpan.FromMilliseconds(500), TimeSpan.FromSeconds(1),
|
||||
TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(4), TimeSpan.FromSeconds(8),
|
||||
};
|
||||
private const int MaxConsecutiveFailures = 20;
|
||||
|
||||
public async Task RunAsync(IFrameHandler handler, CancellationToken ct)
|
||||
{
|
||||
var consecutiveFailures = 0;
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
try { await RunOneConnectionAsync(handler, ct).ConfigureAwait(false); consecutiveFailures = 0; }
|
||||
catch (OperationCanceledException) { break; }
|
||||
catch (Exception ex)
|
||||
{
|
||||
consecutiveFailures++;
|
||||
if (consecutiveFailures >= MaxConsecutiveFailures)
|
||||
{
|
||||
_logger.Fatal(ex, "Sidecar TCP connection loop failed {Count} consecutive times — giving up so supervisor can restart", consecutiveFailures);
|
||||
throw;
|
||||
}
|
||||
var delay = BackoffSteps[Math.Min(consecutiveFailures - 1, BackoffSteps.Length - 1)];
|
||||
_logger.Error(ex, "Sidecar TCP connection loop error (consecutive failure {Count}/{Max}) — retrying in {Delay}", consecutiveFailures, MaxConsecutiveFailures, delay);
|
||||
try { await Task.Delay(delay, ct).ConfigureAwait(false); } catch (OperationCanceledException) { break; }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose() { _cts.Cancel(); try { _listener?.Stop(); } catch { } _cts.Dispose(); }
|
||||
}
|
||||
```
|
||||
|
||||
**Tests (`TcpRoundTripTests`):** with a fake `IFrameHandler` that echoes a known `ReadRawReply`:
|
||||
1. **plaintext round-trip** — server on `127.0.0.1:0`, a raw `TcpClient` does Hello (good secret) → HelloAck.Accepted, then a `ReadRaw` → echoed reply.
|
||||
2. **TLS round-trip** — construct with a self-signed cert; client `SslStream` (pin thumbprint) → same exchange.
|
||||
3. **bad secret** — Hello with wrong secret → `HelloAck.Accepted == false`, `RejectReason == "shared-secret-mismatch"`.
|
||||
4. **single-active serial accept** — while one client is connected, a second connect does not get served until the first disconnects (assert the second's Hello completes only after the first closes).
|
||||
|
||||
Run `dotnet test tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Tests --filter TcpRoundTrip`. Commit by path — `feat(historian-sidecar): TcpFrameServer (TCP + optional TLS)`.
|
||||
|
||||
---
|
||||
|
||||
### Task 6: Sidecar `Program.cs` — TCP bootstrap + env
|
||||
|
||||
**Classification:** high-risk (process entry, env contract)
|
||||
**Estimated implement time:** ~4 min
|
||||
**Parallelizable with:** none (needs Task 5)
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware/Program.cs`
|
||||
- Modify: `tests/.../Driver.Historian.Wonderware.Tests/ProgramSmokeTests.cs`
|
||||
|
||||
Changes:
|
||||
- Remove the `OTOPCUA_ALLOWED_SID` read + `new SecurityIdentifier(...)` + the `using System.Security.Principal;`.
|
||||
- Read new env: `OTOPCUA_HISTORIAN_TCP_PORT` (int, default 32569), `OTOPCUA_HISTORIAN_BIND` (`IPAddress.Parse`, default `IPAddress.Any`), `OTOPCUA_HISTORIAN_TLS_ENABLED` (`== "true"`), and when TLS on, load the cert from `OTOPCUA_HISTORIAN_TLS_CERT` (pfx path or store thumbprint) + `OTOPCUA_HISTORIAN_TLS_CERT_PASSWORD` into an `X509Certificate2?` (null when TLS off). Keep `OTOPCUA_HISTORIAN_SECRET`/`OTOPCUA_HISTORIAN_ENABLED` + the SDK vars.
|
||||
- Preserve the `ENABLED!=true` idle branch (now log "tcp-only idle" wording; still `WaitOne()` → return 0).
|
||||
- Swap line ~62/64-65:
|
||||
```csharp
|
||||
using var server = new TcpFrameServer(bind, tcpPort, sharedSecret, tlsCert, Log.Logger);
|
||||
Log.Information("Wonderware historian sidecar serving — bind={Bind} port={Port} tls={Tls}", bind, tcpPort, tlsCert is not null);
|
||||
try { server.RunAsync(handler, cts.Token).GetAwaiter().GetResult(); }
|
||||
catch (OperationCanceledException) { }
|
||||
```
|
||||
- Update the class doc comment (drop "named-pipe"/"allowed-SID"; say "hosts a TCP server").
|
||||
|
||||
Update `ProgramSmokeTests` to the new env contract (no `OTOPCUA_ALLOWED_SID`; set `OTOPCUA_HISTORIAN_TCP_PORT`). Build the sidecar project → green. Commit by path — `feat(historian-sidecar): TCP bootstrap + env, drop allowed-SID`.
|
||||
|
||||
---
|
||||
|
||||
### Task 7: Remove dead pipe code + finalize options shape
|
||||
|
||||
**Classification:** standard (deletion-heavy; must keep build green)
|
||||
**Estimated implement time:** ~4 min
|
||||
**Parallelizable with:** none (needs Tasks 3, 4, 6)
|
||||
|
||||
**Files:**
|
||||
- Delete: `src/Drivers/…Driver.Historian.Wonderware/Ipc/PipeServer.cs`, `…/Ipc/PipeAcl.cs`
|
||||
- Delete: `tests/.../Driver.Historian.Wonderware.Tests/Ipc/PipeServerSidRejectTests.cs`, `Ipc/PipeRoundTripTests.cs` (superseded by `TcpRoundTripTests`)
|
||||
- Modify: `…Client/Internal/FrameChannel.cs` — delete `DefaultNamedPipeConnectFactory` + `using System.IO.Pipes;`
|
||||
- Modify: `WonderwareHistorianClientOptions.cs` — reshape record to `(string Host, int Port, string SharedSecret, string PeerName="OtOpcUa", TimeSpan? ConnectTimeout=null, TimeSpan? CallTimeout=null)`; drop `PipeName`; keep `UseTls`/`ServerCertThumbprint`/`ProbeTimeoutSeconds` as init props.
|
||||
- Modify call sites that passed `PipeName`: `Host/Program.cs:97` (`new WonderwareHistorianClientOptions(opts.Host, opts.Port, opts.SharedSecret) { UseTls = …, ServerCertThumbprint = … }`), `AlarmHistorianOptions.cs` (drop `PipeName`), and any test constructing options.
|
||||
|
||||
**Step — grep gate:** `grep -rn "PipeName\|PipeServer\|PipeAcl\|System.IO.Pipes\|DefaultNamedPipeConnectFactory\|OTOPCUA_ALLOWED_SID" src tests` must return **zero** non-comment hits before commit. Run the full two suites (`Client.Tests` + `Driver.Historian.Wonderware.Tests`) green. Commit by path — `refactor(historian): remove named-pipe transport`.
|
||||
|
||||
---
|
||||
|
||||
### Task 8: Deploy scripts — env block + firewall + cert
|
||||
|
||||
**Classification:** standard
|
||||
**Estimated implement time:** ~4 min
|
||||
**Parallelizable with:** Task 9, Task 10
|
||||
|
||||
**Files:**
|
||||
- Modify: `scripts/install/Install-Services.ps1` (the `$historianEnv` array, lines ~100-108)
|
||||
- Modify: `scripts/install/Refresh-Services.ps1` (the Step-5 env patch; the Step 4b assertion is unchanged)
|
||||
|
||||
- `$historianEnv`: drop `OTOPCUA_ALLOWED_SID=$sid`; add `OTOPCUA_HISTORIAN_TCP_PORT=$HistorianTcpPort`, `OTOPCUA_HISTORIAN_BIND=$HistorianBind`, `OTOPCUA_HISTORIAN_TLS_ENABLED=$($HistorianUseTls.ToString().ToLower())`, and (when TLS) `OTOPCUA_HISTORIAN_TLS_CERT=…`. Add params `[int]$HistorianTcpPort = 32569`, `[string]$HistorianBind='0.0.0.0'`, `[switch]$HistorianUseTls`, `[string]$HistorianTlsCertThumbprint`.
|
||||
- Add a **Windows Firewall rule** for the port: `New-NetFirewallRule -DisplayName "OtOpcUa Wonderware Historian (TCP $HistorianTcpPort)" -Direction Inbound -Action Allow -Protocol TCP -LocalPort $HistorianTcpPort` (idempotent: remove-then-add or check `Get-NetFirewallRule`).
|
||||
- A comment block on cert provisioning for prod (store thumbprint or pfx in `C:\ProgramData\OtOpcUa\pki`). The SharedSecret handling is unchanged (still generated/printed, never written to a tracked file).
|
||||
|
||||
No automated test (PowerShell). Validate with `pwsh -NoProfile -Command "[Parser]::ParseFile(...)"` parse-check on both scripts (like the Step 4b commit). Commit by path — `feat(install): historian TCP env + firewall rule`.
|
||||
|
||||
---
|
||||
|
||||
### Task 9: AdminUI Test-Connect probe → host/port/TLS
|
||||
|
||||
**Classification:** small
|
||||
**Estimated implement time:** ~3 min
|
||||
**Parallelizable with:** Task 8, Task 10
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/Drivers/Pickers/HistorianWonderwareAddressBuilder.cs`
|
||||
- Modify: the probe path that builds `WonderwareHistorianClientOptions` for the Test-Connect (find via `grep -rn "WonderwareHistorianClientOptions\|ProbeTimeoutSeconds" src/Server/ZB.MOM.WW.OtOpcUa.AdminUI`).
|
||||
|
||||
Replace pipe-name input with Host/Port/UseTls/(optional)Thumbprint fields; build the probe options with those. No bUnit (per repo convention — verified live in Task 11). Build AdminUI green. Commit by path — `feat(adminui): historian probe uses TCP host/port/tls`.
|
||||
|
||||
---
|
||||
|
||||
### Task 10: Docs
|
||||
|
||||
**Classification:** small
|
||||
**Estimated implement time:** ~4 min
|
||||
**Parallelizable with:** Task 8, Task 9
|
||||
|
||||
**Files:**
|
||||
- Modify: `docs/drivers/Historian.Wonderware.md` (rewrite the Architecture ASCII diagram + "named pipe / shared secret + allowed-SID" text → TCP + optional TLS + shared secret; note the remote-host capability)
|
||||
- Modify: `docs/ServiceHosting.md`, `docs/AlarmHistorian.md` (any named-pipe references → TCP)
|
||||
- Optionally: a short note in `CLAUDE.md` if it gains a historian transport line (it currently has none — skip unless adding).
|
||||
|
||||
Grep gate: `grep -rni "named pipe\|allowed-sid\|OTOPCUA_ALLOWED_SID\|PipeName" docs/drivers/Historian.Wonderware.md docs/ServiceHosting.md docs/AlarmHistorian.md` → no stale references. Commit by path — `docs(historian): TCP transport`.
|
||||
|
||||
---
|
||||
|
||||
### Task 11: Verification (build + test + live)
|
||||
|
||||
**Classification:** verification
|
||||
**Estimated implement time:** ~3 min agent + user-driven live
|
||||
**Parallelizable with:** none (needs all)
|
||||
|
||||
**Agent:**
|
||||
- `dotnet build ZB.MOM.WW.OtOpcUa.slnx` → 0 errors.
|
||||
- `dotnet test tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Tests tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Client.Tests` → green; plus `…Runtime.Tests` if Task 4 touched a bound options test.
|
||||
- Final grep gate (Task 7) clean.
|
||||
|
||||
**Live (user-driven — agent does NOT sign in):**
|
||||
1. Publish the sidecar to the VM (the now-master checkout) with TCP env: `OTOPCUA_HISTORIAN_TCP_PORT=32569`, TLS off; open the firewall port (Task 8 rule). Restart `OtOpcUaWonderwareHistorian`; confirm log "serving — bind=… port=32569 tls=False".
|
||||
2. Point a (MacBook-docker) OtOpcUa `Historian:Wonderware` config at `Host=<VM-ip> Port=32569 UseTls=false` + the matching `SharedSecret`; do a `ReadRaw` (live samples) and a `WriteAlarmEvents` round-trip.
|
||||
3. Flip `OTOPCUA_HISTORIAN_TLS_ENABLED=true` (provision a cert) + client `UseTls=true` (+ thumbprint pin); re-verify the read.
|
||||
|
||||
**Done =** build clean + `dotnet test` green + live read/write pass (plaintext, then TLS).
|
||||
|
||||
Then run **superpowers-extended-cc:finishing-a-development-branch**.
|
||||
|
||||
---
|
||||
|
||||
## Dependency graph
|
||||
|
||||
```
|
||||
T0 ─┬─ T1 ─ T2 ─ T3 ─┐
|
||||
│ └── T4 ───────┤
|
||||
└─ T5 ─ T6 ───────┤
|
||||
T7 ─┬─ T8 ─┐
|
||||
├─ T9 ─┤
|
||||
└─ T10 ┤
|
||||
T11
|
||||
```
|
||||
T1∥T5, T2∥T5, T4∥T5 (disjoint projects). T8∥T9∥T10. T3 needs T2; T4 needs T1; T6 needs T5; T7 needs T3+T4+T6; T8/T9/T10 need T7; T11 needs all.
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"planPath": "docs/plans/2026-06-12-historian-tcp-transport.md",
|
||||
"tasks": [
|
||||
{"id": 0, "nativeTaskId": 296, "subject": "Task 0: Create feature branch", "status": "pending"},
|
||||
{"id": 1, "nativeTaskId": 297, "subject": "Task 1: Add TCP/TLS fields to client options", "status": "pending", "blockedBy": [0]},
|
||||
{"id": 2, "nativeTaskId": 298, "subject": "Task 2: Client TCP connect factory + FrameChannel rename", "status": "pending", "blockedBy": [1]},
|
||||
{"id": 3, "nativeTaskId": 299, "subject": "Task 3: Switch client default ctor to TCP", "status": "pending", "blockedBy": [2]},
|
||||
{"id": 4, "nativeTaskId": 300, "subject": "Task 4: Host config binding (Host/Port/TLS)", "status": "pending", "blockedBy": [1]},
|
||||
{"id": 5, "nativeTaskId": 301, "subject": "Task 5: Sidecar TcpFrameServer", "status": "pending", "blockedBy": [0]},
|
||||
{"id": 6, "nativeTaskId": 302, "subject": "Task 6: Sidecar Program.cs — TCP bootstrap + env", "status": "pending", "blockedBy": [5]},
|
||||
{"id": 7, "nativeTaskId": 303, "subject": "Task 7: Remove dead pipe code + finalize options shape", "status": "pending", "blockedBy": [3, 4, 6]},
|
||||
{"id": 8, "nativeTaskId": 304, "subject": "Task 8: Deploy scripts — env block + firewall + cert", "status": "pending", "blockedBy": [7]},
|
||||
{"id": 9, "nativeTaskId": 305, "subject": "Task 9: AdminUI Test-Connect probe to host/port/TLS", "status": "pending", "blockedBy": [7]},
|
||||
{"id": 10, "nativeTaskId": 306, "subject": "Task 10: Docs — TCP transport", "status": "pending", "blockedBy": [7]},
|
||||
{"id": 11, "nativeTaskId": 307, "subject": "Task 11: Verification (build + test + live)", "status": "pending", "blockedBy": [8, 9, 10]}
|
||||
],
|
||||
"lastUpdated": "2026-06-12"
|
||||
}
|
||||
@@ -1,13 +1,16 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Registers the v2 Windows service on a node: OtOpcUaHost (fused binary, .NET 10)
|
||||
and optionally OtOpcUaWonderwareHistorian (Wonderware historian sidecar, net48 x86).
|
||||
and optionally OtOpcUaWonderwareHistorian (Wonderware historian sidecar, net48 x86
|
||||
— communicates over TCP, optionally TLS, instead of a Windows named pipe).
|
||||
|
||||
.DESCRIPTION
|
||||
v2 consolidates the legacy OtOpcUa + OtOpcUaAdmin services into a single role-gated
|
||||
OtOpcUaHost binary. The -Roles parameter sets the OTOPCUA_ROLES service env so
|
||||
Program.cs decides what to mount (admin / driver / both). The Wonderware historian
|
||||
sidecar logic is unchanged from v1; install it with -InstallWonderwareHistorian.
|
||||
sidecar is installed with -InstallWonderwareHistorian; it listens on a TCP port
|
||||
(default 32569, configurable via -HistorianTcpPort) protected by the shared secret.
|
||||
Optional TLS (-HistorianUseTls) is recommended for production cross-host deployments.
|
||||
|
||||
Galaxy access flows through the mxaccessgw sibling repo (separate service); see
|
||||
docs/v2/Galaxy.ParityRig.md for the gateway setup.
|
||||
@@ -39,6 +42,30 @@
|
||||
Per-process secret passed to the historian sidecar via env var. Generated freshly
|
||||
per install when not supplied.
|
||||
|
||||
.PARAMETER HistorianTcpPort
|
||||
TCP port the sidecar listens on (OTOPCUA_HISTORIAN_TCP_PORT). Default 32569. A
|
||||
matching Windows Firewall inbound rule is created automatically.
|
||||
|
||||
.PARAMETER HistorianBind
|
||||
IP address the sidecar binds to (OTOPCUA_HISTORIAN_BIND). Default 0.0.0.0
|
||||
(all interfaces). Set to 127.0.0.1 for loopback-only on same-host deployments.
|
||||
|
||||
.PARAMETER HistorianUseTls
|
||||
When set, enables TLS on the sidecar TCP listener. Supply -HistorianTlsCert with
|
||||
a certificate path or store thumbprint; recommended for cross-host production use.
|
||||
|
||||
.PARAMETER HistorianTlsCert
|
||||
Certificate source for TLS. Either:
|
||||
- Absolute path to a .pfx file (e.g. C:\ProgramData\OtOpcUa\pki\historian.pfx),
|
||||
exported with MachineKeySet so the service account can read the private key; or
|
||||
- A LocalMachine\My store thumbprint (40-hex-char string, no spaces).
|
||||
Do NOT embed a cert path or thumbprint in automation scripts for unattended installs;
|
||||
pass it at call time or from a secrets vault.
|
||||
|
||||
.PARAMETER HistorianTlsCertPassword
|
||||
Password for the .pfx file (if using a pfx path). Leave empty when using a store
|
||||
thumbprint. Never store passwords in scripts or source control.
|
||||
|
||||
.EXAMPLE
|
||||
.\Install-Services.ps1 -InstallRoot 'C:\Program Files\OtOpcUa' `
|
||||
-ServiceAccount 'OTOPCUA\svc-otopcua' -Roles 'admin,driver'
|
||||
@@ -57,12 +84,16 @@ param(
|
||||
[int]$HttpPort = 9000,
|
||||
|
||||
# Wonderware historian sidecar. Optional; gates the OtOpcUaWonderwareHistorian
|
||||
# service. Secret + pipe defaults match the server's Historian:Wonderware appsettings.
|
||||
# service. Secret defaults match the server's AlarmHistorian appsettings.
|
||||
[switch]$InstallWonderwareHistorian,
|
||||
[string]$HistorianSharedSecret,
|
||||
[string]$HistorianPipeName = 'OtOpcUaWonderwareHistorian',
|
||||
[string]$HistorianServer = 'localhost',
|
||||
[int]$HistorianPort = 32568,
|
||||
[int]$HistorianPort = 32568, # SDK port (OTOPCUA_HISTORIAN_PORT) — Wonderware InSQL connection
|
||||
[int]$HistorianTcpPort = 32569, # TCP listen port for the IPC channel (OTOPCUA_HISTORIAN_TCP_PORT)
|
||||
[string]$HistorianBind = '0.0.0.0',
|
||||
[switch]$HistorianUseTls,
|
||||
[string]$HistorianTlsCert,
|
||||
[string]$HistorianTlsCertPassword,
|
||||
[string[]]$AvevaServiceDependencies = @('NmxSvc', 'aaBootstrap', 'aaGR')
|
||||
)
|
||||
|
||||
@@ -87,29 +118,43 @@ if ($InstallWonderwareHistorian -and -not (Test-Path "$InstallRoot\WonderwareHis
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Resolve the SID — the IPC ACL needs the SID, not the down-level name.
|
||||
$sid = if ($ServiceAccount.StartsWith('S-1-')) {
|
||||
$ServiceAccount
|
||||
} else {
|
||||
(New-Object System.Security.Principal.NTAccount $ServiceAccount).Translate([System.Security.Principal.SecurityIdentifier]).Value
|
||||
}
|
||||
|
||||
# --- OtOpcUaWonderwareHistorian sidecar (optional, unchanged from v1) -------
|
||||
# --- OtOpcUaWonderwareHistorian sidecar (optional, TCP transport) -----------
|
||||
$historianDepend = $null
|
||||
if ($InstallWonderwareHistorian) {
|
||||
# Build the TCP/TLS env block.
|
||||
# The Windows named-pipe transport and OTOPCUA_ALLOWED_SID have been retired;
|
||||
# the sidecar now listens on a TCP port protected by the shared secret.
|
||||
# TLS is optional but strongly recommended for cross-host production deployments.
|
||||
#
|
||||
# Cert provisioning for prod (when -HistorianUseTls):
|
||||
# Option A — pfx file: export with -KeyExportPolicy Exportable -KeyStorageFlags MachineKeySet;
|
||||
# place at e.g. C:\ProgramData\OtOpcUa\pki\historian.pfx;
|
||||
# ACL the file so the service account has Read access.
|
||||
# Option B — store thumbprint: import into LocalMachine\My; grant the service account
|
||||
# Read on the private key via certlm.msc → Manage Private Keys.
|
||||
# Either value is passed via -HistorianTlsCert at install time; NEVER hard-code it here.
|
||||
$historianEnv = @(
|
||||
"OTOPCUA_HISTORIAN_PIPE=$HistorianPipeName"
|
||||
"OTOPCUA_ALLOWED_SID=$sid"
|
||||
"OTOPCUA_HISTORIAN_SECRET=$HistorianSharedSecret"
|
||||
"OTOPCUA_HISTORIAN_ENABLED=true"
|
||||
"OTOPCUA_HISTORIAN_ALARM_WRITE_ENABLED=true"
|
||||
"OTOPCUA_HISTORIAN_SERVER=$HistorianServer"
|
||||
"OTOPCUA_HISTORIAN_PORT=$HistorianPort"
|
||||
"OTOPCUA_HISTORIAN_TCP_PORT=$HistorianTcpPort"
|
||||
"OTOPCUA_HISTORIAN_BIND=$HistorianBind"
|
||||
)
|
||||
if ($HistorianUseTls) {
|
||||
$historianEnv += "OTOPCUA_HISTORIAN_TLS_ENABLED=true"
|
||||
$historianEnv += "OTOPCUA_HISTORIAN_TLS_CERT=$HistorianTlsCert"
|
||||
if ($HistorianTlsCertPassword) {
|
||||
$historianEnv += "OTOPCUA_HISTORIAN_TLS_CERT_PASSWORD=$HistorianTlsCertPassword"
|
||||
}
|
||||
} else {
|
||||
$historianEnv += "OTOPCUA_HISTORIAN_TLS_ENABLED=false"
|
||||
}
|
||||
|
||||
Write-Host "Installing OtOpcUaWonderwareHistorian..."
|
||||
& sc.exe create OtOpcUaWonderwareHistorian binPath= "`"$InstallRoot\WonderwareHistorian\OtOpcUa.Driver.Historian.Wonderware.exe`"" `
|
||||
DisplayName= 'OtOpcUa Wonderware Historian Sidecar (out-of-process aahClient)' `
|
||||
DisplayName= 'OtOpcUa Wonderware Historian Sidecar (out-of-process aahClient, TCP)' `
|
||||
start= auto `
|
||||
depend= ($AvevaServiceDependencies -join '/') `
|
||||
obj= $ServiceAccount | Out-Null
|
||||
@@ -120,6 +165,11 @@ if ($InstallWonderwareHistorian) {
|
||||
|
||||
& sc.exe failure OtOpcUaWonderwareHistorian reset= 86400 actions= restart/5000/restart/30000/restart/60000 | Out-Null
|
||||
|
||||
# Idempotent Windows Firewall rule for the sidecar TCP port.
|
||||
$fwName = "OtOpcUa Wonderware Historian (TCP $HistorianTcpPort)"
|
||||
Get-NetFirewallRule -DisplayName $fwName -ErrorAction SilentlyContinue | Remove-NetFirewallRule -ErrorAction SilentlyContinue
|
||||
New-NetFirewallRule -DisplayName $fwName -Direction Inbound -Action Allow -Protocol TCP -LocalPort $HistorianTcpPort | Out-Null
|
||||
|
||||
$historianDepend = 'OtOpcUaWonderwareHistorian'
|
||||
}
|
||||
|
||||
@@ -171,7 +221,7 @@ if ($InstallWonderwareHistorian) { Write-Host " sc.exe start OtOpcUaWonderwareH
|
||||
Write-Host " sc.exe start OtOpcUaHost"
|
||||
if ($InstallWonderwareHistorian) {
|
||||
Write-Host ""
|
||||
Write-Host "Wonderware historian shared secret (configure into appsettings.json Historian:Wonderware:SharedSecret):"
|
||||
Write-Host "Wonderware historian shared secret (configure into appsettings.json AlarmHistorian:SharedSecret):"
|
||||
Write-Host " $HistorianSharedSecret"
|
||||
}
|
||||
Write-Host ""
|
||||
|
||||
@@ -125,7 +125,7 @@ Run {
|
||||
# `dotnet publish` above) silently drops the net48 binding-redirect
|
||||
# .exe.config and the transitive runtime DLLs MessagePack needs — most
|
||||
# notably System.Memory.dll. The sidecar then JIT-load-faults inside
|
||||
# PipeServer.RunOneConnectionAsync ("FileNotFoundException: System.Memory,
|
||||
# TcpFrameServer.RunOneConnectionAsync ("FileNotFoundException: System.Memory,
|
||||
# Version=4.0.1.2") and NSSM crash-loops it (exit 2 every ~2 min, ~120 s of
|
||||
# retry backoff before it gives up). Fail loudly here so an incomplete deploy
|
||||
# is caught at publish time instead of by a production crash-loop.
|
||||
@@ -147,7 +147,7 @@ if (-not $WhatIf) {
|
||||
|
||||
if ($missing.Count -gt 0) {
|
||||
$msg = "Wonderware historian sidecar deploy at '$sidecarDir' is INCOMPLETE — missing: " +
|
||||
"$($missing -join ', '). It would crash-loop with a FileNotFoundException in PipeServer. " +
|
||||
"$($missing -join ', '). It would crash-loop with a FileNotFoundException in TcpFrameServer. " +
|
||||
"Re-run the sidecar 'dotnet publish' into that folder (Step 4) — never hand-copy a partial build output."
|
||||
throw $msg
|
||||
}
|
||||
@@ -158,6 +158,11 @@ if (-not $WhatIf) {
|
||||
# ------------------------------------------------------------------------
|
||||
# Step 5: Service env block — ensure OTOPCUA_HISTORIAN_ALARM_WRITE_ENABLED
|
||||
# is set on the Wonderware historian service (PR C.2 toggle).
|
||||
# Note: the TCP transport env (OTOPCUA_HISTORIAN_TCP_PORT, OTOPCUA_HISTORIAN_BIND,
|
||||
# OTOPCUA_HISTORIAN_TLS_ENABLED, OTOPCUA_HISTORIAN_TLS_CERT) and the Windows
|
||||
# Firewall rule are set once at install time by Install-Services.ps1 and are
|
||||
# not touched here on refresh; re-run Install-Services.ps1 to change them.
|
||||
# OTOPCUA_ALLOWED_SID is no longer used (TCP transport retired the named pipe).
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
if (Test-NssmService 'OtOpcUaWonderwareHistorian') {
|
||||
|
||||
+16
-4
@@ -8,20 +8,22 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Client;
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// <b>Retry / backoff ownership (finding 006):</b> this module performs exactly one
|
||||
/// in-place transport reconnect inside <c>PipeChannel.InvokeAsync</c> with no delay,
|
||||
/// in-place transport reconnect inside <c>FrameChannel.InvokeAsync</c> with no delay,
|
||||
/// and does NOT implement exponential reconnect backoff. Broader retry/backoff is the
|
||||
/// caller's responsibility — the alarm drain worker
|
||||
/// (<c>Core.AlarmHistorian.SqliteStoreAndForwardSink</c>) and the read-side
|
||||
/// history router are expected to layer their own backoff on top.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <param name="PipeName">Named-pipe name the sidecar listens on (matches the sidecar's <c>OTOPCUA_HISTORIAN_PIPE</c>).</param>
|
||||
/// <param name="Host">Sidecar TCP host (DNS name or IP) the client dials.</param>
|
||||
/// <param name="Port">Sidecar TCP port (matches the sidecar's <c>OTOPCUA_HISTORIAN_TCP_PORT</c>).</param>
|
||||
/// <param name="SharedSecret">Per-process shared secret the sidecar will verify in the Hello frame.</param>
|
||||
/// <param name="PeerName">Diagnostic peer identifier sent in Hello — typically the OtOpcUa instance id.</param>
|
||||
/// <param name="ConnectTimeout">Cap on the named-pipe connect + Hello round trip on each (re)connect.</param>
|
||||
/// <param name="ConnectTimeout">Cap on the TCP connect + Hello round trip on each (re)connect.</param>
|
||||
/// <param name="CallTimeout">Cap on a single read/write call once connected.</param>
|
||||
public sealed record WonderwareHistorianClientOptions(
|
||||
string PipeName,
|
||||
string Host,
|
||||
int Port,
|
||||
string SharedSecret,
|
||||
string PeerName = "OtOpcUa",
|
||||
TimeSpan? ConnectTimeout = null,
|
||||
@@ -40,4 +42,14 @@ public sealed record WonderwareHistorianClientOptions(
|
||||
[Display(Name = "Probe timeout (seconds)", Description = "Connection test timeout. Default 15s.", GroupName = "Diagnostics")]
|
||||
[Range(1, 60)]
|
||||
public int ProbeTimeoutSeconds { get; init; } = 15;
|
||||
|
||||
/// <summary>When true, the client wraps the TCP stream in TLS before the Hello handshake.</summary>
|
||||
public bool UseTls { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Optional SHA-1 thumbprint (hex, no spaces) the client pins the sidecar's TLS server
|
||||
/// cert against. When null/empty and <see cref="UseTls"/> is true, the client validates
|
||||
/// the cert chain normally (CA-issued cert).
|
||||
/// </summary>
|
||||
public string? ServerCertThumbprint { get; init; }
|
||||
}
|
||||
|
||||
+53
-19
@@ -1,4 +1,6 @@
|
||||
using System.IO.Pipes;
|
||||
using System.Net.Security;
|
||||
using System.Net.Sockets;
|
||||
using System.Security.Authentication;
|
||||
using MessagePack;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Client.Ipc;
|
||||
@@ -6,17 +8,17 @@ using ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Client.Ipc;
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Client.Internal;
|
||||
|
||||
/// <summary>
|
||||
/// Owns one connection to the Wonderware historian sidecar pipe. Handles the Hello
|
||||
/// Owns one TCP connection to the Wonderware historian sidecar. Handles the Hello
|
||||
/// handshake, serializes outgoing requests + waits for the matching reply frame, and
|
||||
/// reconnects on transport failure with exponential backoff.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Single in-flight call at a time — the sidecar's pipe protocol is request/response
|
||||
/// Single in-flight call at a time — the sidecar's TCP protocol is request/response
|
||||
/// over a single bidirectional stream, so multiple concurrent <see cref="InvokeAsync"/>
|
||||
/// calls would interleave replies. A <see cref="SemaphoreSlim"/> serializes them. PR 6.x
|
||||
/// can layer batching on top.
|
||||
/// </remarks>
|
||||
internal sealed class PipeChannel : IAsyncDisposable
|
||||
internal sealed class FrameChannel : IAsyncDisposable
|
||||
{
|
||||
private readonly WonderwareHistorianClientOptions _options;
|
||||
private readonly Func<CancellationToken, Task<Stream>> _connect;
|
||||
@@ -29,26 +31,58 @@ internal sealed class PipeChannel : IAsyncDisposable
|
||||
private bool _disposed;
|
||||
|
||||
/// <summary>
|
||||
/// Default factory: connects to a real <see cref="NamedPipeClientStream"/> by name.
|
||||
/// Default TCP factory: connects to the sidecar over TCP, optionally wrapping the stream
|
||||
/// in TLS (server-auth; pinned-thumbprint or CA-chain validation). The Hello handshake +
|
||||
/// shared secret still authenticate the caller on top of this.
|
||||
/// </summary>
|
||||
public static Func<WonderwareHistorianClientOptions, CancellationToken, Task<Stream>> DefaultNamedPipeConnectFactory =
|
||||
public static Func<WonderwareHistorianClientOptions, CancellationToken, Task<Stream>> DefaultTcpConnectFactory =
|
||||
async (opts, ct) =>
|
||||
{
|
||||
var pipe = new NamedPipeClientStream(
|
||||
serverName: ".",
|
||||
pipeName: opts.PipeName,
|
||||
direction: PipeDirection.InOut,
|
||||
options: PipeOptions.Asynchronous);
|
||||
if (string.IsNullOrWhiteSpace(opts.Host))
|
||||
throw new InvalidOperationException("WonderwareHistorianClientOptions.Host is required for the TCP transport.");
|
||||
|
||||
await pipe.ConnectAsync((int)opts.EffectiveConnectTimeout.TotalMilliseconds, ct).ConfigureAwait(false);
|
||||
return pipe;
|
||||
var tcp = new TcpClient();
|
||||
try
|
||||
{
|
||||
using var connectCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
connectCts.CancelAfter(opts.EffectiveConnectTimeout);
|
||||
await tcp.ConnectAsync(opts.Host, opts.Port, connectCts.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
tcp.Dispose();
|
||||
throw;
|
||||
}
|
||||
tcp.NoDelay = true;
|
||||
|
||||
// The returned NetworkStream owns the socket (TcpClient.GetStream() uses ownsSocket: true),
|
||||
// so FrameChannel.ResetTransport() disposing this stream closes the underlying socket.
|
||||
Stream stream = tcp.GetStream();
|
||||
if (!opts.UseTls) return stream;
|
||||
|
||||
var ssl = new SslStream(stream, leaveInnerStreamOpen: false, (_, cert, _, errors) =>
|
||||
{
|
||||
if (!string.IsNullOrEmpty(opts.ServerCertThumbprint))
|
||||
return string.Equals(cert?.GetCertHashString(), opts.ServerCertThumbprint, StringComparison.OrdinalIgnoreCase);
|
||||
return errors == SslPolicyErrors.None;
|
||||
});
|
||||
try
|
||||
{
|
||||
await ssl.AuthenticateAsClientAsync(new SslClientAuthenticationOptions { TargetHost = opts.Host }, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
await ssl.DisposeAsync().ConfigureAwait(false);
|
||||
throw;
|
||||
}
|
||||
return ssl;
|
||||
};
|
||||
|
||||
/// <summary>Initializes a new instance of the <see cref="PipeChannel"/> class.</summary>
|
||||
/// <summary>Initializes a new instance of the <see cref="FrameChannel"/> class.</summary>
|
||||
/// <param name="options">Configuration options for the historian client.</param>
|
||||
/// <param name="connect">Function to establish a connection stream.</param>
|
||||
/// <param name="logger">Logger instance for diagnostics.</param>
|
||||
public PipeChannel(
|
||||
public FrameChannel(
|
||||
WonderwareHistorianClientOptions options,
|
||||
Func<CancellationToken, Task<Stream>> connect,
|
||||
ILogger logger)
|
||||
@@ -113,7 +147,7 @@ internal sealed class PipeChannel : IAsyncDisposable
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or EndOfStreamException or ObjectDisposedException)
|
||||
{
|
||||
_logger.LogWarning(ex, "Sidecar pipe transport failure on {Kind}; reconnecting", requestKind);
|
||||
_logger.LogWarning(ex, "Sidecar TCP transport failure on {Kind}; reconnecting", requestKind);
|
||||
ResetTransport();
|
||||
await ConnectInternalAsync(timeout.Token).ConfigureAwait(false);
|
||||
// One retry. If the second attempt also fails, propagate.
|
||||
@@ -128,7 +162,7 @@ internal sealed class PipeChannel : IAsyncDisposable
|
||||
{
|
||||
await _writer!.WriteAsync(requestKind, request, ct).ConfigureAwait(false);
|
||||
var frame = await _reader!.ReadFrameAsync(ct).ConfigureAwait(false)
|
||||
?? throw new EndOfStreamException("Sidecar closed pipe before reply.");
|
||||
?? throw new EndOfStreamException("Sidecar closed connection before reply.");
|
||||
if (frame.Kind != expectedReplyKind)
|
||||
{
|
||||
throw new InvalidDataException(
|
||||
@@ -155,7 +189,7 @@ internal sealed class PipeChannel : IAsyncDisposable
|
||||
await _writer.WriteAsync(MessageKind.Hello, hello, ct).ConfigureAwait(false);
|
||||
|
||||
var ackFrame = await _reader.ReadFrameAsync(ct).ConfigureAwait(false)
|
||||
?? throw new EndOfStreamException("Sidecar closed pipe before HelloAck.");
|
||||
?? throw new EndOfStreamException("Sidecar closed connection before HelloAck.");
|
||||
if (ackFrame.Kind != MessageKind.HelloAck)
|
||||
{
|
||||
ResetTransport();
|
||||
@@ -170,7 +204,7 @@ internal sealed class PipeChannel : IAsyncDisposable
|
||||
$"Sidecar rejected Hello: {ack.RejectReason ?? "<no reason>"}.");
|
||||
}
|
||||
|
||||
_logger.LogInformation("Sidecar pipe connected — host={Host}", ack.HostName);
|
||||
_logger.LogInformation("Sidecar TCP connected — host={Host}", ack.HostName);
|
||||
}
|
||||
|
||||
private void ResetTransport()
|
||||
+15
-15
@@ -16,13 +16,13 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Client;
|
||||
/// (alarm-event drain consumed by <c>Core.AlarmHistorian.SqliteStoreAndForwardSink</c>).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The client owns a single <see cref="PipeChannel"/> with one in-flight call at a time;
|
||||
/// The client owns a single <see cref="FrameChannel"/> with one in-flight call at a time;
|
||||
/// concurrent calls serialize on the channel's gate. Reconnect is handled inside the
|
||||
/// channel — transient transport failures retry once before propagating.
|
||||
/// </remarks>
|
||||
public sealed class WonderwareHistorianClient : IHistorianDataSource, IAlarmHistorianWriter, IAsyncDisposable
|
||||
{
|
||||
private readonly PipeChannel _channel;
|
||||
private readonly FrameChannel _channel;
|
||||
private readonly object _healthLock = new();
|
||||
private DateTime? _lastSuccessUtc;
|
||||
private DateTime? _lastFailureUtc;
|
||||
@@ -33,13 +33,13 @@ public sealed class WonderwareHistorianClient : IHistorianDataSource, IAlarmHist
|
||||
private int _consecutiveFailures;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a client over a real named-pipe connection. Tests that need an in-process
|
||||
/// duplex pair use the <see cref="ForTests"/> factory.
|
||||
/// Creates a client that connects to the Wonderware historian sidecar over TCP.
|
||||
/// Tests that need an in-process duplex pair use the <see cref="ForTests"/> factory.
|
||||
/// </summary>
|
||||
/// <param name="options">The client connection options.</param>
|
||||
/// <param name="logger">Optional logger for diagnostic output.</param>
|
||||
public WonderwareHistorianClient(WonderwareHistorianClientOptions options, ILogger<WonderwareHistorianClient>? logger = null)
|
||||
: this(options, ct => PipeChannel.DefaultNamedPipeConnectFactory(options, ct), logger)
|
||||
: this(options, ct => FrameChannel.DefaultTcpConnectFactory(options, ct), logger)
|
||||
{
|
||||
}
|
||||
|
||||
@@ -61,7 +61,7 @@ public sealed class WonderwareHistorianClient : IHistorianDataSource, IAlarmHist
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
var log = (ILogger?)logger ?? NullLogger.Instance;
|
||||
_channel = new PipeChannel(options, connect, log);
|
||||
_channel = new FrameChannel(options, connect, log);
|
||||
}
|
||||
|
||||
// ===== IHistorianDataSource =====
|
||||
@@ -210,11 +210,11 @@ public sealed class WonderwareHistorianClient : IHistorianDataSource, IAlarmHist
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a snapshot of operation counters and the single pipe channel's connection
|
||||
/// Returns a snapshot of operation counters and the single TCP channel's connection
|
||||
/// state.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This client owns one duplex named-pipe channel to the sidecar — it has no notion of
|
||||
/// This client owns one TCP channel to the sidecar — it has no notion of
|
||||
/// separate process / event connections and no per-node telemetry. The single channel's
|
||||
/// connected state is reported for both <see cref="HistorianHealthSnapshot.ProcessConnectionOpen"/>
|
||||
/// and <see cref="HistorianHealthSnapshot.EventConnectionOpen"/>, and
|
||||
@@ -521,18 +521,18 @@ public sealed class WonderwareHistorianClient : IHistorianDataSource, IAlarmHist
|
||||
_ => throw new NotSupportedException($"Unknown HistoryAggregateType {aggregate}"),
|
||||
};
|
||||
|
||||
/// <summary>Asynchronously disposes the client and its underlying pipe channel.</summary>
|
||||
/// <summary>Asynchronously disposes the client and its underlying TCP channel.</summary>
|
||||
/// <returns>A task that completes when the client has been disposed.</returns>
|
||||
public ValueTask DisposeAsync() => _channel.DisposeAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Synchronous dispose required by <see cref="IDisposable"/> on
|
||||
/// <see cref="IHistorianDataSource"/>. The underlying channel's async cleanup runs
|
||||
/// <see cref="System.IO.Pipes.NamedPipeClientStream"/> teardown, which can block briefly
|
||||
/// on OS handle release — strictly speaking it is not non-blocking — but the
|
||||
/// <c>GetAwaiter()/GetResult()</c> bridge is deadlock-safe because the cleanup never
|
||||
/// awaits a captured <see cref="System.Threading.SynchronizationContext"/> nor takes any
|
||||
/// lock that the caller could hold. (Finding 010.)
|
||||
/// <see cref="IHistorianDataSource"/>. The underlying channel's async cleanup runs the
|
||||
/// TCP socket teardown, which can block briefly on OS handle release — strictly speaking
|
||||
/// it is not non-blocking — but the <c>GetAwaiter()/GetResult()</c> bridge is
|
||||
/// deadlock-safe because the cleanup never awaits a captured
|
||||
/// <see cref="System.Threading.SynchronizationContext"/> nor takes any lock that the
|
||||
/// caller could hold. (Finding 010.)
|
||||
/// </summary>
|
||||
public void Dispose() => _channel.DisposeAsync().AsTask().GetAwaiter().GetResult();
|
||||
}
|
||||
|
||||
+64
-19
@@ -1,16 +1,22 @@
|
||||
using System.Diagnostics;
|
||||
using System.Net.Sockets;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Client.Internal;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Client.Ipc;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Client;
|
||||
|
||||
/// <summary>
|
||||
/// Driver probe for the <see cref="WonderwareHistorianClientOptions"/>-shaped driver config.
|
||||
/// The Wonderware Historian client communicates over a Windows named pipe (not a TCP socket),
|
||||
/// so a cheap TCP-connect probe is not applicable for this transport. This probe always
|
||||
/// returns a well-formed "not applicable" result so the AdminUI can display a meaningful
|
||||
/// message instead of a red error. A full named-pipe connect + Hello-frame probe is a
|
||||
/// documented follow-up.
|
||||
/// TCP-connect probe for the <see cref="WonderwareHistorianClientOptions"/>-shaped driver
|
||||
/// config. Opens a socket to the configured <c>Host:Port</c> (optionally performing the TLS
|
||||
/// client handshake when <c>UseTls</c> is set, reusing the same pinned-thumbprint / CA-chain
|
||||
/// validation as <see cref="FrameChannel.DefaultTcpConnectFactory"/>), then sends a
|
||||
/// <see cref="Hello"/> with the configured shared secret and confirms the sidecar's
|
||||
/// <see cref="HelloAck"/> is accepted — a true end-to-end reachability + auth check.
|
||||
/// Surfaces a green tick + latency on success; a clear red message on timeout / connection
|
||||
/// refused / TLS failure / rejected Hello.
|
||||
/// </summary>
|
||||
public sealed class WonderwareHistorianDriverProbe : IDriverProbe
|
||||
{
|
||||
@@ -24,24 +30,63 @@ public sealed class WonderwareHistorianDriverProbe : IDriverProbe
|
||||
public string DriverType => "Historian.Wonderware";
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<DriverProbeResult> ProbeAsync(string configJson, TimeSpan timeout, CancellationToken ct)
|
||||
public async Task<DriverProbeResult> ProbeAsync(string configJson, TimeSpan timeout, CancellationToken ct)
|
||||
{
|
||||
// Validate the config JSON can at least be parsed — surface bad JSON immediately.
|
||||
WonderwareHistorianClientOptions? opts;
|
||||
try { opts = JsonSerializer.Deserialize<WonderwareHistorianClientOptions>(configJson, _opts); }
|
||||
catch (Exception ex) { return new(false, $"Config JSON is invalid: {ex.Message}", null); }
|
||||
if (opts is null) return new(false, "Config JSON deserialized to null.", null);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(opts.Host) || opts.Port <= 0)
|
||||
return new(false, "Config has no host/port to probe.", null);
|
||||
|
||||
var sw = Stopwatch.StartNew();
|
||||
Stream? stream = null;
|
||||
try
|
||||
{
|
||||
// Reuse the runtime connect factory so the probe exercises the exact TCP + TLS
|
||||
// (pinned-thumbprint or CA-chain) path the client uses in production.
|
||||
stream = await FrameChannel.DefaultTcpConnectFactory(opts, ct).ConfigureAwait(false);
|
||||
|
||||
using var reader = new FrameReader(stream, leaveOpen: true);
|
||||
using var writer = new FrameWriter(stream, leaveOpen: true);
|
||||
|
||||
var hello = new Hello
|
||||
{
|
||||
ProtocolMajor = Hello.CurrentMajor,
|
||||
ProtocolMinor = Hello.CurrentMinor,
|
||||
PeerName = opts.PeerName,
|
||||
SharedSecret = opts.SharedSecret,
|
||||
};
|
||||
await writer.WriteAsync(MessageKind.Hello, hello, ct).ConfigureAwait(false);
|
||||
|
||||
var ackFrame = await reader.ReadFrameAsync(ct).ConfigureAwait(false)
|
||||
?? throw new EndOfStreamException("Sidecar closed connection before HelloAck.");
|
||||
if (ackFrame.Kind != MessageKind.HelloAck)
|
||||
return new(false, $"Sidecar replied to Hello with kind {ackFrame.Kind}; expected HelloAck.", null);
|
||||
|
||||
var ack = FrameReader.Deserialize<HelloAck>(ackFrame.Body);
|
||||
if (!ack.Accepted)
|
||||
return new(false, $"Sidecar rejected Hello: {ack.RejectReason ?? "<no reason>"}.", null);
|
||||
|
||||
sw.Stop();
|
||||
return new(true, $"Connected to {opts.Host}:{opts.Port} (tls={opts.UseTls})", sw.Elapsed);
|
||||
}
|
||||
catch (SocketException ex)
|
||||
{
|
||||
return new(false, $"Connect failed: {ex.SocketErrorCode}", null);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return new(false, $"Probe timed out after {timeout.TotalSeconds:F0}s.", null);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Task.FromResult(new DriverProbeResult(false, $"Config JSON is invalid: {ex.Message}", null));
|
||||
return new(false, ex.Message, null);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (stream is not null) await stream.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
if (opts is null)
|
||||
return Task.FromResult(new DriverProbeResult(false, "Config JSON deserialized to null.", null));
|
||||
|
||||
// The Wonderware Historian sidecar communicates over a Windows named pipe; there is no
|
||||
// TCP endpoint to connect to. A full pipe connect + Hello-frame probe is a follow-up.
|
||||
return Task.FromResult(new DriverProbeResult(
|
||||
false,
|
||||
"TCP probe not applicable for this transport — the Historian sidecar uses a named pipe. " +
|
||||
"A full named-pipe probe is a documented follow-up.",
|
||||
null));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Ipc;
|
||||
|
||||
/// <summary>
|
||||
/// Strategy for handling each post-Hello frame the sidecar's <see cref="TcpFrameServer"/>
|
||||
/// reads. Implementations deserialize the body per the <see cref="MessageKind"/>, dispatch
|
||||
/// to the historian, and write the corresponding reply through the supplied
|
||||
/// <see cref="FrameWriter"/>.
|
||||
/// </summary>
|
||||
public interface IFrameHandler
|
||||
{
|
||||
/// <summary>Handles a frame from the sidecar frame server.</summary>
|
||||
/// <param name="kind">The type of message being handled.</param>
|
||||
/// <param name="body">The serialized message body.</param>
|
||||
/// <param name="writer">The frame writer to send responses.</param>
|
||||
/// <param name="ct">Cancellation token for the operation.</param>
|
||||
Task HandleAsync(MessageKind kind, byte[] body, FrameWriter writer, CancellationToken ct);
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
using System;
|
||||
using System.IO.Pipes;
|
||||
using System.Security.AccessControl;
|
||||
using System.Security.Principal;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Ipc;
|
||||
|
||||
/// <summary>
|
||||
/// Builds a strict <see cref="PipeSecurity"/> for the historian sidecar pipe — only the
|
||||
/// configured server-principal SID gets <c>ReadWrite | Synchronize</c>, LocalSystem is
|
||||
/// explicitly denied (unless it's the allowed principal itself), and the allowed SID owns
|
||||
/// the DACL. Mirrors the policy in Driver.Galaxy.Host's PipeAcl.
|
||||
/// </summary>
|
||||
public static class PipeAcl
|
||||
{
|
||||
/// <summary>Creates a strict PipeSecurity for the historian sidecar pipe.</summary>
|
||||
/// <param name="allowedSid">The security identifier that should have read-write access to the pipe.</param>
|
||||
/// <returns>A configured PipeSecurity object with strict access control.</returns>
|
||||
public static PipeSecurity Create(SecurityIdentifier allowedSid)
|
||||
{
|
||||
if (allowedSid is null) throw new ArgumentNullException(nameof(allowedSid));
|
||||
|
||||
var security = new PipeSecurity();
|
||||
|
||||
security.AddAccessRule(new PipeAccessRule(
|
||||
allowedSid,
|
||||
PipeAccessRights.ReadWrite | PipeAccessRights.Synchronize,
|
||||
AccessControlType.Allow));
|
||||
|
||||
var localSystem = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null);
|
||||
if (allowedSid != localSystem)
|
||||
security.AddAccessRule(new PipeAccessRule(localSystem, PipeAccessRights.FullControl, AccessControlType.Deny));
|
||||
|
||||
// Owner = allowed SID so the deny rules can't be removed without write-DACL rights.
|
||||
security.SetOwner(allowedSid);
|
||||
|
||||
return security;
|
||||
}
|
||||
}
|
||||
@@ -1,258 +0,0 @@
|
||||
using System;
|
||||
using System.IO.Pipes;
|
||||
using System.Security.Principal;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MessagePack;
|
||||
using Serilog;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Ipc;
|
||||
|
||||
/// <summary>
|
||||
/// Accepts one client connection at a time on a named pipe with the strict ACL from
|
||||
/// <see cref="PipeAcl"/>. Verifies the peer SID and the per-process shared secret before
|
||||
/// any frame is dispatched. Mirrors Driver.Galaxy.Host's PipeServer; the sidecar carries
|
||||
/// its own copy so the deletion of Galaxy.Host in PR 7.2 leaves the sidecar self-contained.
|
||||
/// </summary>
|
||||
public sealed class PipeServer : IDisposable
|
||||
{
|
||||
private readonly string _pipeName;
|
||||
private readonly SecurityIdentifier _allowedSid;
|
||||
private readonly string _sharedSecret;
|
||||
private readonly ILogger _logger;
|
||||
private readonly CancellationTokenSource _cts = new();
|
||||
private readonly CallerVerifier _verifier;
|
||||
private NamedPipeServerStream? _current;
|
||||
|
||||
/// <summary>
|
||||
/// Pluggable caller-verification seam. Default implementation calls
|
||||
/// <see cref="VerifyCaller"/>; tests can substitute one that ignores the pipe ACL
|
||||
/// to exercise the rejection paths.
|
||||
/// </summary>
|
||||
/// <param name="pipe">The named pipe server stream to verify.</param>
|
||||
/// <param name="allowedSid">The allowed security identifier.</param>
|
||||
/// <param name="reason">The rejection reason if verification fails.</param>
|
||||
internal delegate bool CallerVerifier(NamedPipeServerStream pipe, SecurityIdentifier allowedSid, out string reason);
|
||||
|
||||
/// <summary>Initializes a new instance of the <see cref="PipeServer"/> class.</summary>
|
||||
/// <param name="pipeName">The name of the named pipe.</param>
|
||||
/// <param name="allowedSid">The security identifier allowed to connect.</param>
|
||||
/// <param name="sharedSecret">The shared secret for client authentication.</param>
|
||||
/// <param name="logger">The logger for diagnostic messages.</param>
|
||||
public PipeServer(string pipeName, SecurityIdentifier allowedSid, string sharedSecret, ILogger logger)
|
||||
: this(pipeName, allowedSid, sharedSecret, logger, DefaultVerifier) { }
|
||||
|
||||
/// <summary>Initializes a new instance of the <see cref="PipeServer"/> class with a custom verifier.</summary>
|
||||
/// <param name="pipeName">The name of the named pipe.</param>
|
||||
/// <param name="allowedSid">The security identifier allowed to connect.</param>
|
||||
/// <param name="sharedSecret">The shared secret for client authentication.</param>
|
||||
/// <param name="logger">The logger for diagnostic messages.</param>
|
||||
/// <param name="verifier">The caller verification delegate.</param>
|
||||
internal PipeServer(
|
||||
string pipeName, SecurityIdentifier allowedSid, string sharedSecret, ILogger logger,
|
||||
CallerVerifier verifier)
|
||||
{
|
||||
_pipeName = pipeName ?? throw new ArgumentNullException(nameof(pipeName));
|
||||
_allowedSid = allowedSid ?? throw new ArgumentNullException(nameof(allowedSid));
|
||||
_sharedSecret = sharedSecret ?? throw new ArgumentNullException(nameof(sharedSecret));
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
_verifier = verifier ?? throw new ArgumentNullException(nameof(verifier));
|
||||
}
|
||||
|
||||
private static bool DefaultVerifier(NamedPipeServerStream pipe, SecurityIdentifier allowedSid, out string reason)
|
||||
=> VerifyCaller(pipe, allowedSid, out reason);
|
||||
|
||||
/// <summary>
|
||||
/// Accepts one connection, performs Hello handshake, then dispatches frames to
|
||||
/// <paramref name="handler"/> until EOF or cancel. Returns when the client disconnects.
|
||||
/// </summary>
|
||||
/// <param name="handler">The frame handler to process frames.</param>
|
||||
/// <param name="ct">Cancellation token for the operation.</param>
|
||||
public async Task RunOneConnectionAsync(IFrameHandler handler, CancellationToken ct)
|
||||
{
|
||||
using var linked = CancellationTokenSource.CreateLinkedTokenSource(_cts.Token, ct);
|
||||
var acl = PipeAcl.Create(_allowedSid);
|
||||
|
||||
_current = new NamedPipeServerStream(
|
||||
_pipeName,
|
||||
PipeDirection.InOut,
|
||||
maxNumberOfServerInstances: 1,
|
||||
PipeTransmissionMode.Byte,
|
||||
PipeOptions.Asynchronous,
|
||||
inBufferSize: 64 * 1024,
|
||||
outBufferSize: 64 * 1024,
|
||||
pipeSecurity: acl);
|
||||
|
||||
try
|
||||
{
|
||||
await _current.WaitForConnectionAsync(linked.Token).ConfigureAwait(false);
|
||||
|
||||
using var reader = new FrameReader(_current, leaveOpen: true);
|
||||
using var writer = new FrameWriter(_current, leaveOpen: true);
|
||||
|
||||
// First frame must be Hello with the correct shared secret. Reading it before
|
||||
// the caller-SID impersonation check satisfies Windows' ERROR_CANNOT_IMPERSONATE
|
||||
// rule — ImpersonateNamedPipeClient fails until at least one frame has been read.
|
||||
var first = await reader.ReadFrameAsync(linked.Token).ConfigureAwait(false);
|
||||
if (first is null || first.Value.Kind != MessageKind.Hello)
|
||||
{
|
||||
_logger.Warning("Sidecar IPC first frame was not Hello; dropping");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!_verifier(_current, _allowedSid, out var reason))
|
||||
{
|
||||
// Driver.Historian.Wonderware-007: send a rejecting HelloAck so the client
|
||||
// learns why instead of having to wait for its own read timeout. The reason
|
||||
// tag "caller-sid-mismatch" is symmetric with the shared-secret-mismatch and
|
||||
// major-version-mismatch acks the two other rejection paths emit below.
|
||||
await writer.WriteAsync(MessageKind.HelloAck,
|
||||
new HelloAck { Accepted = false, RejectReason = $"caller-sid-mismatch: {reason}" },
|
||||
linked.Token).ConfigureAwait(false);
|
||||
_logger.Warning("Sidecar IPC caller rejected: {Reason}", reason);
|
||||
_current.Disconnect();
|
||||
return;
|
||||
}
|
||||
|
||||
var hello = MessagePackSerializer.Deserialize<Hello>(first.Value.Body);
|
||||
if (!string.Equals(hello.SharedSecret, _sharedSecret, StringComparison.Ordinal))
|
||||
{
|
||||
await writer.WriteAsync(MessageKind.HelloAck,
|
||||
new HelloAck { Accepted = false, RejectReason = "shared-secret-mismatch" },
|
||||
linked.Token).ConfigureAwait(false);
|
||||
_logger.Warning("Sidecar IPC Hello rejected: shared-secret-mismatch");
|
||||
return;
|
||||
}
|
||||
|
||||
if (hello.ProtocolMajor != Hello.CurrentMajor)
|
||||
{
|
||||
await writer.WriteAsync(MessageKind.HelloAck,
|
||||
new HelloAck { Accepted = false, RejectReason = $"major-version-mismatch-peer={hello.ProtocolMajor}-server={Hello.CurrentMajor}" },
|
||||
linked.Token).ConfigureAwait(false);
|
||||
_logger.Warning("Sidecar IPC Hello rejected: major mismatch peer={Peer} server={Server}",
|
||||
hello.ProtocolMajor, Hello.CurrentMajor);
|
||||
return;
|
||||
}
|
||||
|
||||
await writer.WriteAsync(MessageKind.HelloAck,
|
||||
new HelloAck { Accepted = true, HostName = Environment.MachineName },
|
||||
linked.Token).ConfigureAwait(false);
|
||||
|
||||
while (!linked.Token.IsCancellationRequested)
|
||||
{
|
||||
var frame = await reader.ReadFrameAsync(linked.Token).ConfigureAwait(false);
|
||||
if (frame is null) break;
|
||||
|
||||
await handler.HandleAsync(frame.Value.Kind, frame.Value.Body, writer, linked.Token).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_current.Dispose();
|
||||
_current = null;
|
||||
}
|
||||
}
|
||||
|
||||
// Backoff sequence for consecutive RunOneConnection failures: 250 ms → 500 ms →
|
||||
// 1 000 ms → 2 000 ms → 4 000 ms → capped at 8 000 ms thereafter.
|
||||
private static readonly TimeSpan[] BackoffSteps =
|
||||
{
|
||||
TimeSpan.FromMilliseconds(250),
|
||||
TimeSpan.FromMilliseconds(500),
|
||||
TimeSpan.FromSeconds(1),
|
||||
TimeSpan.FromSeconds(2),
|
||||
TimeSpan.FromSeconds(4),
|
||||
TimeSpan.FromSeconds(8),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Maximum consecutive failures before the server gives up and lets the process exit
|
||||
/// so the supervisor (NSSM / SCM) can restart the sidecar cleanly.
|
||||
/// </summary>
|
||||
private const int MaxConsecutiveFailures = 20;
|
||||
|
||||
/// <summary>
|
||||
/// Runs the server continuously, handling one connection at a time. When a connection
|
||||
/// ends (clean or error), waits with exponential backoff before accepting the next.
|
||||
/// If <see cref="MaxConsecutiveFailures"/> consecutive failures occur the method
|
||||
/// throws so the supervisor can restart the sidecar.
|
||||
/// </summary>
|
||||
/// <param name="handler">The frame handler to process frames.</param>
|
||||
/// <param name="ct">Cancellation token for the operation.</param>
|
||||
public async Task RunAsync(IFrameHandler handler, CancellationToken ct)
|
||||
{
|
||||
var consecutiveFailures = 0;
|
||||
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
await RunOneConnectionAsync(handler, ct).ConfigureAwait(false);
|
||||
consecutiveFailures = 0; // a clean connection (even a short-lived one) resets the counter
|
||||
}
|
||||
catch (OperationCanceledException) { break; }
|
||||
catch (Exception ex)
|
||||
{
|
||||
consecutiveFailures++;
|
||||
|
||||
if (consecutiveFailures >= MaxConsecutiveFailures)
|
||||
{
|
||||
_logger.Fatal(ex,
|
||||
"Sidecar IPC connection loop failed {Count} consecutive times — giving up so supervisor can restart",
|
||||
consecutiveFailures);
|
||||
throw;
|
||||
}
|
||||
|
||||
var delay = BackoffSteps[Math.Min(consecutiveFailures - 1, BackoffSteps.Length - 1)];
|
||||
_logger.Error(ex,
|
||||
"Sidecar IPC connection loop error (consecutive failure {Count}/{Max}) — retrying in {Delay}",
|
||||
consecutiveFailures, MaxConsecutiveFailures, delay);
|
||||
|
||||
try { await Task.Delay(delay, ct).ConfigureAwait(false); }
|
||||
catch (OperationCanceledException) { break; }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static bool VerifyCaller(NamedPipeServerStream pipe, SecurityIdentifier allowedSid, out string reason)
|
||||
{
|
||||
try
|
||||
{
|
||||
pipe.RunAsClient(() =>
|
||||
{
|
||||
using var wi = WindowsIdentity.GetCurrent();
|
||||
if (wi.User is null)
|
||||
throw new InvalidOperationException("GetCurrent().User is null — cannot verify caller");
|
||||
if (wi.User != allowedSid)
|
||||
throw new UnauthorizedAccessException(
|
||||
$"caller SID {wi.User.Value} does not match allowed {allowedSid.Value}");
|
||||
});
|
||||
reason = string.Empty;
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex) { reason = ex.Message; return false; }
|
||||
}
|
||||
|
||||
/// <summary>Disposes the pipe server and cancels any pending operations.</summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_cts.Cancel();
|
||||
_current?.Dispose();
|
||||
_cts.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Strategy for handling each post-Hello frame the pipe server reads. Implementations
|
||||
/// deserialize the body per the <see cref="MessageKind"/>, dispatch to the historian, and
|
||||
/// write the corresponding reply through the supplied <see cref="FrameWriter"/>.
|
||||
/// </summary>
|
||||
public interface IFrameHandler
|
||||
{
|
||||
/// <summary>Handles a frame from the pipe server.</summary>
|
||||
/// <param name="kind">The type of message being handled.</param>
|
||||
/// <param name="body">The serialized message body.</param>
|
||||
/// <param name="writer">The frame writer to send responses.</param>
|
||||
/// <param name="ct">Cancellation token for the operation.</param>
|
||||
Task HandleAsync(MessageKind kind, byte[] body, FrameWriter writer, CancellationToken ct);
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Security;
|
||||
using System.Net.Sockets;
|
||||
using System.Security.Authentication;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MessagePack;
|
||||
using Serilog;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Ipc;
|
||||
|
||||
/// <summary>
|
||||
/// Accepts one TCP client at a time, optionally over TLS, verifies the shared-secret
|
||||
/// Hello, then dispatches frames to <see cref="IFrameHandler"/>. Authentication is the
|
||||
/// shared secret carried in the Hello frame, optionally over a TLS-protected channel.
|
||||
/// </summary>
|
||||
public sealed class TcpFrameServer : IDisposable
|
||||
{
|
||||
private readonly IPAddress _bind;
|
||||
private readonly int _port;
|
||||
private readonly string _sharedSecret;
|
||||
private readonly X509Certificate2? _tlsCert; // null = plaintext
|
||||
private readonly ILogger _logger;
|
||||
private readonly CancellationTokenSource _cts = new();
|
||||
private TcpListener? _listener;
|
||||
|
||||
/// <summary>Initializes a new instance of the <see cref="TcpFrameServer"/> class.</summary>
|
||||
/// <param name="bind">The IP address to bind the listener to.</param>
|
||||
/// <param name="port">The TCP port to bind (0 lets the OS pick a free port).</param>
|
||||
/// <param name="sharedSecret">The shared secret the client's Hello must match.</param>
|
||||
/// <param name="tlsCert">The server certificate for TLS; <c>null</c> for plaintext.</param>
|
||||
/// <param name="logger">The logger for diagnostic messages.</param>
|
||||
public TcpFrameServer(IPAddress bind, int port, string sharedSecret, X509Certificate2? tlsCert, ILogger logger)
|
||||
{
|
||||
_bind = bind ?? throw new ArgumentNullException(nameof(bind));
|
||||
_port = port;
|
||||
_sharedSecret = sharedSecret ?? throw new ArgumentNullException(nameof(sharedSecret));
|
||||
_tlsCert = tlsCert;
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
}
|
||||
|
||||
/// <summary>The port the listener actually bound (useful when constructed with port 0 in tests).</summary>
|
||||
public int BoundPort => ((IPEndPoint)_listener!.LocalEndpoint).Port;
|
||||
|
||||
private void EnsureListening()
|
||||
{
|
||||
if (_listener is not null) return;
|
||||
_listener = new TcpListener(_bind, _port);
|
||||
_listener.Start();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Accepts one connection, performs the Hello handshake, then dispatches frames to
|
||||
/// <paramref name="handler"/> until EOF or cancel. Returns when the client disconnects.
|
||||
/// </summary>
|
||||
/// <param name="handler">The frame handler to process frames.</param>
|
||||
/// <param name="ct">Cancellation token for the operation.</param>
|
||||
public async Task RunOneConnectionAsync(IFrameHandler handler, CancellationToken ct)
|
||||
{
|
||||
using var linked = CancellationTokenSource.CreateLinkedTokenSource(_cts.Token, ct);
|
||||
EnsureListening();
|
||||
|
||||
// net48 has no AcceptTcpClientAsync(CancellationToken); Stop() unblocks a pending accept.
|
||||
using var reg = linked.Token.Register(() => { try { _listener!.Stop(); } catch { /* ignore */ } });
|
||||
TcpClient client;
|
||||
try { client = await _listener!.AcceptTcpClientAsync().ConfigureAwait(false); }
|
||||
catch (ObjectDisposedException) when (linked.Token.IsCancellationRequested) { throw new OperationCanceledException(linked.Token); }
|
||||
catch (InvalidOperationException) when (linked.Token.IsCancellationRequested) { throw new OperationCanceledException(linked.Token); }
|
||||
catch (SocketException) when (linked.Token.IsCancellationRequested) { throw new OperationCanceledException(linked.Token); }
|
||||
|
||||
using (client)
|
||||
{
|
||||
client.NoDelay = true;
|
||||
Stream stream = client.GetStream();
|
||||
SslStream? ssl = null;
|
||||
try
|
||||
{
|
||||
if (_tlsCert is not null)
|
||||
{
|
||||
ssl = new SslStream(stream, leaveInnerStreamOpen: false);
|
||||
await ssl.AuthenticateAsServerAsync(_tlsCert, clientCertificateRequired: false,
|
||||
enabledSslProtocols: SslProtocols.Tls12, checkCertificateRevocation: false).ConfigureAwait(false);
|
||||
stream = ssl;
|
||||
}
|
||||
|
||||
using var reader = new FrameReader(stream, leaveOpen: true);
|
||||
using var writer = new FrameWriter(stream, leaveOpen: true);
|
||||
|
||||
var first = await reader.ReadFrameAsync(linked.Token).ConfigureAwait(false);
|
||||
if (first is null || first.Value.Kind != MessageKind.Hello)
|
||||
{
|
||||
_logger.Warning("Sidecar TCP first frame was not Hello; dropping");
|
||||
return;
|
||||
}
|
||||
var hello = MessagePackSerializer.Deserialize<Hello>(first.Value.Body);
|
||||
if (!string.Equals(hello.SharedSecret, _sharedSecret, StringComparison.Ordinal))
|
||||
{
|
||||
await writer.WriteAsync(MessageKind.HelloAck,
|
||||
new HelloAck { Accepted = false, RejectReason = "shared-secret-mismatch" }, linked.Token).ConfigureAwait(false);
|
||||
_logger.Warning("Sidecar TCP Hello rejected: shared-secret-mismatch");
|
||||
return;
|
||||
}
|
||||
if (hello.ProtocolMajor != Hello.CurrentMajor)
|
||||
{
|
||||
await writer.WriteAsync(MessageKind.HelloAck,
|
||||
new HelloAck { Accepted = false, RejectReason = $"major-version-mismatch-peer={hello.ProtocolMajor}-server={Hello.CurrentMajor}" },
|
||||
linked.Token).ConfigureAwait(false);
|
||||
_logger.Warning("Sidecar TCP Hello rejected: major mismatch peer={Peer} server={Server}", hello.ProtocolMajor, Hello.CurrentMajor);
|
||||
return;
|
||||
}
|
||||
await writer.WriteAsync(MessageKind.HelloAck,
|
||||
new HelloAck { Accepted = true, HostName = Environment.MachineName }, linked.Token).ConfigureAwait(false);
|
||||
|
||||
while (!linked.Token.IsCancellationRequested)
|
||||
{
|
||||
var frame = await reader.ReadFrameAsync(linked.Token).ConfigureAwait(false);
|
||||
if (frame is null) break;
|
||||
await handler.HandleAsync(frame.Value.Kind, frame.Value.Body, writer, linked.Token).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
finally { ssl?.Dispose(); }
|
||||
}
|
||||
}
|
||||
|
||||
// ---- exponential backoff / give-up policy between accepted connections ----
|
||||
private static readonly TimeSpan[] BackoffSteps =
|
||||
{
|
||||
TimeSpan.FromMilliseconds(250), TimeSpan.FromMilliseconds(500), TimeSpan.FromSeconds(1),
|
||||
TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(4), TimeSpan.FromSeconds(8),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Maximum consecutive failures before the server gives up and lets the process exit
|
||||
/// so the supervisor (NSSM / SCM) can restart the sidecar cleanly.
|
||||
/// </summary>
|
||||
private const int MaxConsecutiveFailures = 20;
|
||||
|
||||
/// <summary>
|
||||
/// Runs the server continuously, handling one connection at a time. When a connection
|
||||
/// ends (clean or error), waits with exponential backoff before accepting the next.
|
||||
/// If <see cref="MaxConsecutiveFailures"/> consecutive failures occur the method
|
||||
/// throws so the supervisor can restart the sidecar.
|
||||
/// </summary>
|
||||
/// <param name="handler">The frame handler to process frames.</param>
|
||||
/// <param name="ct">Cancellation token for the operation.</param>
|
||||
public async Task RunAsync(IFrameHandler handler, CancellationToken ct)
|
||||
{
|
||||
var consecutiveFailures = 0;
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
try { await RunOneConnectionAsync(handler, ct).ConfigureAwait(false); consecutiveFailures = 0; }
|
||||
catch (OperationCanceledException) { break; }
|
||||
catch (Exception ex)
|
||||
{
|
||||
consecutiveFailures++;
|
||||
if (consecutiveFailures >= MaxConsecutiveFailures)
|
||||
{
|
||||
_logger.Fatal(ex, "Sidecar TCP connection loop failed {Count} consecutive times — giving up so supervisor can restart", consecutiveFailures);
|
||||
throw;
|
||||
}
|
||||
var delay = BackoffSteps[Math.Min(consecutiveFailures - 1, BackoffSteps.Length - 1)];
|
||||
_logger.Error(ex, "Sidecar TCP connection loop error (consecutive failure {Count}/{Max}) — retrying in {Delay}", consecutiveFailures, MaxConsecutiveFailures, delay);
|
||||
try { await Task.Delay(delay, ct).ConfigureAwait(false); } catch (OperationCanceledException) { break; }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Disposes the server, stops the listener, and cancels any pending operations.</summary>
|
||||
public void Dispose() { _cts.Cancel(); try { _listener?.Stop(); } catch { /* ignore */ } _cts.Dispose(); }
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using System.Security.Principal;
|
||||
using System.Net;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using System.Threading;
|
||||
using Serilog;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Backend;
|
||||
@@ -8,10 +9,11 @@ using ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Ipc;
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware;
|
||||
|
||||
/// <summary>
|
||||
/// Entry point for the Wonderware Historian sidecar. Reads pipe name, allowed-SID,
|
||||
/// shared secret, and historian connection config from environment (the supervisor
|
||||
/// passes them at spawn time per <c>driver-stability.md</c>). Hosts a named-pipe server
|
||||
/// dispatching the five sidecar contracts (PR 3.3) to the Wonderware Historian SDK.
|
||||
/// Entry point for the Wonderware Historian sidecar. Reads the shared secret, TCP
|
||||
/// bind/port, optional TLS settings, and historian connection config from environment
|
||||
/// (the supervisor passes them at spawn time per <c>driver-stability.md</c>). Hosts a
|
||||
/// TCP server (optionally over TLS) dispatching the five sidecar contracts (PR 3.3) to
|
||||
/// the Wonderware Historian SDK.
|
||||
/// </summary>
|
||||
public static class Program
|
||||
{
|
||||
@@ -29,19 +31,19 @@ public static class Program
|
||||
|
||||
try
|
||||
{
|
||||
var pipeName = Environment.GetEnvironmentVariable("OTOPCUA_HISTORIAN_PIPE")
|
||||
?? throw new InvalidOperationException("OTOPCUA_HISTORIAN_PIPE not set — supervisor must pass the sidecar pipe name");
|
||||
var allowedSidValue = Environment.GetEnvironmentVariable("OTOPCUA_ALLOWED_SID")
|
||||
?? throw new InvalidOperationException("OTOPCUA_ALLOWED_SID not set — supervisor must pass the server principal SID");
|
||||
var sharedSecret = Environment.GetEnvironmentVariable("OTOPCUA_HISTORIAN_SECRET")
|
||||
?? throw new InvalidOperationException("OTOPCUA_HISTORIAN_SECRET not set — supervisor must pass the per-process secret at spawn time");
|
||||
|
||||
var allowedSid = new SecurityIdentifier(allowedSidValue);
|
||||
var tcpPort = TryParseInt("OTOPCUA_HISTORIAN_TCP_PORT", 32569);
|
||||
var bindRaw = Environment.GetEnvironmentVariable("OTOPCUA_HISTORIAN_BIND");
|
||||
var bind = string.IsNullOrWhiteSpace(bindRaw) ? IPAddress.Any : IPAddress.Parse(bindRaw);
|
||||
var tlsEnabled = string.Equals(Environment.GetEnvironmentVariable("OTOPCUA_HISTORIAN_TLS_ENABLED"), "true", StringComparison.OrdinalIgnoreCase);
|
||||
X509Certificate2? tlsCert = tlsEnabled ? LoadTlsCert() : null;
|
||||
|
||||
using var cts = new CancellationTokenSource();
|
||||
Console.CancelKeyPress += (_, e) => { e.Cancel = true; cts.Cancel(); };
|
||||
|
||||
// Sidecar can boot in "pipe-only" mode (no real Wonderware Historian SDK
|
||||
// Sidecar can boot in "tcp idle" mode (no real Wonderware Historian SDK
|
||||
// initialization) for smoke + IPC tests. Production sets ENABLED=true so the
|
||||
// SDK opens its connection up front.
|
||||
var historianEnabled = string.Equals(
|
||||
@@ -50,7 +52,7 @@ public static class Program
|
||||
|
||||
if (!historianEnabled)
|
||||
{
|
||||
Log.Information("Wonderware historian sidecar starting in pipe-only mode (OTOPCUA_HISTORIAN_ENABLED!=true) — pipe={Pipe} allowedSid={Sid}", pipeName, allowedSidValue);
|
||||
Log.Information("Wonderware historian sidecar starting in tcp idle mode (SDK disabled) (OTOPCUA_HISTORIAN_ENABLED!=true) — bind={Bind} port={Port} tls={Tls}", bind, tcpPort, tlsCert is not null);
|
||||
cts.Token.WaitHandle.WaitOne();
|
||||
Log.Information("Wonderware historian sidecar stopping cleanly");
|
||||
return 0;
|
||||
@@ -59,9 +61,9 @@ public static class Program
|
||||
using var historian = BuildHistorian();
|
||||
var alarmWriter = BuildAlarmWriter();
|
||||
var handler = new HistorianFrameHandler(historian, Log.Logger, alarmWriter);
|
||||
using var server = new PipeServer(pipeName, allowedSid, sharedSecret, Log.Logger);
|
||||
using var server = new TcpFrameServer(bind, tcpPort, sharedSecret, tlsCert, Log.Logger);
|
||||
|
||||
Log.Information("Wonderware historian sidecar serving — pipe={Pipe} allowedSid={Sid}", pipeName, allowedSidValue);
|
||||
Log.Information("Wonderware historian sidecar serving — bind={Bind} port={Port} tls={Tls}", bind, tcpPort, tlsCert is not null);
|
||||
try { server.RunAsync(handler, cts.Token).GetAwaiter().GetResult(); }
|
||||
catch (OperationCanceledException) { /* clean shutdown via Ctrl-C */ }
|
||||
|
||||
@@ -112,6 +114,26 @@ public static class Program
|
||||
return int.TryParse(raw, out var parsed) ? parsed : defaultValue;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Loads the TLS server certificate when TLS is enabled. The reference is either a
|
||||
/// <c>.pfx</c> file path (decrypted with the optional password env var) or, if not a
|
||||
/// file, a thumbprint resolved from the <c>LocalMachine\My</c> store.
|
||||
/// </summary>
|
||||
private static X509Certificate2 LoadTlsCert()
|
||||
{
|
||||
var certRef = Environment.GetEnvironmentVariable("OTOPCUA_HISTORIAN_TLS_CERT")
|
||||
?? throw new InvalidOperationException("OTOPCUA_HISTORIAN_TLS_CERT not set but TLS enabled — supply a .pfx path or a LocalMachine\\My store thumbprint");
|
||||
var pwd = Environment.GetEnvironmentVariable("OTOPCUA_HISTORIAN_TLS_CERT_PASSWORD");
|
||||
if (System.IO.File.Exists(certRef))
|
||||
return new X509Certificate2(certRef, pwd, X509KeyStorageFlags.MachineKeySet);
|
||||
// else treat as a thumbprint in LocalMachine\My
|
||||
using var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
|
||||
store.Open(OpenFlags.ReadOnly);
|
||||
var found = store.Certificates.Find(X509FindType.FindByThumbprint, certRef.Replace(" ", ""), validOnly: false);
|
||||
if (found.Count == 0) throw new InvalidOperationException($"OTOPCUA_HISTORIAN_TLS_CERT thumbprint '{certRef}' not found in LocalMachine\\My and is not a file path");
|
||||
return found[0];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Constructs the alarm-event writer when the alarm-write toggle is on, otherwise
|
||||
/// returns <c>null</c> so <see cref="HistorianFrameHandler"/> falls back to the
|
||||
|
||||
+1
-2
@@ -21,8 +21,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="MessagePack"/>
|
||||
<PackageReference Include="System.IO.Pipes.AccessControl"/>
|
||||
<PackageReference Include="System.Memory"/>
|
||||
<PackageReference Include="System.Memory"/>
|
||||
<PackageReference Include="System.Threading.Tasks.Extensions"/>
|
||||
<PackageReference Include="System.Data.SqlClient"/>
|
||||
<PackageReference Include="Serilog"/>
|
||||
|
||||
+37
-10
@@ -66,11 +66,16 @@ else
|
||||
<div class="panel-head">Connection</div>
|
||||
<div style="padding:1rem">
|
||||
<div class="row g-3">
|
||||
<div class="col-md-5">
|
||||
<label class="form-label">Named pipe name</label>
|
||||
<InputText @bind-Value="_form.Historian.PipeName" class="form-control form-control-sm mono"
|
||||
placeholder="otopcua-historian" />
|
||||
<div class="form-text">Must match the sidecar's <code>OTOPCUA_HISTORIAN_PIPE</code> environment variable.</div>
|
||||
<div class="col-md-3">
|
||||
<label class="form-label">Sidecar host</label>
|
||||
<InputText @bind-Value="_form.Historian.Host" class="form-control form-control-sm mono"
|
||||
placeholder="localhost" />
|
||||
<div class="form-text">DNS name or IP the historian sidecar's TCP listener is reachable at.</div>
|
||||
</div>
|
||||
<div class="col-md-2">
|
||||
<label class="form-label">Sidecar port</label>
|
||||
<InputNumber @bind-Value="_form.Historian.Port" class="form-control form-control-sm mono" />
|
||||
<div class="form-text">Must match the sidecar's <code>OTOPCUA_HISTORIAN_TCP_PORT</code>.</div>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<label class="form-label">Shared secret</label>
|
||||
@@ -83,6 +88,19 @@ else
|
||||
placeholder="OtOpcUa" />
|
||||
<div class="form-text">Sent in Hello for sidecar logging. Default: OtOpcUa.</div>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<label class="form-label">TLS</label>
|
||||
<div class="form-check mt-1">
|
||||
<InputCheckbox @bind-Value="_form.Historian.UseTls" class="form-check-input" id="historianUseTls" />
|
||||
<label class="form-check-label" for="historianUseTls">Use TLS</label>
|
||||
</div>
|
||||
<div class="form-text">Wrap the sidecar TCP stream in TLS before the Hello handshake.</div>
|
||||
</div>
|
||||
<div class="col-md-5">
|
||||
<label class="form-label">Server cert thumbprint (TLS pin)</label>
|
||||
<InputText @bind-Value="_form.Historian.ServerCertThumbprint" class="form-control form-control-sm mono" />
|
||||
<div class="form-text">SHA-1 thumbprint to pin; blank = validate CA chain.</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
@@ -95,7 +113,7 @@ else
|
||||
<div class="col-md-3">
|
||||
<label class="form-label">Connect timeout (s, blank = default 10 s)</label>
|
||||
<InputNumber @bind-Value="_form.Historian.ConnectTimeoutSeconds" class="form-control form-control-sm" />
|
||||
<div class="form-text">Cap on pipe connect + Hello round-trip. Null = 10 s.</div>
|
||||
<div class="form-text">Cap on TCP connect + Hello round-trip. Null = 10 s.</div>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<label class="form-label">Call timeout (s, blank = default 30 s)</label>
|
||||
@@ -209,7 +227,7 @@ else
|
||||
}
|
||||
|
||||
private static WonderwareHistorianClientOptions CreateDefaultOptions() =>
|
||||
new(PipeName: "otopcua-historian", SharedSecret: "");
|
||||
new(Host: "localhost", Port: 32569, SharedSecret: "") { UseTls = false, ServerCertThumbprint = null };
|
||||
|
||||
private async Task SubmitAsync()
|
||||
{
|
||||
@@ -309,31 +327,40 @@ else
|
||||
/// </summary>
|
||||
public sealed class WonderwareHistorianClientFormModel
|
||||
{
|
||||
public string PipeName { get; set; } = "otopcua-historian";
|
||||
public string Host { get; set; } = "localhost";
|
||||
public int Port { get; set; } = 32569;
|
||||
public string SharedSecret { get; set; } = "";
|
||||
public string PeerName { get; set; } = "OtOpcUa";
|
||||
public int? ConnectTimeoutSeconds { get; set; }
|
||||
public int? CallTimeoutSeconds { get; set; }
|
||||
public int ProbeTimeoutSeconds { get; set; } = 15;
|
||||
public bool UseTls { get; set; }
|
||||
public string? ServerCertThumbprint { get; set; }
|
||||
|
||||
public static WonderwareHistorianClientFormModel FromRecord(WonderwareHistorianClientOptions r) => new()
|
||||
{
|
||||
PipeName = r.PipeName,
|
||||
Host = r.Host,
|
||||
Port = r.Port,
|
||||
SharedSecret = r.SharedSecret,
|
||||
PeerName = r.PeerName,
|
||||
ConnectTimeoutSeconds = r.ConnectTimeout.HasValue ? (int)r.ConnectTimeout.Value.TotalSeconds : null,
|
||||
CallTimeoutSeconds = r.CallTimeout.HasValue ? (int)r.CallTimeout.Value.TotalSeconds : null,
|
||||
ProbeTimeoutSeconds = r.ProbeTimeoutSeconds,
|
||||
UseTls = r.UseTls,
|
||||
ServerCertThumbprint = r.ServerCertThumbprint,
|
||||
};
|
||||
|
||||
public WonderwareHistorianClientOptions ToRecord() => new(
|
||||
PipeName: PipeName,
|
||||
Host: Host,
|
||||
Port: Port,
|
||||
SharedSecret: SharedSecret,
|
||||
PeerName: PeerName,
|
||||
ConnectTimeout: ConnectTimeoutSeconds.HasValue ? TimeSpan.FromSeconds(ConnectTimeoutSeconds.Value) : null,
|
||||
CallTimeout: CallTimeoutSeconds.HasValue ? TimeSpan.FromSeconds(CallTimeoutSeconds.Value) : null)
|
||||
{
|
||||
ProbeTimeoutSeconds = ProbeTimeoutSeconds,
|
||||
UseTls = UseTls,
|
||||
ServerCertThumbprint = ServerCertThumbprint,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,13 +88,16 @@ if (hasDriver)
|
||||
|
||||
// Config-gated durable alarm-historian sink. When the AlarmHistorian section is enabled this
|
||||
// overrides the NullAlarmHistorianSink default from AddOtOpcUaRuntime (last registration wins)
|
||||
// with a SqliteStoreAndForwardSink draining to the Wonderware named-pipe writer. The writer is
|
||||
// with a SqliteStoreAndForwardSink draining to the Wonderware TCP writer. The writer is
|
||||
// injected here because the Host is the only project that references the Wonderware client —
|
||||
// Runtime owns the gating + Sqlite construction, the Host supplies the concrete downstream.
|
||||
builder.Services.AddAlarmHistorian(
|
||||
builder.Configuration,
|
||||
(opts, sp) => new WonderwareHistorianClient(
|
||||
new WonderwareHistorianClientOptions(opts.PipeName, opts.SharedSecret),
|
||||
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
|
||||
|
||||
@@ -14,7 +14,10 @@
|
||||
"AlarmHistorian": {
|
||||
"Enabled": false,
|
||||
"DatabasePath": "alarm-historian.db",
|
||||
"PipeName": "OtOpcUaHistorian",
|
||||
"Host": "localhost",
|
||||
"Port": 32569,
|
||||
"UseTls": false,
|
||||
"ServerCertThumbprint": null,
|
||||
"SharedSecret": "",
|
||||
"DrainIntervalSeconds": 5,
|
||||
"Capacity": 1000000,
|
||||
|
||||
@@ -8,7 +8,7 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.Historian;
|
||||
/// Binds the <c>AlarmHistorian</c> configuration section that gates the durable
|
||||
/// store-and-forward alarm sink. When <see cref="Enabled"/> is <c>true</c>,
|
||||
/// <c>AddAlarmHistorian</c> registers a <c>SqliteStoreAndForwardSink</c> (draining to the
|
||||
/// Wonderware named-pipe writer supplied by the Host) in place of the
|
||||
/// Wonderware TCP writer supplied by the Host) in place of the
|
||||
/// <c>NullAlarmHistorianSink</c> default; otherwise the Null default survives.
|
||||
/// </summary>
|
||||
public sealed class AlarmHistorianOptions
|
||||
@@ -25,8 +25,17 @@ public sealed class AlarmHistorianOptions
|
||||
/// <summary>Filesystem path to the local SQLite store-and-forward queue database.</summary>
|
||||
public string DatabasePath { get; init; } = "alarm-historian.db";
|
||||
|
||||
/// <summary>Named-pipe name the Wonderware historian sidecar listens on.</summary>
|
||||
public string PipeName { get; init; } = "OtOpcUaHistorian";
|
||||
/// <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; } = "";
|
||||
|
||||
@@ -16,9 +16,9 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.Historian;
|
||||
/// Galaxy native alarm bridge, AB CIP ALMD reader) tells <see cref="AlarmHistorianEvent"/>s to this
|
||||
/// actor; the actor enqueues them on the sink fire-and-forget. Production deployments register
|
||||
/// <see cref="SqliteStoreAndForwardSink"/> against <c>IAlarmHistorianSink</c>; the sink owns the
|
||||
/// durable queue + drain-to-Wonderware-pipe loop. The actor here owns nothing operational beyond
|
||||
/// durable queue + drain-to-Wonderware-TCP-channel loop. The actor here owns nothing operational beyond
|
||||
/// the message contract — its job is to keep the engine actors on Akka's mailbox without blocking
|
||||
/// them on disk I/O or pipe handshakes.
|
||||
/// them on disk I/O or TCP channel handshakes.
|
||||
///
|
||||
/// Query queue depth + drain health via <see cref="GetStatus"/>.
|
||||
/// </summary>
|
||||
|
||||
+108
-99
@@ -1,4 +1,5 @@
|
||||
using System.IO.Pipes;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using MessagePack;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Client.Ipc;
|
||||
|
||||
@@ -7,12 +8,14 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Client.Tests;
|
||||
/// <summary>
|
||||
/// In-process fake of the Wonderware historian sidecar. Reuses the client-side framing
|
||||
/// code (which is byte-identical to the real sidecar) so the wire bytes round-trip
|
||||
/// correctly without requiring the .NET 4.8 sidecar binary at test time.
|
||||
/// correctly without requiring the .NET 4.8 sidecar binary at test time. Listens on a
|
||||
/// loopback <see cref="TcpListener"/> and serves one connection at a time, mirroring the
|
||||
/// real sidecar's <c>TcpFrameServer</c> single-active-connection model.
|
||||
/// </summary>
|
||||
internal sealed class FakeSidecarServer : IAsyncDisposable
|
||||
{
|
||||
private readonly string _pipeName;
|
||||
private readonly string _expectedSecret;
|
||||
private readonly TcpListener _listener;
|
||||
private readonly CancellationTokenSource _cts = new();
|
||||
private Task? _loop;
|
||||
|
||||
@@ -55,141 +58,146 @@ internal sealed class FakeSidecarServer : IAsyncDisposable
|
||||
/// </summary>
|
||||
public bool StallAfterRequest { get; set; }
|
||||
|
||||
/// <summary>Initializes a new instance of FakeSidecarServer with the specified pipe name and expected secret.</summary>
|
||||
/// <param name="pipeName">The name of the named pipe to use for communication.</param>
|
||||
/// <summary>Initializes a new instance of FakeSidecarServer with the specified expected secret.</summary>
|
||||
/// <param name="expectedSecret">The expected shared secret for handshake validation.</param>
|
||||
public FakeSidecarServer(string pipeName, string expectedSecret)
|
||||
public FakeSidecarServer(string expectedSecret)
|
||||
{
|
||||
_pipeName = pipeName;
|
||||
_expectedSecret = expectedSecret;
|
||||
// Bind synchronously in the ctor so BoundPort is readable before StartAsync returns.
|
||||
_listener = new TcpListener(IPAddress.Loopback, 0);
|
||||
_listener.Start();
|
||||
}
|
||||
|
||||
/// <summary>Gets the named pipe name used for communication.</summary>
|
||||
public string PipeName => _pipeName;
|
||||
/// <summary>Gets the loopback host the listener is bound to.</summary>
|
||||
public string Host => "127.0.0.1";
|
||||
|
||||
/// <summary>Starts the fake sidecar server asynchronously.</summary>
|
||||
/// <summary>Gets the TCP port the listener actually bound (OS-assigned).</summary>
|
||||
public int BoundPort => ((IPEndPoint)_listener.LocalEndpoint).Port;
|
||||
|
||||
/// <summary>Starts the fake sidecar server asynchronously. The listener is already bound (ctor).</summary>
|
||||
public Task StartAsync()
|
||||
{
|
||||
_loop = Task.Run(() => RunAsync(_cts.Token));
|
||||
// Give the listener a moment to start so client connect doesn't race.
|
||||
return Task.Delay(50);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private async Task RunAsync(CancellationToken ct)
|
||||
{
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
await using var pipe = new NamedPipeServerStream(
|
||||
_pipeName, PipeDirection.InOut, maxNumberOfServerInstances: 1,
|
||||
PipeTransmissionMode.Byte, PipeOptions.Asynchronous,
|
||||
inBufferSize: 64 * 1024, outBufferSize: 64 * 1024);
|
||||
|
||||
try { await pipe.WaitForConnectionAsync(ct).ConfigureAwait(false); }
|
||||
TcpClient tcpClient;
|
||||
try { tcpClient = await _listener.AcceptTcpClientAsync(ct).ConfigureAwait(false); }
|
||||
catch (OperationCanceledException) { break; }
|
||||
catch (ObjectDisposedException) { break; }
|
||||
|
||||
try
|
||||
using (tcpClient)
|
||||
{
|
||||
using var reader = new FrameReader(pipe, leaveOpen: true);
|
||||
using var writer = new FrameWriter(pipe, leaveOpen: true);
|
||||
|
||||
// Hello handshake.
|
||||
var first = await reader.ReadFrameAsync(ct).ConfigureAwait(false);
|
||||
if (first is null || first.Value.Kind != MessageKind.Hello) continue;
|
||||
var hello = MessagePackSerializer.Deserialize<Hello>(first.Value.Body);
|
||||
|
||||
if (!string.Equals(hello.SharedSecret, _expectedSecret, StringComparison.Ordinal))
|
||||
try
|
||||
{
|
||||
await writer.WriteAsync(MessageKind.HelloAck, new HelloAck { Accepted = false, RejectReason = "shared-secret-mismatch" }, ct);
|
||||
continue;
|
||||
}
|
||||
tcpClient.NoDelay = true;
|
||||
var stream = tcpClient.GetStream();
|
||||
using var reader = new FrameReader(stream, leaveOpen: true);
|
||||
using var writer = new FrameWriter(stream, leaveOpen: true);
|
||||
|
||||
await writer.WriteAsync(MessageKind.HelloAck, new HelloAck { Accepted = true, HostName = "fake-sidecar" }, ct);
|
||||
// Hello handshake.
|
||||
var first = await reader.ReadFrameAsync(ct).ConfigureAwait(false);
|
||||
if (first is null || first.Value.Kind != MessageKind.Hello) continue;
|
||||
var hello = MessagePackSerializer.Deserialize<Hello>(first.Value.Body);
|
||||
|
||||
if (DisconnectAfterHandshake)
|
||||
{
|
||||
DisconnectAfterHandshake = false; // arm once
|
||||
pipe.Disconnect();
|
||||
continue;
|
||||
}
|
||||
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
var frame = await reader.ReadFrameAsync(ct).ConfigureAwait(false);
|
||||
if (frame is null) break;
|
||||
|
||||
// Drop before sending any reply — lets the client fall into its catch /
|
||||
// retry path or propagate on second failure.
|
||||
if (DisconnectBeforeReply)
|
||||
if (!string.Equals(hello.SharedSecret, _expectedSecret, StringComparison.Ordinal))
|
||||
{
|
||||
pipe.Disconnect();
|
||||
break;
|
||||
}
|
||||
|
||||
// Stall indefinitely to let the client's call-timeout token fire.
|
||||
if (StallAfterRequest)
|
||||
{
|
||||
await Task.Delay(Timeout.Infinite, ct).ConfigureAwait(false);
|
||||
break;
|
||||
}
|
||||
|
||||
// Optionally send a deliberately wrong kind back to exercise
|
||||
// InvalidDataException detection in the client's ExchangeAsync.
|
||||
if (ReplyWithWrongKind.HasValue)
|
||||
{
|
||||
var wrongKind = ReplyWithWrongKind.Value;
|
||||
ReplyWithWrongKind = null; // arm once
|
||||
// Send an empty body with the wrong kind so the client can parse it.
|
||||
await writer.WriteAsync(wrongKind, new ReadRawReply { Success = false }, ct);
|
||||
await writer.WriteAsync(MessageKind.HelloAck, new HelloAck { Accepted = false, RejectReason = "shared-secret-mismatch" }, ct);
|
||||
continue;
|
||||
}
|
||||
|
||||
switch (frame.Value.Kind)
|
||||
await writer.WriteAsync(MessageKind.HelloAck, new HelloAck { Accepted = true, HostName = "fake-sidecar" }, ct);
|
||||
|
||||
if (DisconnectAfterHandshake)
|
||||
{
|
||||
case MessageKind.ReadRawRequest:
|
||||
DisconnectAfterHandshake = false; // arm once
|
||||
tcpClient.Close();
|
||||
continue;
|
||||
}
|
||||
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
var frame = await reader.ReadFrameAsync(ct).ConfigureAwait(false);
|
||||
if (frame is null) break;
|
||||
|
||||
// Drop before sending any reply — lets the client fall into its catch /
|
||||
// retry path or propagate on second failure.
|
||||
if (DisconnectBeforeReply)
|
||||
{
|
||||
var req = MessagePackSerializer.Deserialize<ReadRawRequest>(frame.Value.Body);
|
||||
var reply = OnReadRaw(req);
|
||||
reply.CorrelationId = req.CorrelationId;
|
||||
await writer.WriteAsync(MessageKind.ReadRawReply, reply, ct);
|
||||
tcpClient.Close();
|
||||
break;
|
||||
}
|
||||
case MessageKind.ReadProcessedRequest:
|
||||
|
||||
// Stall indefinitely to let the client's call-timeout token fire.
|
||||
if (StallAfterRequest)
|
||||
{
|
||||
var req = MessagePackSerializer.Deserialize<ReadProcessedRequest>(frame.Value.Body);
|
||||
var reply = OnReadProcessed(req);
|
||||
reply.CorrelationId = req.CorrelationId;
|
||||
await writer.WriteAsync(MessageKind.ReadProcessedReply, reply, ct);
|
||||
await Task.Delay(Timeout.Infinite, ct).ConfigureAwait(false);
|
||||
break;
|
||||
}
|
||||
case MessageKind.ReadAtTimeRequest:
|
||||
|
||||
// Optionally send a deliberately wrong kind back to exercise
|
||||
// InvalidDataException detection in the client's ExchangeAsync.
|
||||
if (ReplyWithWrongKind.HasValue)
|
||||
{
|
||||
var req = MessagePackSerializer.Deserialize<ReadAtTimeRequest>(frame.Value.Body);
|
||||
var reply = OnReadAtTime(req);
|
||||
reply.CorrelationId = req.CorrelationId;
|
||||
await writer.WriteAsync(MessageKind.ReadAtTimeReply, reply, ct);
|
||||
break;
|
||||
var wrongKind = ReplyWithWrongKind.Value;
|
||||
ReplyWithWrongKind = null; // arm once
|
||||
// Send an empty body with the wrong kind so the client can parse it.
|
||||
await writer.WriteAsync(wrongKind, new ReadRawReply { Success = false }, ct);
|
||||
continue;
|
||||
}
|
||||
case MessageKind.ReadEventsRequest:
|
||||
|
||||
switch (frame.Value.Kind)
|
||||
{
|
||||
var req = MessagePackSerializer.Deserialize<ReadEventsRequest>(frame.Value.Body);
|
||||
var reply = OnReadEvents(req);
|
||||
reply.CorrelationId = req.CorrelationId;
|
||||
await writer.WriteAsync(MessageKind.ReadEventsReply, reply, ct);
|
||||
break;
|
||||
}
|
||||
case MessageKind.WriteAlarmEventsRequest:
|
||||
{
|
||||
var req = MessagePackSerializer.Deserialize<WriteAlarmEventsRequest>(frame.Value.Body);
|
||||
var reply = OnWriteAlarmEvents(req);
|
||||
reply.CorrelationId = req.CorrelationId;
|
||||
await writer.WriteAsync(MessageKind.WriteAlarmEventsReply, reply, ct);
|
||||
break;
|
||||
case MessageKind.ReadRawRequest:
|
||||
{
|
||||
var req = MessagePackSerializer.Deserialize<ReadRawRequest>(frame.Value.Body);
|
||||
var reply = OnReadRaw(req);
|
||||
reply.CorrelationId = req.CorrelationId;
|
||||
await writer.WriteAsync(MessageKind.ReadRawReply, reply, ct);
|
||||
break;
|
||||
}
|
||||
case MessageKind.ReadProcessedRequest:
|
||||
{
|
||||
var req = MessagePackSerializer.Deserialize<ReadProcessedRequest>(frame.Value.Body);
|
||||
var reply = OnReadProcessed(req);
|
||||
reply.CorrelationId = req.CorrelationId;
|
||||
await writer.WriteAsync(MessageKind.ReadProcessedReply, reply, ct);
|
||||
break;
|
||||
}
|
||||
case MessageKind.ReadAtTimeRequest:
|
||||
{
|
||||
var req = MessagePackSerializer.Deserialize<ReadAtTimeRequest>(frame.Value.Body);
|
||||
var reply = OnReadAtTime(req);
|
||||
reply.CorrelationId = req.CorrelationId;
|
||||
await writer.WriteAsync(MessageKind.ReadAtTimeReply, reply, ct);
|
||||
break;
|
||||
}
|
||||
case MessageKind.ReadEventsRequest:
|
||||
{
|
||||
var req = MessagePackSerializer.Deserialize<ReadEventsRequest>(frame.Value.Body);
|
||||
var reply = OnReadEvents(req);
|
||||
reply.CorrelationId = req.CorrelationId;
|
||||
await writer.WriteAsync(MessageKind.ReadEventsReply, reply, ct);
|
||||
break;
|
||||
}
|
||||
case MessageKind.WriteAlarmEventsRequest:
|
||||
{
|
||||
var req = MessagePackSerializer.Deserialize<WriteAlarmEventsRequest>(frame.Value.Body);
|
||||
var reply = OnWriteAlarmEvents(req);
|
||||
reply.CorrelationId = req.CorrelationId;
|
||||
await writer.WriteAsync(MessageKind.WriteAlarmEventsReply, reply, ct);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) { break; }
|
||||
catch (IOException) { /* peer dropped — accept next */ }
|
||||
}
|
||||
catch (OperationCanceledException) { break; }
|
||||
catch (IOException) { /* peer dropped — accept next */ }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -197,6 +205,7 @@ internal sealed class FakeSidecarServer : IAsyncDisposable
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
_cts.Cancel();
|
||||
try { _listener.Stop(); } catch { /* ignore */ }
|
||||
if (_loop is not null)
|
||||
{
|
||||
try { await _loop.ConfigureAwait(false); } catch { /* ignore shutdown errors */ }
|
||||
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
using System.Net;
|
||||
using System.Net.Security;
|
||||
using System.Net.Sockets;
|
||||
using System.Security.Authentication;
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Client.Internal;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Client.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Tests for <see cref="FrameChannel.DefaultTcpConnectFactory"/>. Each scenario binds a
|
||||
/// loopback <see cref="TcpListener"/> on <c>127.0.0.1:0</c>, accepts on a background task,
|
||||
/// and drives the client factory against it — proving a plaintext stream round-trips a byte,
|
||||
/// a TLS connection succeeds when the pinned thumbprint matches, and fails when it does not.
|
||||
/// </summary>
|
||||
public sealed class TcpConnectFactoryTests
|
||||
{
|
||||
// Generous timeout so the deterministic tests never hang CI if a side stalls.
|
||||
private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10);
|
||||
|
||||
/// <summary>Generates an in-memory self-signed RSA cert with a serverAuth EKU and a private key.</summary>
|
||||
private static X509Certificate2 MakeSelfSignedCert()
|
||||
{
|
||||
using var rsa = RSA.Create(2048);
|
||||
var req = new CertificateRequest("CN=otopcua-historian-sidecar-test", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
|
||||
req.CertificateExtensions.Add(
|
||||
new X509EnhancedKeyUsageExtension(
|
||||
new OidCollection { new Oid("1.3.6.1.5.5.7.3.1") /* serverAuth */ }, critical: false));
|
||||
using var ephemeral = req.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(1));
|
||||
// Round-trip through a PFX so the returned cert carries an exportable private key.
|
||||
var pfx = ephemeral.Export(X509ContentType.Pfx, "pw");
|
||||
return X509CertificateLoader.LoadPkcs12(pfx, "pw", X509KeyStorageFlags.Exportable);
|
||||
}
|
||||
|
||||
/// <summary>Plaintext: the factory returns a connected stream; a byte written server-side reads back client-side.</summary>
|
||||
[Fact]
|
||||
public async Task Plaintext_ReturnsConnectedStream_ByteRoundTrips()
|
||||
{
|
||||
using var cts = new CancellationTokenSource(Timeout);
|
||||
var listener = new TcpListener(IPAddress.Loopback, 0);
|
||||
listener.Start();
|
||||
var boundPort = ((IPEndPoint)listener.LocalEndpoint).Port;
|
||||
|
||||
// Accept one client and push a single byte from the server side.
|
||||
var serverTask = Task.Run(async () =>
|
||||
{
|
||||
using var server = await listener.AcceptTcpClientAsync(cts.Token);
|
||||
var serverStream = server.GetStream();
|
||||
await serverStream.WriteAsync(new byte[] { 0x7A }, cts.Token);
|
||||
await serverStream.FlushAsync(cts.Token);
|
||||
// Hold the connection open until the client has read.
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(200), cts.Token);
|
||||
}, cts.Token);
|
||||
|
||||
var opts = new WonderwareHistorianClientOptions("127.0.0.1", boundPort, "secret")
|
||||
{
|
||||
UseTls = false,
|
||||
};
|
||||
|
||||
await using var clientStream = await FrameChannel.DefaultTcpConnectFactory(opts, cts.Token);
|
||||
var buffer = new byte[1];
|
||||
var read = await clientStream.ReadAsync(buffer, cts.Token);
|
||||
|
||||
read.ShouldBe(1);
|
||||
buffer[0].ShouldBe((byte)0x7A);
|
||||
|
||||
await serverTask;
|
||||
listener.Stop();
|
||||
}
|
||||
|
||||
/// <summary>TLS pin match: a self-signed cert pinned by thumbprint authenticates successfully.</summary>
|
||||
[Fact]
|
||||
public async Task Tls_PinnedThumbprintMatches_ConnectsSuccessfully()
|
||||
{
|
||||
using var cts = new CancellationTokenSource(Timeout);
|
||||
using var cert = MakeSelfSignedCert();
|
||||
var listener = new TcpListener(IPAddress.Loopback, 0);
|
||||
listener.Start();
|
||||
var boundPort = ((IPEndPoint)listener.LocalEndpoint).Port;
|
||||
|
||||
var serverTask = Task.Run(async () =>
|
||||
{
|
||||
using var server = await listener.AcceptTcpClientAsync(cts.Token);
|
||||
var ssl = new SslStream(server.GetStream(), leaveInnerStreamOpen: false);
|
||||
await ssl.AuthenticateAsServerAsync(cert, clientCertificateRequired: false,
|
||||
enabledSslProtocols: SslProtocols.Tls12, checkCertificateRevocation: false);
|
||||
// Hold open until the client finished its handshake.
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(200), cts.Token);
|
||||
ssl.Dispose();
|
||||
}, cts.Token);
|
||||
|
||||
var opts = new WonderwareHistorianClientOptions("127.0.0.1", boundPort, "secret")
|
||||
{
|
||||
UseTls = true,
|
||||
ServerCertThumbprint = cert.GetCertHashString(),
|
||||
};
|
||||
|
||||
await using var stream = await FrameChannel.DefaultTcpConnectFactory(opts, cts.Token);
|
||||
stream.ShouldBeOfType<SslStream>();
|
||||
((SslStream)stream).IsAuthenticated.ShouldBeTrue();
|
||||
|
||||
await serverTask;
|
||||
listener.Stop();
|
||||
}
|
||||
|
||||
/// <summary>TLS wrong thumbprint: the pin check fails the validation callback → AuthenticationException.</summary>
|
||||
[Fact]
|
||||
public async Task Tls_WrongThumbprint_ThrowsAuthenticationException()
|
||||
{
|
||||
using var cts = new CancellationTokenSource(Timeout);
|
||||
using var cert = MakeSelfSignedCert();
|
||||
var listener = new TcpListener(IPAddress.Loopback, 0);
|
||||
listener.Start();
|
||||
var boundPort = ((IPEndPoint)listener.LocalEndpoint).Port;
|
||||
|
||||
// The server still attempts its handshake; it will fault when the client aborts. Swallow.
|
||||
var serverTask = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
using var server = await listener.AcceptTcpClientAsync(cts.Token);
|
||||
var ssl = new SslStream(server.GetStream(), leaveInnerStreamOpen: false);
|
||||
await ssl.AuthenticateAsServerAsync(cert, clientCertificateRequired: false,
|
||||
enabledSslProtocols: SslProtocols.Tls12, checkCertificateRevocation: false);
|
||||
ssl.Dispose();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Expected — the client rejects the cert and tears the connection down.
|
||||
}
|
||||
}, cts.Token);
|
||||
|
||||
var opts = new WonderwareHistorianClientOptions("127.0.0.1", boundPort, "secret")
|
||||
{
|
||||
UseTls = true,
|
||||
ServerCertThumbprint = "00112233445566778899AABBCCDDEEFF00112233", // bogus
|
||||
};
|
||||
|
||||
await Should.ThrowAsync<AuthenticationException>(
|
||||
async () => await FrameChannel.DefaultTcpConnectFactory(opts, cts.Token));
|
||||
|
||||
try { await serverTask; } catch { /* ignore */ }
|
||||
listener.Stop();
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Client.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Unit tests for <see cref="WonderwareHistorianClientOptions"/> TCP/TLS fields.
|
||||
/// </summary>
|
||||
public sealed class WonderwareHistorianClientOptionsTests
|
||||
{
|
||||
[Fact]
|
||||
public void TcpTlsFields_AreStoredCorrectly_WhenExplicitlySet()
|
||||
{
|
||||
var opts = new WonderwareHistorianClientOptions("h", 32569, "secret")
|
||||
{
|
||||
UseTls = true,
|
||||
ServerCertThumbprint = "AB"
|
||||
};
|
||||
|
||||
opts.Host.ShouldBe("h");
|
||||
opts.Port.ShouldBe(32569);
|
||||
opts.UseTls.ShouldBeTrue();
|
||||
opts.ServerCertThumbprint.ShouldBe("AB");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TcpTlsFields_HaveCorrectDefaults_WhenNotSet()
|
||||
{
|
||||
var opts = new WonderwareHistorianClientOptions("host", 32569, "secret");
|
||||
|
||||
opts.Host.ShouldBe("host");
|
||||
opts.Port.ShouldBe(32569);
|
||||
opts.UseTls.ShouldBeFalse();
|
||||
opts.ServerCertThumbprint.ShouldBeNull();
|
||||
}
|
||||
}
|
||||
+161
-61
@@ -1,3 +1,5 @@
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using MessagePack;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
@@ -9,7 +11,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Client.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// End-to-end tests for <see cref="WonderwareHistorianClient"/>: every interface method
|
||||
/// round-trips through a real named pipe against the in-process
|
||||
/// round-trips over a real loopback TCP connection against the in-process
|
||||
/// <see cref="FakeSidecarServer"/>, which reuses the client's own byte-identical framing
|
||||
/// code. Covers byte→uint quality mapping, BadNoData propagation for null aggregate
|
||||
/// buckets, alarm-write per-event status flow, Hello handshake rejection on bad secret,
|
||||
@@ -19,21 +21,29 @@ public sealed class WonderwareHistorianClientTests
|
||||
{
|
||||
private const string Secret = "test-secret-123";
|
||||
|
||||
private static string UniquePipeName() => $"otopcua-historian-test-{Guid.NewGuid():N}";
|
||||
|
||||
private static WonderwareHistorianClientOptions OptsFor(string pipe) => new(
|
||||
PipeName: pipe,
|
||||
private static WonderwareHistorianClientOptions OptsFor(FakeSidecarServer server) => new(
|
||||
Host: "127.0.0.1",
|
||||
Port: server.BoundPort,
|
||||
SharedSecret: Secret,
|
||||
PeerName: "test",
|
||||
ConnectTimeout: TimeSpan.FromSeconds(2),
|
||||
CallTimeout: TimeSpan.FromSeconds(2));
|
||||
CallTimeout: TimeSpan.FromSeconds(2))
|
||||
{
|
||||
UseTls = false,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Creates a client over loopback TCP against the fake's bound port using the public ctor
|
||||
/// (which dials TCP).
|
||||
/// </summary>
|
||||
private static WonderwareHistorianClient TcpClientFor(FakeSidecarServer server)
|
||||
=> new(OptsFor(server));
|
||||
|
||||
/// <summary>Verifies that ReadRawAsync round-trips samples and maps quality bytes to OPC UA status codes.</summary>
|
||||
[Fact]
|
||||
public async Task ReadRawAsync_RoundTripsSamples_AndMapsQualityByteToOpcUaStatusCode()
|
||||
{
|
||||
var pipe = UniquePipeName();
|
||||
await using var server = new FakeSidecarServer(pipe, Secret)
|
||||
await using var server = new FakeSidecarServer(Secret)
|
||||
{
|
||||
OnReadRaw = req => new ReadRawReply
|
||||
{
|
||||
@@ -57,7 +67,7 @@ public sealed class WonderwareHistorianClientTests
|
||||
};
|
||||
await server.StartAsync();
|
||||
|
||||
await using var client = new WonderwareHistorianClient(OptsFor(pipe));
|
||||
await using var client = TcpClientFor(server);
|
||||
var result = await client.ReadRawAsync("Tank.Level",
|
||||
new DateTime(2026, 4, 29, 0, 0, 0, DateTimeKind.Utc),
|
||||
new DateTime(2026, 4, 30, 0, 0, 0, DateTimeKind.Utc),
|
||||
@@ -74,8 +84,7 @@ public sealed class WonderwareHistorianClientTests
|
||||
[Fact]
|
||||
public async Task ReadProcessedAsync_NullBuckets_MapToBadNoData()
|
||||
{
|
||||
var pipe = UniquePipeName();
|
||||
await using var server = new FakeSidecarServer(pipe, Secret)
|
||||
await using var server = new FakeSidecarServer(Secret)
|
||||
{
|
||||
OnReadProcessed = _ => new ReadProcessedReply
|
||||
{
|
||||
@@ -89,7 +98,7 @@ public sealed class WonderwareHistorianClientTests
|
||||
};
|
||||
await server.StartAsync();
|
||||
|
||||
await using var client = new WonderwareHistorianClient(OptsFor(pipe));
|
||||
await using var client = TcpClientFor(server);
|
||||
var result = await client.ReadProcessedAsync("Tank.Level",
|
||||
new DateTime(2026, 4, 29, 0, 0, 0, DateTimeKind.Utc),
|
||||
new DateTime(2026, 4, 29, 0, 2, 0, DateTimeKind.Utc),
|
||||
@@ -106,11 +115,10 @@ public sealed class WonderwareHistorianClientTests
|
||||
[Fact]
|
||||
public async Task ReadAtTimeAsync_PreservesTimestampOrder()
|
||||
{
|
||||
var pipe = UniquePipeName();
|
||||
var t1 = new DateTime(2026, 4, 29, 1, 0, 0, DateTimeKind.Utc);
|
||||
var t2 = new DateTime(2026, 4, 29, 2, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
await using var server = new FakeSidecarServer(pipe, Secret)
|
||||
await using var server = new FakeSidecarServer(Secret)
|
||||
{
|
||||
OnReadAtTime = req => new ReadAtTimeReply
|
||||
{
|
||||
@@ -122,7 +130,7 @@ public sealed class WonderwareHistorianClientTests
|
||||
};
|
||||
await server.StartAsync();
|
||||
|
||||
await using var client = new WonderwareHistorianClient(OptsFor(pipe));
|
||||
await using var client = TcpClientFor(server);
|
||||
var result = await client.ReadAtTimeAsync("Tank.Level", new[] { t1, t2 }, CancellationToken.None);
|
||||
|
||||
result.Samples.Count.ShouldBe(2);
|
||||
@@ -134,12 +142,11 @@ public sealed class WonderwareHistorianClientTests
|
||||
[Fact]
|
||||
public async Task ReadAtTimeAsync_PartialAndReorderedReply_AlignsByTimestamp_AndFillsGapsAsBad()
|
||||
{
|
||||
var pipe = UniquePipeName();
|
||||
var t1 = new DateTime(2026, 4, 29, 1, 0, 0, DateTimeKind.Utc);
|
||||
var t2 = new DateTime(2026, 4, 29, 2, 0, 0, DateTimeKind.Utc);
|
||||
var t3 = new DateTime(2026, 4, 29, 3, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
await using var server = new FakeSidecarServer(pipe, Secret)
|
||||
await using var server = new FakeSidecarServer(Secret)
|
||||
{
|
||||
// Sidecar returns only t3 and t1 (out of order), drops t2 entirely. A
|
||||
// contract-compliant client must realign by timestamp and synthesize a
|
||||
@@ -164,7 +171,7 @@ public sealed class WonderwareHistorianClientTests
|
||||
};
|
||||
await server.StartAsync();
|
||||
|
||||
await using var client = new WonderwareHistorianClient(OptsFor(pipe));
|
||||
await using var client = TcpClientFor(server);
|
||||
var result = await client.ReadAtTimeAsync("Tank.Level", new[] { t1, t2, t3 }, CancellationToken.None);
|
||||
|
||||
// Result MUST be the same length and order as the request.
|
||||
@@ -188,9 +195,8 @@ public sealed class WonderwareHistorianClientTests
|
||||
[Fact]
|
||||
public async Task ReadEventsAsync_PreservesEventFields()
|
||||
{
|
||||
var pipe = UniquePipeName();
|
||||
var eid = Guid.NewGuid().ToString("N");
|
||||
await using var server = new FakeSidecarServer(pipe, Secret)
|
||||
await using var server = new FakeSidecarServer(Secret)
|
||||
{
|
||||
OnReadEvents = _ => new ReadEventsReply
|
||||
{
|
||||
@@ -209,7 +215,7 @@ public sealed class WonderwareHistorianClientTests
|
||||
};
|
||||
await server.StartAsync();
|
||||
|
||||
await using var client = new WonderwareHistorianClient(OptsFor(pipe));
|
||||
await using var client = TcpClientFor(server);
|
||||
var result = await client.ReadEventsAsync("Tank.HiHi",
|
||||
new DateTime(2026, 4, 29, 0, 0, 0, DateTimeKind.Utc),
|
||||
new DateTime(2026, 4, 30, 0, 0, 0, DateTimeKind.Utc),
|
||||
@@ -226,14 +232,13 @@ public sealed class WonderwareHistorianClientTests
|
||||
[Fact]
|
||||
public async Task ReadRawAsync_ServerError_ThrowsInvalidOperation()
|
||||
{
|
||||
var pipe = UniquePipeName();
|
||||
await using var server = new FakeSidecarServer(pipe, Secret)
|
||||
await using var server = new FakeSidecarServer(Secret)
|
||||
{
|
||||
OnReadRaw = _ => new ReadRawReply { Success = false, Error = "historian unreachable" },
|
||||
};
|
||||
await server.StartAsync();
|
||||
|
||||
await using var client = new WonderwareHistorianClient(OptsFor(pipe));
|
||||
await using var client = TcpClientFor(server);
|
||||
|
||||
var ex = await Should.ThrowAsync<InvalidOperationException>(() =>
|
||||
client.ReadRawAsync("Tag", DateTime.UtcNow, DateTime.UtcNow, 100, CancellationToken.None));
|
||||
@@ -244,8 +249,7 @@ public sealed class WonderwareHistorianClientTests
|
||||
[Fact]
|
||||
public async Task WriteBatchAsync_PerEventOk_MapsToAckOrRetryPlease()
|
||||
{
|
||||
var pipe = UniquePipeName();
|
||||
await using var server = new FakeSidecarServer(pipe, Secret)
|
||||
await using var server = new FakeSidecarServer(Secret)
|
||||
{
|
||||
OnWriteAlarmEvents = req => new WriteAlarmEventsReply
|
||||
{
|
||||
@@ -255,7 +259,7 @@ public sealed class WonderwareHistorianClientTests
|
||||
};
|
||||
await server.StartAsync();
|
||||
|
||||
await using var client = new WonderwareHistorianClient(OptsFor(pipe));
|
||||
await using var client = TcpClientFor(server);
|
||||
var batch = new[]
|
||||
{
|
||||
new AlarmHistorianEvent("ev-1", "Tank/HiHi", "HiHi", "LimitAlarm", AlarmSeverity.High, "Activated", "msg", "operator", null, DateTime.UtcNow),
|
||||
@@ -273,8 +277,7 @@ public sealed class WonderwareHistorianClientTests
|
||||
[Fact]
|
||||
public async Task WriteBatchAsync_WholeCallFailure_ReturnsRetryPleaseForEveryEvent()
|
||||
{
|
||||
var pipe = UniquePipeName();
|
||||
await using var server = new FakeSidecarServer(pipe, Secret)
|
||||
await using var server = new FakeSidecarServer(Secret)
|
||||
{
|
||||
OnWriteAlarmEvents = _ => new WriteAlarmEventsReply
|
||||
{
|
||||
@@ -285,7 +288,7 @@ public sealed class WonderwareHistorianClientTests
|
||||
};
|
||||
await server.StartAsync();
|
||||
|
||||
await using var client = new WonderwareHistorianClient(OptsFor(pipe));
|
||||
await using var client = TcpClientFor(server);
|
||||
var batch = new[]
|
||||
{
|
||||
new AlarmHistorianEvent("ev-1", "Tank/HiHi", "HiHi", "LimitAlarm", AlarmSeverity.High, "Activated", "msg", "u", null, DateTime.UtcNow),
|
||||
@@ -303,11 +306,10 @@ public sealed class WonderwareHistorianClientTests
|
||||
[Fact]
|
||||
public async Task Hello_BadSecret_ThrowsUnauthorizedAccess()
|
||||
{
|
||||
var pipe = UniquePipeName();
|
||||
await using var server = new FakeSidecarServer(pipe, "different-secret");
|
||||
await using var server = new FakeSidecarServer("different-secret");
|
||||
await server.StartAsync();
|
||||
|
||||
await using var client = new WonderwareHistorianClient(OptsFor(pipe));
|
||||
await using var client = TcpClientFor(server);
|
||||
|
||||
var ex = await Should.ThrowAsync<UnauthorizedAccessException>(() =>
|
||||
client.ReadRawAsync("Tag", DateTime.UtcNow, DateTime.UtcNow, 100, CancellationToken.None));
|
||||
@@ -318,8 +320,7 @@ public sealed class WonderwareHistorianClientTests
|
||||
[Fact]
|
||||
public async Task Reconnect_AfterTransportDrop_RetriesOnce()
|
||||
{
|
||||
var pipe = UniquePipeName();
|
||||
await using var server = new FakeSidecarServer(pipe, Secret)
|
||||
await using var server = new FakeSidecarServer(Secret)
|
||||
{
|
||||
// First connection drops after handshake → client retries on next call.
|
||||
DisconnectAfterHandshake = true,
|
||||
@@ -331,7 +332,7 @@ public sealed class WonderwareHistorianClientTests
|
||||
};
|
||||
await server.StartAsync();
|
||||
|
||||
await using var client = new WonderwareHistorianClient(OptsFor(pipe));
|
||||
await using var client = TcpClientFor(server);
|
||||
|
||||
// First call: handshake + dropped. Reconnect kicks in inside the channel; second
|
||||
// attempt within the same InvokeAsync succeeds. From the caller's perspective it's
|
||||
@@ -348,9 +349,8 @@ public sealed class WonderwareHistorianClientTests
|
||||
[Fact]
|
||||
public async Task GetHealthSnapshot_TracksSuccessAndFailureCounts()
|
||||
{
|
||||
var pipe = UniquePipeName();
|
||||
var failNext = false;
|
||||
await using var server = new FakeSidecarServer(pipe, Secret)
|
||||
await using var server = new FakeSidecarServer(Secret)
|
||||
{
|
||||
OnReadRaw = _ => failNext
|
||||
? new ReadRawReply { Success = false, Error = "boom" }
|
||||
@@ -358,7 +358,7 @@ public sealed class WonderwareHistorianClientTests
|
||||
};
|
||||
await server.StartAsync();
|
||||
|
||||
await using var client = new WonderwareHistorianClient(OptsFor(pipe));
|
||||
await using var client = TcpClientFor(server);
|
||||
|
||||
await client.ReadRawAsync("Tag", DateTime.UtcNow, DateTime.UtcNow, 1, CancellationToken.None);
|
||||
|
||||
@@ -384,17 +384,16 @@ public sealed class WonderwareHistorianClientTests
|
||||
[Fact]
|
||||
public async Task WriteBatchAsync_TransportDropDuringWrite_ReturnsRetryPleaseForEveryEvent()
|
||||
{
|
||||
var pipe = UniquePipeName();
|
||||
// Server disconnects before replying to the write request. The client's single retry
|
||||
// reconnects; on the second attempt the server is still armed to disconnect, so both
|
||||
// attempts fail and the catch block fires.
|
||||
await using var server = new FakeSidecarServer(pipe, Secret)
|
||||
await using var server = new FakeSidecarServer(Secret)
|
||||
{
|
||||
DisconnectBeforeReply = true,
|
||||
};
|
||||
await server.StartAsync();
|
||||
|
||||
await using var client = new WonderwareHistorianClient(OptsFor(pipe));
|
||||
await using var client = TcpClientFor(server);
|
||||
var batch = new[]
|
||||
{
|
||||
new AlarmHistorianEvent("ev-1", "Tank/HiHi", "HiHi", "LimitAlarm", AlarmSeverity.High, "Activated", "msg", "u", null, DateTime.UtcNow),
|
||||
@@ -416,16 +415,15 @@ public sealed class WonderwareHistorianClientTests
|
||||
[Fact]
|
||||
public async Task InvokeAsync_BothAttemptsFailTransport_PropagatesException()
|
||||
{
|
||||
var pipe = UniquePipeName();
|
||||
// DisconnectBeforeReply stays true so both the first attempt and the single retry
|
||||
// inside InvokeAsync are dropped, causing the second ExchangeAsync to throw.
|
||||
await using var server = new FakeSidecarServer(pipe, Secret)
|
||||
await using var server = new FakeSidecarServer(Secret)
|
||||
{
|
||||
DisconnectBeforeReply = true,
|
||||
};
|
||||
await server.StartAsync();
|
||||
|
||||
await using var client = new WonderwareHistorianClient(OptsFor(pipe));
|
||||
await using var client = TcpClientFor(server);
|
||||
|
||||
// ReadRawAsync uses Invoke, which propagates the exception when both attempts fail.
|
||||
await Should.ThrowAsync<Exception>(() =>
|
||||
@@ -439,19 +437,22 @@ public sealed class WonderwareHistorianClientTests
|
||||
[Fact]
|
||||
public async Task ReadRawAsync_StalledSidecar_TimesOutWithOperationCanceledException()
|
||||
{
|
||||
var pipe = UniquePipeName();
|
||||
await using var server = new FakeSidecarServer(pipe, Secret)
|
||||
await using var server = new FakeSidecarServer(Secret)
|
||||
{
|
||||
StallAfterRequest = true,
|
||||
};
|
||||
await server.StartAsync();
|
||||
|
||||
var opts = new WonderwareHistorianClientOptions(
|
||||
PipeName: pipe,
|
||||
Host: "127.0.0.1",
|
||||
Port: server.BoundPort,
|
||||
SharedSecret: Secret,
|
||||
PeerName: "test",
|
||||
ConnectTimeout: TimeSpan.FromSeconds(2),
|
||||
CallTimeout: TimeSpan.FromMilliseconds(500)); // short timeout for test speed
|
||||
CallTimeout: TimeSpan.FromMilliseconds(500)) // short timeout for test speed
|
||||
{
|
||||
UseTls = false,
|
||||
};
|
||||
|
||||
await using var client = new WonderwareHistorianClient(opts);
|
||||
|
||||
@@ -469,11 +470,10 @@ public sealed class WonderwareHistorianClientTests
|
||||
[Fact]
|
||||
public async Task ReadProcessedAsync_TotalAggregate_ThrowsNotSupported()
|
||||
{
|
||||
var pipe = UniquePipeName();
|
||||
await using var server = new FakeSidecarServer(pipe, Secret);
|
||||
await using var server = new FakeSidecarServer(Secret);
|
||||
await server.StartAsync();
|
||||
|
||||
await using var client = new WonderwareHistorianClient(OptsFor(pipe));
|
||||
await using var client = TcpClientFor(server);
|
||||
|
||||
await Should.ThrowAsync<NotSupportedException>(() =>
|
||||
client.ReadProcessedAsync("Tag",
|
||||
@@ -489,15 +489,14 @@ public sealed class WonderwareHistorianClientTests
|
||||
[Fact]
|
||||
public async Task ReadRawAsync_SidecarRepliesWithWrongKind_ThrowsInvalidDataException()
|
||||
{
|
||||
var pipe = UniquePipeName();
|
||||
await using var server = new FakeSidecarServer(pipe, Secret)
|
||||
await using var server = new FakeSidecarServer(Secret)
|
||||
{
|
||||
// Force the server to reply with ReadAtTimeReply instead of ReadRawReply.
|
||||
ReplyWithWrongKind = MessageKind.ReadAtTimeReply,
|
||||
};
|
||||
await server.StartAsync();
|
||||
|
||||
await using var client = new WonderwareHistorianClient(OptsFor(pipe));
|
||||
await using var client = TcpClientFor(server);
|
||||
|
||||
await Should.ThrowAsync<InvalidDataException>(() =>
|
||||
client.ReadRawAsync("Tag", DateTime.UtcNow, DateTime.UtcNow, 100, CancellationToken.None));
|
||||
@@ -516,14 +515,13 @@ public sealed class WonderwareHistorianClientTests
|
||||
[Fact]
|
||||
public async Task GetHealthSnapshot_SidecarFailure_NeverInflatesSuccessCounter()
|
||||
{
|
||||
var pipe = UniquePipeName();
|
||||
await using var server = new FakeSidecarServer(pipe, Secret)
|
||||
await using var server = new FakeSidecarServer(Secret)
|
||||
{
|
||||
OnReadRaw = _ => new ReadRawReply { Success = false, Error = "boom" },
|
||||
};
|
||||
await server.StartAsync();
|
||||
|
||||
await using var client = new WonderwareHistorianClient(OptsFor(pipe));
|
||||
await using var client = TcpClientFor(server);
|
||||
|
||||
await Should.ThrowAsync<InvalidOperationException>(() =>
|
||||
client.ReadRawAsync("Tag", DateTime.UtcNow, DateTime.UtcNow, 1, CancellationToken.None));
|
||||
@@ -547,14 +545,13 @@ public sealed class WonderwareHistorianClientTests
|
||||
[Fact]
|
||||
public async Task GetHealthSnapshot_ConcurrentCallsAndReads_CountersAreInternallyConsistent()
|
||||
{
|
||||
var pipe = UniquePipeName();
|
||||
await using var server = new FakeSidecarServer(pipe, Secret)
|
||||
await using var server = new FakeSidecarServer(Secret)
|
||||
{
|
||||
OnReadRaw = _ => new ReadRawReply { Success = true },
|
||||
};
|
||||
await server.StartAsync();
|
||||
|
||||
await using var client = new WonderwareHistorianClient(OptsFor(pipe));
|
||||
await using var client = TcpClientFor(server);
|
||||
|
||||
using var stop = new CancellationTokenSource();
|
||||
var readerSawInconsistent = false;
|
||||
@@ -593,4 +590,107 @@ public sealed class WonderwareHistorianClientTests
|
||||
final.TotalSuccesses.ShouldBe(50);
|
||||
final.TotalFailures.ShouldBe(0);
|
||||
}
|
||||
|
||||
// ===== Task 3: default public ctor dials TCP =====
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that the default public ctor connects over TCP rather than named-pipe by
|
||||
/// constructing the client against a loopback <see cref="TcpListener"/> and asserting
|
||||
/// that a ReadRaw round-trip returns the known sample. If the ctor still dialled a
|
||||
/// named pipe the connect would fail because no pipe is listening.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task DefaultCtor_DialsTcp_ReadRawRoundTrips()
|
||||
{
|
||||
using var cts = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
|
||||
cts.CancelAfter(TimeSpan.FromSeconds(10));
|
||||
|
||||
// 1. Start a loopback TCP listener on an OS-assigned port.
|
||||
var listener = new TcpListener(IPAddress.Loopback, 0);
|
||||
listener.Start();
|
||||
var boundPort = ((IPEndPoint)listener.LocalEndpoint).Port;
|
||||
|
||||
var expectedTicks = new DateTime(2026, 6, 12, 8, 0, 0, DateTimeKind.Utc).Ticks;
|
||||
var expectedValue = MessagePackSerializer.Serialize<object>(99.0, cancellationToken: TestContext.Current.CancellationToken);
|
||||
|
||||
// 2. Accept one client in the background and drive the server side of the protocol.
|
||||
// Intentional: the background server task uses cts.Token (a linked+timeout source)
|
||||
// rather than TestContext.Current.CancellationToken directly, because it adds a
|
||||
// wall-clock safety bound so the test never hangs CI.
|
||||
#pragma warning disable xUnit1051
|
||||
var serverTask = Task.Run(async () =>
|
||||
{
|
||||
using var server = await listener.AcceptTcpClientAsync(cts.Token);
|
||||
server.NoDelay = true;
|
||||
var stream = server.GetStream();
|
||||
using var reader = new FrameReader(stream, leaveOpen: true);
|
||||
using var writer = new FrameWriter(stream, leaveOpen: true);
|
||||
|
||||
// Hello handshake.
|
||||
var helloFrame = await reader.ReadFrameAsync(cts.Token);
|
||||
helloFrame.ShouldNotBeNull();
|
||||
helloFrame!.Value.Kind.ShouldBe(MessageKind.Hello);
|
||||
await writer.WriteAsync(MessageKind.HelloAck,
|
||||
new HelloAck { Accepted = true, HostName = "test-tcp-sidecar" }, cts.Token);
|
||||
|
||||
// ReadRaw request.
|
||||
var reqFrame = await reader.ReadFrameAsync(cts.Token);
|
||||
reqFrame.ShouldNotBeNull();
|
||||
reqFrame!.Value.Kind.ShouldBe(MessageKind.ReadRawRequest);
|
||||
var req = MessagePackSerializer.Deserialize<ReadRawRequest>(reqFrame.Value.Body);
|
||||
|
||||
var reply = new ReadRawReply
|
||||
{
|
||||
Success = true,
|
||||
CorrelationId = req.CorrelationId,
|
||||
Samples =
|
||||
[
|
||||
new HistorianSampleDto
|
||||
{
|
||||
ValueBytes = expectedValue,
|
||||
Quality = 192, // Good
|
||||
TimestampUtcTicks = expectedTicks,
|
||||
},
|
||||
],
|
||||
};
|
||||
await writer.WriteAsync(MessageKind.ReadRawReply, reply, cts.Token);
|
||||
}, cts.Token);
|
||||
#pragma warning restore xUnit1051
|
||||
|
||||
// 3. Construct the client via the PUBLIC ctor (no ForTests factory).
|
||||
var opts = new WonderwareHistorianClientOptions(
|
||||
Host: "127.0.0.1",
|
||||
Port: boundPort,
|
||||
SharedSecret: Secret,
|
||||
ConnectTimeout: TimeSpan.FromSeconds(5),
|
||||
CallTimeout: TimeSpan.FromSeconds(5))
|
||||
{
|
||||
UseTls = false,
|
||||
};
|
||||
|
||||
WonderwareHistorianClient? client = null;
|
||||
try
|
||||
{
|
||||
client = new WonderwareHistorianClient(opts);
|
||||
|
||||
var result = await client.ReadRawAsync(
|
||||
"Tank.Level",
|
||||
new DateTime(2026, 6, 12, 0, 0, 0, DateTimeKind.Utc),
|
||||
new DateTime(2026, 6, 13, 0, 0, 0, DateTimeKind.Utc),
|
||||
100, cts.Token);
|
||||
|
||||
// 4. Assert the known sample came back.
|
||||
result.Samples.Count.ShouldBe(1);
|
||||
result.Samples[0].StatusCode.ShouldBe(0x00000000u); // Good
|
||||
result.Samples[0].SourceTimestampUtc.ShouldBe(new DateTime(expectedTicks, DateTimeKind.Utc));
|
||||
result.Samples[0].Value.ShouldBe(99.0);
|
||||
|
||||
await serverTask;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (client is not null) await client.DisposeAsync();
|
||||
listener.Stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-348
@@ -1,348 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MessagePack;
|
||||
using Serilog;
|
||||
using Serilog.Core;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Backend;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Ipc;
|
||||
using SidecarHistorianEventDto = ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Ipc.HistorianEventDto;
|
||||
using BackendHistorianEventDto = ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Backend.HistorianEventDto;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Tests.Ipc;
|
||||
|
||||
/// <summary>
|
||||
/// Round-trip tests for the sidecar pipe contract added in PR 3.3. Each scenario serializes
|
||||
/// a Request through the wire framing, dispatches via <see cref="HistorianFrameHandler"/>
|
||||
/// against a fake historian, and asserts the returned Reply round-trips with the expected
|
||||
/// content. No real named pipe is opened — the framing is exercised over a back-to-back
|
||||
/// <see cref="MemoryStream"/> pair so tests stay fast and platform-independent.
|
||||
/// </summary>
|
||||
public sealed class PipeRoundTripTests
|
||||
{
|
||||
private static readonly ILogger Quiet = Logger.None;
|
||||
|
||||
private sealed class FakeHistorian : IHistorianDataSource
|
||||
{
|
||||
/// <summary>Gets or sets the raw samples to return from reads.</summary>
|
||||
public List<HistorianSample> RawSamples { get; set; } = new();
|
||||
|
||||
/// <summary>Gets or sets the aggregate samples to return from reads.</summary>
|
||||
public List<HistorianAggregateSample> AggregateSamples { get; set; } = new();
|
||||
|
||||
/// <summary>Gets or sets the at-time samples to return from reads.</summary>
|
||||
public List<HistorianSample> AtTimeSamples { get; set; } = new();
|
||||
|
||||
/// <summary>Gets or sets the events to return from reads.</summary>
|
||||
public List<BackendHistorianEventDto> Events { get; set; } = new();
|
||||
|
||||
/// <summary>Gets or sets an exception to throw from read operations.</summary>
|
||||
public Exception? ThrowFromRead { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Reads raw samples from the fake historian or throws if configured.
|
||||
/// </summary>
|
||||
/// <param name="tagName">The tag name.</param>
|
||||
/// <param name="startTime">The start time.</param>
|
||||
/// <param name="endTime">The end time.</param>
|
||||
/// <param name="maxValues">The maximum number of values to return.</param>
|
||||
/// <param name="ct">Cancellation token.</param>
|
||||
/// <returns>The raw samples.</returns>
|
||||
public Task<List<HistorianSample>> ReadRawAsync(string tagName, DateTime startTime, DateTime endTime, int maxValues, CancellationToken ct = default)
|
||||
{
|
||||
if (ThrowFromRead is not null) throw ThrowFromRead;
|
||||
return Task.FromResult(RawSamples);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads aggregate samples from the fake historian.
|
||||
/// </summary>
|
||||
/// <param name="tagName">The tag name.</param>
|
||||
/// <param name="startTime">The start time.</param>
|
||||
/// <param name="endTime">The end time.</param>
|
||||
/// <param name="intervalMs">The interval in milliseconds.</param>
|
||||
/// <param name="aggregateColumn">The aggregate column name.</param>
|
||||
/// <param name="ct">Cancellation token.</param>
|
||||
/// <returns>The aggregate samples.</returns>
|
||||
public Task<List<HistorianAggregateSample>> ReadAggregateAsync(string tagName, DateTime startTime, DateTime endTime, double intervalMs, string aggregateColumn, CancellationToken ct = default)
|
||||
=> Task.FromResult(AggregateSamples);
|
||||
|
||||
/// <summary>
|
||||
/// Reads at-time samples from the fake historian.
|
||||
/// </summary>
|
||||
/// <param name="tagName">The tag name.</param>
|
||||
/// <param name="timestamps">The timestamps to read at.</param>
|
||||
/// <param name="ct">Cancellation token.</param>
|
||||
/// <returns>The at-time samples.</returns>
|
||||
public Task<List<HistorianSample>> ReadAtTimeAsync(string tagName, DateTime[] timestamps, CancellationToken ct = default)
|
||||
=> Task.FromResult(AtTimeSamples);
|
||||
|
||||
/// <summary>
|
||||
/// Reads events from the fake historian.
|
||||
/// </summary>
|
||||
/// <param name="sourceName">The event source name.</param>
|
||||
/// <param name="startTime">The start time.</param>
|
||||
/// <param name="endTime">The end time.</param>
|
||||
/// <param name="maxEvents">The maximum number of events to return.</param>
|
||||
/// <param name="ct">Cancellation token.</param>
|
||||
/// <returns>The events.</returns>
|
||||
public Task<List<BackendHistorianEventDto>> ReadEventsAsync(string? sourceName, DateTime startTime, DateTime endTime, int maxEvents, CancellationToken ct = default)
|
||||
=> Task.FromResult(Events);
|
||||
|
||||
/// <summary>Gets a health snapshot of the fake historian.</summary>
|
||||
/// <returns>A health snapshot.</returns>
|
||||
public HistorianHealthSnapshot GetHealthSnapshot() => new();
|
||||
|
||||
/// <summary>Disposes the fake historian.</summary>
|
||||
public void Dispose() { }
|
||||
}
|
||||
|
||||
private sealed class FakeAlarmWriter : IAlarmEventWriter
|
||||
{
|
||||
/// <summary>Gets the events received by this writer.</summary>
|
||||
public List<AlarmHistorianEventDto> Received { get; } = new();
|
||||
|
||||
/// <summary>Gets or sets a delegate that decides whether each event should be marked as successfully written.</summary>
|
||||
public Func<AlarmHistorianEventDto, bool> Decide { get; set; } = _ => true;
|
||||
|
||||
/// <summary>
|
||||
/// Writes alarm events to the fake writer and returns per-event status based on the <see cref="Decide"/> delegate.
|
||||
/// </summary>
|
||||
/// <param name="events">The events to write.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>An array of booleans indicating success for each event.</returns>
|
||||
public Task<bool[]> WriteAsync(AlarmHistorianEventDto[] events, CancellationToken cancellationToken)
|
||||
{
|
||||
Received.AddRange(events);
|
||||
var result = new bool[events.Length];
|
||||
for (var i = 0; i < events.Length; i++) result[i] = Decide(events[i]);
|
||||
return Task.FromResult(result);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Drives one round trip: serialize <paramref name="request"/>, run the handler,
|
||||
/// read the reply frame, deserialize it. Returns the reply.
|
||||
/// </summary>
|
||||
private static async Task<TReply> RoundTripAsync<TRequest, TReply>(
|
||||
MessageKind requestKind,
|
||||
MessageKind expectedReplyKind,
|
||||
TRequest request,
|
||||
IFrameHandler handler)
|
||||
{
|
||||
// Build the request body the same way FrameWriter would, but feed it directly into
|
||||
// the handler's Handle method (the pipe server has already read the kind + body
|
||||
// before handing them to the handler).
|
||||
var requestBody = MessagePackSerializer.Serialize(request);
|
||||
|
||||
using var stream = new MemoryStream();
|
||||
using var writer = new FrameWriter(stream, leaveOpen: true);
|
||||
|
||||
await handler.HandleAsync(requestKind, requestBody, writer, CancellationToken.None);
|
||||
|
||||
stream.Position = 0;
|
||||
using var reader = new FrameReader(stream, leaveOpen: true);
|
||||
var frame = await reader.ReadFrameAsync(CancellationToken.None);
|
||||
frame.ShouldNotBeNull();
|
||||
frame!.Value.Kind.ShouldBe(expectedReplyKind);
|
||||
return MessagePackSerializer.Deserialize<TReply>(frame.Value.Body);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that raw historian samples round-trip correctly through the frame handler.</summary>
|
||||
[Fact]
|
||||
public async Task ReadRaw_RoundTripsSamples()
|
||||
{
|
||||
var historian = new FakeHistorian();
|
||||
historian.RawSamples.Add(new HistorianSample { Value = 42.0, Quality = 192, TimestampUtc = new DateTime(2026, 4, 29, 12, 0, 0, DateTimeKind.Utc) });
|
||||
historian.RawSamples.Add(new HistorianSample { Value = 43.5, Quality = 192, TimestampUtc = new DateTime(2026, 4, 29, 12, 0, 1, DateTimeKind.Utc) });
|
||||
|
||||
var handler = new HistorianFrameHandler(historian, Quiet);
|
||||
var reply = await RoundTripAsync<ReadRawRequest, ReadRawReply>(
|
||||
MessageKind.ReadRawRequest, MessageKind.ReadRawReply,
|
||||
new ReadRawRequest
|
||||
{
|
||||
TagName = "Tank.Level",
|
||||
StartUtcTicks = new DateTime(2026, 4, 29, 0, 0, 0, DateTimeKind.Utc).Ticks,
|
||||
EndUtcTicks = new DateTime(2026, 4, 30, 0, 0, 0, DateTimeKind.Utc).Ticks,
|
||||
MaxValues = 100,
|
||||
CorrelationId = "corr-1",
|
||||
}, handler);
|
||||
|
||||
reply.Success.ShouldBeTrue();
|
||||
reply.Error.ShouldBeNull();
|
||||
reply.CorrelationId.ShouldBe("corr-1");
|
||||
reply.Samples.Length.ShouldBe(2);
|
||||
reply.Samples[0].Quality.ShouldBe((byte)192);
|
||||
reply.Samples[0].TimestampUtcTicks.ShouldBe(new DateTime(2026, 4, 29, 12, 0, 0, DateTimeKind.Utc).Ticks);
|
||||
reply.Samples[0].ValueBytes.ShouldNotBeNull();
|
||||
MessagePackSerializer.Deserialize<double>(reply.Samples[0].ValueBytes!).ShouldBe(42.0);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that read failures are properly surfaced as error replies.</summary>
|
||||
[Fact]
|
||||
public async Task ReadRaw_FailureSurfacesAsErrorReply()
|
||||
{
|
||||
var historian = new FakeHistorian { ThrowFromRead = new InvalidOperationException("boom") };
|
||||
var handler = new HistorianFrameHandler(historian, Quiet);
|
||||
var reply = await RoundTripAsync<ReadRawRequest, ReadRawReply>(
|
||||
MessageKind.ReadRawRequest, MessageKind.ReadRawReply,
|
||||
new ReadRawRequest { TagName = "Tag", CorrelationId = "fail-1" }, handler);
|
||||
|
||||
reply.Success.ShouldBeFalse();
|
||||
reply.Error.ShouldBe("boom");
|
||||
reply.CorrelationId.ShouldBe("fail-1");
|
||||
reply.Samples.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
/// <summary>Verifies that processed (aggregate) historian samples round-trip correctly through the frame handler.</summary>
|
||||
[Fact]
|
||||
public async Task ReadProcessed_RoundTripsBuckets()
|
||||
{
|
||||
var historian = new FakeHistorian();
|
||||
historian.AggregateSamples.Add(new HistorianAggregateSample { Value = 50.0, TimestampUtc = new DateTime(2026, 4, 29, 0, 0, 0, DateTimeKind.Utc) });
|
||||
historian.AggregateSamples.Add(new HistorianAggregateSample { Value = null, TimestampUtc = new DateTime(2026, 4, 29, 0, 1, 0, DateTimeKind.Utc) });
|
||||
|
||||
var handler = new HistorianFrameHandler(historian, Quiet);
|
||||
var reply = await RoundTripAsync<ReadProcessedRequest, ReadProcessedReply>(
|
||||
MessageKind.ReadProcessedRequest, MessageKind.ReadProcessedReply,
|
||||
new ReadProcessedRequest { TagName = "Tank.Level", IntervalMs = 60000, AggregateColumn = "Average", CorrelationId = "p-1" },
|
||||
handler);
|
||||
|
||||
reply.Success.ShouldBeTrue();
|
||||
reply.Buckets.Length.ShouldBe(2);
|
||||
reply.Buckets[0].Value.ShouldBe(50.0);
|
||||
reply.Buckets[1].Value.ShouldBeNull(); // unavailable bucket
|
||||
}
|
||||
|
||||
/// <summary>Verifies that at-time historian samples round-trip correctly through the frame handler.</summary>
|
||||
[Fact]
|
||||
public async Task ReadAtTime_RoundTripsSamples()
|
||||
{
|
||||
var historian = new FakeHistorian();
|
||||
historian.AtTimeSamples.Add(new HistorianSample { Value = 7, Quality = 192, TimestampUtc = new DateTime(2026, 4, 29, 0, 0, 0, DateTimeKind.Utc) });
|
||||
|
||||
var handler = new HistorianFrameHandler(historian, Quiet);
|
||||
var reply = await RoundTripAsync<ReadAtTimeRequest, ReadAtTimeReply>(
|
||||
MessageKind.ReadAtTimeRequest, MessageKind.ReadAtTimeReply,
|
||||
new ReadAtTimeRequest
|
||||
{
|
||||
TagName = "Tank.Level",
|
||||
TimestampsUtcTicks = new[] { new DateTime(2026, 4, 29, 0, 0, 0, DateTimeKind.Utc).Ticks },
|
||||
CorrelationId = "t-1",
|
||||
}, handler);
|
||||
|
||||
reply.Success.ShouldBeTrue();
|
||||
reply.Samples.Length.ShouldBe(1);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that historian events round-trip correctly through the frame handler.</summary>
|
||||
[Fact]
|
||||
public async Task ReadEvents_RoundTripsEvents()
|
||||
{
|
||||
var historian = new FakeHistorian();
|
||||
var eid = Guid.Parse("11111111-1111-1111-1111-111111111111");
|
||||
historian.Events.Add(new BackendHistorianEventDto
|
||||
{
|
||||
Id = eid,
|
||||
Source = "Tank.HiHi",
|
||||
EventTime = new DateTime(2026, 4, 29, 1, 0, 0, DateTimeKind.Utc),
|
||||
ReceivedTime = new DateTime(2026, 4, 29, 1, 0, 1, DateTimeKind.Utc),
|
||||
DisplayText = "Level high-high",
|
||||
Severity = 800,
|
||||
});
|
||||
|
||||
var handler = new HistorianFrameHandler(historian, Quiet);
|
||||
var reply = await RoundTripAsync<ReadEventsRequest, ReadEventsReply>(
|
||||
MessageKind.ReadEventsRequest, MessageKind.ReadEventsReply,
|
||||
new ReadEventsRequest { SourceName = "Tank.HiHi", MaxEvents = 100, CorrelationId = "e-1" },
|
||||
handler);
|
||||
|
||||
reply.Success.ShouldBeTrue();
|
||||
reply.Events.Length.ShouldBe(1);
|
||||
reply.Events[0].EventId.ShouldBe(eid.ToString());
|
||||
reply.Events[0].Source.ShouldBe("Tank.HiHi");
|
||||
reply.Events[0].DisplayText.ShouldBe("Level high-high");
|
||||
reply.Events[0].Severity.ShouldBe((ushort)800);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that alarm events are routed to the writer and per-event status is returned.</summary>
|
||||
[Fact]
|
||||
public async Task WriteAlarmEvents_RoutesToWriter_AndReturnsPerEventStatus()
|
||||
{
|
||||
var historian = new FakeHistorian();
|
||||
var alarmWriter = new FakeAlarmWriter
|
||||
{
|
||||
// Simulate "second event fails" to verify per-event status flows through.
|
||||
Decide = e => e.EventId != "ev-2",
|
||||
};
|
||||
var handler = new HistorianFrameHandler(historian, Quiet, alarmWriter);
|
||||
|
||||
var request = new WriteAlarmEventsRequest
|
||||
{
|
||||
CorrelationId = "wa-1",
|
||||
Events = new[]
|
||||
{
|
||||
new AlarmHistorianEventDto { EventId = "ev-1", SourceName = "Tank.HiHi", AlarmType = "Active", Severity = 800, EventTimeUtcTicks = DateTime.UtcNow.Ticks },
|
||||
new AlarmHistorianEventDto { EventId = "ev-2", SourceName = "Tank.HiHi", AlarmType = "Acknowledged", Severity = 800, EventTimeUtcTicks = DateTime.UtcNow.Ticks },
|
||||
},
|
||||
};
|
||||
|
||||
var reply = await RoundTripAsync<WriteAlarmEventsRequest, WriteAlarmEventsReply>(
|
||||
MessageKind.WriteAlarmEventsRequest, MessageKind.WriteAlarmEventsReply,
|
||||
request, handler);
|
||||
|
||||
reply.Success.ShouldBeTrue();
|
||||
reply.PerEventOk.Length.ShouldBe(2);
|
||||
reply.PerEventOk[0].ShouldBeTrue();
|
||||
reply.PerEventOk[1].ShouldBeFalse();
|
||||
alarmWriter.Received.Count.ShouldBe(2);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that writing alarm events fails cleanly when no writer is configured.</summary>
|
||||
[Fact]
|
||||
public async Task WriteAlarmEvents_FailsCleanly_WhenNoWriterConfigured()
|
||||
{
|
||||
var historian = new FakeHistorian();
|
||||
var handler = new HistorianFrameHandler(historian, Quiet, alarmWriter: null);
|
||||
|
||||
var reply = await RoundTripAsync<WriteAlarmEventsRequest, WriteAlarmEventsReply>(
|
||||
MessageKind.WriteAlarmEventsRequest, MessageKind.WriteAlarmEventsReply,
|
||||
new WriteAlarmEventsRequest
|
||||
{
|
||||
CorrelationId = "wa-2",
|
||||
Events = new[] { new AlarmHistorianEventDto { EventId = "ev-1" } },
|
||||
}, handler);
|
||||
|
||||
reply.Success.ShouldBeFalse();
|
||||
reply.Error.ShouldNotBeNull();
|
||||
reply.PerEventOk.Length.ShouldBe(1);
|
||||
reply.PerEventOk[0].ShouldBeFalse();
|
||||
}
|
||||
|
||||
/// <summary>Verifies that frame reader and writer preserve message kind and body through a round trip.</summary>
|
||||
[Fact]
|
||||
public async Task FrameReader_FrameWriter_RoundTripPreservesKindAndBody()
|
||||
{
|
||||
// Pure framing-layer test — confirms the length-prefix + kind-byte + body protocol
|
||||
// is the same on both sides without any handler in the loop.
|
||||
using var stream = new MemoryStream();
|
||||
using var writer = new FrameWriter(stream, leaveOpen: true);
|
||||
|
||||
var hello = new Hello { ProtocolMajor = 1, PeerName = "test-peer", SharedSecret = "secret" };
|
||||
await writer.WriteAsync(MessageKind.Hello, hello, CancellationToken.None);
|
||||
|
||||
stream.Position = 0;
|
||||
using var reader = new FrameReader(stream, leaveOpen: true);
|
||||
var frame = await reader.ReadFrameAsync(CancellationToken.None);
|
||||
|
||||
frame.ShouldNotBeNull();
|
||||
frame!.Value.Kind.ShouldBe(MessageKind.Hello);
|
||||
var decoded = MessagePackSerializer.Deserialize<Hello>(frame.Value.Body);
|
||||
decoded.PeerName.ShouldBe("test-peer");
|
||||
decoded.SharedSecret.ShouldBe("secret");
|
||||
}
|
||||
}
|
||||
-90
@@ -1,90 +0,0 @@
|
||||
using System;
|
||||
using System.IO.Pipes;
|
||||
using System.Security.Principal;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MessagePack;
|
||||
using Serilog;
|
||||
using Serilog.Core;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Ipc;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Tests.Ipc;
|
||||
|
||||
/// <summary>
|
||||
/// Driver.Historian.Wonderware-007 regression. The two other rejection paths
|
||||
/// (shared-secret-mismatch and major-version-mismatch) both write a <see cref="HelloAck"/>
|
||||
/// with <c>Accepted=false</c> before disconnecting; the caller-SID-mismatch path used to
|
||||
/// just disconnect abruptly, leaving the client to time out instead of learning why.
|
||||
/// The fix sends a symmetric <c>caller-sid-mismatch</c> ack before disconnecting.
|
||||
///
|
||||
/// The test uses the internal test-seam constructor so the verifier rejects without
|
||||
/// needing to actually relax the pipe ACL (which would block the test client itself).
|
||||
/// </summary>
|
||||
public sealed class PipeServerSidRejectTests
|
||||
{
|
||||
private static readonly ILogger Quiet = Logger.None;
|
||||
|
||||
/// <summary>Verifies that a caller SID mismatch sends HelloAck with reject reason before disconnect.</summary>
|
||||
[Fact]
|
||||
public async Task Caller_SID_mismatch_sends_HelloAck_with_reject_reason_before_disconnect()
|
||||
{
|
||||
// The pipe ACL must allow the current process to connect — so wire up the pipe
|
||||
// with the current user's SID. Then have the verifier seam simulate the SID
|
||||
// mismatch by returning false. This isolates the "what does the server do on a
|
||||
// rejected caller" question from the (separate) "is the ACL correct" question.
|
||||
var current = WindowsIdentity.GetCurrent().User
|
||||
?? throw new InvalidOperationException("WindowsIdentity.GetCurrent().User was null — cannot run test");
|
||||
|
||||
var pipeName = $"otopcua-hist-sidreject-test-{Guid.NewGuid():N}";
|
||||
|
||||
PipeServer.CallerVerifier rejecting = (NamedPipeServerStream _, SecurityIdentifier _, out string reason) =>
|
||||
{
|
||||
reason = "synthetic-mismatch";
|
||||
return false;
|
||||
};
|
||||
using var server = new PipeServer(pipeName, current, "secret", Quiet, rejecting);
|
||||
|
||||
var serverTask = Task.Run(() => server.RunOneConnectionAsync(new NoopHandler(), CancellationToken.None));
|
||||
|
||||
using var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous);
|
||||
await client.ConnectAsync(5_000);
|
||||
|
||||
using var writer = new FrameWriter(client, leaveOpen: true);
|
||||
using var reader = new FrameReader(client, leaveOpen: true);
|
||||
|
||||
var hello = new Hello { ProtocolMajor = Hello.CurrentMajor, PeerName = "test", SharedSecret = "secret" };
|
||||
await writer.WriteAsync(MessageKind.Hello, hello, CancellationToken.None);
|
||||
|
||||
// Read the rejecting HelloAck the server is expected to send before disconnecting.
|
||||
var frame = await reader.ReadFrameAsync(CancellationToken.None);
|
||||
frame.ShouldNotBeNull("server must send a HelloAck on caller-SID rejection, not just disconnect");
|
||||
frame!.Value.Kind.ShouldBe(MessageKind.HelloAck);
|
||||
|
||||
var ack = MessagePackSerializer.Deserialize<HelloAck>(frame.Value.Body);
|
||||
ack.Accepted.ShouldBeFalse();
|
||||
ack.RejectReason.ShouldNotBeNullOrEmpty();
|
||||
ack.RejectReason!.ShouldContain("caller-sid-mismatch",
|
||||
Case.Insensitive,
|
||||
"reject reason must match the documented caller-sid-mismatch tag so clients can diagnose");
|
||||
|
||||
await serverTask;
|
||||
}
|
||||
|
||||
/// <summary>Handler that asserts it is never called — the connection must be rejected at Hello.</summary>
|
||||
private sealed class NoopHandler : IFrameHandler
|
||||
{
|
||||
/// <summary>Throws if called, as the connection should be rejected before reaching this handler.</summary>
|
||||
/// <param name="kind">The message kind (unused).</param>
|
||||
/// <param name="body">The message body (unused).</param>
|
||||
/// <param name="writer">The frame writer (unused).</param>
|
||||
/// <param name="ct">Cancellation token (unused).</param>
|
||||
/// <returns>Never returns; always throws.</returns>
|
||||
public Task HandleAsync(MessageKind kind, byte[] body, FrameWriter writer, CancellationToken ct)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Handler must not be reached on a rejected caller; got frame {kind}");
|
||||
}
|
||||
}
|
||||
}
|
||||
+267
@@ -0,0 +1,267 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Security;
|
||||
using System.Net.Sockets;
|
||||
using System.Security.Authentication;
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MessagePack;
|
||||
using Serilog;
|
||||
using Serilog.Core;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Ipc;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Tests.Ipc;
|
||||
|
||||
/// <summary>
|
||||
/// Round-trip tests for <see cref="TcpFrameServer"/> added with the TCP transport. Each
|
||||
/// scenario binds the server on <c>127.0.0.1:0</c>, connects a real <see cref="TcpClient"/>,
|
||||
/// performs the Hello handshake, and exercises a request/reply over the wire framing — both
|
||||
/// plaintext and over TLS. These target net48 and run on Windows in CI; on the macOS dev box
|
||||
/// they only compile.
|
||||
/// </summary>
|
||||
public sealed class TcpRoundTripTests
|
||||
{
|
||||
private static readonly ILogger Quiet = Logger.None;
|
||||
|
||||
// Generous timeout so the deterministic tests don't hang CI if the server misbehaves.
|
||||
private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10);
|
||||
|
||||
/// <summary>
|
||||
/// Fake handler that echoes a fixed <see cref="ReadRawReply"/> when it sees a
|
||||
/// <see cref="MessageKind.ReadRawRequest"/>, mirroring the client correlation id.
|
||||
/// </summary>
|
||||
private sealed class EchoHandler : IFrameHandler
|
||||
{
|
||||
public Task HandleAsync(MessageKind kind, byte[] body, FrameWriter writer, CancellationToken ct)
|
||||
{
|
||||
if (kind != MessageKind.ReadRawRequest)
|
||||
return Task.CompletedTask;
|
||||
|
||||
var request = MessagePackSerializer.Deserialize<ReadRawRequest>(body);
|
||||
var reply = new ReadRawReply
|
||||
{
|
||||
CorrelationId = request.CorrelationId,
|
||||
Success = true,
|
||||
Samples = new[]
|
||||
{
|
||||
new HistorianSampleDto
|
||||
{
|
||||
ValueBytes = MessagePackSerializer.Serialize(42.0),
|
||||
Quality = 192,
|
||||
TimestampUtcTicks = new DateTime(2026, 6, 12, 0, 0, 0, DateTimeKind.Utc).Ticks,
|
||||
},
|
||||
},
|
||||
};
|
||||
return writer.WriteAsync(MessageKind.ReadRawReply, reply, ct);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Generates an in-memory self-signed RSA cert with a serverAuth EKU and a private key.</summary>
|
||||
private static X509Certificate2 MakeSelfSignedCert()
|
||||
{
|
||||
using var rsa = RSA.Create(2048);
|
||||
var req = new CertificateRequest("CN=otopcua-historian-sidecar-test", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
|
||||
req.CertificateExtensions.Add(
|
||||
new X509EnhancedKeyUsageExtension(
|
||||
new OidCollection { new Oid("1.3.6.1.5.5.7.3.1") /* serverAuth */ }, critical: false));
|
||||
using var ephemeral = req.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(1));
|
||||
// Round-trip through a PFX so the returned cert carries an exportable private key on net48.
|
||||
var pfx = ephemeral.Export(X509ContentType.Pfx, "pw");
|
||||
return new X509Certificate2(pfx, "pw", X509KeyStorageFlags.Exportable);
|
||||
}
|
||||
|
||||
/// <summary>Performs the Hello handshake on the given stream and returns the deserialized ack.</summary>
|
||||
private static async Task<HelloAck> HelloAsync(Stream stream, string secret, CancellationToken ct)
|
||||
{
|
||||
using var writer = new FrameWriter(stream, leaveOpen: true);
|
||||
using var reader = new FrameReader(stream, leaveOpen: true);
|
||||
|
||||
await writer.WriteAsync(MessageKind.Hello,
|
||||
new Hello { ProtocolMajor = Hello.CurrentMajor, PeerName = "test-client", SharedSecret = secret }, ct);
|
||||
|
||||
var ackFrame = await reader.ReadFrameAsync(ct);
|
||||
ackFrame.ShouldNotBeNull();
|
||||
ackFrame!.Value.Kind.ShouldBe(MessageKind.HelloAck);
|
||||
return MessagePackSerializer.Deserialize<HelloAck>(ackFrame.Value.Body);
|
||||
}
|
||||
|
||||
/// <summary>Wraps a connected client socket stream in an SslStream that pins the server cert thumbprint.</summary>
|
||||
private static async Task<SslStream> ClientTlsAsync(NetworkStream inner, string expectedThumbprint, CancellationToken ct)
|
||||
{
|
||||
var ssl = new SslStream(inner, leaveInnerStreamOpen: false,
|
||||
userCertificateValidationCallback: (_, cert, _, _) =>
|
||||
cert is not null &&
|
||||
string.Equals(
|
||||
cert.GetCertHashString(),
|
||||
expectedThumbprint,
|
||||
StringComparison.OrdinalIgnoreCase));
|
||||
await ssl.AuthenticateAsClientAsync("otopcua-historian-sidecar-test", clientCertificates: null,
|
||||
enabledSslProtocols: SslProtocols.Tls12, checkCertificateRevocation: false);
|
||||
return ssl;
|
||||
}
|
||||
|
||||
/// <summary>Plaintext: Hello (good secret) is accepted and a ReadRaw request is echoed back.</summary>
|
||||
[Fact]
|
||||
public async Task Plaintext_RoundTrip_HelloAcceptedAndRequestEchoed()
|
||||
{
|
||||
using var cts = new CancellationTokenSource(Timeout);
|
||||
using var server = new TcpFrameServer(IPAddress.Loopback, 0, "shh", tlsCert: null, Quiet);
|
||||
var serverTask = server.RunOneConnectionAsync(new EchoHandler(), cts.Token);
|
||||
|
||||
using var client = new TcpClient();
|
||||
await client.ConnectAsync(IPAddress.Loopback, server.BoundPort);
|
||||
var stream = client.GetStream();
|
||||
|
||||
var ack = await HelloAsync(stream, "shh", cts.Token);
|
||||
ack.Accepted.ShouldBeTrue();
|
||||
|
||||
using var writer = new FrameWriter(stream, leaveOpen: true);
|
||||
using var reader = new FrameReader(stream, leaveOpen: true);
|
||||
|
||||
await writer.WriteAsync(MessageKind.ReadRawRequest,
|
||||
new ReadRawRequest { TagName = "Tank.Level", MaxValues = 10, CorrelationId = "corr-1" }, cts.Token);
|
||||
|
||||
var replyFrame = await reader.ReadFrameAsync(cts.Token);
|
||||
replyFrame.ShouldNotBeNull();
|
||||
replyFrame!.Value.Kind.ShouldBe(MessageKind.ReadRawReply);
|
||||
var reply = MessagePackSerializer.Deserialize<ReadRawReply>(replyFrame.Value.Body);
|
||||
reply.Success.ShouldBeTrue();
|
||||
reply.CorrelationId.ShouldBe("corr-1");
|
||||
reply.Samples.Length.ShouldBe(1);
|
||||
MessagePackSerializer.Deserialize<double>(reply.Samples[0].ValueBytes!).ShouldBe(42.0);
|
||||
|
||||
client.Close();
|
||||
await serverTask;
|
||||
}
|
||||
|
||||
/// <summary>TLS: a self-signed server cert; the client pins its thumbprint; same exchange succeeds.</summary>
|
||||
[Fact]
|
||||
public async Task Tls_RoundTrip_HelloAcceptedAndRequestEchoed()
|
||||
{
|
||||
using var cts = new CancellationTokenSource(Timeout);
|
||||
using var cert = MakeSelfSignedCert();
|
||||
using var server = new TcpFrameServer(IPAddress.Loopback, 0, "shh", tlsCert: cert, Quiet);
|
||||
var serverTask = server.RunOneConnectionAsync(new EchoHandler(), cts.Token);
|
||||
|
||||
using var client = new TcpClient();
|
||||
await client.ConnectAsync(IPAddress.Loopback, server.BoundPort);
|
||||
using var ssl = await ClientTlsAsync(client.GetStream(), cert.Thumbprint, cts.Token);
|
||||
|
||||
var ack = await HelloAsync(ssl, "shh", cts.Token);
|
||||
ack.Accepted.ShouldBeTrue();
|
||||
|
||||
using var writer = new FrameWriter(ssl, leaveOpen: true);
|
||||
using var reader = new FrameReader(ssl, leaveOpen: true);
|
||||
|
||||
await writer.WriteAsync(MessageKind.ReadRawRequest,
|
||||
new ReadRawRequest { TagName = "Tank.Level", MaxValues = 10, CorrelationId = "tls-1" }, cts.Token);
|
||||
|
||||
var replyFrame = await reader.ReadFrameAsync(cts.Token);
|
||||
replyFrame.ShouldNotBeNull();
|
||||
replyFrame!.Value.Kind.ShouldBe(MessageKind.ReadRawReply);
|
||||
var reply = MessagePackSerializer.Deserialize<ReadRawReply>(replyFrame.Value.Body);
|
||||
reply.Success.ShouldBeTrue();
|
||||
reply.CorrelationId.ShouldBe("tls-1");
|
||||
|
||||
client.Close();
|
||||
await serverTask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// TLS: when the client pins a wrong thumbprint the validation callback returns false,
|
||||
/// causing <see cref="SslStream.AuthenticateAsClientAsync"/> to throw
|
||||
/// <see cref="AuthenticationException"/> before any Hello is exchanged.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Tls_BadThumbprint_AuthenticationFails()
|
||||
{
|
||||
using var cts = new CancellationTokenSource(Timeout);
|
||||
using var cert = MakeSelfSignedCert();
|
||||
using var server = new TcpFrameServer(IPAddress.Loopback, 0, "shh", tlsCert: cert, Quiet);
|
||||
var serverTask = server.RunOneConnectionAsync(new EchoHandler(), cts.Token);
|
||||
|
||||
using var client = new TcpClient();
|
||||
await client.ConnectAsync(IPAddress.Loopback, server.BoundPort);
|
||||
|
||||
// Deliberately pin the wrong thumbprint — all zeros.
|
||||
const string wrongThumbprint = "0000000000000000000000000000000000000000";
|
||||
var ssl = new SslStream(client.GetStream(), leaveInnerStreamOpen: false,
|
||||
userCertificateValidationCallback: (_, serverCert, _, _) =>
|
||||
serverCert is not null &&
|
||||
string.Equals(serverCert.GetCertHashString(), wrongThumbprint, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
await Should.ThrowAsync<AuthenticationException>(async () =>
|
||||
await ssl.AuthenticateAsClientAsync("otopcua-historian-sidecar-test", clientCertificates: null,
|
||||
enabledSslProtocols: SslProtocols.Tls12, checkCertificateRevocation: false));
|
||||
|
||||
ssl.Dispose();
|
||||
// Server will see the broken TLS handshake and end the connection; let it finish.
|
||||
try { await serverTask; } catch { /* server may throw on the aborted TLS */ }
|
||||
}
|
||||
|
||||
/// <summary>Bad secret: Hello is rejected with Accepted=false and the shared-secret-mismatch reason.</summary>
|
||||
[Fact]
|
||||
public async Task BadSecret_HelloRejected()
|
||||
{
|
||||
using var cts = new CancellationTokenSource(Timeout);
|
||||
using var server = new TcpFrameServer(IPAddress.Loopback, 0, "right-secret", tlsCert: null, Quiet);
|
||||
var serverTask = server.RunOneConnectionAsync(new EchoHandler(), cts.Token);
|
||||
|
||||
using var client = new TcpClient();
|
||||
await client.ConnectAsync(IPAddress.Loopback, server.BoundPort);
|
||||
|
||||
var ack = await HelloAsync(client.GetStream(), "wrong-secret", cts.Token);
|
||||
ack.Accepted.ShouldBeFalse();
|
||||
ack.RejectReason.ShouldBe("shared-secret-mismatch");
|
||||
|
||||
client.Close();
|
||||
await serverTask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Single-active serial accept: while client A is connected (Hello done), client B's
|
||||
/// Hello does not complete until A disconnects. The server only accepts one connection
|
||||
/// per <see cref="TcpFrameServer.RunOneConnectionAsync"/>, so B's handshake is served by
|
||||
/// the second loop iteration that runs only after A's connection ends.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task SingleActive_SecondClientHelloCompletesOnlyAfterFirstCloses()
|
||||
{
|
||||
using var cts = new CancellationTokenSource(Timeout);
|
||||
using var server = new TcpFrameServer(IPAddress.Loopback, 0, "shh", tlsCert: null, Quiet);
|
||||
|
||||
// Run the server loop: it accepts one connection at a time, serially.
|
||||
var serverLoop = server.RunAsync(new EchoHandler(), cts.Token);
|
||||
|
||||
// Client A connects and completes its Hello — it now owns the single active slot.
|
||||
using var clientA = new TcpClient();
|
||||
await clientA.ConnectAsync(IPAddress.Loopback, server.BoundPort);
|
||||
var ackA = await HelloAsync(clientA.GetStream(), "shh", cts.Token);
|
||||
ackA.Accepted.ShouldBeTrue();
|
||||
|
||||
// Client B connects. The TCP connect may complete (OS backlog) but the server is still
|
||||
// busy with A, so B's Hello round-trip must NOT complete yet.
|
||||
using var clientB = new TcpClient();
|
||||
await clientB.ConnectAsync(IPAddress.Loopback, server.BoundPort);
|
||||
var bHelloTask = HelloAsync(clientB.GetStream(), "shh", cts.Token);
|
||||
|
||||
// Give B a chance to (wrongly) complete — it must remain pending while A is connected.
|
||||
var earlyWinner = await Task.WhenAny(bHelloTask, Task.Delay(TimeSpan.FromMilliseconds(500), cts.Token));
|
||||
earlyWinner.ShouldNotBe(bHelloTask, "client B's Hello completed while client A was still connected");
|
||||
|
||||
// Now disconnect A. The server's next loop iteration accepts B and serves its Hello.
|
||||
clientA.Close();
|
||||
|
||||
var ackB = await bHelloTask;
|
||||
ackB.Accepted.ShouldBeTrue();
|
||||
|
||||
// Tear down: cancel the loop and let it unwind.
|
||||
cts.Cancel();
|
||||
try { await serverLoop; } catch (OperationCanceledException) { /* expected */ }
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -6,8 +6,8 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Smoke test confirming the sidecar project links and the test project resolves a
|
||||
/// ProjectReference to it. Real behavioural tests arrive in PR 3.2 (backend lift) and
|
||||
/// PR 3.3 (pipe server). For PR 3.1 we just verify the assembly identity is what the
|
||||
/// ProjectReference to it. Real behavioural tests live with the TCP frame server
|
||||
/// (<c>TcpFrameServer</c>); here we just verify the assembly identity is what the
|
||||
/// csproj declares.
|
||||
/// </summary>
|
||||
public class ProgramSmokeTests
|
||||
|
||||
+24
-7
@@ -19,20 +19,24 @@ public sealed class HistorianWonderwareDriverPageFormSerializationTests
|
||||
public void RoundTrip_PreservesKnownFields()
|
||||
{
|
||||
var original = new WonderwareHistorianClientOptions(
|
||||
PipeName: "otopcua-historian-prod",
|
||||
Host: "historian-prod.zb.local",
|
||||
Port: 32569,
|
||||
SharedSecret: "t0ps3cr3t",
|
||||
PeerName: "OtOpcUa-Primary",
|
||||
ConnectTimeout: TimeSpan.FromSeconds(20),
|
||||
CallTimeout: TimeSpan.FromSeconds(60))
|
||||
{
|
||||
ProbeTimeoutSeconds = 25,
|
||||
UseTls = true,
|
||||
ServerCertThumbprint = "A1B2C3D4E5F60718293A4B5C6D7E8F9012345678",
|
||||
};
|
||||
|
||||
var json = JsonSerializer.Serialize(original, _opts);
|
||||
var back = JsonSerializer.Deserialize<WonderwareHistorianClientOptions>(json, _opts);
|
||||
|
||||
back.ShouldNotBeNull();
|
||||
back.PipeName.ShouldBe("otopcua-historian-prod");
|
||||
back.Host.ShouldBe("historian-prod.zb.local");
|
||||
back.Port.ShouldBe(32569);
|
||||
back.SharedSecret.ShouldBe("t0ps3cr3t");
|
||||
back.PeerName.ShouldBe("OtOpcUa-Primary");
|
||||
back.ConnectTimeout.ShouldBe(TimeSpan.FromSeconds(20));
|
||||
@@ -40,13 +44,16 @@ public sealed class HistorianWonderwareDriverPageFormSerializationTests
|
||||
back.EffectiveConnectTimeout.ShouldBe(TimeSpan.FromSeconds(20));
|
||||
back.EffectiveCallTimeout.ShouldBe(TimeSpan.FromSeconds(60));
|
||||
back.ProbeTimeoutSeconds.ShouldBe(25);
|
||||
back.UseTls.ShouldBeTrue();
|
||||
back.ServerCertThumbprint.ShouldBe("A1B2C3D4E5F60718293A4B5C6D7E8F9012345678");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RoundTrip_NullTimeouts_UsesDefaults()
|
||||
{
|
||||
var original = new WonderwareHistorianClientOptions(
|
||||
PipeName: "otopcua-historian",
|
||||
Host: "localhost",
|
||||
Port: 32569,
|
||||
SharedSecret: "secret");
|
||||
|
||||
var json = JsonSerializer.Serialize(original, _opts);
|
||||
@@ -57,6 +64,8 @@ public sealed class HistorianWonderwareDriverPageFormSerializationTests
|
||||
back.CallTimeout.ShouldBeNull();
|
||||
back.EffectiveConnectTimeout.ShouldBe(TimeSpan.FromSeconds(10));
|
||||
back.EffectiveCallTimeout.ShouldBe(TimeSpan.FromSeconds(30));
|
||||
back.UseTls.ShouldBeFalse();
|
||||
back.ServerCertThumbprint.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -65,7 +74,8 @@ public sealed class HistorianWonderwareDriverPageFormSerializationTests
|
||||
var jsonWithExtra = """
|
||||
{
|
||||
"unknownField": "old-value",
|
||||
"pipeName": "otopcua-historian",
|
||||
"host": "historian.zb.local",
|
||||
"port": 32569,
|
||||
"sharedSecret": "s3cr3t",
|
||||
"probeTimeoutSeconds": 20
|
||||
}
|
||||
@@ -79,7 +89,8 @@ public sealed class HistorianWonderwareDriverPageFormSerializationTests
|
||||
var back = JsonSerializer.Deserialize<WonderwareHistorianClientOptions>(jsonWithExtra, optsWithSkip);
|
||||
back.ShouldNotBeNull();
|
||||
back.ProbeTimeoutSeconds.ShouldBe(20);
|
||||
back.PipeName.ShouldBe("otopcua-historian");
|
||||
back.Host.ShouldBe("historian.zb.local");
|
||||
back.Port.ShouldBe(32569);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -88,19 +99,23 @@ public sealed class HistorianWonderwareDriverPageFormSerializationTests
|
||||
// Construct a record with non-default values for every property and verify
|
||||
// that WonderwareHistorianClientFormModel.FromRecord → ToRecord is lossless.
|
||||
var original = new WonderwareHistorianClientOptions(
|
||||
PipeName: "otopcua-historian-prod",
|
||||
Host: "historian-prod.zb.local",
|
||||
Port: 32570,
|
||||
SharedSecret: "sup3rs3cr3t",
|
||||
PeerName: "OtOpcUa-Redundant",
|
||||
ConnectTimeout: TimeSpan.FromSeconds(18),
|
||||
CallTimeout: TimeSpan.FromSeconds(45))
|
||||
{
|
||||
ProbeTimeoutSeconds = 30,
|
||||
UseTls = true,
|
||||
ServerCertThumbprint = "0011223344556677889AABBCCDDEEFF001122334",
|
||||
};
|
||||
|
||||
var form = HistorianWonderwareDriverPage.WonderwareHistorianClientFormModel.FromRecord(original);
|
||||
var result = form.ToRecord();
|
||||
|
||||
result.PipeName.ShouldBe("otopcua-historian-prod");
|
||||
result.Host.ShouldBe("historian-prod.zb.local");
|
||||
result.Port.ShouldBe(32570);
|
||||
result.SharedSecret.ShouldBe("sup3rs3cr3t");
|
||||
result.PeerName.ShouldBe("OtOpcUa-Redundant");
|
||||
result.ConnectTimeout.ShouldBe(TimeSpan.FromSeconds(18));
|
||||
@@ -108,5 +123,7 @@ public sealed class HistorianWonderwareDriverPageFormSerializationTests
|
||||
result.EffectiveConnectTimeout.ShouldBe(TimeSpan.FromSeconds(18));
|
||||
result.EffectiveCallTimeout.ShouldBe(TimeSpan.FromSeconds(45));
|
||||
result.ProbeTimeoutSeconds.ShouldBe(30);
|
||||
result.UseTls.ShouldBeTrue();
|
||||
result.ServerCertThumbprint.ShouldBe("0011223344556677889AABBCCDDEEFF001122334");
|
||||
}
|
||||
}
|
||||
|
||||
+20
@@ -169,4 +169,24 @@ public sealed class AlarmHistorianRegistrationTests
|
||||
warnings.ShouldContain(w => w.Contains("DatabasePath"));
|
||||
warnings.Count.ShouldBeGreaterThanOrEqualTo(2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Section_binds_tcp_host_port_tls_fields()
|
||||
{
|
||||
var config = ConfigFrom(new Dictionary<string, string?>
|
||||
{
|
||||
["AlarmHistorian:Host"] = "historian.example.com",
|
||||
["AlarmHistorian:Port"] = "12345",
|
||||
["AlarmHistorian:UseTls"] = "true",
|
||||
["AlarmHistorian:ServerCertThumbprint"] = "AABBCCDDEEFF",
|
||||
});
|
||||
|
||||
var opts = config.GetSection(AlarmHistorianOptions.SectionName).Get<AlarmHistorianOptions>();
|
||||
|
||||
opts.ShouldNotBeNull();
|
||||
opts.Host.ShouldBe("historian.example.com");
|
||||
opts.Port.ShouldBe(12345);
|
||||
opts.UseTls.ShouldBeTrue();
|
||||
opts.ServerCertThumbprint.ShouldBe("AABBCCDDEEFF");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user