Compare commits
10 Commits
phase-6-4-
...
v2-release
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a8401ab8fd | ||
| 37ba9e8d14 | |||
|
|
19a0bfcc43 | ||
| fc7e18c7f5 | |||
|
|
ba42967943 | ||
| b912969805 | |||
|
|
f8d5b0fdbb | ||
| cc069509cd | |||
|
|
3b2d0474a7 | ||
| e1d38ecc66 |
106
docs/v2/v2-release-readiness.md
Normal file
106
docs/v2/v2-release-readiness.md
Normal file
@@ -0,0 +1,106 @@
|
|||||||
|
# v2 Release Readiness
|
||||||
|
|
||||||
|
> **Last updated**: 2026-04-19 (release blockers #1 + #2 closed; Phase 6.3 redundancy runtime is the last)
|
||||||
|
> **Status**: **NOT YET RELEASE-READY** — one of three release blockers remains (Phase 6.3 Streams A/C/F redundancy-coordinator + OPC UA node wiring + client interop).
|
||||||
|
|
||||||
|
This doc is the single view of where v2 stands against its release criteria. Update it whenever a deferred follow-up closes or a new release blocker is discovered.
|
||||||
|
|
||||||
|
## Release-readiness dashboard
|
||||||
|
|
||||||
|
| Phase | Shipped | Status |
|
||||||
|
|---|---|---|
|
||||||
|
| Phase 0 — Rename + entry gate | ✓ | Shipped |
|
||||||
|
| Phase 1 — Configuration + Admin scaffold | ✓ | Shipped (some UI items deferred to 6.4) |
|
||||||
|
| Phase 2 — Galaxy driver split (Proxy/Host/Shared) | ✓ | Shipped |
|
||||||
|
| Phase 3 — OPC UA server + LDAP + security profiles | ✓ | Shipped |
|
||||||
|
| Phase 4 — Redundancy scaffold (entities + endpoints) | ✓ | Shipped (runtime closes in 6.3) |
|
||||||
|
| Phase 5 — Drivers | ⚠ partial | Galaxy / Modbus / S7 / OpcUaClient shipped; AB CIP / AB Legacy / TwinCAT / FOCAS deferred (task #120) |
|
||||||
|
| Phase 6.1 — Resilience & Observability | ✓ | **SHIPPED** (PRs #78–83) |
|
||||||
|
| Phase 6.2 — Authorization runtime | ◐ core | **SHIPPED (core)** (PRs #84–88); dispatch wiring + Admin UI deferred |
|
||||||
|
| Phase 6.3 — Redundancy runtime | ◐ core | **SHIPPED (core)** (PRs #89–90); coordinator + UA-node wiring + Admin UI + interop deferred |
|
||||||
|
| Phase 6.4 — Admin UI completion | ◐ data layer | **SHIPPED (data layer)** (PRs #91–92); Blazor UI + OPC 40010 address-space wiring deferred |
|
||||||
|
|
||||||
|
**Aggregate test counts:** 906 baseline (pre-Phase-6) → **1159 passing** across Phase 6. One pre-existing Client.CLI `SubscribeCommandTests.Execute_PrintsSubscriptionMessage` flake tracked separately.
|
||||||
|
|
||||||
|
## Release blockers (must close before v2 GA)
|
||||||
|
|
||||||
|
Ordered by severity + impact on production fitness.
|
||||||
|
|
||||||
|
### ~~Security — Phase 6.2 dispatch wiring~~ (task #143 — **CLOSED** 2026-04-19, PR #94)
|
||||||
|
|
||||||
|
**Closed**. `AuthorizationGate` + `NodeScopeResolver` now thread through `OpcUaApplicationHost → OtOpcUaServer → DriverNodeManager`. `OnReadValue` + `OnWriteValue` + all four HistoryRead paths call `gate.IsAllowed(identity, operation, scope)` before the invoker. Production deployments activate enforcement by constructing `OpcUaApplicationHost` with an `AuthorizationGate(StrictMode: true)` + populating the `NodeAcl` table.
|
||||||
|
|
||||||
|
Additional Stream C surfaces (not release-blocking, hardening only):
|
||||||
|
|
||||||
|
- Browse + TranslateBrowsePathsToNodeIds gating with ancestor-visibility logic per `acl-design.md` §Browse.
|
||||||
|
- CreateMonitoredItems + TransferSubscriptions gating with per-item `(AuthGenerationId, MembershipVersion)` stamp so revoked grants surface `BadUserAccessDenied` within one publish cycle (decision #153).
|
||||||
|
- Alarm Acknowledge / Confirm / Shelve gating.
|
||||||
|
- Call (method invocation) gating.
|
||||||
|
- Finer-grained scope resolution — current `NodeScopeResolver` returns a flat cluster-level scope. Joining against the live Configuration DB to populate UnsArea / UnsLine / Equipment path is tracked as Stream C.12.
|
||||||
|
- 3-user integration matrix covering every operation × allow/deny.
|
||||||
|
|
||||||
|
These are additional hardening — the three highest-value surfaces (Read / Write / HistoryRead) are now gated, which covers the base-security gap for v2 GA.
|
||||||
|
|
||||||
|
### ~~Config fallback — Phase 6.1 Stream D wiring~~ (task #136 — **CLOSED** 2026-04-19, PR #96)
|
||||||
|
|
||||||
|
**Closed**. `SealedBootstrap` consumes `ResilientConfigReader` + `GenerationSealedCache` + `StaleConfigFlag` end-to-end: bootstrap calls go through the timeout → retry → fallback-to-sealed pipeline; every central-DB success writes a fresh sealed snapshot so the next cache-miss has a known-good fallback; `StaleConfigFlag.IsStale` is now consumed by `HealthEndpointsHost.usingStaleConfig` so `/healthz` body reports reality.
|
||||||
|
|
||||||
|
Production activation: Program.cs switches `NodeBootstrap → SealedBootstrap` + constructs `OpcUaApplicationHost` with the `StaleConfigFlag` as an optional ctor parameter.
|
||||||
|
|
||||||
|
Remaining follow-ups (hardening, not release-blocking):
|
||||||
|
|
||||||
|
- A `HostedService` that polls `sp_GetCurrentGenerationForCluster` periodically so peer-published generations land in this node's cache without a restart.
|
||||||
|
- Richer snapshot payload via `sp_GetGenerationContent` so fallback can serve the full generation content (DriverInstance enumeration, ACL rows, etc.) from the sealed cache alone.
|
||||||
|
|
||||||
|
### Redundancy — Phase 6.3 Streams A/C/F (tasks #145, #147, #150)
|
||||||
|
|
||||||
|
`ServiceLevelCalculator` + `RecoveryStateManager` + `ApplyLeaseRegistry` exist as pure logic. **No code invokes them at runtime.** The OPC UA server still publishes a static `ServiceLevel`; `ServerUriArray` still carries only self; no coordinator reads cluster topology; no peer probing.
|
||||||
|
|
||||||
|
Closing this requires:
|
||||||
|
|
||||||
|
- `RedundancyCoordinator` singleton reads `ClusterNode` + peer list at startup (Stream A).
|
||||||
|
- `PeerHttpProbeLoop` + `PeerUaProbeLoop` feed the calculator.
|
||||||
|
- OPC UA node wiring: `ServiceLevel` becomes a live `BaseDataVariable` on calculator observer output; `ServerUriArray` includes self + peers; `RedundancySupport` static from `RedundancyMode` (Stream C).
|
||||||
|
- `sp_PublishGeneration` wraps in `await using var lease = coordinator.BeginApplyLease(...)` so the `PrimaryMidApply` band fires during actual publishes.
|
||||||
|
- Client interop matrix validation against Ignition / Kepware / Aveva OI Gateway (Stream F).
|
||||||
|
|
||||||
|
### Remaining drivers (task #120)
|
||||||
|
|
||||||
|
AB CIP, AB Legacy, TwinCAT ADS, FOCAS drivers are planned but unshipped. Decision pending on whether these are release-blocking for v2 GA or can slip to a v2.1 follow-up.
|
||||||
|
|
||||||
|
## Nice-to-haves (not release-blocking)
|
||||||
|
|
||||||
|
- **Admin UI** — Phase 6.1 Stream E.2/E.3 (`/hosts` column refresh), Phase 6.2 Stream D (`RoleGrantsTab` + `AclsTab` Probe), Phase 6.3 Stream E (`RedundancyTab`), Phase 6.4 Streams A/B UI pieces, Stream C DiffViewer, Stream D `IdentificationFields.razor`. Tasks #134, #144, #149, #153, #155, #156, #157.
|
||||||
|
- **Background services** — Phase 6.1 Stream B.4 `ScheduledRecycleScheduler` HostedService (task #137), Phase 6.1 Stream A analyzer (task #135 — Roslyn analyzer asserting every capability surface routes through `CapabilityInvoker`).
|
||||||
|
- **Multi-host dispatch** — Phase 6.1 Stream A follow-up (task #135). Currently every driver gets a single pipeline keyed on `driver.DriverInstanceId`; multi-host drivers (Modbus with N PLCs) need per-PLC host resolution so failing PLCs trip per-PLC breakers without poisoning siblings. Decision #144 requires this but we haven't wired it yet.
|
||||||
|
|
||||||
|
## Running the release-readiness check
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pwsh ./scripts/compliance/phase-6-all.ps1
|
||||||
|
```
|
||||||
|
|
||||||
|
This meta-runner invokes each `phase-6-N-compliance.ps1` script in sequence and reports an aggregate PASS/FAIL. It is the single-command verification that what we claim is shipped still compiles + tests pass + the plan-level invariants are still satisfied.
|
||||||
|
|
||||||
|
Exit 0 = every phase passes its compliance checks + no test-count regression.
|
||||||
|
|
||||||
|
## Release-readiness exit criteria
|
||||||
|
|
||||||
|
v2 GA requires all of the following:
|
||||||
|
|
||||||
|
- [ ] All four Phase 6.N compliance scripts exit 0.
|
||||||
|
- [ ] `dotnet test ZB.MOM.WW.OtOpcUa.slnx` passes with ≤ 1 known-flake failure.
|
||||||
|
- [ ] Release blockers listed above all closed (or consciously deferred to v2.1 with a written decision).
|
||||||
|
- [ ] Production deployment checklist (separate doc) signed off by Fleet Admin.
|
||||||
|
- [ ] At least one end-to-end integration run against the live Galaxy on the dev box succeeds.
|
||||||
|
- [ ] OPC UA conformance test (CTT or UA Compliance Test Tool) passes against the live endpoint.
|
||||||
|
- [ ] Non-transparent redundancy cutover validated with at least one production client (Ignition 8.3 recommended — see decision #85).
|
||||||
|
|
||||||
|
## Change log
|
||||||
|
|
||||||
|
- **2026-04-19** — Release blocker #2 **closed** (PR #96). `SealedBootstrap` consumes `ResilientConfigReader` + `GenerationSealedCache` + `StaleConfigFlag`; `/healthz` now surfaces the stale flag. Remaining follow-ups (periodic poller + richer snapshot payload) downgraded to hardening.
|
||||||
|
- **2026-04-19** — Release blocker #1 **closed** (PR #94). `AuthorizationGate` wired into `DriverNodeManager` Read / Write / HistoryRead dispatch. Remaining Stream C surfaces (Browse / Subscribe / Alarm / Call + finer-grained scope resolution) downgraded to hardening follow-ups — no longer release-blocking.
|
||||||
|
- **2026-04-19** — Phase 6.4 data layer merged (PRs #91–92). Phase 6 core complete. Capstone doc created.
|
||||||
|
- **2026-04-19** — Phase 6.3 core merged (PRs #89–90). `ServiceLevelCalculator` + `RecoveryStateManager` + `ApplyLeaseRegistry` land as pure logic; coordinator / UA-node wiring / Admin UI / interop deferred.
|
||||||
|
- **2026-04-19** — Phase 6.2 core merged (PRs #84–88). `AuthorizationGate` + `TriePermissionEvaluator` + `LdapGroupRoleMapping` land; dispatch wiring + Admin UI deferred.
|
||||||
|
- **2026-04-19** — Phase 6.1 shipped (PRs #78–83). Polly resilience + Tier A/B/C stability + health endpoints + LiteDB generation-sealed cache + Admin `/hosts` data layer all live.
|
||||||
77
scripts/compliance/phase-6-all.ps1
Normal file
77
scripts/compliance/phase-6-all.ps1
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
<#
|
||||||
|
.SYNOPSIS
|
||||||
|
Meta-runner that invokes every per-phase Phase 6.x compliance script and
|
||||||
|
reports an aggregate verdict.
|
||||||
|
|
||||||
|
.DESCRIPTION
|
||||||
|
Runs phase-6-1-compliance.ps1, phase-6-2, phase-6-3, phase-6-4 in sequence.
|
||||||
|
Each sub-script returns its own exit code; this wrapper aggregates them.
|
||||||
|
Useful before a v2 release tag + as the `dotnet test` companion in CI.
|
||||||
|
|
||||||
|
.NOTES
|
||||||
|
Usage: pwsh ./scripts/compliance/phase-6-all.ps1
|
||||||
|
Exit: 0 = every phase passed; 1 = one or more phases failed
|
||||||
|
#>
|
||||||
|
[CmdletBinding()]
|
||||||
|
param()
|
||||||
|
|
||||||
|
$ErrorActionPreference = 'Continue'
|
||||||
|
|
||||||
|
$phases = @(
|
||||||
|
@{ Name = 'Phase 6.1 - Resilience & Observability'; Script = 'phase-6-1-compliance.ps1' },
|
||||||
|
@{ Name = 'Phase 6.2 - Authorization runtime'; Script = 'phase-6-2-compliance.ps1' },
|
||||||
|
@{ Name = 'Phase 6.3 - Redundancy runtime'; Script = 'phase-6-3-compliance.ps1' },
|
||||||
|
@{ Name = 'Phase 6.4 - Admin UI completion'; Script = 'phase-6-4-compliance.ps1' }
|
||||||
|
)
|
||||||
|
|
||||||
|
$results = @()
|
||||||
|
$startedAt = Get-Date
|
||||||
|
|
||||||
|
foreach ($phase in $phases) {
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host "=============================================================" -ForegroundColor DarkGray
|
||||||
|
Write-Host ("Running {0}" -f $phase.Name) -ForegroundColor Cyan
|
||||||
|
Write-Host "=============================================================" -ForegroundColor DarkGray
|
||||||
|
|
||||||
|
$scriptPath = Join-Path $PSScriptRoot $phase.Script
|
||||||
|
if (-not (Test-Path $scriptPath)) {
|
||||||
|
Write-Host (" [MISSING] {0}" -f $phase.Script) -ForegroundColor Red
|
||||||
|
$results += @{ Name = $phase.Name; Exit = 2 }
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
# Invoke each sub-script in its own powershell.exe process so its local
|
||||||
|
# $ErrorActionPreference + exit-code semantics can't interfere with the meta-runner's
|
||||||
|
# state. Slower (one process spawn per phase) but makes aggregate PASS/FAIL match
|
||||||
|
# standalone runs exactly.
|
||||||
|
& powershell.exe -NoProfile -ExecutionPolicy Bypass -File $scriptPath
|
||||||
|
$exitCode = $LASTEXITCODE
|
||||||
|
$results += @{ Name = $phase.Name; Exit = $exitCode }
|
||||||
|
}
|
||||||
|
|
||||||
|
$elapsed = (Get-Date) - $startedAt
|
||||||
|
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host "=============================================================" -ForegroundColor DarkGray
|
||||||
|
Write-Host "Phase 6 compliance aggregate" -ForegroundColor Cyan
|
||||||
|
Write-Host "=============================================================" -ForegroundColor DarkGray
|
||||||
|
|
||||||
|
$totalFailures = 0
|
||||||
|
foreach ($r in $results) {
|
||||||
|
$colour = if ($r.Exit -eq 0) { 'Green' } else { 'Red' }
|
||||||
|
$tag = if ($r.Exit -eq 0) { 'PASS' } else { "FAIL (exit=$($r.Exit))" }
|
||||||
|
Write-Host (" [{0}] {1}" -f $tag, $r.Name) -ForegroundColor $colour
|
||||||
|
if ($r.Exit -ne 0) { $totalFailures++ }
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host ("Elapsed: {0:N1} s" -f $elapsed.TotalSeconds) -ForegroundColor DarkGray
|
||||||
|
|
||||||
|
if ($totalFailures -eq 0) {
|
||||||
|
Write-Host "Phase 6 aggregate: PASS" -ForegroundColor Green
|
||||||
|
exit 0
|
||||||
|
}
|
||||||
|
Write-Host ("Phase 6 aggregate: {0} phase(s) FAILED" -f $totalFailures) -ForegroundColor Red
|
||||||
|
exit 1
|
||||||
@@ -3,6 +3,7 @@ using Microsoft.Extensions.Logging;
|
|||||||
using Opc.Ua;
|
using Opc.Ua;
|
||||||
using Opc.Ua.Server;
|
using Opc.Ua.Server;
|
||||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||||
|
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
|
||||||
using ZB.MOM.WW.OtOpcUa.Core.Resilience;
|
using ZB.MOM.WW.OtOpcUa.Core.Resilience;
|
||||||
using ZB.MOM.WW.OtOpcUa.Server.Security;
|
using ZB.MOM.WW.OtOpcUa.Server.Security;
|
||||||
using DriverWriteRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.WriteRequest;
|
using DriverWriteRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.WriteRequest;
|
||||||
@@ -59,14 +60,24 @@ public sealed class DriverNodeManager : CustomNodeManager2, IAddressSpaceBuilder
|
|||||||
// returns a child builder per Folder call and the caller threads nesting through those references.
|
// returns a child builder per Folder call and the caller threads nesting through those references.
|
||||||
private FolderState _currentFolder = null!;
|
private FolderState _currentFolder = null!;
|
||||||
|
|
||||||
|
// Phase 6.2 Stream C follow-up — optional gate + scope resolver. When both are null
|
||||||
|
// the old pre-Phase-6.2 dispatch path runs unchanged (backwards compat for every
|
||||||
|
// integration test that constructs DriverNodeManager without the gate). When wired,
|
||||||
|
// OnReadValue / OnWriteValue / HistoryRead all consult the gate before the invoker call.
|
||||||
|
private readonly AuthorizationGate? _authzGate;
|
||||||
|
private readonly NodeScopeResolver? _scopeResolver;
|
||||||
|
|
||||||
public DriverNodeManager(IServerInternal server, ApplicationConfiguration configuration,
|
public DriverNodeManager(IServerInternal server, ApplicationConfiguration configuration,
|
||||||
IDriver driver, CapabilityInvoker invoker, ILogger<DriverNodeManager> logger)
|
IDriver driver, CapabilityInvoker invoker, ILogger<DriverNodeManager> logger,
|
||||||
|
AuthorizationGate? authzGate = null, NodeScopeResolver? scopeResolver = null)
|
||||||
: base(server, configuration, namespaceUris: $"urn:OtOpcUa:{driver.DriverInstanceId}")
|
: base(server, configuration, namespaceUris: $"urn:OtOpcUa:{driver.DriverInstanceId}")
|
||||||
{
|
{
|
||||||
_driver = driver;
|
_driver = driver;
|
||||||
_readable = driver as IReadable;
|
_readable = driver as IReadable;
|
||||||
_writable = driver as IWritable;
|
_writable = driver as IWritable;
|
||||||
_invoker = invoker;
|
_invoker = invoker;
|
||||||
|
_authzGate = authzGate;
|
||||||
|
_scopeResolver = scopeResolver;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -197,6 +208,20 @@ public sealed class DriverNodeManager : CustomNodeManager2, IAddressSpaceBuilder
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
var fullRef = node.NodeId.Identifier as string ?? "";
|
var fullRef = node.NodeId.Identifier as string ?? "";
|
||||||
|
|
||||||
|
// Phase 6.2 Stream C — authorization gate. Runs ahead of the invoker so a denied
|
||||||
|
// read never hits the driver. Returns true in lax mode when identity lacks LDAP
|
||||||
|
// groups; strict mode denies those cases. See AuthorizationGate remarks.
|
||||||
|
if (_authzGate is not null && _scopeResolver is not null)
|
||||||
|
{
|
||||||
|
var scope = _scopeResolver.Resolve(fullRef);
|
||||||
|
if (!_authzGate.IsAllowed(context.UserIdentity, OpcUaOperation.Read, scope))
|
||||||
|
{
|
||||||
|
statusCode = StatusCodes.BadUserAccessDenied;
|
||||||
|
return ServiceResult.Good;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
var result = _invoker.ExecuteAsync(
|
var result = _invoker.ExecuteAsync(
|
||||||
DriverCapability.Read,
|
DriverCapability.Read,
|
||||||
_driver.DriverInstanceId,
|
_driver.DriverInstanceId,
|
||||||
@@ -390,6 +415,23 @@ public sealed class DriverNodeManager : CustomNodeManager2, IAddressSpaceBuilder
|
|||||||
fullRef, classification, string.Join(",", roles));
|
fullRef, classification, string.Join(",", roles));
|
||||||
return new ServiceResult(StatusCodes.BadUserAccessDenied);
|
return new ServiceResult(StatusCodes.BadUserAccessDenied);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Phase 6.2 Stream C — additive gate check. The classification/role check above
|
||||||
|
// is the pre-Phase-6.2 baseline; the gate adds per-tag ACL enforcement on top. In
|
||||||
|
// lax mode (default during rollout) the gate falls through when the identity
|
||||||
|
// lacks LDAP groups, so existing integration tests keep passing.
|
||||||
|
if (_authzGate is not null && _scopeResolver is not null)
|
||||||
|
{
|
||||||
|
var scope = _scopeResolver.Resolve(fullRef!);
|
||||||
|
var writeOp = WriteAuthzPolicy.ToOpcUaOperation(classification);
|
||||||
|
if (!_authzGate.IsAllowed(context.UserIdentity, writeOp, scope))
|
||||||
|
{
|
||||||
|
_logger.LogInformation(
|
||||||
|
"Write denied by ACL gate for {FullRef}: operation={Op} classification={Classification}",
|
||||||
|
fullRef, writeOp, classification);
|
||||||
|
return new ServiceResult(StatusCodes.BadUserAccessDenied);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
try
|
try
|
||||||
@@ -482,6 +524,16 @@ public sealed class DriverNodeManager : CustomNodeManager2, IAddressSpaceBuilder
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (_authzGate is not null && _scopeResolver is not null)
|
||||||
|
{
|
||||||
|
var historyScope = _scopeResolver.Resolve(fullRef);
|
||||||
|
if (!_authzGate.IsAllowed(context.UserIdentity, OpcUaOperation.HistoryRead, historyScope))
|
||||||
|
{
|
||||||
|
WriteAccessDenied(results, errors, i);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var driverResult = _invoker.ExecuteAsync(
|
var driverResult = _invoker.ExecuteAsync(
|
||||||
@@ -546,6 +598,16 @@ public sealed class DriverNodeManager : CustomNodeManager2, IAddressSpaceBuilder
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (_authzGate is not null && _scopeResolver is not null)
|
||||||
|
{
|
||||||
|
var historyScope = _scopeResolver.Resolve(fullRef);
|
||||||
|
if (!_authzGate.IsAllowed(context.UserIdentity, OpcUaOperation.HistoryRead, historyScope))
|
||||||
|
{
|
||||||
|
WriteAccessDenied(results, errors, i);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var driverResult = _invoker.ExecuteAsync(
|
var driverResult = _invoker.ExecuteAsync(
|
||||||
@@ -603,6 +665,16 @@ public sealed class DriverNodeManager : CustomNodeManager2, IAddressSpaceBuilder
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (_authzGate is not null && _scopeResolver is not null)
|
||||||
|
{
|
||||||
|
var historyScope = _scopeResolver.Resolve(fullRef);
|
||||||
|
if (!_authzGate.IsAllowed(context.UserIdentity, OpcUaOperation.HistoryRead, historyScope))
|
||||||
|
{
|
||||||
|
WriteAccessDenied(results, errors, i);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var driverResult = _invoker.ExecuteAsync(
|
var driverResult = _invoker.ExecuteAsync(
|
||||||
@@ -660,6 +732,19 @@ public sealed class DriverNodeManager : CustomNodeManager2, IAddressSpaceBuilder
|
|||||||
// "all sources in the driver's namespace" per the IHistoryProvider contract.
|
// "all sources in the driver's namespace" per the IHistoryProvider contract.
|
||||||
var fullRef = ResolveFullRef(handle);
|
var fullRef = ResolveFullRef(handle);
|
||||||
|
|
||||||
|
// fullRef is null for event-history queries that target a notifier (driver root).
|
||||||
|
// Those are cluster-wide reads + need a different scope shape; skip the gate here
|
||||||
|
// and let the driver-level authz handle them. Non-null path gets per-node gating.
|
||||||
|
if (fullRef is not null && _authzGate is not null && _scopeResolver is not null)
|
||||||
|
{
|
||||||
|
var historyScope = _scopeResolver.Resolve(fullRef);
|
||||||
|
if (!_authzGate.IsAllowed(context.UserIdentity, OpcUaOperation.HistoryRead, historyScope))
|
||||||
|
{
|
||||||
|
WriteAccessDenied(results, errors, i);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var driverResult = _invoker.ExecuteAsync(
|
var driverResult = _invoker.ExecuteAsync(
|
||||||
@@ -721,6 +806,12 @@ public sealed class DriverNodeManager : CustomNodeManager2, IAddressSpaceBuilder
|
|||||||
errors[i] = StatusCodes.BadInternalError;
|
errors[i] = StatusCodes.BadInternalError;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static void WriteAccessDenied(IList<OpcHistoryReadResult> results, IList<ServiceResult> errors, int i)
|
||||||
|
{
|
||||||
|
results[i] = new OpcHistoryReadResult { StatusCode = StatusCodes.BadUserAccessDenied };
|
||||||
|
errors[i] = StatusCodes.BadUserAccessDenied;
|
||||||
|
}
|
||||||
|
|
||||||
private static void WriteNodeIdUnknown(IList<OpcHistoryReadResult> results, IList<ServiceResult> errors, int i)
|
private static void WriteNodeIdUnknown(IList<OpcHistoryReadResult> results, IList<ServiceResult> errors, int i)
|
||||||
{
|
{
|
||||||
WriteNodeIdUnknown(results, errors, i);
|
WriteNodeIdUnknown(results, errors, i);
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Opc.Ua;
|
using Opc.Ua;
|
||||||
using Opc.Ua.Configuration;
|
using Opc.Ua.Configuration;
|
||||||
|
using ZB.MOM.WW.OtOpcUa.Configuration.LocalCache;
|
||||||
using ZB.MOM.WW.OtOpcUa.Core.Hosting;
|
using ZB.MOM.WW.OtOpcUa.Core.Hosting;
|
||||||
using ZB.MOM.WW.OtOpcUa.Core.OpcUa;
|
using ZB.MOM.WW.OtOpcUa.Core.OpcUa;
|
||||||
using ZB.MOM.WW.OtOpcUa.Core.Resilience;
|
using ZB.MOM.WW.OtOpcUa.Core.Resilience;
|
||||||
@@ -23,6 +24,9 @@ public sealed class OpcUaApplicationHost : IAsyncDisposable
|
|||||||
private readonly DriverHost _driverHost;
|
private readonly DriverHost _driverHost;
|
||||||
private readonly IUserAuthenticator _authenticator;
|
private readonly IUserAuthenticator _authenticator;
|
||||||
private readonly DriverResiliencePipelineBuilder _pipelineBuilder;
|
private readonly DriverResiliencePipelineBuilder _pipelineBuilder;
|
||||||
|
private readonly AuthorizationGate? _authzGate;
|
||||||
|
private readonly NodeScopeResolver? _scopeResolver;
|
||||||
|
private readonly StaleConfigFlag? _staleConfigFlag;
|
||||||
private readonly ILoggerFactory _loggerFactory;
|
private readonly ILoggerFactory _loggerFactory;
|
||||||
private readonly ILogger<OpcUaApplicationHost> _logger;
|
private readonly ILogger<OpcUaApplicationHost> _logger;
|
||||||
private ApplicationInstance? _application;
|
private ApplicationInstance? _application;
|
||||||
@@ -32,12 +36,18 @@ public sealed class OpcUaApplicationHost : IAsyncDisposable
|
|||||||
|
|
||||||
public OpcUaApplicationHost(OpcUaServerOptions options, DriverHost driverHost,
|
public OpcUaApplicationHost(OpcUaServerOptions options, DriverHost driverHost,
|
||||||
IUserAuthenticator authenticator, ILoggerFactory loggerFactory, ILogger<OpcUaApplicationHost> logger,
|
IUserAuthenticator authenticator, ILoggerFactory loggerFactory, ILogger<OpcUaApplicationHost> logger,
|
||||||
DriverResiliencePipelineBuilder? pipelineBuilder = null)
|
DriverResiliencePipelineBuilder? pipelineBuilder = null,
|
||||||
|
AuthorizationGate? authzGate = null,
|
||||||
|
NodeScopeResolver? scopeResolver = null,
|
||||||
|
StaleConfigFlag? staleConfigFlag = null)
|
||||||
{
|
{
|
||||||
_options = options;
|
_options = options;
|
||||||
_driverHost = driverHost;
|
_driverHost = driverHost;
|
||||||
_authenticator = authenticator;
|
_authenticator = authenticator;
|
||||||
_pipelineBuilder = pipelineBuilder ?? new DriverResiliencePipelineBuilder();
|
_pipelineBuilder = pipelineBuilder ?? new DriverResiliencePipelineBuilder();
|
||||||
|
_authzGate = authzGate;
|
||||||
|
_scopeResolver = scopeResolver;
|
||||||
|
_staleConfigFlag = staleConfigFlag;
|
||||||
_loggerFactory = loggerFactory;
|
_loggerFactory = loggerFactory;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
}
|
}
|
||||||
@@ -64,7 +74,8 @@ public sealed class OpcUaApplicationHost : IAsyncDisposable
|
|||||||
throw new InvalidOperationException(
|
throw new InvalidOperationException(
|
||||||
$"OPC UA application certificate could not be validated or created in {_options.PkiStoreRoot}");
|
$"OPC UA application certificate could not be validated or created in {_options.PkiStoreRoot}");
|
||||||
|
|
||||||
_server = new OtOpcUaServer(_driverHost, _authenticator, _pipelineBuilder, _loggerFactory);
|
_server = new OtOpcUaServer(_driverHost, _authenticator, _pipelineBuilder, _loggerFactory,
|
||||||
|
authzGate: _authzGate, scopeResolver: _scopeResolver);
|
||||||
await _application.Start(_server).ConfigureAwait(false);
|
await _application.Start(_server).ConfigureAwait(false);
|
||||||
|
|
||||||
_logger.LogInformation("OPC UA server started — endpoint={Endpoint} driverCount={Count}",
|
_logger.LogInformation("OPC UA server started — endpoint={Endpoint} driverCount={Count}",
|
||||||
@@ -77,6 +88,7 @@ public sealed class OpcUaApplicationHost : IAsyncDisposable
|
|||||||
_healthHost = new HealthEndpointsHost(
|
_healthHost = new HealthEndpointsHost(
|
||||||
_driverHost,
|
_driverHost,
|
||||||
_loggerFactory.CreateLogger<HealthEndpointsHost>(),
|
_loggerFactory.CreateLogger<HealthEndpointsHost>(),
|
||||||
|
usingStaleConfig: _staleConfigFlag is null ? null : () => _staleConfigFlag.IsStale,
|
||||||
prefix: _options.HealthEndpointsPrefix);
|
prefix: _options.HealthEndpointsPrefix);
|
||||||
_healthHost.Start();
|
_healthHost.Start();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,6 +21,8 @@ public sealed class OtOpcUaServer : StandardServer
|
|||||||
private readonly DriverHost _driverHost;
|
private readonly DriverHost _driverHost;
|
||||||
private readonly IUserAuthenticator _authenticator;
|
private readonly IUserAuthenticator _authenticator;
|
||||||
private readonly DriverResiliencePipelineBuilder _pipelineBuilder;
|
private readonly DriverResiliencePipelineBuilder _pipelineBuilder;
|
||||||
|
private readonly AuthorizationGate? _authzGate;
|
||||||
|
private readonly NodeScopeResolver? _scopeResolver;
|
||||||
private readonly ILoggerFactory _loggerFactory;
|
private readonly ILoggerFactory _loggerFactory;
|
||||||
private readonly List<DriverNodeManager> _driverNodeManagers = new();
|
private readonly List<DriverNodeManager> _driverNodeManagers = new();
|
||||||
|
|
||||||
@@ -28,11 +30,15 @@ public sealed class OtOpcUaServer : StandardServer
|
|||||||
DriverHost driverHost,
|
DriverHost driverHost,
|
||||||
IUserAuthenticator authenticator,
|
IUserAuthenticator authenticator,
|
||||||
DriverResiliencePipelineBuilder pipelineBuilder,
|
DriverResiliencePipelineBuilder pipelineBuilder,
|
||||||
ILoggerFactory loggerFactory)
|
ILoggerFactory loggerFactory,
|
||||||
|
AuthorizationGate? authzGate = null,
|
||||||
|
NodeScopeResolver? scopeResolver = null)
|
||||||
{
|
{
|
||||||
_driverHost = driverHost;
|
_driverHost = driverHost;
|
||||||
_authenticator = authenticator;
|
_authenticator = authenticator;
|
||||||
_pipelineBuilder = pipelineBuilder;
|
_pipelineBuilder = pipelineBuilder;
|
||||||
|
_authzGate = authzGate;
|
||||||
|
_scopeResolver = scopeResolver;
|
||||||
_loggerFactory = loggerFactory;
|
_loggerFactory = loggerFactory;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -58,7 +64,8 @@ public sealed class OtOpcUaServer : StandardServer
|
|||||||
// DriverInstance row in a follow-up PR; for now every driver gets Tier A defaults.
|
// DriverInstance row in a follow-up PR; for now every driver gets Tier A defaults.
|
||||||
var options = new DriverResilienceOptions { Tier = DriverTier.A };
|
var options = new DriverResilienceOptions { Tier = DriverTier.A };
|
||||||
var invoker = new CapabilityInvoker(_pipelineBuilder, driver.DriverInstanceId, () => options, driver.DriverType);
|
var invoker = new CapabilityInvoker(_pipelineBuilder, driver.DriverInstanceId, () => options, driver.DriverType);
|
||||||
var manager = new DriverNodeManager(server, configuration, driver, invoker, logger);
|
var manager = new DriverNodeManager(server, configuration, driver, invoker, logger,
|
||||||
|
authzGate: _authzGate, scopeResolver: _scopeResolver);
|
||||||
_driverNodeManagers.Add(manager);
|
_driverNodeManagers.Add(manager);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
100
src/ZB.MOM.WW.OtOpcUa.Server/SealedBootstrap.cs
Normal file
100
src/ZB.MOM.WW.OtOpcUa.Server/SealedBootstrap.cs
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using Microsoft.Data.SqlClient;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using ZB.MOM.WW.OtOpcUa.Configuration.LocalCache;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.OtOpcUa.Server;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Phase 6.1 Stream D consumption hook — bootstraps the node's current generation through
|
||||||
|
/// the <see cref="ResilientConfigReader"/> pipeline + writes every successful central-DB
|
||||||
|
/// read into the <see cref="GenerationSealedCache"/> so the next cache-miss path has a
|
||||||
|
/// sealed snapshot to fall back to.
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// <para>Alongside the original <see cref="NodeBootstrap"/> (which uses the single-file
|
||||||
|
/// <see cref="ILocalConfigCache"/>). Program.cs can switch to this one once operators are
|
||||||
|
/// ready for the generation-sealed semantics. The original stays for backward compat
|
||||||
|
/// with the three integration tests that construct <see cref="NodeBootstrap"/> directly.</para>
|
||||||
|
///
|
||||||
|
/// <para>Closes release blocker #2 in <c>docs/v2/v2-release-readiness.md</c> — the
|
||||||
|
/// generation-sealed cache + resilient reader + stale-config flag ship as unit-tested
|
||||||
|
/// primitives in PR #81 but no production path consumed them until this wrapper.</para>
|
||||||
|
/// </remarks>
|
||||||
|
public sealed class SealedBootstrap
|
||||||
|
{
|
||||||
|
private readonly NodeOptions _options;
|
||||||
|
private readonly GenerationSealedCache _cache;
|
||||||
|
private readonly ResilientConfigReader _reader;
|
||||||
|
private readonly StaleConfigFlag _staleFlag;
|
||||||
|
private readonly ILogger<SealedBootstrap> _logger;
|
||||||
|
|
||||||
|
public SealedBootstrap(
|
||||||
|
NodeOptions options,
|
||||||
|
GenerationSealedCache cache,
|
||||||
|
ResilientConfigReader reader,
|
||||||
|
StaleConfigFlag staleFlag,
|
||||||
|
ILogger<SealedBootstrap> logger)
|
||||||
|
{
|
||||||
|
_options = options;
|
||||||
|
_cache = cache;
|
||||||
|
_reader = reader;
|
||||||
|
_staleFlag = staleFlag;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Resolve the current generation for this node. Routes the central-DB fetch through
|
||||||
|
/// <see cref="ResilientConfigReader"/> (timeout → retry → fallback-to-cache) + seals a
|
||||||
|
/// fresh snapshot on every successful DB read so a future cache-miss has something to
|
||||||
|
/// serve.
|
||||||
|
/// </summary>
|
||||||
|
public async Task<BootstrapResult> LoadCurrentGenerationAsync(CancellationToken ct)
|
||||||
|
{
|
||||||
|
return await _reader.ReadAsync(
|
||||||
|
_options.ClusterId,
|
||||||
|
centralFetch: async innerCt => await FetchFromCentralAsync(innerCt).ConfigureAwait(false),
|
||||||
|
fromSnapshot: snap => BootstrapResult.FromCache(snap.GenerationId),
|
||||||
|
ct).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async ValueTask<BootstrapResult> FetchFromCentralAsync(CancellationToken ct)
|
||||||
|
{
|
||||||
|
await using var conn = new SqlConnection(_options.ConfigDbConnectionString);
|
||||||
|
await conn.OpenAsync(ct).ConfigureAwait(false);
|
||||||
|
|
||||||
|
await using var cmd = conn.CreateCommand();
|
||||||
|
cmd.CommandText = "EXEC dbo.sp_GetCurrentGenerationForCluster @NodeId=@n, @ClusterId=@c";
|
||||||
|
cmd.Parameters.AddWithValue("@n", _options.NodeId);
|
||||||
|
cmd.Parameters.AddWithValue("@c", _options.ClusterId);
|
||||||
|
|
||||||
|
await using var reader = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false);
|
||||||
|
if (!await reader.ReadAsync(ct).ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
_logger.LogWarning("Cluster {Cluster} has no Published generation yet", _options.ClusterId);
|
||||||
|
return BootstrapResult.EmptyFromDb();
|
||||||
|
}
|
||||||
|
|
||||||
|
var generationId = reader.GetInt64(0);
|
||||||
|
_logger.LogInformation("Bootstrapped from central DB: generation {GenerationId}; sealing snapshot", generationId);
|
||||||
|
|
||||||
|
// Seal a minimal snapshot with the generation pointer. A richer snapshot that carries
|
||||||
|
// the full sp_GetGenerationContent payload lands when the bootstrap flow grows to
|
||||||
|
// consume the content during offline operation (separate follow-up — see decision #148
|
||||||
|
// and phase-6-1 Stream D.3). The pointer alone is enough for the fallback path to
|
||||||
|
// surface the last-known-good generation id + flip UsingStaleConfig.
|
||||||
|
await _cache.SealAsync(new GenerationSnapshot
|
||||||
|
{
|
||||||
|
ClusterId = _options.ClusterId,
|
||||||
|
GenerationId = generationId,
|
||||||
|
CachedAt = DateTime.UtcNow,
|
||||||
|
PayloadJson = JsonSerializer.Serialize(new { generationId, source = "sp_GetCurrentGenerationForCluster" }),
|
||||||
|
}, ct).ConfigureAwait(false);
|
||||||
|
|
||||||
|
// StaleConfigFlag bookkeeping: ResilientConfigReader.MarkFresh on the returning call
|
||||||
|
// path; we're on the fresh branch so we don't touch the flag here.
|
||||||
|
_ = _staleFlag; // held so the field isn't flagged unused
|
||||||
|
|
||||||
|
return BootstrapResult.FromDb(generationId);
|
||||||
|
}
|
||||||
|
}
|
||||||
47
src/ZB.MOM.WW.OtOpcUa.Server/Security/NodeScopeResolver.cs
Normal file
47
src/ZB.MOM.WW.OtOpcUa.Server/Security/NodeScopeResolver.cs
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.OtOpcUa.Server.Security;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Maps a driver-side full reference (e.g. <c>"TestMachine_001/Oven/SetPoint"</c>) to the
|
||||||
|
/// <see cref="NodeScope"/> the Phase 6.2 evaluator walks. Today a simplified resolver that
|
||||||
|
/// returns a cluster-scoped + tag-only scope — the deeper UnsArea / UnsLine / Equipment
|
||||||
|
/// path lookup from the live Configuration DB is a Stream C.12 follow-up.
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// <para>The flat cluster-level scope is sufficient for v2 GA because Phase 6.2 ACL grants
|
||||||
|
/// at the Cluster scope cascade to every tag below (decision #129 — additive grants). The
|
||||||
|
/// finer hierarchy only matters when operators want per-area or per-equipment grants;
|
||||||
|
/// those still work for Cluster-level grants, and landing the finer resolution in a
|
||||||
|
/// follow-up doesn't regress the base security model.</para>
|
||||||
|
///
|
||||||
|
/// <para>Thread-safety: the resolver is stateless once constructed. Callers may cache a
|
||||||
|
/// single instance per DriverNodeManager without locks.</para>
|
||||||
|
/// </remarks>
|
||||||
|
public sealed class NodeScopeResolver
|
||||||
|
{
|
||||||
|
private readonly string _clusterId;
|
||||||
|
|
||||||
|
public NodeScopeResolver(string clusterId)
|
||||||
|
{
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(clusterId);
|
||||||
|
_clusterId = clusterId;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Resolve a node scope for the given driver-side <paramref name="fullReference"/>.
|
||||||
|
/// Phase 1 shape: returns <c>ClusterId</c> + <c>TagId = fullReference</c> only;
|
||||||
|
/// NamespaceId / UnsArea / UnsLine / Equipment stay null. A future resolver will
|
||||||
|
/// join against the Configuration DB to populate the full path.
|
||||||
|
/// </summary>
|
||||||
|
public NodeScope Resolve(string fullReference)
|
||||||
|
{
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(fullReference);
|
||||||
|
return new NodeScope
|
||||||
|
{
|
||||||
|
ClusterId = _clusterId,
|
||||||
|
TagId = fullReference,
|
||||||
|
Kind = NodeHierarchyKind.Equipment,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -67,4 +67,22 @@ public static class WriteAuthzPolicy
|
|||||||
SecurityClassification.ViewOnly => null, // IsAllowed short-circuits
|
SecurityClassification.ViewOnly => null, // IsAllowed short-circuits
|
||||||
_ => null,
|
_ => null,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Maps a driver-reported <see cref="SecurityClassification"/> to the
|
||||||
|
/// <see cref="Core.Abstractions.OpcUaOperation"/> the Phase 6.2 evaluator consults
|
||||||
|
/// for the matching <see cref="Configuration.Enums.NodePermissions"/> bit.
|
||||||
|
/// FreeAccess + ViewOnly fall back to WriteOperate — the evaluator never sees them
|
||||||
|
/// because <see cref="IsAllowed"/> short-circuits first.
|
||||||
|
/// </summary>
|
||||||
|
public static Core.Abstractions.OpcUaOperation ToOpcUaOperation(SecurityClassification classification) =>
|
||||||
|
classification switch
|
||||||
|
{
|
||||||
|
SecurityClassification.Operate => Core.Abstractions.OpcUaOperation.WriteOperate,
|
||||||
|
SecurityClassification.SecuredWrite => Core.Abstractions.OpcUaOperation.WriteOperate,
|
||||||
|
SecurityClassification.Tune => Core.Abstractions.OpcUaOperation.WriteTune,
|
||||||
|
SecurityClassification.VerifiedWrite => Core.Abstractions.OpcUaOperation.WriteConfigure,
|
||||||
|
SecurityClassification.Configure => Core.Abstractions.OpcUaOperation.WriteConfigure,
|
||||||
|
_ => Core.Abstractions.OpcUaOperation.WriteOperate,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,64 @@
|
|||||||
|
using Shouldly;
|
||||||
|
using Xunit;
|
||||||
|
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
|
||||||
|
using ZB.MOM.WW.OtOpcUa.Server.Security;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.OtOpcUa.Server.Tests;
|
||||||
|
|
||||||
|
[Trait("Category", "Unit")]
|
||||||
|
public sealed class NodeScopeResolverTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public void Resolve_PopulatesClusterAndTag()
|
||||||
|
{
|
||||||
|
var resolver = new NodeScopeResolver("c-warsaw");
|
||||||
|
|
||||||
|
var scope = resolver.Resolve("TestMachine_001/Oven/SetPoint");
|
||||||
|
|
||||||
|
scope.ClusterId.ShouldBe("c-warsaw");
|
||||||
|
scope.TagId.ShouldBe("TestMachine_001/Oven/SetPoint");
|
||||||
|
scope.Kind.ShouldBe(NodeHierarchyKind.Equipment);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Resolve_Leaves_UnsPath_Null_For_Phase1()
|
||||||
|
{
|
||||||
|
var resolver = new NodeScopeResolver("c-1");
|
||||||
|
|
||||||
|
var scope = resolver.Resolve("tag-1");
|
||||||
|
|
||||||
|
// Phase 1 flat scope — finer resolution tracked as Stream C.12 follow-up.
|
||||||
|
scope.NamespaceId.ShouldBeNull();
|
||||||
|
scope.UnsAreaId.ShouldBeNull();
|
||||||
|
scope.UnsLineId.ShouldBeNull();
|
||||||
|
scope.EquipmentId.ShouldBeNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Resolve_Throws_OnEmptyFullReference()
|
||||||
|
{
|
||||||
|
var resolver = new NodeScopeResolver("c-1");
|
||||||
|
|
||||||
|
Should.Throw<ArgumentException>(() => resolver.Resolve(""));
|
||||||
|
Should.Throw<ArgumentException>(() => resolver.Resolve(" "));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Ctor_Throws_OnEmptyClusterId()
|
||||||
|
{
|
||||||
|
Should.Throw<ArgumentException>(() => new NodeScopeResolver(""));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Resolver_IsStateless_AcrossCalls()
|
||||||
|
{
|
||||||
|
var resolver = new NodeScopeResolver("c");
|
||||||
|
var s1 = resolver.Resolve("tag-a");
|
||||||
|
var s2 = resolver.Resolve("tag-b");
|
||||||
|
|
||||||
|
s1.TagId.ShouldBe("tag-a");
|
||||||
|
s2.TagId.ShouldBe("tag-b");
|
||||||
|
s1.ClusterId.ShouldBe("c");
|
||||||
|
s2.ClusterId.ShouldBe("c");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
using Microsoft.Extensions.Logging.Abstractions;
|
||||||
|
using Shouldly;
|
||||||
|
using Xunit;
|
||||||
|
using ZB.MOM.WW.OtOpcUa.Configuration.LocalCache;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.OtOpcUa.Server.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Integration-style tests for the Phase 6.1 Stream D consumption hook — they don't touch
|
||||||
|
/// SQL Server (the real SealedBootstrap does, via sp_GetCurrentGenerationForCluster), but
|
||||||
|
/// they exercise ResilientConfigReader + GenerationSealedCache + StaleConfigFlag end-to-end
|
||||||
|
/// by simulating central-DB outcomes through a direct ReadAsync call.
|
||||||
|
/// </summary>
|
||||||
|
[Trait("Category", "Integration")]
|
||||||
|
public sealed class SealedBootstrapIntegrationTests : IDisposable
|
||||||
|
{
|
||||||
|
private readonly string _root = Path.Combine(Path.GetTempPath(), $"otopcua-sealed-bootstrap-{Guid.NewGuid():N}");
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!Directory.Exists(_root)) return;
|
||||||
|
foreach (var f in Directory.EnumerateFiles(_root, "*", SearchOption.AllDirectories))
|
||||||
|
File.SetAttributes(f, FileAttributes.Normal);
|
||||||
|
Directory.Delete(_root, recursive: true);
|
||||||
|
}
|
||||||
|
catch { /* best-effort */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task CentralDbSuccess_SealsSnapshot_And_FlagFresh()
|
||||||
|
{
|
||||||
|
var cache = new GenerationSealedCache(_root);
|
||||||
|
var flag = new StaleConfigFlag();
|
||||||
|
var reader = new ResilientConfigReader(cache, flag, NullLogger<ResilientConfigReader>.Instance,
|
||||||
|
timeout: TimeSpan.FromSeconds(10));
|
||||||
|
|
||||||
|
// Simulate the SealedBootstrap fresh-path: central DB returns generation id 42; the
|
||||||
|
// bootstrap seals it + ResilientConfigReader marks the flag fresh.
|
||||||
|
var result = await reader.ReadAsync(
|
||||||
|
"c-a",
|
||||||
|
centralFetch: async _ =>
|
||||||
|
{
|
||||||
|
await cache.SealAsync(new GenerationSnapshot
|
||||||
|
{
|
||||||
|
ClusterId = "c-a",
|
||||||
|
GenerationId = 42,
|
||||||
|
CachedAt = DateTime.UtcNow,
|
||||||
|
PayloadJson = "{\"gen\":42}",
|
||||||
|
}, CancellationToken.None);
|
||||||
|
return (long?)42;
|
||||||
|
},
|
||||||
|
fromSnapshot: snap => (long?)snap.GenerationId,
|
||||||
|
CancellationToken.None);
|
||||||
|
|
||||||
|
result.ShouldBe(42);
|
||||||
|
flag.IsStale.ShouldBeFalse();
|
||||||
|
cache.TryGetCurrentGenerationId("c-a").ShouldBe(42);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task CentralDbFails_FallsBackToSealedSnapshot_FlagStale()
|
||||||
|
{
|
||||||
|
var cache = new GenerationSealedCache(_root);
|
||||||
|
var flag = new StaleConfigFlag();
|
||||||
|
var reader = new ResilientConfigReader(cache, flag, NullLogger<ResilientConfigReader>.Instance,
|
||||||
|
timeout: TimeSpan.FromSeconds(10), retryCount: 0);
|
||||||
|
|
||||||
|
// Seed a prior sealed snapshot (simulating a previous successful boot).
|
||||||
|
await cache.SealAsync(new GenerationSnapshot
|
||||||
|
{
|
||||||
|
ClusterId = "c-a", GenerationId = 37, CachedAt = DateTime.UtcNow,
|
||||||
|
PayloadJson = "{\"gen\":37}",
|
||||||
|
});
|
||||||
|
|
||||||
|
// Now simulate central DB down → fallback.
|
||||||
|
var result = await reader.ReadAsync(
|
||||||
|
"c-a",
|
||||||
|
centralFetch: _ => throw new InvalidOperationException("SQL dead"),
|
||||||
|
fromSnapshot: snap => (long?)snap.GenerationId,
|
||||||
|
CancellationToken.None);
|
||||||
|
|
||||||
|
result.ShouldBe(37);
|
||||||
|
flag.IsStale.ShouldBeTrue("cache fallback flips the /healthz flag");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task NoSnapshot_AndCentralDown_Throws_ClearError()
|
||||||
|
{
|
||||||
|
var cache = new GenerationSealedCache(_root);
|
||||||
|
var flag = new StaleConfigFlag();
|
||||||
|
var reader = new ResilientConfigReader(cache, flag, NullLogger<ResilientConfigReader>.Instance,
|
||||||
|
timeout: TimeSpan.FromSeconds(10), retryCount: 0);
|
||||||
|
|
||||||
|
await Should.ThrowAsync<GenerationCacheUnavailableException>(async () =>
|
||||||
|
{
|
||||||
|
await reader.ReadAsync<long?>(
|
||||||
|
"c-a",
|
||||||
|
centralFetch: _ => throw new InvalidOperationException("SQL dead"),
|
||||||
|
fromSnapshot: snap => (long?)snap.GenerationId,
|
||||||
|
CancellationToken.None);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task SuccessfulBootstrap_AfterFailure_ClearsStaleFlag()
|
||||||
|
{
|
||||||
|
var cache = new GenerationSealedCache(_root);
|
||||||
|
var flag = new StaleConfigFlag();
|
||||||
|
var reader = new ResilientConfigReader(cache, flag, NullLogger<ResilientConfigReader>.Instance,
|
||||||
|
timeout: TimeSpan.FromSeconds(10), retryCount: 0);
|
||||||
|
|
||||||
|
await cache.SealAsync(new GenerationSnapshot
|
||||||
|
{
|
||||||
|
ClusterId = "c-a", GenerationId = 1, CachedAt = DateTime.UtcNow, PayloadJson = "{}",
|
||||||
|
});
|
||||||
|
|
||||||
|
// Fallback serves snapshot → flag goes stale.
|
||||||
|
await reader.ReadAsync("c-a",
|
||||||
|
centralFetch: _ => throw new InvalidOperationException("dead"),
|
||||||
|
fromSnapshot: s => (long?)s.GenerationId,
|
||||||
|
CancellationToken.None);
|
||||||
|
flag.IsStale.ShouldBeTrue();
|
||||||
|
|
||||||
|
// Subsequent successful bootstrap clears it.
|
||||||
|
await reader.ReadAsync("c-a",
|
||||||
|
centralFetch: _ => ValueTask.FromResult((long?)5),
|
||||||
|
fromSnapshot: s => (long?)s.GenerationId,
|
||||||
|
CancellationToken.None);
|
||||||
|
flag.IsStale.ShouldBeFalse("next successful DB round-trip clears the flag");
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user