Merge ConfigDb follow-ups: script FKs + ZTag/SAPID filtered unique indexes, ExternalIdReservation retired (#1040/#1049, migration ScriptForeignKeysAndExternalIdUniqueness with pre-check), SqlNamedQueryInvalid deploy rule (#1058), read-only otopcua-preflight upgrade tool (#1013/#1015/#1021)

# Conflicts:
#	docs/VirtualTags.md
This commit is contained in:
Joseph Doherty
2026-12-03 15:42:25 -05:00
56 changed files with 4623 additions and 710 deletions
+5
View File
@@ -271,6 +271,11 @@ shipped. `Core.AlarmHistorian` now carries a surgical direct pin of
SQLite 3.50.2+ patch), overriding the `2.1.11` that `Microsoft.Data.Sqlite` pulls
transitively. `dotnet restore`/`build` is clean with the audit active.
**Before upgrading a populated ConfigDb, run the upgrade preflight** (`src/Tooling/ZB.MOM.WW.OtOpcUa.UpgradePreflight`,
exe `otopcua-preflight`, `OTOPCUA_CONFIG_CONNECTION`): read-only; names every row a pending migration's pre-check or the
next deploy would refuse; exit 1 on any. A new constraint-adding migration must add its row-naming twin to
`ControlPlane/Preflight/MigrationPreChecks.cs`. See `docs/v2/upgrade-preflight.md`.
Test projects live under `tests/<module>/` (Core, Server, Drivers,
Drivers/Cli, Client, Tooling) — there is no single unit-test project.
Unit suites are named `*.Tests`; integration suites are `*.IntegrationTests`
+1 -1
View File
@@ -154,7 +154,7 @@ per-protocol driver CLIs in [docs/DriverClis.md](docs/DriverClis.md).
| Configuration (appsettings + env vars) | [docs/Configuration.md](docs/Configuration.md) |
| Service hosting and role gating | [docs/ServiceHosting.md](docs/ServiceHosting.md) |
| Security (transport, LDAP, API keys, ACLs) | [docs/security.md](docs/security.md) |
| ZTag / SAPID reservations | [docs/Reservations.md](docs/Reservations.md) |
| ZTag / SAPID uniqueness (reservation ledger retired) | [docs/Reservations.md](docs/Reservations.md) |
| AdminUI | [docs/v2/admin-ui.md](docs/v2/admin-ui.md) |
| Test and deployment infrastructure | [infra/README.md](infra/README.md) |
| Dev environment | [docs/v2/dev-environment.md](docs/v2/dev-environment.md) |
+1
View File
@@ -80,6 +80,7 @@
</Folder>
<Folder Name="/src/Tooling/">
<Project Path="src/Tooling/ZB.MOM.WW.OtOpcUa.Analyzers/ZB.MOM.WW.OtOpcUa.Analyzers.csproj" />
<Project Path="src/Tooling/ZB.MOM.WW.OtOpcUa.UpgradePreflight/ZB.MOM.WW.OtOpcUa.UpgradePreflight.csproj" />
</Folder>
<Folder Name="/tests/" />
<Folder Name="/tests/Core/">
+2 -1
View File
@@ -85,11 +85,12 @@ Integration-test fixtures: [Modbus](drivers/Modbus-Test-Fixture.md) · [S7](driv
| [ServiceHosting.md](ServiceHosting.md) | Single fused `OtOpcUa.Host` binary install/uninstall with role gating, Traefik, script-worker isolation |
| [security.md](security.md) | Transport security profiles, LDAP (AdminUI), data-plane API keys, ACLs, role grants, OTOPCUA0001 analyzer |
| [Redundancy.md](Redundancy.md) | `RedundancyStateActor`, `ServiceLevelCalculator`, per-cluster meshes, deploy acks, Prometheus metrics |
| [Reservations.md](Reservations.md) | Fleet-wide ZTag / SAPID external-ID reservations — publish-time claim, release flow |
| [Reservations.md](Reservations.md) | Fleet-wide ZTag / SAPID uniqueness — authoring check, deploy gate, unique indexes (reservation ledger retired, #1049) |
| [v2/admin-ui.md](v2/admin-ui.md) | AdminUI spec |
| [StatusDashboard.md](StatusDashboard.md) | Pointer — superseded by [v2/admin-ui.md](v2/admin-ui.md) |
| [ui-consistency-validation.md](ui-consistency-validation.md) | Shared UI consistency validation record (2026-11) |
| [v2/dev-environment.md](v2/dev-environment.md) | Dev-box bootstrap + endpoint inventory |
| [v2/upgrade-preflight.md](v2/upgrade-preflight.md) | `otopcua-preflight` — read-only pre-upgrade ConfigDb check (migration pre-checks, deploy gate, script gate) |
| [v2/redundancy-interop-playbook.md](v2/redundancy-interop-playbook.md) | Redundancy interop playbook |
### Client tooling
+1 -1
View File
@@ -150,7 +150,7 @@ The parent links of the config tables (Tag→Device/TagGroup, Device→DriverIns
**logical** foreign keys only, and the service-layer "is it empty?" delete checks are not serialised against a concurrent add. The deploy gate
(`DraftValidator.ValidateDanglingReferences`) therefore names every orphan as `DanglingReference` instead of letting each composer silently skip a
row with no path. Also enforced at the gate: fleet-wide `Equipment.ZTag` / `SAPID` uniqueness (`BadDuplicateExternalIdentifier`; see
`docs/Reservations.md`) and duplicate owned historian tagnames (`HistorianTagnameDuplicate`, `.claude/rules/historian.md`). The never-firing
`docs/Reservations.md`; since #1049 also the filtered unique indexes `UX_Equipment_ZTag` / `UX_Equipment_SAPID`) and duplicate owned historian tagnames (`HistorianTagnameDuplicate`, `.claude/rules/historian.md`). The never-firing
`PathTooLong` and `EquipmentUuidImmutable` rules were deleted (the UnsSegment charset already bounds the path at 164 chars; no prior-generation
table exists to diff).
+22 -145
View File
@@ -1,154 +1,31 @@
# External-ID Reservations
# External-ID (ZTag / SAPID) uniqueness
> **Status (lmxopcua#998, 2026-12): the reservation ledger has no writer.** `sp_PublishGeneration`, the only code
> that inserted `ExternalIdReservation` rows, was retired with the generation model (it now only `RAISERROR`s), so the
> table stays empty and the pre-flight below can only fire against rows an operator inserted by hand. **Fleet-wide
> ZTag / SAPID uniqueness is now enforced by the deploy gate itself**: `DraftValidator.ValidateEquipmentExternalIdUniqueness`
> groups every equipment row in the (whole-DB) draft snapshot by trimmed, case-insensitive ZTag and by SAPID and
> reports each duplicate as `BadDuplicateExternalIdentifier` naming the other equipment (same cluster or not).
> Blank values mean "no identifier". The permanent-claim semantics described below (a retired asset's id staying
> reserved) are **not** provided; the table, `/reservations` page and release procedure remain for any rows that
> already exist. The equipment page's field hint says "rejected when you deploy", matching this. A filtered unique
> index on `Equipment.ZTag` / `SAPID` was not added (needs a duplicate pre-clean migration); the gate is the authority.
> **The reservation ledger is retired (lmxopcua#1049, 2026-12).** `ExternalIdReservation`, the `/reservations`
> page, `sp_ReleaseExternalIdReservation` and the deploy gate's reservation pre-flight are gone. The ledger's only
> writer, `sp_PublishGeneration`, was retired with the generation model, so the table stayed empty and the
> pre-flight could never fire (review 2026-12-02, C-3). The permanent "a retired asset's id stays claimed" semantics
> of decision #124 were therefore never in force in v3, and are not provided now.
The reservation subsystem guarantees that an asset's **external identifiers**
— its `ZTag` and `SAPID` — belong to exactly one piece of equipment across the
entire fleet, for all time. It is the mechanism that stops two pieces of
equipment (in the same cluster or different clusters, in the current generation
or an old one) from silently claiming the same plant tag.
An equipment's **external identifiers** — its `ZTag` (ERP id) and `SAPID` (SAP PM id) — are unique **fleet-wide**:
no two `Equipment` rows, in the same cluster or different clusters, may carry the same value. Both are optional; a
blank value means "no identifier".
This is **decision #124** in `docs/v2/plan.md`.
## Where it is enforced
## What a reservation is
| Layer | What | Comparison |
|---|---|---|
| Authoring (`UnsTreeService`) | Equipment create / update / CSV import refuse a value another equipment holds and name that equipment; an import names each clashing row (against the DB or an earlier row of the same file) and still imports the clean rows. Values are stored trimmed; blank is stored as `NULL`. | Trimmed; the DB's case-insensitive collation |
| Deploy gate (`DraftValidator.ValidateEquipmentExternalIdUniqueness`) | The authority: every duplicate in the whole-DB draft snapshot is reported as `BadDuplicateExternalIdentifier`, naming the other equipment. | Trimmed, case-insensitive, blank = none |
| Storage (`UX_Equipment_ZTag`, `UX_Equipment_SAPID`) | Filtered UNIQUE indexes, `WHERE [ZTag] IS NOT NULL AND [ZTag] <> N''` (same for `SAPID`) — the backstop for a concurrent save or a hand edit. Never stricter than the gate. | Column collation (case-insensitive) |
An `ExternalIdReservation` row is a permanent, fleet-wide claim on one
identifier value by one `EquipmentUuid`. There are two kinds
(`ReservationKind`):
## Upgrading a populated ConfigDb
| Kind | What it is |
|---------|------------|
| `ZTag` | The plant's tag identity for a physical asset. |
| `SAPID` | The asset's SAP record ID. |
An `Equipment` row may carry a `ZTag`, a `SAPID`, both, or neither. Whenever it
carries one and the generation is published, a reservation is created for that
value.
## Why it sits outside the generation flow
Every other part of the configuration is **generation-versioned** — authored in
a draft, promoted by publish, superseded by the next publish, and reversible by
rollback. Reservations deliberately are **not**.
The reason: a single ZTag can legitimately appear in many places at once — the
current published generation, several superseded generations, and a piece of
equipment that has since been disabled. A per-generation uniqueness index would
fail the instant you roll back to an older generation or re-enable disabled
equipment, because the "old" copy of the identifier is still on disk.
So the reservation table is a flat, fleet-wide ledger that lives *beside* the
generation flow. It is append-mostly: rows are created, their `LastPublishedAt`
is refreshed, and they are eventually *released* — but never silently deleted.
## The table
`ExternalIdReservation` (Config DB):
| Column | Notes |
|--------------------|-------|
| `ReservationId` | Surrogate PK (`NEWSEQUENTIALID()`). |
| `Kind` | `ZTag` or `SAPID`. |
| `Value` | The reserved identifier string. |
| `EquipmentUuid` | The equipment that owns the claim. Stays bound even when that equipment is disabled. |
| `ClusterId` | The first cluster to publish the reservation. |
| `FirstPublishedAt` / `FirstPublishedBy` | When and by whom the claim was first made. |
| `LastPublishedAt` | Refreshed on every subsequent publish that re-asserts the same `(Kind, Value, EquipmentUuid)`. |
| `ReleasedAt` / `ReleasedBy` / `ReleaseReason` | Non-null once an Administrator explicitly releases the claim. `ReleasedBy` is the LDAP operator name (passed explicitly as `@ReleasedBy`; not `SUSER_SNAME()`). A row with `ReleasedAt IS NULL` is *active*. |
There is no foreign key from `EquipmentUuid` / `ClusterId` to their tables — by
design, so a reservation survives the deletion or disabling of the equipment
that owns it.
## Lifecycle
### 1. Authoring
You give an `Equipment` row a `ZTag` and/or `SAPID` in a **draft** generation —
either by hand in the draft editor or via equipment CSV import. Nothing is
reserved yet; the draft is just a proposal.
> Equipment CSV import does **not** pre-check reservation conflicts (tracked as
> task #197). A conflict introduced by import surfaces at publish time, below.
### 2. Publish precheck
`sp_PublishGeneration` runs the draft validation first. If a `ZTag` or `SAPID`
in the draft is already reserved — `ReleasedAt IS NULL` — by a **different**
`EquipmentUuid`, the publish is rejected:
```
BadDuplicateExternalIdentifier: a ZTag in the draft is reserved by a
different EquipmentUuid
```
The same value owned by the *same* `EquipmentUuid` is fine — that is just the
asset keeping its identifier across generations.
### 3. Publish (the reservation is created)
When the publish succeeds, `sp_PublishGeneration` runs a `MERGE` into
`ExternalIdReservation` for every `ZTag`/`SAPID` in the published generation:
- **New** `(Kind, Value, EquipmentUuid)` → a reservation row is **inserted**.
`FirstPublishedBy` is the publishing user; `ClusterId` is the publishing
cluster.
- **Already present** → only `LastPublishedAt` is bumped.
So the *first* publish of an equipment carrying a ZTag is what claims that ZTag
for the fleet. After that the claim is permanent — it survives the equipment
being disabled, the generation being superseded, or a rollback.
### 4. Release
Reusing an identifier for a **different** piece of equipment requires an
Administrator to explicitly release the existing claim. Release runs
`sp_ReleaseExternalIdReservation`, which:
- Requires a non-empty **reason** — a hard audit invariant; the procedure
raises an error without one.
- Requires a non-empty **`@ReleasedBy`** — the LDAP operator name supplied
by the caller; the procedure raises an error without it.
- Stamps `ReleasedAt`, `ReleasedBy` (the supplied operator name), and
`ReleaseReason` rather than deleting the row, so the history is preserved.
- Once released, the `(Kind, Value)` pair is free — a different
`EquipmentUuid` can claim it on a future publish.
Release the claim **only** when the physical asset is permanently retired and
its identifier genuinely needs to be reused. A reservation is meant to be
permanent for the life of the asset.
## The Admin page
`/reservations` (Admin UI) is the operator surface. It requires authentication
(`[Authorize]`) but is not restricted to a specific Admin UI role — any signed-in
user can view it.
The page is a **read-only list** of `ExternalIdReservation` rows, ordered by Kind
then Value. It shows Kind, Value, owning `EquipmentUuid`, and Cluster. Since
#996 (review A-8) it lists **active** rows by default (a "Show released" toggle
adds the released ones and a Released column), reads only the displayed columns
(`ReservationListQuery`) and shows at most 200 rows with a "Showing N of M"
header — released rows accumulate for the life of the database. There is no
Release action and no Release dialog on this page.
You cannot *create* a reservation from this page — reservations only ever come
into existence as a side-effect of publishing a generation. The release flow
is described in `docs/v2/admin-ui.md` § "Release an external-ID reservation"
and runs via `sp_ReleaseExternalIdReservation`.
Migration `ScriptForeignKeysAndExternalIdUniqueness` creates the unique indexes and drops the ledger. It refuses
(error 51049, nothing changed) while any non-blank ZTag or SAPID is duplicated, or while `ExternalIdReservation`
still holds rows (export them if their history matters, then delete them). Run the upgrade preflight first — it lists
exactly those rows: [docs/v2/upgrade-preflight.md](v2/upgrade-preflight.md).
## Related
- `docs/v2/plan.md` — decision #124 (reservations outside the generation flow).
- `docs/v2/admin-ui.md` — § "Release an external-ID reservation".
- `docs/v2/config-db-schema.md` — full Config DB schema.
- `OpcUaServer.md` — generations, draft/publish flow.
- `docs/v2/plan.md` — decision #124 (the original reservation design, historical).
- `docs/Raw.md` — the other deploy-gate uniqueness rules (#998).
+1 -1
View File
@@ -362,7 +362,7 @@ Virtual-tag nodes are materialised by `AddressSpaceApplier` and fed by `VirtualT
- **AdminUI.** The script editor's completion/hover catalog (`ScriptTagCatalog`) lists each VirtualTag under its key instead of its bare leaf name.
- Pinned by `VirtualTagToVirtualTagFlowTests` (Host.Tests: real mux + host + Roslyn evaluator; value, change and disabled-upstream propagation), `VirtualTagOutputRoutingTests` (Runtime.Tests: mux pinning/replay/release, host routing, re-assert exclusion, runtime cycle backstop) and `DraftValidatorVirtualTagCycleTests`.
- **Supervision restart re-applies.** A restart of `VirtualTagHostActor` builds a host with no children and no definitions; its `PostRestart` tells the parent `VirtualTagHostRestarted` and `DriverHostActor` re-sends the last `ApplyVirtualTags` (mirroring the scripted-alarm host's `ScriptedAlarmHostRestarted`), so VirtualTags resume without waiting for the next deploy. Pinned by `DriverHostActorVirtualTagTests.After_a_supervision_restart_the_virtual_tag_host_is_re_applied`.
- **Names and scripts are gated (lmxopcua#978).** A VirtualTag `Name` is its UNS NodeId leaf (`{EquipmentId}/{Name}`), so the modal, `UnsTreeService` and the deploy gate (`VirtualTagNameInvalid`) all apply `V3NodeIds.ValidateSegment` (no `/`, no leading/trailing whitespace). Every VirtualTag `ScriptId` and ScriptedAlarm `PredicateScriptId` must name an existing script (`VirtualTagScriptNotFound` / `ScriptedAlarmScriptNotFound`, disabled rows included), and the `/scripts/{id}` delete refuses a script still used by a VirtualTag, ScriptedAlarm or Calculation tag, naming them (`ScriptUsage`; there is no FK, so a concurrent bind is caught by the gate). As a backstop for an artifact that bypassed the gate, `VirtualTagHostActor` skips a plan whose NodeId cannot be built (logged at Error) instead of crashing the host — which used to stop every VirtualTag on the node with nothing re-applying — and `AddressSpaceApplier.MaterialiseEquipmentVirtualTags` counts it as a failed node (degraded apply) instead of aborting the pass. Pinned by `DraftValidatorUnsLeafNameAndScriptTests`, `UnsLeafNameAuthorityTests`, `VirtualTagHostActorTests.An_illegal_name_is_skipped_and_the_good_tags_keep_working` and `ScriptEditLifecycleTests.A_script_in_use_is_not_deleted_and_the_user_is_named`.
- **Names and scripts are gated (lmxopcua#978).** A VirtualTag `Name` is its UNS NodeId leaf (`{EquipmentId}/{Name}`), so the modal, `UnsTreeService` and the deploy gate (`VirtualTagNameInvalid`) all apply `V3NodeIds.ValidateSegment` (no `/`, no leading/trailing whitespace). Every VirtualTag `ScriptId` and ScriptedAlarm `PredicateScriptId` must name an existing script (`VirtualTagScriptNotFound` / `ScriptedAlarmScriptNotFound`, disabled rows included), and the `/scripts/{id}` delete refuses a script still used by a VirtualTag, ScriptedAlarm or Calculation tag, naming them (`ScriptUsage`). Since lmxopcua#1040 the database refuses it too: `FK_VirtualTag_Script` / `FK_ScriptedAlarm_Script` (Restrict) onto the `Script.ScriptId` alternate key, so a concurrent bind cannot leave a dangling row and an in-use delete fails; `UnsTreeService` refuses a missing script by name before the FK would. Calculation tags name their script inside `TagConfig` JSON, so only the delete guard and the gate (`CalculationScriptNotFound`) cover them. As a backstop for an artifact that bypassed the gate, `VirtualTagHostActor` skips a plan whose NodeId cannot be built (logged at Error) instead of crashing the host — which used to stop every VirtualTag on the node with nothing re-applying — and `AddressSpaceApplier.MaterialiseEquipmentVirtualTags` counts it as a failed node (degraded apply) instead of aborting the pass. Pinned by `DraftValidatorUnsLeafNameAndScriptTests`, `UnsLeafNameAuthorityTests`, `VirtualTagHostActorTests.An_illegal_name_is_skipped_and_the_good_tags_keep_working` and `ScriptEditLifecycleTests.A_script_in_use_is_not_deleted_and_the_user_is_named`.
- **Timer-driven evaluation (lmxopcua#783).** `VirtualTag.TimerIntervalMs` re-evaluates the tag on a fixed cadence (minimum 50 ms, clamped) via an Akka scheduler owned by `VirtualTagActor` — started in `PreStart`, cancelled in `PostStop`, so a stop or a redeploy respawn never leaves a ticker. `ChangeTriggered=false` makes the timer the only trigger (dependencies are still tracked). A tick that lands while a script run is in flight is dropped rather than stashed, so a slow script never builds a backlog of runs. A tick that lands within half an interval of the last timer evaluation is dropped too (#1061): Akka's scheduler delivers every tick it missed during a stall of its thread (GC pause, CPU starvation) as one burst when it resumes, which used to run the script once per missed tick. Before this the field was stored, validated and edited but never consumed, so a timer-only tag sat at `BadWaitingForInitialData` forever. The deploy gate `VirtualTagNoEffectiveTrigger` (mirror of `CalculationNoEffectiveTrigger`) rejects a tag with neither a timer nor a change-trigger with a literal `ctx.GetTag` read. Pinned by `VirtualTagActorTimerTests` and `DraftValidatorVirtualTagTriggerTests`.
- **Calculation tags and scripted alarms still evaluate one script at a time per driver / per engine (deliberately, for now).** Neither blocks a thread — both await the run — but a slow script still delays its siblings. Running independent scripts in parallel was considered for #779 and not done, because it is not semantics-neutral: for Calculation, the single pump is what bounds a driver to one pool thread of script work (per-tag lanes would let N slow tags hold N pool threads, the pool Akka's dispatchers also run on, so it needs a bounded-parallelism knob), it would reorder publishes across tags, and the timer path would need per-tag exclusion with the pump; for scripted alarms, the engine gate is also the consistency boundary of the Part 9 state machine, persist-before-update and ack/shelve/load, a predicate's transition time is sampled just before its own run, and a store failure mid-batch today leaves later predicates un-run (in parallel they would already have run, moving their run-guard strike streaks and writing script logs for results that are then discarded). The out-of-process runner's batch-submit `IScriptRunner` (#750) is where that concurrency belongs, with the runner owning the bound.
- **`IHistoryWriter`** — the equipment-namespace path threads `Historize` end-to-end and `VirtualTagHostActor` invokes the injected writer on historized results (H5); the writer is resolved through `DriverHostActor` DI with a `NullHistoryWriter` default. No *durable* writer ships on this seam — durable continuous historization now flows through the separate `ContinuousHistorizationRecorder` → HistorianGateway `WriteLiveValues` path (see the `IHistoryWriter` section above and [Historian.md](Historian.md)).
+10 -4
View File
@@ -223,9 +223,11 @@ row:
`SELECT`**, with no `INTO` and no `OPENQUERY` / `OPENROWSET` / `OPENDATASOURCE` (they run text on another
server or read a file). CTEs, subqueries, window functions, `UNION`, `OPTION (…)` and `@name` parameters
are ordinary `SELECT`s and pass. An Odbc statement's positional `?` markers are read as variables for the
parse; anything else SQL Server's grammar does not accept — a PostgreSQL `::` cast, `LIMIT`, a T-SQL
reserved word used as a bare alias (`AS top`) — is refused on Odbc, so quote or rename it. The lexical
rules remain as a second, independent layer.
parse; anything else SQL Server's grammar does not accept — a PostgreSQL `::` cast of a literal or an
expression (`'a'::text`, `(v)::numeric`), `LIMIT`, `ILIKE`, a T-SQL reserved word used as a bare alias
(`AS top`) — is refused on Odbc, so quote or rename it. (`col::type` between two bare identifiers happens
to PARSE as T-SQL static-member syntax and is accepted.) The lexical rules remain as a second, independent
layer.
- **It executes in a read-only transaction where the provider has one** — always rolled back regardless:
PostgreSQL and Oracle `SET TRANSACTION READ ONLY`, MySQL a read-only **session** plus `START TRANSACTION
READ ONLY` (a smuggled `COMMIT` ends a transaction, not a session; the session is restored afterwards). A
@@ -246,7 +248,11 @@ row:
**must** connect with a `SELECT`-only login (see [Database login](#database-login-required)).
- A tag naming a query the driver config does not declare is **skipped** at Initialize (it reads
`BadNodeIdUnknown`, and `/hosts` names the missing query). One unusable `queries` entry **fails the
driver** instead, because every tag that names it would otherwise go dark unexplained.
driver** instead, because every tag that names it would otherwise go dark unexplained. Since lmxopcua#1058
the **deploy gate refuses it first** (`SqlNamedQueryInvalid`, naming the driver instance): it runs the same
`SqlNamedQueryRules.Describe` over the same merged config with the instance's provider. Before upgrading
a deployment that has Odbc drivers, run the [upgrade preflight](../v2/upgrade-preflight.md), which lists
every stored query the new guard refuses.
- Query tags read no table, so they need **no catalog gate** — a driver serving only named queries skips
the catalog load entirely. Nothing from a Query tag is ever quoted into SQL.
+4 -2
View File
@@ -447,7 +447,9 @@ CREATE INDEX IX_Equipment_Generation_MachineCode
ON dbo.Equipment (GenerationId, MachineCode);
```
**Note on ZTag/SAPID uniqueness**: per-generation indexes above are non-unique (only `IX_*`, not `UX_*`). Fleet-wide uniqueness lives in the `ExternalIdReservation` table (see below). Per-generation indexes exist only for fast lookup; uniqueness is enforced at publish time against the reservation table, which is rollback-safe.
> **Current (v3, lmxopcua#1049):** the reservation ledger below is retired and dropped. Uniqueness is enforced by `UnsTreeService`, the deploy gate (`BadDuplicateExternalIdentifier`) and the filtered unique indexes `UX_Equipment_ZTag` / `UX_Equipment_SAPID` — see `docs/Reservations.md`.
**Note on ZTag/SAPID uniqueness (historical v2 design)**: per-generation indexes above are non-unique (only `IX_*`, not `UX_*`). Fleet-wide uniqueness lives in the `ExternalIdReservation` table (see below). Per-generation indexes exist only for fast lookup; uniqueness is enforced at publish time against the reservation table, which is rollback-safe.
**Identifier responsibilities** — equipment carries five distinct identifiers, each with a different audience:
@@ -572,7 +574,7 @@ The migrations widen `NodeAcl.ScopeKind` to 32 characters for mapping-specific g
The database stores references for outbound connection credentials. See
[Data connections](../DataConnections.md) for authorization and credential provisioning.
### `ExternalIdReservation`
### `ExternalIdReservation` (retired — dropped by migration `ScriptForeignKeysAndExternalIdUniqueness`, lmxopcua#1049)
```sql
CREATE TABLE dbo.ExternalIdReservation (
+83
View File
@@ -0,0 +1,83 @@
# Upgrade preflight (`otopcua-preflight`)
A **read-only** check of an OtOpcUa ConfigDb, run from the **new** build **before** its migrations are applied.
It reports every row that the upgrade — or the first deploy after it — would refuse, so the clean-up happens
before the maintenance window instead of in the middle of it. It issues only `SELECT`s.
Introduced for the 2026-12-02 review remediation follow-ups lmxopcua#1013, #1015, #1021 and #1058.
## What it checks
| Section | What | Severity | Issue |
|---|---|---|---|
| `schema` | Applied vs pending migrations; tables/columns a pending migration creates (read as empty/default — see below); whether `ALLOW_SNAPSHOT_ISOLATION` is on. | Info / Warning | — |
| `migration:ConfigurationGapsIndexesAndRowVersions` | Duplicate `NodeAcl` rows per (cluster, principal, scope kind, scope id) — typically several Cluster-scope rows for one principal — and duplicate `LdapGroupRoleMapping` rows per (group, cluster), incl. system-wide. The migration THROWs on either. | Blocking | #1021 |
| `migration:ScriptForeignKeysAndExternalIdUniqueness` | `Script.ScriptId` NULL; a VirtualTag / ScriptedAlarm naming a script that does not exist; a non-blank ZTag or SAPID on more than one equipment (case-insensitive, as the new unique index); any `ExternalIdReservation` row (the table is dropped). The migration THROWs on any of them. | Blocking | #1040, #1049 |
| `deploy-gate` | The deploy gate's own rule pass (`DeployGateRules` — the code `AdminOperationsActor` runs): every `DraftValidator` rule, incl. the #978 rules `VirtualTagNameInvalid`, `UnsEffectiveNameInvalid` (illegal VirtualTag names / display-name overrides), `VirtualTagScriptNotFound`, `ScriptedAlarmScriptNotFound` (dangling script references), the #998 rules (`BadDuplicateExternalIdentifier`, `DanglingReference`, `HistorianTagnameDuplicate`), and `SqlNamedQueryInvalid`; the per-cluster topology check; the TagConfig inspection (Warning unless `--tagconfig-mode Error`). | Blocking (rules) / Warning | #1015, #1058 |
| `script-gate` | Every script the runtime will compile (enabled VirtualTags, enabled scripted-alarm predicates, Calculation tags, `{{equip}}` resolved) through the Roslyn compile + sandbox allow-list (`RoslynDeployScriptChecker`, as the deploy gate). Also every **unused** stored script, compiled as a value script — a Warning, since binding it later would be refused. | Blocking (Error mode) / Warning | #1013 |
`SqlNamedQueryInvalid` (#1058) is a deploy-gate rule added with the preflight: the Sql driver checks every named
query with `SqlNamedQueryRules.Describe` under its provider at construction and one refused query fails the whole
driver. Since #974 that includes a T-SQL ScriptDom parse for SqlServer, Odbc and no-provider configs, so an **Odbc**
query written in another dialect (`LIMIT`, `ILIKE`, `'a'::text`, `(x)::numeric`) is refused — the deploy gate now
says so before the driver goes dark. (A bare `col::type` parses as T-SQL static-member syntax and is accepted.)
### Reading an older schema
The preflight reads the snapshot through **this build's** EF model, but the database is still on the old schema.
A table a pending migration creates is mapped to a typed zero-row query (it will be empty right after the
migration); a column a pending migration adds is left out of the model (the property keeps its default). The
`schema` section lists exactly which. A schema change the tolerance cannot bridge (e.g. a NULL in a column the new
model requires) is reported as `deploy-gate/SnapshotUnreadable`; fix the migration pre-check findings and re-run.
Only v3 ConfigDbs (with `20260715230637_V3Initial` applied) are accepted; anything else exits 2.
## Running it
Build or publish it from the **new** source tree (it must carry the new rules and migrations):
```bash
dotnet publish src/Tooling/ZB.MOM.WW.OtOpcUa.UpgradePreflight -c Release -o out/preflight
# Windows target: add -r win-x64 --self-contained to run it on the box without an SDK
```
Pass the connection string through the environment (a command-line argument is visible in the process list and
shell history). A login with `db_datareader` on the ConfigDb is enough.
```bash
export OTOPCUA_CONFIG_CONNECTION='Server=<host>,<port>;Database=<ConfigDb>;User Id=<reader>;Password=<...>;TrustServerCertificate=True'
out/preflight/otopcua-preflight # human-readable; Blocking + Warning findings
out/preflight/otopcua-preflight --verbose # + Info (pending migrations, clean sections)
out/preflight/otopcua-preflight --json > preflight.json
```
| Option | Default | Meaning |
|---|---|---|
| `--connection "<cs>"` | `OTOPCUA_CONFIG_CONNECTION` | ConfigDb connection string |
| `--tagconfig-mode Warn\|Error` | `Warn` | the target's `Deployment:TagConfigValidationMode` |
| `--script-gate Error\|Warn\|Off` | `Error` | the target's `Deployment:ScriptCompileGateMode` |
| `--no-unused-scripts` | off | skip compiling scripts nothing uses |
| `--json` / `--verbose` | off | output format |
**Exit codes:** `0` nothing blocks the upgrade or the next deploy · `1` at least one Blocking finding · `2` usage
error, unreachable database, or not a v3 ConfigDb.
## Upgrade procedure
1. On the running (old) build's ConfigDb, run the preflight from the new build. It is read-only and safe to run
against a live database; under SNAPSHOT isolation it does not block editors.
2. Fix every Blocking finding through the AdminUI (re-point or delete the VirtualTag/ScriptedAlarm, clear the
duplicate ZTag, merge the duplicate ACL rows, rewrite the Odbc query, fix the script) — or, for
`ExternalIdReservation` rows, export them if their history matters and delete them. Re-run until exit 0.
3. Apply the new build (its migrations). A migration that still finds a bad row THROWs (error 50998 / 51049) and
changes nothing; re-run the preflight to see why.
4. Deploy. The deploy gate runs the same rules the preflight ran.
## Results recorded
| Date | Target | Schema at | Result |
|---|---|---|---|
| 2026-12-03 | docker-dev ConfigDb `OtOpcUa` (read from a copy of the stopped rig's SQL volume; the rig was not touched) | `EnableSnapshotIsolation` (6 pending) | exit 0 — both migration pre-checks clean, deploy gate clean, 3 in-use scripts compile; no Sql drivers |
| 2026-12-03 | `10.100.0.35,14330` / `OtOpcUaCfg_gate_scratch` | `V3Initial` (14 pending) | exit 0 — empty config; the NodeAcl duplicate pre-check could not run on the pre-#520 `LdapGroup` column (Warning) |
| 2026-12-03 | `10.100.0.35,14330` / `OtOpcUaConfig`, `OtOpcUaConfig_Dev` | v2 schema | exit 2 — not v3 ConfigDbs (nothing to check) |
| — | **production (wonder-app-vd03 / vq03 / vq04)** | — | **not run — user-gated.** Remote commands on the wonder boxes are on hold (see `CLAUDE.md`); an operator with SQL access runs step 1 there. |
@@ -97,8 +97,7 @@ public static class EquipmentReferenceMap
var names = new HashSet<string>(StringComparer.Ordinal);
foreach (var r in references)
{
var effectiveName = r.DisplayNameOverride
?? (tagNameById.TryGetValue(r.TagId, out var n) ? n : null);
var effectiveName = EffectiveName(r.DisplayNameOverride, tagNameById.TryGetValue(r.TagId, out var n) ? n : null);
if (!string.IsNullOrEmpty(effectiveName)) names.Add(effectiveName);
}
return names;
@@ -1,44 +0,0 @@
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
namespace ZB.MOM.WW.OtOpcUa.Configuration.Entities;
/// <summary>
/// Fleet-wide rollback-safe reservation of ZTag and SAPID. NOT generation-versioned.
/// Exists outside generation flow specifically because old generations and disabled equipment can
/// still hold the same external IDs; per-generation uniqueness indexes fail under rollback/re-enable.
/// </summary>
public sealed class ExternalIdReservation
{
/// <summary>Gets or sets the unique reservation identifier.</summary>
public Guid ReservationId { get; set; }
/// <summary>Gets or sets the kind of reservation (ZTag or SAPID).</summary>
public required ReservationKind Kind { get; set; }
/// <summary>Gets or sets the reserved external ID value.</summary>
public required string Value { get; set; }
/// <summary>The equipment that owns this reservation. Stays bound even when equipment is disabled.</summary>
public Guid EquipmentUuid { get; set; }
/// <summary>First cluster to publish this reservation.</summary>
public required string ClusterId { get; set; }
/// <summary>Gets or sets the timestamp when the reservation was first published.</summary>
public DateTime FirstPublishedAt { get; set; } = DateTime.UtcNow;
/// <summary>Gets or sets the identifier of the user or system that first published the reservation.</summary>
public required string FirstPublishedBy { get; set; }
/// <summary>Gets or sets the timestamp of the most recent publication.</summary>
public DateTime LastPublishedAt { get; set; } = DateTime.UtcNow;
/// <summary>Non-null when explicitly released by FleetAdmin (audit-logged, requires reason).</summary>
public DateTime? ReleasedAt { get; set; }
/// <summary>Gets or sets the identifier of the user or system that released the reservation.</summary>
public string? ReleasedBy { get; set; }
/// <summary>Gets or sets the reason for releasing the reservation.</summary>
public string? ReleaseReason { get; set; }
}
@@ -1,8 +0,0 @@
namespace ZB.MOM.WW.OtOpcUa.Configuration.Enums;
/// <summary>External-ID reservation kind.</summary>
public enum ReservationKind
{
ZTag,
SAPID,
}
@@ -0,0 +1,267 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations
{
/// <summary>
/// lmxopcua#1040 + lmxopcua#1049 (follow-ups of the 2026-12-02 review, #978 C-2 and #998 C-3).
/// <list type="bullet">
/// <item>Real FKs <c>FK_VirtualTag_Script</c> / <c>FK_ScriptedAlarm_Script</c> (ON DELETE NO ACTION) onto
/// <c>Script.ScriptId</c>, which becomes NOT NULL and an alternate key (the unique constraint
/// <c>UX_Script_LogicalId</c> replaces the filtered unique index of the same name).</item>
/// <item>Filtered UNIQUE indexes <c>UX_Equipment_ZTag</c> / <c>UX_Equipment_SAPID</c> (blank = no identifier,
/// as the deploy gate) replace the non-unique <c>IX_Equipment_ZTag</c> / <c>IX_Equipment_SAPID</c>.</item>
/// <item><c>ExternalIdReservation</c> and <c>sp_ReleaseExternalIdReservation</c> are dropped: the ledger has
/// had no writer since the generation model retired.</item>
/// </list>
/// <para><b>Pre-check, never a silent clean.</b> Each change would fail half-way (or delete history) over rows
/// that break it, so <see cref="PreCheckSql"/> runs first and THROWs one error naming every offending row class:
/// a NULL <c>Script.ScriptId</c>, a VirtualTag / ScriptedAlarm naming a missing script, a duplicated non-blank
/// ZTag or SAPID, and any <c>ExternalIdReservation</c> row. Nothing is altered until the operator fixes them; the
/// <c>preflight</c> tool (docs/v2/upgrade-preflight.md) lists the same rows ahead of the upgrade.</para>
/// </summary>
public partial class ScriptForeignKeysAndExternalIdUniqueness : Migration
{
/// <summary>The read-only pre-check; THROWs 51049 naming every problem class, or does nothing.</summary>
internal const string PreCheckSql = @"
DECLARE @problems nvarchar(max) = N'';
DECLARE @n int, @sample nvarchar(max);
SELECT @n = COUNT(*) FROM [Script] WHERE [ScriptId] IS NULL;
IF @n > 0 SET @problems += CONCAT(N' [', @n, N' Script row(s) with a NULL ScriptId: give each a unique ScriptId or delete it]');
SET @sample = N'';
SELECT @n = COUNT(*) FROM [VirtualTag] v WHERE NOT EXISTS (SELECT 1 FROM [Script] s WHERE s.[ScriptId] = v.[ScriptId]);
SELECT TOP (5) @sample += CONCAT(N' ', v.[VirtualTagId], N'->', v.[ScriptId])
FROM [VirtualTag] v WHERE NOT EXISTS (SELECT 1 FROM [Script] s WHERE s.[ScriptId] = v.[ScriptId]) ORDER BY v.[VirtualTagId];
IF @n > 0 SET @problems += CONCAT(N' [', @n, N' VirtualTag row(s) name a script that does not exist (VirtualTagId->ScriptId:', @sample, N'): point them at an existing script or delete them]');
SET @sample = N'';
SELECT @n = COUNT(*) FROM [ScriptedAlarm] a WHERE NOT EXISTS (SELECT 1 FROM [Script] s WHERE s.[ScriptId] = a.[PredicateScriptId]);
SELECT TOP (5) @sample += CONCAT(N' ', a.[ScriptedAlarmId], N'->', a.[PredicateScriptId])
FROM [ScriptedAlarm] a WHERE NOT EXISTS (SELECT 1 FROM [Script] s WHERE s.[ScriptId] = a.[PredicateScriptId]) ORDER BY a.[ScriptedAlarmId];
IF @n > 0 SET @problems += CONCAT(N' [', @n, N' ScriptedAlarm row(s) name a predicate script that does not exist (ScriptedAlarmId->PredicateScriptId:', @sample, N'): point them at an existing script or delete them]');
SET @sample = N'';
SELECT @n = COUNT(*) FROM (SELECT [ZTag] FROM [Equipment] WHERE [ZTag] IS NOT NULL AND [ZTag] <> N'' GROUP BY [ZTag] HAVING COUNT(*) > 1) d;
SELECT TOP (5) @sample += CONCAT(N' ''', d.[ZTag], N''' x', d.c)
FROM (SELECT [ZTag], COUNT(*) AS c FROM [Equipment] WHERE [ZTag] IS NOT NULL AND [ZTag] <> N'' GROUP BY [ZTag] HAVING COUNT(*) > 1) d ORDER BY d.[ZTag];
IF @n > 0 SET @problems += CONCAT(N' [', @n, N' ZTag value(s) are set on more than one Equipment row (', @sample, N'): keep each ZTag on one equipment and clear or change the others]');
SET @sample = N'';
SELECT @n = COUNT(*) FROM (SELECT [SAPID] FROM [Equipment] WHERE [SAPID] IS NOT NULL AND [SAPID] <> N'' GROUP BY [SAPID] HAVING COUNT(*) > 1) d;
SELECT TOP (5) @sample += CONCAT(N' ''', d.[SAPID], N''' x', d.c)
FROM (SELECT [SAPID], COUNT(*) AS c FROM [Equipment] WHERE [SAPID] IS NOT NULL AND [SAPID] <> N'' GROUP BY [SAPID] HAVING COUNT(*) > 1) d ORDER BY d.[SAPID];
IF @n > 0 SET @problems += CONCAT(N' [', @n, N' SAPID value(s) are set on more than one Equipment row (', @sample, N'): keep each SAPID on one equipment and clear or change the others]');
IF OBJECT_ID(N'[ExternalIdReservation]', N'U') IS NOT NULL
BEGIN
SELECT @n = COUNT(*) FROM [ExternalIdReservation];
IF @n > 0 SET @problems += CONCAT(N' [', @n, N' ExternalIdReservation row(s): the ledger is retired and its table is dropped by this migration; export the rows if you need their history, DELETE FROM [ExternalIdReservation], then re-run]');
END
IF LEN(@problems) > 0
BEGIN
DECLARE @msg nvarchar(2048) = LEFT(CONCAT(N'ScriptForeignKeysAndExternalIdUniqueness (lmxopcua#1040/#1049) refused - nothing was changed:', @problems), 2048);
THROW 51049, @msg, 1;
END
";
// sp_ReleaseExternalIdReservation as V3Initial created it — re-created by Down only.
private const string ReleaseExternalIdReservationProc = @"
CREATE OR ALTER PROCEDURE dbo.sp_ReleaseExternalIdReservation
@Kind nvarchar(16),
@Value nvarchar(64),
@ReleaseReason nvarchar(512)
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
IF @ReleaseReason IS NULL OR LEN(@ReleaseReason) = 0
BEGIN
RAISERROR('ReleaseReason is required', 16, 1);
RETURN;
END
UPDATE dbo.ExternalIdReservation
SET ReleasedAt = SYSUTCDATETIME(),
ReleasedBy = SUSER_SNAME(),
ReleaseReason = @ReleaseReason
WHERE Kind = @Kind AND Value = @Value AND ReleasedAt IS NULL;
IF @@ROWCOUNT = 0
BEGIN
RAISERROR('No active reservation found for (%s, %s)', 16, 1, @Kind, @Value);
RETURN;
END
INSERT dbo.ConfigAuditLog (Principal, EventType, DetailsJson)
VALUES (SUSER_SNAME(), 'ExternalIdReleased',
CONCAT('{""kind"":""', STRING_ESCAPE(@Kind, 'json'),
'"",""value"":""', STRING_ESCAPE(@Value, 'json'), '""}'));
END
";
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql(PreCheckSql);
migrationBuilder.Sql("IF OBJECT_ID(N'dbo.sp_ReleaseExternalIdReservation', N'P') IS NOT NULL DROP PROCEDURE dbo.sp_ReleaseExternalIdReservation;");
migrationBuilder.DropTable(
name: "ExternalIdReservation");
migrationBuilder.DropIndex(
name: "UX_Script_LogicalId",
table: "Script");
migrationBuilder.DropIndex(
name: "IX_Equipment_SAPID",
table: "Equipment");
migrationBuilder.DropIndex(
name: "IX_Equipment_ZTag",
table: "Equipment");
migrationBuilder.AlterColumn<string>(
name: "ScriptId",
table: "Script",
type: "nvarchar(64)",
maxLength: 64,
nullable: false,
oldClrType: typeof(string),
oldType: "nvarchar(64)",
oldMaxLength: 64,
oldNullable: true);
migrationBuilder.AddUniqueConstraint(
name: "UX_Script_LogicalId",
table: "Script",
column: "ScriptId");
migrationBuilder.CreateIndex(
name: "UX_Equipment_SAPID",
table: "Equipment",
column: "SAPID",
unique: true,
filter: "[SAPID] IS NOT NULL AND [SAPID] <> N''");
migrationBuilder.CreateIndex(
name: "UX_Equipment_ZTag",
table: "Equipment",
column: "ZTag",
unique: true,
filter: "[ZTag] IS NOT NULL AND [ZTag] <> N''");
migrationBuilder.AddForeignKey(
name: "FK_ScriptedAlarm_Script",
table: "ScriptedAlarm",
column: "PredicateScriptId",
principalTable: "Script",
principalColumn: "ScriptId",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_VirtualTag_Script",
table: "VirtualTag",
column: "ScriptId",
principalTable: "Script",
principalColumn: "ScriptId",
onDelete: ReferentialAction.Restrict);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_ScriptedAlarm_Script",
table: "ScriptedAlarm");
migrationBuilder.DropForeignKey(
name: "FK_VirtualTag_Script",
table: "VirtualTag");
migrationBuilder.DropUniqueConstraint(
name: "UX_Script_LogicalId",
table: "Script");
migrationBuilder.DropIndex(
name: "UX_Equipment_SAPID",
table: "Equipment");
migrationBuilder.DropIndex(
name: "UX_Equipment_ZTag",
table: "Equipment");
migrationBuilder.AlterColumn<string>(
name: "ScriptId",
table: "Script",
type: "nvarchar(64)",
maxLength: 64,
nullable: true,
oldClrType: typeof(string),
oldType: "nvarchar(64)",
oldMaxLength: 64);
migrationBuilder.CreateTable(
name: "ExternalIdReservation",
columns: table => new
{
ReservationId = table.Column<Guid>(type: "uniqueidentifier", nullable: false, defaultValueSql: "NEWSEQUENTIALID()"),
ClusterId = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: false),
EquipmentUuid = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
FirstPublishedAt = table.Column<DateTime>(type: "datetime2(3)", nullable: false, defaultValueSql: "SYSUTCDATETIME()"),
FirstPublishedBy = table.Column<string>(type: "nvarchar(128)", maxLength: 128, nullable: false),
Kind = table.Column<string>(type: "nvarchar(16)", maxLength: 16, nullable: false),
LastPublishedAt = table.Column<DateTime>(type: "datetime2(3)", nullable: false, defaultValueSql: "SYSUTCDATETIME()"),
ReleaseReason = table.Column<string>(type: "nvarchar(512)", maxLength: 512, nullable: true),
ReleasedAt = table.Column<DateTime>(type: "datetime2(3)", nullable: true),
ReleasedBy = table.Column<string>(type: "nvarchar(128)", maxLength: 128, nullable: true),
Value = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ExternalIdReservation", x => x.ReservationId);
});
migrationBuilder.CreateIndex(
name: "UX_Script_LogicalId",
table: "Script",
column: "ScriptId",
unique: true,
filter: "[ScriptId] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_Equipment_SAPID",
table: "Equipment",
column: "SAPID",
filter: "[SAPID] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_Equipment_ZTag",
table: "Equipment",
column: "ZTag",
filter: "[ZTag] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_ExternalIdReservation_Equipment",
table: "ExternalIdReservation",
column: "EquipmentUuid");
migrationBuilder.CreateIndex(
name: "UX_ExternalIdReservation_KindValue_Active",
table: "ExternalIdReservation",
columns: new[] { "Kind", "Value" },
unique: true,
filter: "[ReleasedAt] IS NULL");
migrationBuilder.Sql(ReleaseExternalIdReservationProc);
migrationBuilder.Sql(@"
IF DATABASE_PRINCIPAL_ID('OtOpcUaAdmin') IS NOT NULL
GRANT EXECUTE ON OBJECT::dbo.sp_ReleaseExternalIdReservation TO OtOpcUaAdmin;");
}
}
}
@@ -864,15 +864,17 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations
.HasDatabaseName("IX_Equipment_MachineCode");
b.HasIndex("SAPID")
.HasDatabaseName("IX_Equipment_SAPID")
.HasFilter("[SAPID] IS NOT NULL");
.IsUnique()
.HasDatabaseName("UX_Equipment_SAPID")
.HasFilter("[SAPID] IS NOT NULL AND [SAPID] <> N''");
b.HasIndex("UnsLineId")
.HasDatabaseName("IX_Equipment_Line");
b.HasIndex("ZTag")
.HasDatabaseName("IX_Equipment_ZTag")
.HasFilter("[ZTag] IS NOT NULL");
.IsUnique()
.HasDatabaseName("UX_Equipment_ZTag")
.HasFilter("[ZTag] IS NOT NULL AND [ZTag] <> N''");
b.HasIndex("UnsLineId", "Name")
.IsUnique()
@@ -881,70 +883,6 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations
b.ToTable("Equipment", (string)null);
});
modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ExternalIdReservation", b =>
{
b.Property<Guid>("ReservationId")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier")
.HasDefaultValueSql("NEWSEQUENTIALID()");
b.Property<string>("ClusterId")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<Guid>("EquipmentUuid")
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("FirstPublishedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime2(3)")
.HasDefaultValueSql("SYSUTCDATETIME()");
b.Property<string>("FirstPublishedBy")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("nvarchar(128)");
b.Property<string>("Kind")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("nvarchar(16)");
b.Property<DateTime>("LastPublishedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime2(3)")
.HasDefaultValueSql("SYSUTCDATETIME()");
b.Property<string>("ReleaseReason")
.HasMaxLength(512)
.HasColumnType("nvarchar(512)");
b.Property<DateTime?>("ReleasedAt")
.HasColumnType("datetime2(3)");
b.Property<string>("ReleasedBy")
.HasMaxLength(128)
.HasColumnType("nvarchar(128)");
b.Property<string>("Value")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.HasKey("ReservationId");
b.HasIndex("EquipmentUuid")
.HasDatabaseName("IX_ExternalIdReservation_Equipment");
b.HasIndex("Kind", "Value")
.IsUnique()
.HasDatabaseName("UX_ExternalIdReservation_KindValue_Active")
.HasFilter("[ReleasedAt] IS NULL");
b.ToTable("ExternalIdReservation", (string)null);
});
modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.LdapGroupRoleMapping", b =>
{
b.Property<Guid>("Id")
@@ -1362,6 +1300,7 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations
.HasColumnType("rowversion");
b.Property<string>("ScriptId")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
@@ -1376,10 +1315,8 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations
b.HasKey("ScriptRowId");
b.HasIndex("ScriptId")
.IsUnique()
.HasDatabaseName("UX_Script_LogicalId")
.HasFilter("[ScriptId] IS NOT NULL");
b.HasAlternateKey("ScriptId")
.HasName("UX_Script_LogicalId");
b.HasIndex("SourceHash")
.HasDatabaseName("IX_Script_SourceHash");
@@ -1991,6 +1928,17 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations
.IsRequired();
});
modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ScriptedAlarm", b =>
{
b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.Script", null)
.WithMany()
.HasForeignKey("PredicateScriptId")
.HasPrincipalKey("ScriptId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired()
.HasConstraintName("FK_ScriptedAlarm_Script");
});
modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.UnsArea", b =>
{
b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", "Cluster")
@@ -2002,6 +1950,17 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations
b.Navigation("Cluster");
});
modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.VirtualTag", b =>
{
b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.Script", null)
.WithMany()
.HasForeignKey("ScriptId")
.HasPrincipalKey("ScriptId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired()
.HasConstraintName("FK_VirtualTag_Script");
});
modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ClusterNode", b =>
{
b.Navigation("Credentials");
@@ -50,8 +50,6 @@ public sealed class OtOpcUaConfigDbContext(DbContextOptions<OtOpcUaConfigDbConte
public DbSet<ApiKey> ApiKeys => Set<ApiKey>();
/// <summary>Gets the DbSet of configuration audit logs.</summary>
public DbSet<ConfigAuditLog> ConfigAuditLogs => Set<ConfigAuditLog>();
/// <summary>Gets the DbSet of external ID reservations.</summary>
public DbSet<ExternalIdReservation> ExternalIdReservations => Set<ExternalIdReservation>();
/// <summary>Gets the DbSet of LDAP group role mappings.</summary>
public DbSet<LdapGroupRoleMapping> LdapGroupRoleMappings => Set<LdapGroupRoleMapping>();
/// <summary>Gets the DbSet of scripts.</summary>
@@ -104,7 +102,6 @@ public sealed class OtOpcUaConfigDbContext(DbContextOptions<OtOpcUaConfigDbConte
ConfigureNodeAcl(modelBuilder);
ConfigureApiKey(modelBuilder);
ConfigureConfigAuditLog(modelBuilder);
ConfigureExternalIdReservation(modelBuilder);
ConfigureLdapGroupRoleMapping(modelBuilder);
ConfigureScript(modelBuilder);
ConfigureVirtualTag(modelBuilder);
@@ -454,8 +451,16 @@ public sealed class OtOpcUaConfigDbContext(DbContextOptions<OtOpcUaConfigDbConte
e.HasIndex(x => x.EquipmentId).IsUnique().HasDatabaseName("UX_Equipment_LogicalId");
e.HasIndex(x => new { x.UnsLineId, x.Name }).IsUnique().HasDatabaseName("UX_Equipment_LinePath");
e.HasIndex(x => x.EquipmentUuid).IsUnique().HasDatabaseName("UX_Equipment_Uuid");
e.HasIndex(x => x.ZTag).HasFilter("[ZTag] IS NOT NULL").HasDatabaseName("IX_Equipment_ZTag");
e.HasIndex(x => x.SAPID).HasFilter("[SAPID] IS NOT NULL").HasDatabaseName("IX_Equipment_SAPID");
// lmxopcua#1049 (#998 C-3 follow-up): ZTag and SAPID are unique fleet-wide. The deploy gate
// (DraftValidator.ValidateEquipmentExternalIdUniqueness, trimmed + case-insensitive, blank = none) stays
// the authority that names every duplicate; these filtered UNIQUE indexes are the storage backstop, so a
// concurrent save or a hand edit cannot persist a second claim. The filter matches the gate's "blank
// means no identifier" (SQL Server compares '' and ' ' equal, so both are exempt); the column
// collation is case-insensitive, as the gate is. ExternalIdReservation is retired (same issue).
e.HasIndex(x => x.ZTag).IsUnique()
.HasFilter("[ZTag] IS NOT NULL AND [ZTag] <> N''").HasDatabaseName("UX_Equipment_ZTag");
e.HasIndex(x => x.SAPID).IsUnique()
.HasFilter("[SAPID] IS NOT NULL AND [SAPID] <> N''").HasDatabaseName("UX_Equipment_SAPID");
e.HasIndex(x => x.MachineCode).HasDatabaseName("IX_Equipment_MachineCode");
});
}
@@ -612,34 +617,11 @@ public sealed class OtOpcUaConfigDbContext(DbContextOptions<OtOpcUaConfigDbConte
});
}
private static void ConfigureExternalIdReservation(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ExternalIdReservation>(e =>
{
e.ToTable("ExternalIdReservation");
e.HasKey(x => x.ReservationId);
e.Property(x => x.ReservationId).HasDefaultValueSql("NEWSEQUENTIALID()");
e.Property(x => x.Kind).HasConversion<string>().HasMaxLength(16);
e.Property(x => x.Value).HasMaxLength(64);
e.Property(x => x.ClusterId).HasMaxLength(64);
e.Property(x => x.FirstPublishedAt).HasColumnType("datetime2(3)").HasDefaultValueSql("SYSUTCDATETIME()");
e.Property(x => x.FirstPublishedBy).HasMaxLength(128);
e.Property(x => x.LastPublishedAt).HasColumnType("datetime2(3)").HasDefaultValueSql("SYSUTCDATETIME()");
e.Property(x => x.ReleasedAt).HasColumnType("datetime2(3)");
e.Property(x => x.ReleasedBy).HasMaxLength(128);
e.Property(x => x.ReleaseReason).HasMaxLength(512);
// Active reservations unique per (Kind, Value) — filtered index lets released rows coexist with a new reservation of the same value.
// The UX_ filtered index covers active-reservation lookups; history queries over released rows
// fall back to the table scan (released rows are rare + small). No separate non-unique (Kind, Value)
// index is declared because EF Core merges duplicate column sets into a single index, which would
// clobber the filtered-unique name.
e.HasIndex(x => new { x.Kind, x.Value }).IsUnique()
.HasFilter("[ReleasedAt] IS NULL")
.HasDatabaseName("UX_ExternalIdReservation_KindValue_Active");
e.HasIndex(x => x.EquipmentUuid).HasDatabaseName("IX_ExternalIdReservation_Equipment");
});
}
// ConfigureExternalIdReservation is GONE (lmxopcua#1049). The ledger's only writer was sp_PublishGeneration,
// retired with the generation model, so the table stayed empty and the reservation pre-flight could not fire.
// Fleet-wide ZTag / SAPID uniqueness is the deploy gate's DraftValidator rule plus the filtered unique indexes
// on Equipment (ConfigureEquipment). Migration ScriptForeignKeysAndExternalIdUniqueness drops the table and
// sp_ReleaseExternalIdReservation, refusing (THROW) while any row exists so no history is silently deleted.
// ConfigureDriverHostStatus is GONE. The DriverHostStatus table held per-host
// connectivity that a publisher hosted service was supposed to upsert from each driver node. That
@@ -729,7 +711,10 @@ public sealed class OtOpcUaConfigDbContext(DbContextOptions<OtOpcUaConfigDbConte
e.Property(x => x.Language).HasMaxLength(16);
e.Property(x => x.RowVersion).IsRowVersion();
e.HasIndex(x => x.ScriptId).IsUnique().HasDatabaseName("UX_Script_LogicalId");
// The logical id is the principal key of VirtualTag.ScriptId / ScriptedAlarm.PredicateScriptId
// (lmxopcua#1040). An alternate key is a unique constraint, so it replaces the former unique index of
// the same name instead of sitting beside it.
e.HasAlternateKey(x => x.ScriptId).HasName("UX_Script_LogicalId");
e.HasIndex(x => x.SourceHash).HasDatabaseName("IX_Script_SourceHash");
});
}
@@ -757,6 +742,15 @@ public sealed class OtOpcUaConfigDbContext(DbContextOptions<OtOpcUaConfigDbConte
e.HasIndex(x => x.VirtualTagId).IsUnique().HasDatabaseName("UX_VirtualTag_LogicalId");
e.HasIndex(x => new { x.EquipmentId, x.Name }).IsUnique().HasDatabaseName("UX_VirtualTag_EquipmentPath");
e.HasIndex(x => x.ScriptId).HasDatabaseName("IX_VirtualTag_Script");
// lmxopcua#1040 (#978 C-2 follow-up): a real FK. The deploy gate's VirtualTagScriptNotFound rule and the
// /scripts in-use delete guard still name the problem; this makes the database refuse it too (a delete
// racing a new reference, a hand edit). Restrict: deleting an in-use script is an error, never a cascade.
e.HasOne<Script>().WithMany()
.HasForeignKey(x => x.ScriptId)
.HasPrincipalKey(x => x.ScriptId)
.OnDelete(DeleteBehavior.Restrict)
.HasConstraintName("FK_VirtualTag_Script");
});
}
@@ -783,6 +777,13 @@ public sealed class OtOpcUaConfigDbContext(DbContextOptions<OtOpcUaConfigDbConte
e.HasIndex(x => x.ScriptedAlarmId).IsUnique().HasDatabaseName("UX_ScriptedAlarm_LogicalId");
e.HasIndex(x => new { x.EquipmentId, x.Name }).IsUnique().HasDatabaseName("UX_ScriptedAlarm_EquipmentPath");
e.HasIndex(x => x.PredicateScriptId).HasDatabaseName("IX_ScriptedAlarm_Script");
// lmxopcua#1040: as FK_VirtualTag_Script — the predicate script must exist; deleting it is refused.
e.HasOne<Script>().WithMany()
.HasForeignKey(x => x.PredicateScriptId)
.HasPrincipalKey(x => x.ScriptId)
.OnDelete(DeleteBehavior.Restrict)
.HasConstraintName("FK_ScriptedAlarm_Script");
});
}
@@ -1,54 +0,0 @@
using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
namespace ZB.MOM.WW.OtOpcUa.Configuration.Queries;
/// <summary>One displayed <c>ExternalIdReservation</c> row (only the columns the /reservations page shows).</summary>
/// <param name="Kind">ZTag or SAPID.</param>
/// <param name="Value">The reserved external id.</param>
/// <param name="EquipmentUuid">Owning equipment.</param>
/// <param name="ClusterId">Cluster it was published in.</param>
/// <param name="ReleasedAt">When it was released, or null while active.</param>
public sealed record ReservationRow(ReservationKind Kind, string Value, Guid EquipmentUuid, string ClusterId, DateTime? ReleasedAt);
/// <summary>A bounded page of reservations plus the total matching the filter.</summary>
/// <param name="Rows">At most <c>pageSize</c> rows, ordered by kind then value.</param>
/// <param name="Total">All rows matching the filter (so the page can say "showing N of M").</param>
public sealed record ReservationPage(IReadOnlyList<ReservationRow> Rows, int Total);
/// <summary>
/// The /reservations page's read (lmxopcua#996, review A-8): active rows by default, projected to the displayed columns and
/// capped — the page used to render every row, released ones included, which accumulate for the life of the database.
/// </summary>
public static class ReservationListQuery
{
/// <summary>Rows shown per page (the cluster-audit page's size).</summary>
public const int DefaultPageSize = 200;
/// <summary>The filtered, ordered, projected query (exposed so a test can pin its SQL shape).</summary>
/// <param name="db">The config DB context.</param>
/// <param name="includeReleased">True to include released rows.</param>
/// <returns>The unbounded ordered projection.</returns>
public static IQueryable<ReservationRow> Query(OtOpcUaConfigDbContext db, bool includeReleased)
{
var rows = db.ExternalIdReservations.AsNoTracking().AsQueryable();
if (!includeReleased) rows = rows.Where(r => r.ReleasedAt == null);
return rows.OrderBy(r => r.Kind).ThenBy(r => r.Value)
.Select(r => new ReservationRow(r.Kind, r.Value, r.EquipmentUuid, r.ClusterId, r.ReleasedAt));
}
/// <summary>Loads one capped page and the total count for the filter.</summary>
/// <param name="db">The config DB context.</param>
/// <param name="includeReleased">True to include released rows.</param>
/// <param name="pageSize">Maximum rows returned.</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>The page and the total.</returns>
public static async Task<ReservationPage> LoadAsync(
OtOpcUaConfigDbContext db, bool includeReleased, int pageSize = DefaultPageSize, CancellationToken ct = default)
{
var query = Query(db, includeReleased);
var total = await query.CountAsync(ct);
var rows = await query.Take(pageSize).ToListAsync(ct);
return new ReservationPage(rows, total);
}
}
@@ -77,7 +77,4 @@ public sealed class DraftSnapshot
/// composer ships the keys a driver-only node authenticates against from the one consistent read.
/// </summary>
public IReadOnlyList<ApiKey> ApiKeys { get; init; } = [];
/// <summary>Active reservations (<c>ReleasedAt IS NULL</c>) for pre-flight.</summary>
public IReadOnlyList<ExternalIdReservation> ActiveReservations { get; init; } = [];
}
@@ -165,9 +165,5 @@ public static class DraftSnapshotFactory
PollGroups = await db.PollGroups.AsNoTracking().OrderBy(x => x.PollGroupId).ToListAsync(ct),
NodeAcls = await db.NodeAcls.AsNoTracking().OrderBy(x => x.NodeAclId).ToListAsync(ct),
ApiKeys = await db.ApiKeys.AsNoTracking().OrderBy(x => x.ApiKeyId).ToListAsync(ct),
ActiveReservations = await db.ExternalIdReservations
.AsNoTracking()
.Where(r => r.ReleasedAt == null) // active only — matches DraftSnapshot.ActiveReservations semantics
.ToListAsync(ct),
};
}
@@ -28,7 +28,6 @@ public static class DraftValidator
ValidateUnsSegments(draft, errors);
ValidateDanglingReferences(draft, errors);
ValidateEquipmentExternalIdUniqueness(draft, errors);
ValidateReservationPreflight(draft, errors);
ValidateEquipmentIdDerivation(draft, errors);
// v3 rules. The retired rules ValidateSameClusterNamespaceBinding (Namespace entity gone)
@@ -47,6 +46,7 @@ public static class DraftValidator
ValidateSqlConnectionStringNotPersisted(draft, errors);
errors.AddRange(SqlTagDeployChecks.UndeclaredQueryErrors(draft));
errors.AddRange(SqlTagDeployChecks.WriteBlockErrors(draft));
errors.AddRange(SqlTagDeployChecks.NamedQueryErrors(draft));
ValidateMTConnectSingleDevice(draft, errors);
errors.AddRange(HeidenhainDeployChecks.Errors(draft));
errors.AddRange(CredentialReferenceDeployChecks.Errors(draft));
@@ -1069,9 +1069,10 @@ public static class DraftValidator
/// <summary>
/// lmxopcua#998 (review C-3): <c>Equipment.ZTag</c> and <c>Equipment.SAPID</c> are unique fleet-wide. The
/// former writer of the reservation ledger (<c>sp_PublishGeneration</c>) is gone, so
/// <see cref="ValidateReservationPreflight"/> alone enforced nothing; the draft snapshot is the whole config
/// DB (every cluster), so the duplicate check is done here, on the draft, which IS the authority.
/// former writer of the reservation ledger (<c>sp_PublishGeneration</c>) is gone, and the ledger itself was
/// retired by lmxopcua#1049; the draft snapshot is the whole config DB (every cluster), so the duplicate check
/// is done here, on the draft, which IS the authority. The filtered unique indexes <c>UX_Equipment_ZTag</c> /
/// <c>UX_Equipment_SAPID</c> are the storage backstop (never stricter than this rule).
/// Compared trimmed and case-insensitively (the DB collation is); blank values mean "no identifier".
/// </summary>
private static void ValidateEquipmentExternalIdUniqueness(DraftSnapshot draft, List<ValidationError> errors)
@@ -1098,29 +1099,6 @@ public static class DraftValidator
Check("SAPID", e => e.SAPID);
}
private static void ValidateReservationPreflight(DraftSnapshot draft, List<ValidationError> errors)
{
var activeByKindValue = draft.ActiveReservations
.ToDictionary(r => (r.Kind, r.Value), r => r.EquipmentUuid);
foreach (var eq in draft.Equipment)
{
if (eq.ZTag is not null &&
activeByKindValue.TryGetValue((ReservationKind.ZTag, eq.ZTag), out var ztagOwner) &&
ztagOwner != eq.EquipmentUuid)
errors.Add(new("BadDuplicateExternalIdentifier",
$"ZTag '{eq.ZTag}' is already reserved by EquipmentUuid '{ztagOwner}'",
eq.EquipmentId));
if (eq.SAPID is not null &&
activeByKindValue.TryGetValue((ReservationKind.SAPID, eq.SAPID), out var sapOwner) &&
sapOwner != eq.EquipmentUuid)
errors.Add(new("BadDuplicateExternalIdentifier",
$"SAPID '{eq.SAPID}' is already reserved by EquipmentUuid '{sapOwner}'",
eq.EquipmentId));
}
}
/// <summary>EquipmentId = 'EQ-' + lowercase first 12 hex chars of the UUID.</summary>
/// <param name="uuid">The equipment UUID to derive the ID from.</param>
/// <returns>The derived <c>EQ-</c>-prefixed EquipmentId.</returns>
@@ -106,6 +106,69 @@ public static class SqlTagDeployChecks
return errors;
}
/// <summary>Error code for a named query the Sql driver would refuse at construction (lmxopcua#1058).</summary>
public const string NamedQueryInvalidCode = "SqlNamedQueryInvalid";
/// <summary>
/// The driver factory's config reader options (<c>SqlDriverFactoryExtensions.JsonOptions</c>, which lives in the
/// driver assembly this one does not reference): case-insensitive, comments + trailing commas tolerated, unknown
/// members skipped, enums by name. Keep in step — a looser reader here could pass a blob the driver refuses.
/// </summary>
private static readonly JsonSerializerOptions SqlConfigJson = new()
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
ReadCommentHandling = JsonCommentHandling.Skip,
AllowTrailingCommas = true,
UnmappedMemberHandling = System.Text.Json.Serialization.JsonUnmappedMemberHandling.Skip,
Converters = { new System.Text.Json.Serialization.JsonStringEnumConverter() },
};
/// <summary>
/// lmxopcua#1058 (#974 follow-up). The driver checks every <c>queries</c> entry with
/// <see cref="SqlNamedQueryRules.Describe"/> under its provider when it is constructed, and ONE refused query
/// fails the whole driver — every tag on it reads <c>BadNodeIdUnknown</c>. Since #974 that includes a T-SQL
/// ScriptDom parse for SqlServer / Odbc, so an Odbc query written in another dialect (PostgreSQL <c>::</c> casts,
/// <c>LIMIT</c>) that used to pass is refused. This runs the same rule over the same merged config (DriverConfig
/// plus, for a single-device instance, the DeviceConfig) so the deploy refuses what the driver would. A blob that
/// does not parse, or names an unknown provider, is left to the driver's own construction error.
/// </summary>
/// <param name="draft">The snapshot being validated.</param>
/// <returns>One error per refused named query.</returns>
public static IReadOnlyList<ValidationError> NamedQueryErrors(DraftSnapshot draft)
{
var errors = new List<ValidationError>();
foreach (var (driver, devices) in SqlInstances(draft))
{
SqlDriverConfigDto? dto;
try
{
var merged = DriverDeviceConfigMerger.Merge(
driver.DriverConfig, devices.Select(d => new DriverDeviceConfigMerger.DeviceRow(d.Name, d.DeviceConfig)).ToList(), []);
dto = JsonSerializer.Deserialize<SqlDriverConfigDto>(merged, SqlConfigJson);
}
catch (JsonException)
{
continue;
}
if (dto?.Queries is not { Count: > 0 } queries) continue;
foreach (var (name, query) in queries.OrderBy(q => q.Key, StringComparer.Ordinal))
{
if (SqlNamedQueryRules.Describe(name, query, dto.Provider) is not { } problem) continue;
errors.Add(new(NamedQueryInvalidCode,
$"Sql driver instance '{driver.DriverInstanceId}' (provider {dto.Provider}): {problem} — the driver " +
"refuses its whole config at start, so every tag on it would read BadNodeIdUnknown. Rewrite the query " +
(dto.Provider == SqlProvider.Odbc
? "so it parses as a single T-SQL SELECT (an Odbc backend is unknown, so the strictest dialect applies), or use the backend's native provider."
: "as a single read-only SELECT."),
driver.DriverInstanceId));
}
}
return errors;
}
/// <summary>The merged config's <c>provider</c> (default SqlServer), or null when it is not a provider name.</summary>
private static SqlProvider? ReadProvider(DriverInstance driver, List<Device> devices)
{
@@ -28,7 +28,6 @@
<NavRailItem Href="/raw" Text="Raw" />
<NavRailItem Href="/deployments" Text="Deployments" />
</AuthorizeView>
<NavRailItem Href="/reservations" Text="Reservations" />
<NavRailItem Href="/certificates" Text="Certificates" />
</NavRailSection>
<NavRailSection Title="Scripting" Key="scripting">
@@ -1,82 +0,0 @@
@page "/reservations"
@attribute [Authorize(Policy = AdminUiPolicies.AuthenticatedRead)]
@rendermode RenderMode.InteractiveServer
@using Microsoft.EntityFrameworkCore
@using ZB.MOM.WW.OtOpcUa.Configuration
@using ZB.MOM.WW.OtOpcUa.Configuration.Queries
@inject IDbContextFactory<OtOpcUaConfigDbContext> DbFactory
<PageErrorBoundary>
<PageTitle>External ID reservations · OtOpcUa</PageTitle>
<div class="page-head">
<h1>External ID reservations</h1>
<span class="spacer"></span>
<label class="form-check-label"><input type="checkbox" class="form-check-input" checked="@_includeReleased" @onchange="ToggleReleased" /> Show released</label>
</div>
@if (_rows is null)
{
<p>Loading…</p>
}
else
{
<section class="panel rise mt-3" style="animation-delay:.08s">
<h2 class="panel-head">@(_total > _rows.Count ? $"Showing {_rows.Count} of {_total}" : _total.ToString()) @(_includeReleased ? "" : "active ")reservation@(_total == 1 ? "" : "s")</h2>
@if (_rows.Count == 0)
{
<div style="padding:1rem" class="text-muted">No reservations. (Nothing writes this ledger any more: ZTag / SAPID uniqueness is enforced by the deploy gate.)</div>
}
else
{
<div class="table-wrap" role="region" aria-label="External ID reservations" tabindex="0">
<table class="data-table">
<thead>
<tr>
<th scope="col">Kind</th>
<th scope="col">Value</th>
<th scope="col">Equipment UUID</th>
<th scope="col">Cluster</th>
@if (_includeReleased) { <th scope="col">Released</th> }
</tr>
</thead>
<tbody>
@foreach (var r in _rows)
{
<tr>
<td><span class="chip chip-idle">@r.Kind</span></td>
<td><span class="mono">@r.Value</span></td>
<td><span class="mono small">@r.EquipmentUuid</span></td>
<td><span class="mono small">@r.ClusterId</span></td>
@if (_includeReleased) { <td><span class="mono small">@(r.ReleasedAt?.ToString("u") ?? "active")</span></td> }
</tr>
}
</tbody>
</table>
</div>
}
</section>
}
</PageErrorBoundary>
@code {
private IReadOnlyList<ReservationRow>? _rows;
private int _total;
private bool _includeReleased;
protected override async Task OnInitializedAsync() => await LoadAsync();
private async Task ToggleReleased(ChangeEventArgs e)
{
_includeReleased = e.Value is true;
await LoadAsync();
}
private async Task LoadAsync()
{
// Active rows only by default, projected to the shown columns and capped (#996 / A-8).
await using var db = await DbFactory.CreateDbContextAsync();
var page = await ReservationListQuery.LoadAsync(db, _includeReleased);
_rows = page.Rows;
_total = page.Total;
}
}
@@ -255,8 +255,10 @@ else
var entity = await db.Scripts.FirstOrDefaultAsync(s => s.ScriptId == intent.Id);
if (!Current(generation)) return;
if (entity is null) { Nav.NavigateTo("/scripts"); return; }
// lmxopcua#978 (review C-2): no FK protects a script in use, so refuse here and name the users —
// a deleted predicate used to drop its scripted alarm silently on the next green deploy.
// lmxopcua#978 (review C-2): refuse here and name the users — a deleted predicate used to drop its
// scripted alarm silently on the next green deploy. FK_VirtualTag_Script / FK_ScriptedAlarm_Script
// (lmxopcua#1040) back this for a reference added concurrently; Calculation tags (TagConfig JSON) only
// have this check.
var inUse = await ZB.MOM.WW.OtOpcUa.AdminUI.Uns.ScriptUsage.DescribeBlockingUsageAsync(db, intent.Id);
if (!Current(generation)) return;
if (inUse is not null)
@@ -272,6 +274,7 @@ else
if (Current(generation)) Nav.NavigateTo("/scripts");
}
catch (DbUpdateConcurrencyException) { if (Current(generation)) _error = "Another user changed this script while you were viewing it."; }
catch (DbUpdateException) { if (Current(generation)) _error = "Not deleted: a virtual tag or scripted alarm started using this script meanwhile. Reload to see its users."; }
catch (Exception ex) { if (Current(generation)) _error = $"Delete failed: {ex.Message}."; }
finally { if (Current(generation)) _busy = false; }
}
@@ -117,12 +117,12 @@ else
<div class="col-md-6 mb-3">
<label class="form-label" for='@FieldId("eq-ztag")'>ZTag (ERP)</label>
<InputText id='@FieldId("eq-ztag")' aria-describedby='@FieldId("eq-ztag-hint")' @bind-Value="form.ZTag" class="form-control form-control-sm" />
<div id='@FieldId("eq-ztag-hint")' class="form-text">Must be unique fleet-wide (case-insensitive); a duplicate is rejected when you deploy.</div>
<div id='@FieldId("eq-ztag-hint")' class="form-text">Must be unique fleet-wide (case-insensitive); a value another equipment holds is refused on save.</div>
</div>
<div class="col-md-6 mb-3">
<label class="form-label" for='@FieldId("eq-sap")'>SAPID</label>
<InputText id='@FieldId("eq-sap")' @bind-Value="form.SAPID" class="form-control form-control-sm" />
<div class="form-text">Must be unique fleet-wide (case-insensitive); a duplicate is rejected when you deploy.</div>
<div class="form-text">Must be unique fleet-wide (case-insensitive); a value another equipment holds is refused on save.</div>
</div>
</div>
<div class="mb-3">
@@ -139,13 +139,13 @@ public sealed class UnsTreeService(
// Backing tag missing (should not happen — raw-tag delete is reference-blocked); surface a
// clearly-degraded row rather than dropping it so the operator can remove the dangling ref.
rows.Add(new EquipmentReferenceRow(
r.UnsTagReferenceId, r.DisplayNameOverride ?? "(missing tag)", "(missing tag)",
r.UnsTagReferenceId, EquipmentReferenceMap.EffectiveName(r.DisplayNameOverride, "(missing tag)")!, "(missing tag)",
"", TagAccessLevel.Read, r.DisplayNameOverride, r.SortOrder, r.RowVersion));
continue;
}
var rawPath = resolver?.TryBuildTagPath(tag.DeviceId, tag.TagGroupId, tag.Name) ?? tag.Name;
var effectiveName = string.IsNullOrEmpty(r.DisplayNameOverride) ? tag.Name : r.DisplayNameOverride;
var effectiveName = EquipmentReferenceMap.EffectiveName(r.DisplayNameOverride, tag.Name)!;
rows.Add(new EquipmentReferenceRow(
r.UnsTagReferenceId, effectiveName, rawPath, tag.DataType, tag.AccessLevel,
r.DisplayNameOverride, r.SortOrder, r.RowVersion));
@@ -887,6 +887,8 @@ public sealed class UnsTreeService(
if (EquipmentLengthError(input) is { } tooLong) return new UnsMutationResult(false, tooLong);
if (await ExternalIdClashAsync(db, input, excludeEquipmentId: null, ct) is { } clash) return new UnsMutationResult(false, clash);
// v3: equipment no longer binds a driver — the reference-only Tags tab points at raw tags — so
// the old driver-cluster guard is gone.
@@ -901,8 +903,8 @@ public sealed class UnsTreeService(
UnsLineId = input.UnsLineId,
Name = input.Name,
MachineCode = input.MachineCode,
ZTag = string.IsNullOrWhiteSpace(input.ZTag) ? null : input.ZTag,
SAPID = string.IsNullOrWhiteSpace(input.SAPID) ? null : input.SAPID,
ZTag = ExternalId(input.ZTag),
SAPID = ExternalId(input.SAPID),
Manufacturer = input.Manufacturer,
Model = input.Model,
SerialNumber = input.SerialNumber,
@@ -921,7 +923,7 @@ public sealed class UnsTreeService(
}
catch (DbUpdateException)
{
return new UnsMutationResult(false, DuplicateEquipmentName(input.Name) + " (or a value was rejected by the database) - reload and retry.");
return new UnsMutationResult(false, DuplicateEquipmentName(input.Name) + " (or another equipment now holds this MachineCode, ZTag or SAPID) - reload and retry.");
}
}
@@ -947,6 +949,20 @@ public sealed class UnsTreeService(
.Select(e => (e.UnsLineId, e.Name))
.ToHashSet(LineNameComparer.Instance);
// lmxopcua#1049: ZTag / SAPID are unique fleet-wide (UX_Equipment_ZTag / UX_Equipment_SAPID, and the deploy
// gate). Owners already in the DB plus those claimed earlier in this batch, case-insensitive as both are — a
// clash would otherwise fail the WHOLE batch at SaveChanges with no row named.
var ids = await db.Equipment.AsNoTracking()
.Where(e => e.ZTag != null || e.SAPID != null)
.Select(e => new { e.EquipmentId, e.ZTag, e.SAPID }).ToListAsync(ct);
var zTagOwner = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
var sapIdOwner = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (var e in ids)
{
if (ExternalId(e.ZTag) is { } z) zTagOwner.TryAdd(z, e.EquipmentId);
if (ExternalId(e.SAPID) is { } p) sapIdOwner.TryAdd(p, e.EquipmentId);
}
var inserted = 0;
var skipped = 0;
var errors = new List<string>();
@@ -987,6 +1003,20 @@ public sealed class UnsTreeService(
continue;
}
var rowZTag = ExternalId(row.ZTag);
var rowSapId = ExternalId(row.SAPID);
if (rowZTag is not null && zTagOwner.TryGetValue(rowZTag, out var zOwner))
{
errors.Add($"Row '{row.MachineCode}': {ExternalIdTaken("ZTag", rowZTag, zOwner)}");
continue;
}
if (rowSapId is not null && sapIdOwner.TryGetValue(rowSapId, out var sOwner))
{
errors.Add($"Row '{row.MachineCode}': {ExternalIdTaken("SAPID", rowSapId, sOwner)}");
continue;
}
// v3: equipment no longer binds a driver, so there is no per-row driver-cluster guard.
var uuid = Guid.NewGuid();
@@ -1000,8 +1030,8 @@ public sealed class UnsTreeService(
UnsLineId = row.UnsLineId,
Name = row.Name,
MachineCode = row.MachineCode,
ZTag = string.IsNullOrWhiteSpace(row.ZTag) ? null : row.ZTag,
SAPID = string.IsNullOrWhiteSpace(row.SAPID) ? null : row.SAPID,
ZTag = ExternalId(row.ZTag),
SAPID = ExternalId(row.SAPID),
Manufacturer = row.Manufacturer,
Model = row.Model,
SerialNumber = row.SerialNumber,
@@ -1015,6 +1045,8 @@ public sealed class UnsTreeService(
});
existing.Add(row.MachineCode);
existingNames.Add((row.UnsLineId, row.Name));
if (rowZTag is not null) zTagOwner[rowZTag] = equipmentId;
if (rowSapId is not null) sapIdOwner[rowSapId] = equipmentId;
inserted++;
}
@@ -1028,7 +1060,7 @@ public sealed class UnsTreeService(
{
// A concurrent writer slipped a clashing row past the pre-checks: the batch is atomic, so
// nothing was imported.
errors.Add("Import failed - a concurrent change clashed with this file (duplicate name or MachineCode). Nothing was imported; reload and retry.");
errors.Add("Import failed - a concurrent change clashed with this file (duplicate name, MachineCode, ZTag or SAPID). Nothing was imported; reload and retry.");
return new EquipmentImportResult(0, skipped, errors);
}
}
@@ -1066,14 +1098,16 @@ public sealed class UnsTreeService(
if (EquipmentLengthError(input) is { } tooLong) return new UnsMutationResult(false, tooLong);
if (await ExternalIdClashAsync(db, input, equipmentId, ct) is { } clash) return new UnsMutationResult(false, clash);
// v3: equipment no longer binds a driver — no driver-cluster guard.
// Equipment↔driver binding retired in v3 — no DriverInstanceId column remains.
entity.UnsLineId = input.UnsLineId;
entity.Name = input.Name;
entity.MachineCode = input.MachineCode;
entity.ZTag = string.IsNullOrWhiteSpace(input.ZTag) ? null : input.ZTag;
entity.SAPID = string.IsNullOrWhiteSpace(input.SAPID) ? null : input.SAPID;
entity.ZTag = ExternalId(input.ZTag);
entity.SAPID = ExternalId(input.SAPID);
entity.Manufacturer = input.Manufacturer;
entity.Model = input.Model;
entity.SerialNumber = input.SerialNumber;
@@ -1096,7 +1130,7 @@ public sealed class UnsTreeService(
}
catch (DbUpdateException)
{
return new UnsMutationResult(false, DuplicateEquipmentName(input.Name) + " (or a value was rejected by the database) - reload and retry.");
return new UnsMutationResult(false, DuplicateEquipmentName(input.Name) + " (or another equipment now holds this MachineCode, ZTag or SAPID) - reload and retry.");
}
}
@@ -1362,6 +1396,47 @@ public sealed class UnsTreeService(
/// otherwise (no slash-token, or all resolve). Replaces the v2 <c>DeriveEquipmentBase(empty)→null</c>
/// check, which rejected ALL <c>{{equip}}</c> VirtualTags with a now-impossible "add a driver tag" message.
/// </summary>
/// <summary>A ZTag / SAPID as stored: trimmed, and blank means "no identifier" (NULL) — the deploy gate's reading.</summary>
private static string? ExternalId(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim();
private static string ExternalIdTaken(string label, string value, string owner) =>
$"{label} '{value}' is already set on equipment '{owner}'; a {label} must be unique fleet-wide.";
/// <summary>
/// lmxopcua#1049: the authoring mirror of the deploy gate's <c>BadDuplicateExternalIdentifier</c> rule and of the
/// <c>UX_Equipment_ZTag</c> / <c>UX_Equipment_SAPID</c> unique indexes, naming the equipment that already holds the
/// value. Compared by the database (case-insensitive collation on SQL Server).
/// </summary>
private static async Task<string?> ExternalIdClashAsync(
OtOpcUaConfigDbContext db, EquipmentInput input, string? excludeEquipmentId, CancellationToken ct)
{
if (ExternalId(input.ZTag) is { } zTag
&& await db.Equipment.Where(e => e.ZTag == zTag && e.EquipmentId != excludeEquipmentId)
.Select(e => e.EquipmentId).FirstOrDefaultAsync(ct) is { } zOwner)
return ExternalIdTaken("ZTag", zTag, zOwner);
if (ExternalId(input.SAPID) is { } sapId
&& await db.Equipment.Where(e => e.SAPID == sapId && e.EquipmentId != excludeEquipmentId)
.Select(e => e.EquipmentId).FirstOrDefaultAsync(ct) is { } sOwner)
return ExternalIdTaken("SAPID", sapId, sOwner);
return null;
}
/// <summary>
/// lmxopcua#1040: a VirtualTag's script / a scripted alarm's predicate script must exist — the authoring mirror of
/// the deploy gate's <c>VirtualTagScriptNotFound</c> / <c>ScriptedAlarmScriptNotFound</c> rules and of the
/// <c>FK_VirtualTag_Script</c> / <c>FK_ScriptedAlarm_Script</c> constraints, said before the database refuses it.
/// </summary>
private static async Task<UnsMutationResult?> ScriptMissingAsync(OtOpcUaConfigDbContext db, string? scriptId, CancellationToken ct) =>
!string.IsNullOrEmpty(scriptId) && await db.Scripts.AnyAsync(s => s.ScriptId == scriptId, ct)
? null
: new UnsMutationResult(false, $"Script '{scriptId}' does not exist — pick an existing script.");
/// <summary>The save-time refusal when a pre-checked script vanished (or another constraint clashed) concurrently.</summary>
private static string ScriptGoneOrClash(string? scriptId) =>
$"The save was refused by the database: script '{scriptId}' may have been deleted meanwhile, or a name now clashes. Reload and retry.";
private static async Task<UnsMutationResult?> ValidateEquipTokenAsync(
OtOpcUaConfigDbContext db, string equipmentId, string scriptId, CancellationToken ct)
{
@@ -1412,9 +1487,8 @@ public sealed class UnsTreeService(
var effectiveNames = new HashSet<string>(StringComparer.Ordinal);
foreach (var r in refs)
{
var eff = string.IsNullOrEmpty(r.DisplayNameOverride)
? (tagNameById.TryGetValue(r.TagId, out var n) ? n : null)
: r.DisplayNameOverride;
var eff = EquipmentReferenceMap.EffectiveName(
r.DisplayNameOverride, tagNameById.TryGetValue(r.TagId, out var n) ? n : null);
if (!string.IsNullOrEmpty(eff)) effectiveNames.Add(eff!);
}
return effectiveNames;
@@ -1466,6 +1540,8 @@ public sealed class UnsTreeService(
var nameGuard = await _guard.CheckAsync(equipmentId, input.Name, EffectiveNameSourceKind.VirtualTag, null, ct);
if (nameGuard is not null) return new UnsMutationResult(false, nameGuard);
if (await ScriptMissingAsync(db, input.ScriptId, ct) is { } missingScript) return missingScript;
var equipGuard = await ValidateEquipTokenAsync(db, equipmentId, input.ScriptId, ct);
if (equipGuard is not null) return equipGuard.Value;
@@ -1481,8 +1557,15 @@ public sealed class UnsTreeService(
Historize = input.Historize,
Enabled = input.Enabled,
});
await db.SaveChangesAsync(ct);
return new UnsMutationResult(true, null);
try
{
await db.SaveChangesAsync(ct);
return new UnsMutationResult(true, null);
}
catch (DbUpdateException)
{
return new UnsMutationResult(false, ScriptGoneOrClash(input.ScriptId));
}
}
/// <inheritdoc />
@@ -1519,6 +1602,8 @@ public sealed class UnsTreeService(
var nameGuard = await _guard.CheckAsync(entity.EquipmentId, input.Name, EffectiveNameSourceKind.VirtualTag, virtualTagId, ct);
if (nameGuard is not null) return new UnsMutationResult(false, nameGuard);
if (await ScriptMissingAsync(db, input.ScriptId, ct) is { } missingScript) return missingScript;
var equipGuard = await ValidateEquipTokenAsync(db, entity.EquipmentId, input.ScriptId, ct);
if (equipGuard is not null) return equipGuard.Value;
@@ -1540,6 +1625,10 @@ public sealed class UnsTreeService(
{
return new UnsMutationResult(false, "Another user changed this virtual tag while you were editing.");
}
catch (DbUpdateException)
{
return new UnsMutationResult(false, ScriptGoneOrClash(input.ScriptId));
}
}
/// <inheritdoc />
@@ -1790,6 +1879,8 @@ public sealed class UnsTreeService(
if (nameGuard is not null) return new UnsMutationResult(false, nameGuard);
// v3: {{equip}}/<RefName> in the predicate script or message template must resolve.
if (await ScriptMissingAsync(db, input.PredicateScriptId, ct) is { } missingScript) return missingScript;
var equipGuard = await ValidateEquipTokenForAlarmAsync(db, equipmentId, input.PredicateScriptId, input.MessageTemplate, ct);
if (equipGuard is not null) return equipGuard.Value;
@@ -1806,8 +1897,15 @@ public sealed class UnsTreeService(
Retain = input.Retain,
Enabled = input.Enabled,
});
await db.SaveChangesAsync(ct);
return new UnsMutationResult(true, null, input.ScriptedAlarmId);
try
{
await db.SaveChangesAsync(ct);
return new UnsMutationResult(true, null, input.ScriptedAlarmId);
}
catch (DbUpdateException)
{
return new UnsMutationResult(false, ScriptGoneOrClash(input.PredicateScriptId));
}
}
/// <inheritdoc />
@@ -1828,6 +1926,8 @@ public sealed class UnsTreeService(
if (nameGuard is not null) return new UnsMutationResult(false, nameGuard);
// v3: {{equip}}/<RefName> in the predicate script or message template must resolve.
if (await ScriptMissingAsync(db, input.PredicateScriptId, ct) is { } missingScript) return missingScript;
var equipGuard = await ValidateEquipTokenForAlarmAsync(db, entity.EquipmentId, input.PredicateScriptId, input.MessageTemplate, ct);
if (equipGuard is not null) return equipGuard.Value;
@@ -1850,6 +1950,10 @@ public sealed class UnsTreeService(
{
return new UnsMutationResult(false, "Another user changed this scripted alarm while you were editing.");
}
catch (DbUpdateException)
{
return new UnsMutationResult(false, ScriptGoneOrClash(input.PredicateScriptId));
}
}
/// <inheritdoc />
@@ -550,83 +550,23 @@ public sealed class AdminOperationsActor : ReceiveActor
// derivation, cross-cluster/namespace binding, driver-namespace compat, signal collisions,
// …) gates the deploy. A green build in this repo does not prove the config is valid; this
// is the last guard before a bad address space (or a non-derived EquipmentId) ships.
// NOTE: a BadDuplicateExternalIdentifier rejection from the reservation pre-flight can
// (rarely) be a false positive if an external-id reservation release has not yet been
// committed/visible when the snapshot is read — operators seeing a spurious one should
// check ExternalIdReservation state before re-submitting.
var draft = await DraftSnapshotFactory.FromConfigDbAsync(db);
phases.Mark("snapshot-read");
var errors = DraftValidator.Validate(draft).ToList();
// Cluster-topology guard. The SQL
// CK_ServerCluster_RedundancyMode_NodeCount CHECK enforces the (NodeCount, RedundancyMode)
// pair on the row itself, but it cannot see the per-node ClusterNode.Enabled flag — an
// operator can disable a node (effective enabled-count = 1) while leaving RedundancyMode at
// Hot/Warm and the constraint stays green, which would boot the runtime into an
// InvalidTopology band. ValidateClusterTopology catches that drift; it is not part of
// DraftValidator.Validate, so it runs separately here over the snapshot's cluster/node rows.
// Errors fold into the same reject summary alongside the snapshot rules so a deploy failing
// either check is rejected with both sets of messages. ClusterId-ordered for a deterministic summary.
// R03:3.2 — both come off the SAME snapshot read as every other table (one SNAPSHOT
// transaction), not a second query that could observe a later edit.
var clusters = draft.ServerClusters.OrderBy(c => c.ClusterId, StringComparer.Ordinal).ToList();
var nodesByCluster = draft.ClusterNodes
.GroupBy(n => n.ClusterId, StringComparer.Ordinal)
.ToDictionary(g => g.Key, g => g.ToList(), StringComparer.Ordinal);
foreach (var cluster in clusters)
{
var nodes = nodesByCluster.TryGetValue(cluster.ClusterId, out var ns)
? (IReadOnlyList<ClusterNode>)ns
: [];
errors.AddRange(DraftValidator.ValidateClusterTopology(cluster, nodes));
}
// Deploy-time TagConfig strictness inspection over equipment tags. The
// driver-typed EquipmentTagConfigInspector surfaces every blob the driver's own reader would
// REJECT — a present-but-invalid enum value, an absent or malformed address field, a
// structurally-unparseable TagConfig — each of which makes the driver skip the tag so it reads
// BadNodeIdUnknown forever. (The runtime used to silently default a typo'd enum;
// it now rejects the tag, so these warnings describe rejections.) In Warn mode
// (default) these are non-blocking (logged + appended to the accepted result Message); in Error
// mode they fold into the reject list so a typo'd config cannot be re-deployed until fixed.
// Running servers are untouched either way — the gate only sees re-deploys.
// v3: a raw Tag's driver is resolved via its Device (Tag no longer carries EquipmentId /
// DriverInstanceId). Inspect EVERY raw tag's TagConfig against its device's driver type.
var driverTypeById = draft.DriverInstances
.GroupBy(d => d.DriverInstanceId, StringComparer.Ordinal)
.ToDictionary(g => g.Key, g => g.First().DriverType, StringComparer.Ordinal);
var driverByDevice = draft.Devices
.GroupBy(d => d.DeviceId, StringComparer.Ordinal)
.ToDictionary(g => g.Key, g => g.First().DriverInstanceId, StringComparer.Ordinal);
var deviceConfigById = draft.Devices
.GroupBy(d => d.DeviceId, StringComparer.Ordinal)
.ToDictionary(g => g.Key, g => g.First().DeviceConfig, StringComparer.Ordinal);
var tagConfigWarnings = new List<(string TagId, string Text)>();
foreach (var t in draft.Tags)
{
if (!driverByDevice.TryGetValue(t.DeviceId, out var driverInstanceId)) continue;
if (!driverTypeById.TryGetValue(driverInstanceId, out var driverType)) continue;
foreach (var w in EquipmentTagConfigInspector.Inspect(
driverType, t.TagConfig, deviceConfigById.GetValueOrDefault(t.DeviceId)))
tagConfigWarnings.Add((t.TagId, $"tag '{t.TagId}': {w}"));
}
if (tagConfigWarnings.Count > 0)
{
if (_tagConfigValidationMode == TagConfigValidationMode.Error)
errors.AddRange(tagConfigWarnings.Select(x => new ValidationError("TagConfigInvalid", x.Text, x.TagId)));
else
foreach (var x in tagConfigWarnings)
_log.Warning("StartDeployment: TagConfig warning (Warn mode, non-blocking): {Warning}", x.Text);
}
// The rule pass — DraftValidator, per-cluster topology, TagConfig inspection, the non-blocking Sql / data-
// connection warnings — is DeployGateRules (shared with the upgrade preflight, lmxopcua#1013/#1015/#1058).
// R03:3.2: every check runs off this ONE snapshot read.
var gate = DeployGateRules.Evaluate(draft, _tagConfigValidationMode);
var errors = gate.Errors.ToList();
foreach (var w in gate.TagConfigWarnings)
_log.Warning("StartDeployment: TagConfig warning (Warn mode, non-blocking): {Warning}", w.Message);
// lmxopcua#781 item 3: always non-blocking (independent of TagConfigValidationMode) — the Tag
// entity's Writable flag and the Sql blob's "writable" disagree.
var writableWarnings = SqlTagDeployChecks.WritableMismatchWarnings(draft);
foreach (var w in writableWarnings)
foreach (var w in gate.SqlWritableWarnings)
_log.Warning("StartDeployment: Sql writable mismatch (non-blocking): {Warning}", w);
// A2b (plan §6): Σ MaxConditions × 49 of a consumer node's alarm mappings over the host cap — non-blocking.
foreach (var w in DataConnectionValidator.DeployWarnings(draft))
foreach (var w in gate.DataConnectionWarnings)
_log.Warning("StartDeployment: data-connection warning (non-blocking): {Warning}", w);
phases.Mark("validate");
@@ -749,8 +689,8 @@ public sealed class AdminOperationsActor : ReceiveActor
// the operator sees the non-blocking strictness findings on a successful deploy.
var messageParts = new List<string>();
if (advisory is not null) messageParts.Add(advisory);
messageParts.AddRange(tagConfigWarnings.Select(x => x.Text));
messageParts.AddRange(writableWarnings);
messageParts.AddRange(gate.TagConfigWarnings.Select(x => x.Message));
messageParts.AddRange(gate.SqlWritableWarnings);
messageParts.AddRange(scriptWarnings);
var acceptedMessage = messageParts.Count > 0 ? string.Join("; ", messageParts) : null;
@@ -0,0 +1,85 @@
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
namespace ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations;
/// <summary>
/// The deploy gate's rule pass over one <see cref="DraftSnapshot"/> — everything <c>AdminOperationsActor</c> checks
/// before the script compile gate (<see cref="DeployScriptGate"/>), stated once so the upgrade preflight
/// (<c>Preflight.UpgradePreflight</c>, lmxopcua#1013/#1015/#1021/#1058) reports exactly what the next deploy would
/// refuse instead of a re-implementation that drifts.
/// </summary>
public static class DeployGateRules
{
/// <summary>The deploy-gate error code a TagConfig inspection finding carries in Error mode.</summary>
public const string TagConfigInvalidCode = "TagConfigInvalid";
/// <summary>What the rule pass found.</summary>
/// <param name="Errors">Blocking: <see cref="DraftValidator.Validate"/>, the per-cluster topology check, and — in
/// <see cref="TagConfigValidationMode.Error"/> — the TagConfig inspection.</param>
/// <param name="TagConfigWarnings">The TagConfig inspection in <see cref="TagConfigValidationMode.Warn"/> mode
/// (non-blocking); empty in Error mode, where they are in <paramref name="Errors"/>.</param>
/// <param name="SqlWritableWarnings">Always non-blocking (lmxopcua#781 item 3).</param>
/// <param name="DataConnectionWarnings">Always non-blocking (data-connection alarm-mapping budget).</param>
public sealed record Result(
IReadOnlyList<ValidationError> Errors,
IReadOnlyList<ValidationError> TagConfigWarnings,
IReadOnlyList<string> SqlWritableWarnings,
IReadOnlyList<string> DataConnectionWarnings);
/// <summary>Runs every rule over the snapshot.</summary>
/// <param name="draft">The whole-DB snapshot (<see cref="DraftSnapshotFactory.FromConfigDbAsync"/>).</param>
/// <param name="tagConfigMode">The configured <c>Deployment:TagConfigValidationMode</c>.</param>
/// <returns>The findings.</returns>
public static Result Evaluate(DraftSnapshot draft, TagConfigValidationMode tagConfigMode)
{
ArgumentNullException.ThrowIfNull(draft);
// Full pre-seal gate: the complete DraftValidator (one pass, all rules).
var errors = DraftValidator.Validate(draft).ToList();
// Cluster-topology guard. The SQL CK_ServerCluster_RedundancyMode_NodeCount CHECK enforces the
// (NodeCount, RedundancyMode) pair on the row itself, but it cannot see the per-node ClusterNode.Enabled
// flag — an operator can disable a node (effective enabled-count = 1) while leaving RedundancyMode at
// Hot/Warm, which would boot the runtime into an InvalidTopology band. Not part of DraftValidator.Validate,
// so it runs here over the snapshot's cluster/node rows, ClusterId-ordered for a deterministic summary.
// R03:3.2 — both come off the SAME snapshot read as every other table.
var nodesByCluster = draft.ClusterNodes
.GroupBy(n => n.ClusterId, StringComparer.Ordinal)
.ToDictionary(g => g.Key, g => g.ToList(), StringComparer.Ordinal);
foreach (var cluster in draft.ServerClusters.OrderBy(c => c.ClusterId, StringComparer.Ordinal))
{
var nodes = nodesByCluster.TryGetValue(cluster.ClusterId, out var ns) ? (IReadOnlyList<ClusterNode>)ns : [];
errors.AddRange(DraftValidator.ValidateClusterTopology(cluster, nodes));
}
// Deploy-time TagConfig strictness inspection. The driver-typed EquipmentTagConfigInspector surfaces every
// blob the driver's own reader would REJECT — each of which makes the driver skip the tag so it reads
// BadNodeIdUnknown forever. Warn mode (default): non-blocking; Error mode: blocking. A raw Tag's driver is
// resolved via its Device.
var driverTypeById = draft.DriverInstances
.GroupBy(d => d.DriverInstanceId, StringComparer.Ordinal)
.ToDictionary(g => g.Key, g => g.First().DriverType, StringComparer.Ordinal);
var deviceById = draft.Devices
.GroupBy(d => d.DeviceId, StringComparer.Ordinal)
.ToDictionary(g => g.Key, g => g.First(), StringComparer.Ordinal);
var tagConfigFindings = new List<ValidationError>();
foreach (var t in draft.Tags)
{
if (!deviceById.TryGetValue(t.DeviceId, out var device)) continue;
if (!driverTypeById.TryGetValue(device.DriverInstanceId, out var driverType)) continue;
foreach (var w in EquipmentTagConfigInspector.Inspect(driverType, t.TagConfig, device.DeviceConfig))
tagConfigFindings.Add(new ValidationError(TagConfigInvalidCode, $"tag '{t.TagId}': {w}", t.TagId));
}
IReadOnlyList<ValidationError> tagConfigWarnings = [];
if (tagConfigMode == TagConfigValidationMode.Error) errors.AddRange(tagConfigFindings);
else tagConfigWarnings = tagConfigFindings;
return new Result(
errors,
tagConfigWarnings,
SqlTagDeployChecks.WritableMismatchWarnings(draft),
DataConnectionValidator.DeployWarnings(draft));
}
}
@@ -0,0 +1,151 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.DependencyInjection;
using ZB.MOM.WW.OtOpcUa.Configuration;
namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Preflight;
/// <summary>
/// Lets THIS build's <see cref="OtOpcUaConfigDbContext"/> read a ConfigDb that is still on an OLDER schema — the
/// whole point of a pre-upgrade preflight is to run before the pending migrations. A table a pending migration
/// creates is read as empty (mapped to a typed zero-row query); a column a pending migration adds is left out of
/// the model (the property keeps its CLR default). Nothing else is changed, so every rule sees exactly the rows a
/// deploy right after the upgrade would see, minus data that cannot exist yet.
/// </summary>
internal static class LegacySchemaTolerance
{
/// <summary>The tables / columns of the current model that are absent from the database.</summary>
/// <param name="MissingTables">Table names, case-insensitive.</param>
/// <param name="MissingColumns">(table, column) pairs on tables that exist.</param>
internal sealed record SchemaGaps(IReadOnlySet<string> MissingTables, IReadOnlySet<(string Table, string Column)> MissingColumns)
{
/// <summary>No gap at all — the plain model reads the database.</summary>
public bool IsEmpty => MissingTables.Count == 0 && MissingColumns.Count == 0;
/// <summary>Stable text form; also the model-cache discriminator.</summary>
public string Signature =>
string.Join(";", MissingTables.Order(StringComparer.OrdinalIgnoreCase)) + "|" +
string.Join(";", MissingColumns.Select(c => $"{c.Table}.{c.Column}").Order(StringComparer.OrdinalIgnoreCase));
}
/// <summary>Compares the model's tables/columns with the database's (<c>dbo</c> schema).</summary>
/// <param name="model">The current model.</param>
/// <param name="present">Database table → its columns.</param>
/// <returns>The gaps.</returns>
internal static SchemaGaps Compare(IModel model, IReadOnlyDictionary<string, HashSet<string>> present)
{
var tables = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var columns = new HashSet<(string, string)>();
foreach (var entity in model.GetEntityTypes())
{
var table = entity.GetTableName();
if (table is null) continue;
if (!present.TryGetValue(table, out var have))
{
tables.Add(table);
continue;
}
var store = StoreObjectIdentifier.Table(table, entity.GetSchema());
foreach (var p in entity.GetProperties())
if (p.GetColumnName(store) is { } column && !have.Contains(column))
columns.Add((table, column));
}
return new SchemaGaps(tables, columns);
}
/// <summary>Configures <paramref name="builder"/> to read through <paramref name="gaps"/>.</summary>
/// <param name="builder">The options builder (SQL Server already selected).</param>
/// <param name="gaps">The gaps; nothing is changed when empty.</param>
internal static void Apply(DbContextOptionsBuilder<OtOpcUaConfigDbContext> builder, SchemaGaps gaps)
{
if (gaps.IsEmpty) return;
((IDbContextOptionsBuilderInfrastructure)builder).AddOrUpdateExtension(new GapsExtension(gaps));
builder.ReplaceService<IModelCustomizer, TolerantModelCustomizer>();
builder.ReplaceService<IModelCacheKeyFactory, GapsAwareModelCacheKeyFactory>();
}
/// <summary>Carries the gaps to the model customizer (and into the internal service-provider/model caches).</summary>
private sealed class GapsExtension(SchemaGaps gaps) : IDbContextOptionsExtension
{
public SchemaGaps Gaps { get; } = gaps;
public DbContextOptionsExtensionInfo Info => new ExtensionInfo(this);
public void ApplyServices(IServiceCollection services)
{
}
public void Validate(IDbContextOptions options)
{
}
private sealed class ExtensionInfo(GapsExtension extension) : DbContextOptionsExtensionInfo(extension)
{
public override bool IsDatabaseProvider => false;
public override string LogFragment => "LegacySchemaTolerance ";
public override int GetServiceProviderHashCode() =>
StringComparer.Ordinal.GetHashCode(((GapsExtension)Extension).Gaps.Signature);
public override bool ShouldUseSameServiceProvider(DbContextOptionsExtensionInfo other) =>
other is ExtensionInfo o && o.Extension is GapsExtension g &&
string.Equals(g.Gaps.Signature, ((GapsExtension)Extension).Gaps.Signature, StringComparison.Ordinal);
public override void PopulateDebugInfo(IDictionary<string, string> debugInfo) =>
debugInfo["LegacySchemaTolerance"] = ((GapsExtension)Extension).Gaps.Signature;
}
}
/// <summary>Runs the context's own model building, then maps the gaps.</summary>
private sealed class TolerantModelCustomizer(ModelCustomizerDependencies dependencies) : RelationalModelCustomizer(dependencies)
{
public override void Customize(ModelBuilder modelBuilder, DbContext context)
{
base.Customize(modelBuilder, context);
var gaps = context.GetService<IDbContextOptions>().FindExtension<GapsExtension>()?.Gaps;
if (gaps is null) return;
var typeMappings = context.GetService<IRelationalTypeMappingSource>();
foreach (var entity in modelBuilder.Model.GetEntityTypes().ToList())
{
var table = entity.GetTableName();
if (table is null) continue;
if (gaps.MissingTables.Contains(table))
{
// A typed, zero-row stand-in: the deploy reads the table as empty, as it will be right after the
// migration creates it. Types matter only so predicates/ORDER BY over it compile.
var store = StoreObjectIdentifier.Table(table, entity.GetSchema());
var columns = entity.GetProperties().Select(p =>
{
var clr = p.GetValueConverter()?.ProviderClrType ?? p.GetProviderClrType() ?? p.ClrType;
var type = p.GetColumnType() ?? typeMappings.FindMapping(Nullable.GetUnderlyingType(clr) ?? clr)?.StoreType ?? "sql_variant";
if (type.Equals("rowversion", StringComparison.OrdinalIgnoreCase)) type = "binary(8)";
return $"CAST(NULL AS {type}) AS [{p.GetColumnName(store) ?? p.Name}]";
});
modelBuilder.Entity(entity.ClrType).ToSqlQuery($"SELECT TOP (0) {string.Join(", ", columns)}");
continue;
}
foreach (var p in entity.GetProperties().ToList())
{
var column = p.GetColumnName(StoreObjectIdentifier.Table(table, entity.GetSchema())) ?? p.Name;
if (gaps.MissingColumns.Contains((table, column)))
modelBuilder.Entity(entity.ClrType).Ignore(p.Name);
}
}
}
}
/// <summary>Two contexts over databases with different gaps must not share a cached model.</summary>
private sealed class GapsAwareModelCacheKeyFactory : IModelCacheKeyFactory
{
public object Create(DbContext context, bool designTime) =>
(context.GetType(), designTime, context.GetService<IDbContextOptions>().FindExtension<GapsExtension>()?.Gaps.Signature);
}
}
@@ -0,0 +1,146 @@
using Microsoft.Data.SqlClient;
namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Preflight;
/// <summary>
/// The read-only, row-naming twins of the pre-checks inside the migrations that add constraints over existing data
/// (lmxopcua#1021): each migration THROWs and changes nothing when its data cannot hold the new constraint; these
/// list every offending row up front, so the operator can clean up before the upgrade window instead of during it.
/// Keep a new constraint-adding migration's pre-check and its entry here in step.
/// </summary>
internal static class MigrationPreChecks
{
/// <summary>One check: a SELECT whose rows are the offenders (group key in column 0, row id in column 1).</summary>
/// <param name="Migration">The migration name suffix (the part after the timestamp).</param>
/// <param name="Code">Finding code.</param>
/// <param name="Sql">The SELECT. Column 0 = group label (rows sharing it are one problem), column 1 = row id.</param>
/// <param name="Describe">Builds the message from the group label and its row ids.</param>
internal sealed record Check(string Migration, string Code, string Sql, Func<string, IReadOnlyList<string>, string> Describe);
internal const string ConfigurationGaps = "ConfigurationGapsIndexesAndRowVersions";
internal const string ScriptForeignKeys = "ScriptForeignKeysAndExternalIdUniqueness";
/// <summary>Every known check, in migration order.</summary>
internal static readonly IReadOnlyList<Check> All =
[
// lmxopcua#998 C-8: UX_NodeAcl_PrincipalScope / UX_LdapGroupRoleMapping_Group_Cluster become unfiltered, so
// NULL-keyed rows (Cluster-scope ACLs, system-wide mappings) must be unique too. PARTITION BY groups NULLs
// together and compares with the column collation — exactly what the unique index will do.
new(ConfigurationGaps, "DuplicateNodeAcl", """
SELECT CONCAT(N'cluster ''', ClusterId, N''', principal ''', Principal, N''', scope ', ScopeKind, N' ''', ISNULL(ScopeId, N'(cluster)'), N''''), NodeAclId
FROM (SELECT *, COUNT(*) OVER (PARTITION BY ClusterId, Principal, ScopeKind, ScopeId) AS n FROM [NodeAcl]) x
WHERE n > 1 ORDER BY ClusterId, Principal, ScopeKind, ScopeId, NodeAclId
""",
(key, ids) => $"{ids.Count} NodeAcl rows share {key}: {Join(ids)}. Delete or merge all but one."),
new(ConfigurationGaps, "DuplicateLdapGroupRoleMapping", """
SELECT CONCAT(N'group ''', LdapGroup, N''' in ', ISNULL(N'cluster ''' + ClusterId + N'''', N'(system-wide)')), CONVERT(nvarchar(36), Id)
FROM (SELECT *, COUNT(*) OVER (PARTITION BY LdapGroup, ClusterId) AS n FROM [LdapGroupRoleMapping]) x
WHERE n > 1 ORDER BY LdapGroup, ClusterId, Id
""",
(key, ids) => $"{ids.Count} LdapGroupRoleMapping rows share {key}: {Join(ids)}. Delete or merge all but one."),
// lmxopcua#1040 / #1049: script FKs, Script.ScriptId NOT NULL, unique ZTag / SAPID, reservation ledger dropped.
new(ScriptForeignKeys, "ScriptIdNull", """
SELECT N'Script rows with a NULL ScriptId', CONCAT(CONVERT(nvarchar(36), ScriptRowId), N' (', Name, N')')
FROM [Script] WHERE ScriptId IS NULL ORDER BY Name
""",
(_, ids) => $"{ids.Count} Script row(s) have a NULL ScriptId: {Join(ids)}. Give each a unique ScriptId or delete it."),
new(ScriptForeignKeys, "VirtualTagScriptDangling", """
SELECT CONCAT(N'missing script ''', v.ScriptId, N''''), CONCAT(v.VirtualTagId, N' (equipment ', v.EquipmentId, N', ''', v.Name, N''')')
FROM [VirtualTag] v WHERE NOT EXISTS (SELECT 1 FROM [Script] s WHERE s.ScriptId = v.ScriptId) ORDER BY v.ScriptId, v.VirtualTagId
""",
(key, ids) => $"VirtualTag row(s) name {key}: {Join(ids)}. Point them at an existing script or delete them."),
new(ScriptForeignKeys, "ScriptedAlarmScriptDangling", """
SELECT CONCAT(N'missing predicate script ''', a.PredicateScriptId, N''''), CONCAT(a.ScriptedAlarmId, N' (equipment ', a.EquipmentId, N', ''', a.Name, N''')')
FROM [ScriptedAlarm] a WHERE NOT EXISTS (SELECT 1 FROM [Script] s WHERE s.ScriptId = a.PredicateScriptId) ORDER BY a.PredicateScriptId, a.ScriptedAlarmId
""",
(key, ids) => $"ScriptedAlarm row(s) name {key}: {Join(ids)}. Point them at an existing script or delete them."),
new(ScriptForeignKeys, "DuplicateZTag", """
SELECT CONCAT(N'ZTag ''', ZTag, N''''), EquipmentId
FROM (SELECT *, COUNT(*) OVER (PARTITION BY ZTag) AS n FROM [Equipment] WHERE ZTag IS NOT NULL AND ZTag <> N'') x
WHERE n > 1 ORDER BY ZTag, EquipmentId
""",
(key, ids) => $"{key} is set on {ids.Count} equipment rows: {Join(ids)}. Keep it on one and clear or change the others."),
new(ScriptForeignKeys, "DuplicateSAPID", """
SELECT CONCAT(N'SAPID ''', SAPID, N''''), EquipmentId
FROM (SELECT *, COUNT(*) OVER (PARTITION BY SAPID) AS n FROM [Equipment] WHERE SAPID IS NOT NULL AND SAPID <> N'') x
WHERE n > 1 ORDER BY SAPID, EquipmentId
""",
(key, ids) => $"{key} is set on {ids.Count} equipment rows: {Join(ids)}. Keep it on one and clear or change the others."),
new(ScriptForeignKeys, "ExternalIdReservationRows", """
IF OBJECT_ID(N'[ExternalIdReservation]', N'U') IS NOT NULL
EXEC(N'SELECT N''ExternalIdReservation rows'', CONCAT(Kind, N'' '''''', Value, N'''''' -> '', CONVERT(nvarchar(36), EquipmentUuid), CASE WHEN ReleasedAt IS NULL THEN N'' (active)'' ELSE N'' (released)'' END) FROM [ExternalIdReservation] ORDER BY Kind, Value');
""",
(_, ids) => $"{ids.Count} ExternalIdReservation row(s): {Join(ids)}. The ledger is retired and its table is dropped by the migration, " +
"which refuses while it holds rows. Export them if their history matters, then DELETE FROM [ExternalIdReservation]."),
];
private const int MaxIdsNamed = 25;
private static string Join(IReadOnlyList<string> ids) =>
string.Join(", ", ids.Take(MaxIdsNamed)) + (ids.Count > MaxIdsNamed ? $" (+{ids.Count - MaxIdsNamed} more)" : string.Empty);
/// <summary>Runs every check whose migration is pending; already-applied migrations are reported as Info.</summary>
/// <param name="connection">An open connection to the ConfigDb.</param>
/// <param name="pendingMigrationIds">The pending migration ids (timestamp-prefixed).</param>
/// <param name="ct">Cancellation.</param>
/// <returns>The findings.</returns>
internal static async Task<IReadOnlyList<PreflightFinding>> RunAsync(
SqlConnection connection, IReadOnlyCollection<string> pendingMigrationIds, CancellationToken ct)
{
var findings = new List<PreflightFinding>();
foreach (var migration in All.Select(c => c.Migration).Distinct())
{
var check = $"migration:{migration}";
if (!pendingMigrationIds.Any(id => id.EndsWith("_" + migration, StringComparison.Ordinal)))
{
findings.Add(new(check, "AlreadyApplied", PreflightSeverity.Info,
$"{migration} is already applied (or not part of this build); its pre-check is not needed."));
continue;
}
var clean = true;
foreach (var c in All.Where(c => c.Migration == migration))
{
List<(string Key, string Id)> rows;
try
{
rows = await QueryAsync(connection, c.Sql, ct).ConfigureAwait(false);
}
catch (SqlException ex)
{
clean = false;
findings.Add(new(check, c.Code, PreflightSeverity.Warning,
$"pre-check {c.Code} could not run against this schema ({OneLine(ex.Message)}); the migration's own pre-check will still refuse bad rows."));
continue;
}
foreach (var group in rows.GroupBy(r => r.Key, StringComparer.Ordinal))
{
clean = false;
var ids = group.Select(r => r.Id).ToList();
findings.Add(new(check, c.Code, PreflightSeverity.Blocking, c.Describe(group.Key, ids), ids.Count == 1 ? ids[0] : null));
}
}
if (clean)
findings.Add(new(check, "Clean", PreflightSeverity.Info, $"{migration} will apply: no row breaks its new constraints."));
}
return findings;
}
private static string OneLine(string message) =>
string.Join(" ", message.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Distinct(StringComparer.Ordinal));
private static async Task<List<(string Key, string Id)>> QueryAsync(SqlConnection connection, string sql, CancellationToken ct)
{
var rows = new List<(string, string)>();
await using var cmd = connection.CreateCommand();
cmd.CommandText = sql;
await using var reader = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false);
while (await reader.ReadAsync(ct).ConfigureAwait(false))
rows.Add((reader.IsDBNull(0) ? string.Empty : reader.GetString(0), reader.IsDBNull(1) ? string.Empty : reader.GetString(1)));
return rows;
}
}
@@ -0,0 +1,55 @@
namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Preflight;
/// <summary>How much a preflight finding matters for the upgrade.</summary>
public enum PreflightSeverity
{
/// <summary>The upgrade (a migration) or the next deploy will be REFUSED until this is fixed.</summary>
Blocking,
/// <summary>Not refused, but worth fixing (behaviour change, or refused only in a non-default mode).</summary>
Warning,
/// <summary>Context only.</summary>
Info,
}
/// <summary>One preflight finding.</summary>
/// <param name="Check">Which check produced it (<c>schema</c>, <c>migration:&lt;name&gt;</c>, <c>deploy-gate</c>, <c>script-gate</c>).</param>
/// <param name="Code">The rule code — the deploy gate's own code for gate findings.</param>
/// <param name="Severity">How much it matters.</param>
/// <param name="Message">Operator-facing text naming the rows.</param>
/// <param name="Subject">The offending row's id, when there is one.</param>
public sealed record PreflightFinding(string Check, string Code, PreflightSeverity Severity, string Message, string? Subject = null);
/// <summary>The whole preflight result for one ConfigDb.</summary>
/// <param name="Server">The SQL Server data source (never the credentials).</param>
/// <param name="Database">The database name.</param>
/// <param name="AppliedMigrations">Migrations already applied, oldest first.</param>
/// <param name="PendingMigrations">Migrations this build would apply, oldest first.</param>
/// <param name="Findings">Every finding, in check order.</param>
public sealed record PreflightReport(
string Server,
string Database,
IReadOnlyList<string> AppliedMigrations,
IReadOnlyList<string> PendingMigrations,
IReadOnlyList<PreflightFinding> Findings)
{
/// <summary>True when any finding would refuse the upgrade or the next deploy.</summary>
public bool HasBlocking => Findings.Any(f => f.Severity == PreflightSeverity.Blocking);
}
/// <summary>Preflight knobs — set them as the target deployment's appsettings are.</summary>
public sealed record UpgradePreflightOptions
{
/// <summary><c>Deployment:TagConfigValidationMode</c> of the target (Warn is the shipped default).</summary>
public AdminOperations.TagConfigValidationMode TagConfigMode { get; init; } = AdminOperations.TagConfigValidationMode.Warn;
/// <summary><c>Deployment:ScriptCompileGateMode</c> of the target (Error is the shipped default).</summary>
public AdminOperations.ScriptCompileGateMode ScriptGateMode { get; init; } = AdminOperations.ScriptCompileGateMode.Error;
/// <summary>Also compile scripts no enabled VirtualTag / scripted alarm / Calculation tag uses (Warning only).</summary>
public bool CheckUnusedScripts { get; init; } = true;
}
/// <summary>The target is not something the preflight can check (not a v3 ConfigDb, unreachable).</summary>
public sealed class PreflightUnsupportedException(string message, Exception? inner = null) : Exception(message, inner);
@@ -0,0 +1,201 @@
using System.Data;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
using ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations;
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Preflight;
/// <summary>
/// The read-only pre-upgrade preflight (lmxopcua#1013, #1015, #1021, #1058): connects to a ConfigDb — normally
/// BEFORE this build's migrations are applied to it — and reports every row the upgrade would refuse:
/// <list type="number">
/// <item><b>Migration pre-checks</b> (<see cref="MigrationPreChecks"/>) — the rows each pending constraint-adding
/// migration would THROW on, named.</item>
/// <item><b>The deploy gate</b> — <see cref="DeployGateRules"/> (every <c>DraftValidator</c> rule incl. the new
/// VirtualTag name / effective-name / script-reference / ZTag / dangling-reference / Sql named-query rules, the
/// topology check, the TagConfig inspection) over the same whole-DB snapshot a deploy reads, through this build's
/// code. The first deploy after the upgrade is refused for every Blocking one.</item>
/// <item><b>The script compile gate</b> — <see cref="DeployScriptGate"/> through the supplied
/// <see cref="IDeployScriptChecker"/> (the Roslyn compile + sandbox allow-list the runtime runs); optionally
/// also every stored script nothing currently uses.</item>
/// </list>
/// Only SELECTs are issued. The snapshot is read under SNAPSHOT isolation when the database allows it (the deploy
/// path's own read), else READ COMMITTED.
/// </summary>
public static class UpgradePreflight
{
private const string V3InitialSuffix = "_V3Initial";
/// <summary>Runs every check against the ConfigDb at <paramref name="connectionString"/>.</summary>
/// <param name="connectionString">The ConfigDb connection string.</param>
/// <param name="scriptChecker">The compile checker (the Host's <c>RoslynDeployScriptChecker</c>); null skips the script gate.</param>
/// <param name="options">Mode knobs matching the target deployment.</param>
/// <param name="ct">Cancellation.</param>
/// <returns>The report.</returns>
/// <exception cref="PreflightUnsupportedException">The database is unreachable or not a v3 ConfigDb.</exception>
public static async Task<PreflightReport> RunAsync(
string connectionString, IDeployScriptChecker? scriptChecker, UpgradePreflightOptions? options = null, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(connectionString);
options ??= new UpgradePreflightOptions();
var csb = new SqlConnectionStringBuilder(connectionString);
var findings = new List<PreflightFinding>();
await using var connection = new SqlConnection(connectionString);
try
{
await connection.OpenAsync(ct).ConfigureAwait(false);
}
catch (SqlException ex)
{
throw new PreflightUnsupportedException($"cannot connect to '{csb.DataSource}' / '{csb.InitialCatalog}': {ex.Message}", ex);
}
var applied = await ReadAppliedMigrationsAsync(connection, ct).ConfigureAwait(false);
if (!applied.Any(id => id.EndsWith(V3InitialSuffix, StringComparison.Ordinal)))
throw new PreflightUnsupportedException(
$"'{connection.Database}' is not a v3 OtOpcUa ConfigDb (no {V3InitialSuffix[1..]} migration in __EFMigrationsHistory); " +
"this preflight checks an upgrade between v3 builds only.");
var plainOptions = new DbContextOptionsBuilder<OtOpcUaConfigDbContext>().UseSqlServer(connectionString).Options;
IReadOnlyList<string> pending;
Microsoft.EntityFrameworkCore.Metadata.IModel model;
await using (var plain = new OtOpcUaConfigDbContext(plainOptions))
{
pending = plain.Database.GetMigrations().Except(applied, StringComparer.Ordinal).ToList();
model = plain.Model;
var unknown = applied.Except(plain.Database.GetMigrations(), StringComparer.Ordinal).ToList();
if (unknown.Count > 0)
findings.Add(new("schema", "UnknownMigrations", PreflightSeverity.Warning,
$"the database has migration(s) this build does not know ({string.Join(", ", unknown)}) — it is NEWER than this build; " +
"the checks below may not match what it will do."));
}
findings.Add(new("schema", "PendingMigrations", PreflightSeverity.Info, pending.Count == 0
? "no pending migrations — the schema is already this build's."
: $"{pending.Count} pending migration(s) this build would apply: {string.Join(", ", pending)}."));
// 1. Migration pre-checks (raw SQL against the current schema).
findings.AddRange(await MigrationPreChecks.RunAsync(connection, pending, ct).ConfigureAwait(false));
// 2 + 3. The deploy gate, on a snapshot read through this build's model, tolerant of an older schema.
var gaps = LegacySchemaTolerance.Compare(model, await ReadSchemaAsync(connection, ct).ConfigureAwait(false));
if (!gaps.IsEmpty)
findings.Add(new("schema", "ReadAsEmpty", PreflightSeverity.Info,
"tables / columns a pending migration creates are read as empty / default: " + gaps.Signature.Replace("|", " | ", StringComparison.Ordinal)));
DraftSnapshot draft;
try
{
draft = await ReadSnapshotAsync(connectionString, gaps, await SnapshotIsolationAllowedAsync(connection, ct).ConfigureAwait(false), findings, ct)
.ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
findings.Add(new("deploy-gate", "SnapshotUnreadable", PreflightSeverity.Blocking,
$"this build could not read the configuration snapshot ({ex.GetType().Name}: {ex.Message}) — the deploy would fail the same way. " +
"Fix the migration pre-check findings above (a NULL Script.ScriptId is one cause) and re-run."));
return new PreflightReport(csb.DataSource, connection.Database, applied, pending, findings);
}
var gate = DeployGateRules.Evaluate(draft, options.TagConfigMode);
findings.AddRange(gate.Errors.Select(e => new PreflightFinding("deploy-gate", e.Code, PreflightSeverity.Blocking, e.Message, e.Context)));
findings.AddRange(gate.TagConfigWarnings.Select(e => new PreflightFinding("deploy-gate", e.Code, PreflightSeverity.Warning,
e.Message + " (blocking only with Deployment:TagConfigValidationMode=Error)", e.Context)));
findings.AddRange(gate.SqlWritableWarnings.Select(w => new PreflightFinding("deploy-gate", "SqlWritableMismatch", PreflightSeverity.Warning, w)));
findings.AddRange(gate.DataConnectionWarnings.Select(w => new PreflightFinding("deploy-gate", "DataConnectionWarning", PreflightSeverity.Warning, w)));
if (gate.Errors.Count == 0)
findings.Add(new("deploy-gate", "Clean", PreflightSeverity.Info, "every deploy-gate rule passes."));
RunScriptGate(scriptChecker, draft, options, findings, ct);
return new PreflightReport(csb.DataSource, connection.Database, applied, pending, findings);
}
private static void RunScriptGate(
IDeployScriptChecker? checker, DraftSnapshot draft, UpgradePreflightOptions options, List<PreflightFinding> findings, CancellationToken ct)
{
if (checker is null || options.ScriptGateMode == ScriptCompileGateMode.Off)
{
findings.Add(new("script-gate", "Skipped", PreflightSeverity.Info, "script compile gate not run."));
return;
}
var severity = options.ScriptGateMode == ScriptCompileGateMode.Error ? PreflightSeverity.Blocking : PreflightSeverity.Warning;
var refused = DeployScriptGate.Run(checker, draft, ct);
findings.AddRange(refused.Select(f => new PreflightFinding("script-gate", DeployScriptGate.ErrorCode, severity, f.Text, f.ScriptId)));
var used = DeployScriptGate.CollectUses(draft).Select(u => u.ScriptId).ToHashSet(StringComparer.Ordinal);
var unused = draft.Scripts.Where(s => !used.Contains(s.ScriptId)).OrderBy(s => s.ScriptId, StringComparer.Ordinal).ToList();
if (options.CheckUnusedScripts && unused.Count > 0)
{
// Nothing compiles these today, so they block nothing — but binding one to a VirtualTag / alarm later is
// refused at that deploy. Checked as a value script (the seam a VirtualTag or Calculation tag compiles for).
var results = checker.Check(unused.Select(s => new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, s.SourceCode ?? string.Empty)).ToList(), ct);
for (var i = 0; i < unused.Count; i++)
if (!results[i].Passed)
findings.Add(new("script-gate", "UnusedScriptDoesNotCompile", PreflightSeverity.Warning,
$"script '{unused[i].ScriptId}' ('{unused[i].Name}') is not used by any enabled VirtualTag, scripted alarm or Calculation tag, " +
$"and would not compile as a value script: {string.Join("; ", results[i].Problems)}",
unused[i].ScriptId));
}
findings.Add(new("script-gate", refused.Count == 0 ? "Clean" : "Summary", PreflightSeverity.Info,
$"{used.Count} script(s) in use checked, {refused.Count} refused" +
(options.CheckUnusedScripts ? $"; {unused.Count} unused script(s) checked." : ".")));
}
private static async Task<DraftSnapshot> ReadSnapshotAsync(
string connectionString, LegacySchemaTolerance.SchemaGaps gaps, bool snapshotAllowed, List<PreflightFinding> findings, CancellationToken ct)
{
var builder = new DbContextOptionsBuilder<OtOpcUaConfigDbContext>().UseSqlServer(connectionString);
LegacySchemaTolerance.Apply(builder, gaps);
await using var db = new OtOpcUaConfigDbContext(builder.Options);
if (snapshotAllowed) return await DraftSnapshotFactory.FromConfigDbAsync(db, ct).ConfigureAwait(false);
findings.Add(new("schema", "NoSnapshotIsolation", PreflightSeverity.Warning,
"ALLOW_SNAPSHOT_ISOLATION is OFF (migration EnableSnapshotIsolation not applied?) — read under READ COMMITTED, so an edit " +
"committed mid-read could show as a transient finding; re-run to confirm. The deploy itself requires snapshot isolation."));
await using var tx = await db.Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct).ConfigureAwait(false);
var draft = await DraftSnapshotFactory.FromConfigDbAsync(db, ct).ConfigureAwait(false);
await tx.RollbackAsync(ct).ConfigureAwait(false);
return draft;
}
private static async Task<List<string>> ReadAppliedMigrationsAsync(SqlConnection connection, CancellationToken ct)
{
await using var cmd = connection.CreateCommand();
cmd.CommandText = "IF OBJECT_ID(N'[__EFMigrationsHistory]', N'U') IS NOT NULL SELECT MigrationId FROM [__EFMigrationsHistory] ORDER BY MigrationId";
var ids = new List<string>();
await using var reader = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false);
while (await reader.ReadAsync(ct).ConfigureAwait(false)) ids.Add(reader.GetString(0));
return ids;
}
private static async Task<Dictionary<string, HashSet<string>>> ReadSchemaAsync(SqlConnection connection, CancellationToken ct)
{
await using var cmd = connection.CreateCommand();
cmd.CommandText = "SELECT TABLE_NAME, COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = N'dbo'";
var schema = new Dictionary<string, HashSet<string>>(StringComparer.OrdinalIgnoreCase);
await using var reader = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false);
while (await reader.ReadAsync(ct).ConfigureAwait(false))
{
var table = reader.GetString(0);
if (!schema.TryGetValue(table, out var columns))
schema[table] = columns = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
columns.Add(reader.GetString(1));
}
return schema;
}
private static async Task<bool> SnapshotIsolationAllowedAsync(SqlConnection connection, CancellationToken ct)
{
await using var cmd = connection.CreateCommand();
cmd.CommandText = "SELECT snapshot_isolation_state FROM sys.databases WHERE name = DB_NAME()";
return await cmd.ExecuteScalarAsync(ct).ConfigureAwait(false) is byte state && state == 1;
}
}
@@ -958,7 +958,7 @@ public static class AddressSpaceComposer
if (!equipFolderPath.TryGetValue(r.EquipmentId, out var equipPath)) continue;
var rawPath = topology.Resolver.TryBuildTagPath(tag.DeviceId, tag.TagGroupId, tag.Name);
if (rawPath is null) continue;
var effectiveName = string.IsNullOrEmpty(r.DisplayNameOverride) ? tag.Name : r.DisplayNameOverride!;
var effectiveName = EquipmentReferenceMap.EffectiveName(r.DisplayNameOverride, tag.Name)!;
string nodeId;
try
@@ -217,8 +217,7 @@ public sealed partial class LocalExportCatalog
|| !equipmentById.TryGetValue(reference.EquipmentId, out var owner)
|| !lineById.TryGetValue(owner.UnsLineId, out var line) || !areaById.TryGetValue(line.UnsAreaId, out var area))
continue;
var effectiveName = string.IsNullOrEmpty(reference.DisplayNameOverride) ? tagById[reference.TagId].Name
: reference.DisplayNameOverride!;
var effectiveName = EquipmentReferenceMap.EffectiveName(reference.DisplayNameOverride, tagById[reference.TagId].Name)!;
string reserved;
try { reserved = V3NodeIds.UnsChild(V3NodeIds.Uns(area.Name, line.Name, owner.Name), effectiveName); }
catch (ArgumentException) { continue; } // an invalid name segment: the deploy gate rejects it; never listed
@@ -1240,9 +1240,8 @@ internal sealed partial class ParsedDeploymentArtifact : IDisposable
// Effective name = the override when present, else the backing raw tag's own name. This is the
// same rule the address space materializes UNS variables under; a reference whose tag is
// missing from the artifact has no resolvable name and is skipped.
var effective = ReadNullableString(el, "DisplayNameOverride");
if (string.IsNullOrWhiteSpace(effective))
effective = tags.TryGetValue(tagId, out var t) ? t.Name : null;
var effective = EquipmentReferenceMap.EffectiveName(
ReadNullableString(el, "DisplayNameOverride"), tags.TryGetValue(tagId, out var t) ? t.Name : null);
if (effective is null) continue;
references.Add((equipmentId, tagId, effective));
@@ -0,0 +1,109 @@
using System.Text.Json;
using System.Text.Json.Serialization;
using ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations;
using ZB.MOM.WW.OtOpcUa.ControlPlane.Preflight;
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
// otopcua-preflight — read-only pre-upgrade check of an OtOpcUa ConfigDb (docs/v2/upgrade-preflight.md).
// Exit codes: 0 = nothing blocks the upgrade or the next deploy; 1 = at least one Blocking finding;
// 2 = usage error, unreachable database, or not a v3 ConfigDb.
const string Usage = """
otopcua-preflight — read-only pre-upgrade check of an OtOpcUa ConfigDb (issues only SELECTs).
Usage:
otopcua-preflight [--connection "<ConfigDb connection string>"] [options]
The connection string defaults to the OTOPCUA_CONFIG_CONNECTION environment variable (prefer it: a
command-line argument is visible in the process list and shell history).
Options:
--tagconfig-mode Warn|Error the target's Deployment:TagConfigValidationMode (default Warn)
--script-gate Error|Warn|Off the target's Deployment:ScriptCompileGateMode (default Error)
--no-unused-scripts do not compile scripts nothing uses
--json machine-readable report on stdout
--verbose also print Info findings
-h, --help this text
Exit codes: 0 nothing blocks; 1 blocking findings; 2 usage / connection / not a v3 ConfigDb.
""";
string? connection = Environment.GetEnvironmentVariable("OTOPCUA_CONFIG_CONNECTION");
var options = new UpgradePreflightOptions();
var json = false;
var verbose = false;
for (var i = 0; i < args.Length; i++)
{
string Next() => i + 1 < args.Length ? args[++i] : throw new ArgumentException($"{args[i]} needs a value");
try
{
switch (args[i])
{
case "--connection": connection = Next(); break;
case "--tagconfig-mode": options = options with { TagConfigMode = Enum.Parse<TagConfigValidationMode>(Next(), ignoreCase: true) }; break;
case "--script-gate": options = options with { ScriptGateMode = Enum.Parse<ScriptCompileGateMode>(Next(), ignoreCase: true) }; break;
case "--no-unused-scripts": options = options with { CheckUnusedScripts = false }; break;
case "--json": json = true; break;
case "--verbose": verbose = true; break;
case "-h" or "--help": Console.Out.WriteLine(Usage); return 0;
default: throw new ArgumentException($"unknown argument '{args[i]}'");
}
}
catch (ArgumentException ex)
{
Console.Error.WriteLine($"error: {ex.Message}\n\n{Usage}");
return 2;
}
}
if (string.IsNullOrWhiteSpace(connection))
{
Console.Error.WriteLine($"error: no connection string (--connection or OTOPCUA_CONFIG_CONNECTION)\n\n{Usage}");
return 2;
}
PreflightReport report;
try
{
report = await UpgradePreflight.RunAsync(connection, new RoslynDeployScriptChecker(), options);
}
catch (PreflightUnsupportedException ex)
{
Console.Error.WriteLine($"error: {ex.Message}");
return 2;
}
if (json)
{
Console.Out.WriteLine(JsonSerializer.Serialize(report, new JsonSerializerOptions
{
WriteIndented = true,
Converters = { new JsonStringEnumConverter() },
}));
return report.HasBlocking ? 1 : 0;
}
Console.Out.WriteLine($"OtOpcUa upgrade preflight — server '{report.Server}', database '{report.Database}'");
Console.Out.WriteLine($" applied migrations: {report.AppliedMigrations.Count} (latest {report.AppliedMigrations.LastOrDefault() ?? "-"})");
Console.Out.WriteLine($" pending migrations: {report.PendingMigrations.Count}");
foreach (var group in report.Findings.GroupBy(f => f.Check))
{
var shown = group.Where(f => verbose || f.Severity != PreflightSeverity.Info).ToList();
var blocking = group.Count(f => f.Severity == PreflightSeverity.Blocking);
var warnings = group.Count(f => f.Severity == PreflightSeverity.Warning);
Console.Out.WriteLine();
Console.Out.WriteLine($"[{group.Key}] {blocking} blocking, {warnings} warning(s)");
foreach (var f in shown)
Console.Out.WriteLine($" {f.Severity.ToString().ToUpperInvariant(),-8} {f.Code}: {f.Message}");
if (!verbose)
foreach (var f in group.Where(f => f.Severity == PreflightSeverity.Info && f.Code is "Clean" or "Summary" or "PendingMigrations"))
Console.Out.WriteLine($" {f.Message}");
}
var total = report.Findings.Count(f => f.Severity == PreflightSeverity.Blocking);
Console.Out.WriteLine();
Console.Out.WriteLine(report.HasBlocking
? $"RESULT: {total} blocking finding(s) — fix them before upgrading (exit 1)."
: "RESULT: nothing blocks the upgrade or the next deploy (exit 0).");
return report.HasBlocking ? 1 : 0;
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
lmxopcua#1013 / #1015 / #1021 / #1058: the read-only pre-upgrade preflight. Run it from the NEW build against a
ConfigDb BEFORE applying that build's migrations; see docs/v2/upgrade-preflight.md. The checks themselves live in
ControlPlane (Preflight.UpgradePreflight) so they run the deploy gate's own code; this is only the console shell
plus the Roslyn script checker (ControlPlane is Roslyn-free by design).
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<RootNamespace>ZB.MOM.WW.OtOpcUa.UpgradePreflight</RootNamespace>
<AssemblyName>otopcua-preflight</AssemblyName>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\Server\ZB.MOM.WW.OtOpcUa.ControlPlane\ZB.MOM.WW.OtOpcUa.ControlPlane.csproj"/>
<ProjectReference Include="..\..\Core\ZB.MOM.WW.OtOpcUa.Core.Scripting\ZB.MOM.WW.OtOpcUa.Core.Scripting.csproj"/>
</ItemGroup>
</Project>
@@ -0,0 +1,35 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
namespace ZB.MOM.WW.OtOpcUa.Commons.Tests;
/// <summary>
/// lmxopcua#1040 (#978 follow-up): the effective-name rule is stated once
/// (<see cref="EquipmentReferenceMap.EffectiveName"/>) — an EMPTY override means "no override". Every other
/// helper on the map must agree with it, including <see cref="EquipmentReferenceMap.EffectiveNames"/>, which
/// used <c>??</c> and so dropped an empty-override reference instead of naming it after its tag.
/// </summary>
public sealed class EquipmentReferenceMapEffectiveNameTests
{
[Theory]
[InlineData(null, "Speed", "Speed")]
[InlineData("", "Speed", "Speed")]
[InlineData("Rate", "Speed", "Rate")]
public void EffectiveName_empty_override_is_no_override(string? displayNameOverride, string tagName, string expected) =>
EquipmentReferenceMap.EffectiveName(displayNameOverride, tagName).ShouldBe(expected);
[Fact]
public void EffectiveNames_agrees_with_EffectiveName_for_an_empty_override()
{
var names = EquipmentReferenceMap.EffectiveNames(
[
new EquipmentReferenceMap.ReferenceRow("R1", "EQ-1", "T1", ""),
new EquipmentReferenceMap.ReferenceRow("R2", "EQ-1", "T2", null),
new EquipmentReferenceMap.ReferenceRow("R3", "EQ-1", "T3", "Override"),
],
new Dictionary<string, string> { ["T1"] = "Speed", ["T2"] = "Temp", ["T3"] = "Level" });
names.ShouldBe(["Speed", "Temp", "Override"], ignoreOrder: true);
}
}
@@ -0,0 +1,165 @@
using System.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests;
/// <summary>
/// lmxopcua#1049 (#998 C-10 follow-up) on the real provider. The raw-tree parent links are LOGICAL foreign keys,
/// so the race the review described — user A's "is the device empty?" check passes, user B adds a tag under it,
/// A deletes the device — really commits both on SQL Server, and the deploy gate's <c>DanglingReference</c> rule is
/// what names the orphan. And because the deploy reads its whole snapshot under SNAPSHOT isolation, a
/// concurrent, perfectly consistent commit landing MID-read cannot make the gate report a dangling row that never
/// existed in any committed state (a parent read before the commit, its child read after it).
/// </summary>
[Trait("Category", "SchemaCompliance")]
[Collection(nameof(SchemaComplianceCollection))]
public sealed class DanglingReferenceSqlServerTests
{
private readonly SchemaComplianceFixture _fixture;
/// <summary>Initializes a new instance of the <see cref="DanglingReferenceSqlServerTests"/> class.</summary>
/// <param name="fixture">The migrated test database.</param>
public DanglingReferenceSqlServerTests(SchemaComplianceFixture fixture) => _fixture = fixture;
private OtOpcUaConfigDbContext NewContext(params IInterceptor[] interceptors) => new(
new DbContextOptionsBuilder<OtOpcUaConfigDbContext>().UseSqlServer(_fixture.ConnectionString)
.AddInterceptors(interceptors).Options);
private static string Id(string prefix) => $"{prefix}-{Guid.NewGuid():N}";
private static Tag NewTag(string tagId, string deviceId) => new()
{
TagId = tagId, DeviceId = deviceId, Name = tagId, DataType = "Int32", AccessLevel = TagAccessLevel.Read, TagConfig = "{}",
};
/// <summary>Seeds cluster → driver → device; returns (driverId, deviceId).</summary>
private (string DriverId, string DeviceId) SeedDevice()
{
var clusterId = Id("cl")[..30];
var driverId = Id("di");
var deviceId = Id("dev");
using var db = NewContext();
db.ServerClusters.Add(new ServerCluster
{
ClusterId = clusterId, Name = Id("Cluster"), Enterprise = "zb", Site = "dev", NodeCount = 1,
RedundancyMode = RedundancyMode.None, CreatedBy = "t1049",
});
db.DriverInstances.Add(new DriverInstance
{
DriverInstanceId = driverId, ClusterId = clusterId, Name = Id("drv"), DriverType = "Modbus", DriverConfig = "{}",
});
db.Devices.Add(new Device { DeviceId = deviceId, DriverInstanceId = driverId, Name = Id("plc"), DeviceConfig = "{}" });
db.SaveChanges();
return (driverId, deviceId);
}
private static IEnumerable<ValidationError> DanglingFor(DraftSnapshot draft, string tagId) =>
DraftValidator.Validate(draft).Where(e => e.Code == DraftValidator.DanglingReferenceCode && e.Context == tagId);
/// <summary>
/// The review's race, interleaved on two real connections: A's emptiness check, B's tag add, A's device delete.
/// Both commit (no FK); the deploy snapshot then names the orphaned tag.
/// </summary>
[Fact]
public async Task A_device_deleted_while_a_tag_is_added_under_it_is_reported_by_the_deploy_gate()
{
var ct = TestContext.Current.CancellationToken;
var (_, deviceId) = SeedDevice();
var tagId = Id("tag");
await using (var userA = NewContext())
{
await using var tx = await userA.Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct);
(await userA.Tags.AnyAsync(t => t.DeviceId == deviceId, ct)).ShouldBeFalse(); // "the device is empty"
await using (var userB = NewContext())
{
userB.Tags.Add(NewTag(tagId, deviceId));
await userB.SaveChangesAsync(ct); // commits while A's check result is already stale
}
userA.Devices.Remove(await userA.Devices.SingleAsync(d => d.DeviceId == deviceId, ct));
await userA.SaveChangesAsync(ct);
await tx.CommitAsync(ct);
}
await using var deploy = NewContext();
var draft = await DraftSnapshotFactory.FromConfigDbAsync(deploy, ct);
draft.Tags.ShouldContain(t => t.TagId == tagId);
draft.Devices.ShouldNotContain(d => d.DeviceId == deviceId);
DanglingFor(draft, tagId).ShouldHaveSingleItem().Message.ShouldContain($"Device '{deviceId}'");
}
/// <summary>
/// A device and its tag added together in ONE commit that lands after the snapshot read has passed the Devices
/// table but before it reads Tags: under the factory's SNAPSHOT transaction neither is seen, so no false
/// <c>DanglingReference</c>. Positive control: the same interleave inside a READ COMMITTED transaction (the
/// factory then reads in the caller's transaction) DOES report the tag as dangling — so the isolation, not the
/// timing, is what keeps the gate honest; and a read after the commit sees both rows and no error.
/// </summary>
[Fact]
public async Task A_consistent_commit_landing_mid_read_is_never_reported_as_dangling_under_snapshot_isolation()
{
var ct = TestContext.Current.CancellationToken;
var (driverId, deviceId) = SeedDevice();
// Snapshot read (the deploy path): the concurrent commit is invisible.
var (lateDevice, lateTag) = (Id("dev"), Id("tag"));
await using (var db = NewContext(new CommitDeviceAndTagWhenDeviceMaterialises(_fixture.ConnectionString, deviceId, driverId, lateDevice, lateTag)))
{
var draft = await DraftSnapshotFactory.FromConfigDbAsync(db, ct);
draft.Tags.ShouldNotContain(t => t.TagId == lateTag);
DanglingFor(draft, lateTag).ShouldBeEmpty();
}
// Positive control 1: the same interleave read unisolated produces exactly the false positive.
var (lateDevice2, lateTag2) = (Id("dev"), Id("tag"));
await using (var db = NewContext(new CommitDeviceAndTagWhenDeviceMaterialises(_fixture.ConnectionString, deviceId, driverId, lateDevice2, lateTag2)))
{
await using var tx = await db.Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct);
var draft = await DraftSnapshotFactory.FromConfigDbAsync(db, ct);
draft.Tags.ShouldContain(t => t.TagId == lateTag2);
DanglingFor(draft, lateTag2).ShouldHaveSingleItem();
}
// Positive control 2: both commits really landed, and a read started afterwards sees them whole.
await using var after = NewContext();
var later = await DraftSnapshotFactory.FromConfigDbAsync(after, ct);
later.Tags.ShouldContain(t => t.TagId == lateTag);
later.Devices.ShouldContain(d => d.DeviceId == lateDevice);
DanglingFor(later, lateTag).ShouldBeEmpty();
DanglingFor(later, lateTag2).ShouldBeEmpty();
}
/// <summary>
/// When the snapshot read materialises the seeded device (Devices is read before Tags), commits a NEW device and a
/// tag under it — one consistent transaction — on a separate connection.
/// </summary>
private sealed class CommitDeviceAndTagWhenDeviceMaterialises(
string connectionString, string triggerDeviceId, string driverId, string newDeviceId, string newTagId)
: IMaterializationInterceptor
{
private int _fired;
public object InitializedInstance(MaterializationInterceptionData materializationData, object entity)
{
if (entity is Device d && d.DeviceId == triggerDeviceId && Interlocked.Exchange(ref _fired, 1) == 0)
{
using var other = new OtOpcUaConfigDbContext(
new DbContextOptionsBuilder<OtOpcUaConfigDbContext>().UseSqlServer(connectionString).Options);
other.Devices.Add(new Device { DeviceId = newDeviceId, DriverInstanceId = driverId, Name = newDeviceId, DeviceConfig = "{}" });
other.Tags.Add(NewTag(newTagId, newDeviceId));
other.SaveChanges();
}
return entity;
}
}
}
@@ -65,44 +65,6 @@ public sealed class DraftSnapshotFactoryTests : IDisposable
DraftValidator.Validate(snapshot).ShouldNotContain(e => e.Code == "UnsEffectiveNameCollision");
}
/// <summary>Seeds one active and one released reservation for the same equipment context;
/// only the active row (ReleasedAt == null) should appear in the snapshot.</summary>
[Fact]
public async Task FromConfigDb_ActiveReservations_excludes_released_rows()
{
var equipmentUuid = Guid.NewGuid();
_db.ExternalIdReservations.Add(new ExternalIdReservation
{
ReservationId = Guid.NewGuid(),
Kind = ReservationKind.ZTag,
Value = "ZT-001",
EquipmentUuid = equipmentUuid,
ClusterId = "cluster-a",
FirstPublishedBy = "test",
ReleasedAt = null, // active
});
_db.ExternalIdReservations.Add(new ExternalIdReservation
{
ReservationId = Guid.NewGuid(),
Kind = ReservationKind.ZTag,
Value = "ZT-002",
EquipmentUuid = equipmentUuid,
ClusterId = "cluster-a",
FirstPublishedBy = "test",
ReleasedAt = new DateTime(2025, 1, 1, 0, 0, 0, DateTimeKind.Utc), // released
ReleasedBy = "test",
ReleaseReason = "retired",
});
await _db.SaveChangesAsync(TestContext.Current.CancellationToken);
var snapshot = await DraftSnapshotFactory.FromConfigDbAsync(_db, TestContext.Current.CancellationToken);
snapshot.ActiveReservations.Count.ShouldBe(1);
snapshot.ActiveReservations[0].Value.ShouldBe("ZT-001");
snapshot.ActiveReservations[0].ReleasedAt.ShouldBeNull();
}
/// <summary>
/// R03:3.2 — the deploy path validates AND composes from ONE snapshot, so the tables the composer
/// needs beyond the validator's set (clusters, nodes, API keys) must ride the same read.
@@ -0,0 +1,68 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests;
/// <summary>
/// lmxopcua#1058 (#974 follow-up): a Sql driver's named query is checked by
/// <c>SqlNamedQueryRules.Describe</c> with the instance's provider when the driver is constructed, and ONE refused
/// query fails the whole driver. The deploy gate now runs the same rule over the same merged config, so a config
/// the driver would refuse at start (e.g. an Odbc query written in PostgreSQL that no longer parses as T-SQL) is
/// refused at deploy instead — and the upgrade preflight finds the ones already stored.
/// </summary>
[Trait("Category", "Unit")]
public sealed class DraftValidatorSqlNamedQueryTests
{
private const string Code = SqlTagDeployChecks.NamedQueryInvalidCode;
private static DraftSnapshot Draft(string driverConfig, string deviceConfig = "{}", string driverType = "Sql") => new()
{
GenerationId = 1, ClusterId = "c",
DriverInstances = [new DriverInstance
{ DriverInstanceId = "di", ClusterId = "c", Name = "sql", DriverType = driverType, DriverConfig = driverConfig }],
Devices = [new Device { DeviceId = "dev", DriverInstanceId = "di", Name = "d", DeviceConfig = deviceConfig }],
};
private static string Config(string provider, string sql) =>
"{\"provider\":\"" + provider + "\",\"queries\":{\"line\":{\"sql\":\"" + sql + "\"}}}";
[Theory]
[InlineData("Odbc", "SELECT 'a'::text AS v")] // PostgreSQL cast of a literal: not T-SQL
[InlineData("Odbc", "SELECT (v)::numeric AS v FROM t")] // ... of an expression
[InlineData("Odbc", "SELECT v FROM t WHERE v ILIKE 'a%'")] // ILIKE: not T-SQL
[InlineData("Odbc", "SELECT v FROM t LIMIT 1")] // LIMIT: not T-SQL
[InlineData("SqlServer", "SELECT 1 AS v COMMIT")] // a second statement without ';'
[InlineData("SqlServer", "DELETE FROM t")]
public void A_named_query_the_driver_would_refuse_is_a_deploy_error(string provider, string sql)
{
var errors = DraftValidator.Validate(Draft(Config(provider, sql)));
errors.ShouldContain(e => e.Code == Code && e.Context == "di" && e.Message.Contains("'line'"));
}
[Theory]
[InlineData("Odbc", "SELECT v FROM t WHERE k = ?")]
[InlineData("SqlServer", "SELECT TOP 1 v FROM t")]
[InlineData("Postgres", "SELECT v::int AS v FROM t LIMIT 1")] // native provider: PostgreSQL dialect is fine
// NB: "col::type" (identifier::identifier) PARSES as T-SQL static-member syntax, so the driver accepts it too.
[InlineData("Odbc", "SELECT v::int AS v FROM t")]
public void Positive_control_a_query_the_driver_accepts_is_quiet(string provider, string sql) =>
DraftValidator.Validate(Draft(Config(provider, sql))).ShouldNotContain(e => e.Code == Code);
[Fact]
public void An_absent_provider_reads_as_SqlServer_like_the_driver() =>
DraftValidator.Validate(Draft("""{"queries":{"q":{"sql":"SELECT 1 AS v COMMIT"}}}"""))
.ShouldContain(e => e.Code == Code);
[Fact]
public void Queries_declared_on_the_single_device_config_are_checked() =>
DraftValidator.Validate(Draft("""{"provider":"Odbc"}""", deviceConfig: """{"queries":{"line":{"sql":"SELECT 1 LIMIT 1"}}}"""))
.ShouldContain(e => e.Code == Code);
[Fact]
public void Non_Sql_drivers_are_not_checked() =>
DraftValidator.Validate(Draft(Config("Odbc", "SELECT 1 LIMIT 1"), driverType: "Modbus"))
.ShouldNotContain(e => e.Code == Code);
}
@@ -51,23 +51,6 @@ public sealed class DraftValidatorTests
hasUnsError.ShouldBe(!shouldPass);
}
/// <summary>Verifies that a ZTag cannot be reserved by a different equipment UUID.</summary>
[Fact]
public void ZTag_reserved_by_different_uuid_is_rejected()
{
var uuid = Guid.NewGuid();
var otherUuid = Guid.NewGuid();
var draft = new DraftSnapshot
{
GenerationId = 1, ClusterId = "c",
Equipment = [new Equipment { EquipmentUuid = uuid, EquipmentId = DraftValidator.DeriveEquipmentId(uuid), Name = "eq", UnsLineId = "line-a", MachineCode = "m", ZTag = "ZT-001" }],
ActiveReservations = [new ExternalIdReservation { Kind = ReservationKind.ZTag, Value = "ZT-001", EquipmentUuid = otherUuid, ClusterId = "c", FirstPublishedBy = "t" }],
};
DraftValidator.Validate(draft).ShouldContain(e => e.Code == "BadDuplicateExternalIdentifier");
}
/// <summary>Verifies that equipment ID must be derived from its UUID.</summary>
[Fact]
public void EquipmentId_that_does_not_match_derivation_is_rejected()
@@ -0,0 +1,86 @@
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests;
/// <summary>
/// A private, throw-away ConfigDb on the shared test SQL Server that a test migrates to a chosen migration
/// (not necessarily the latest), so a migration's pre-check can be exercised against data that the NEXT
/// migration must refuse. Named with <see cref="SchemaComplianceFixture.TestDatabasePrefix"/> so an orphan is
/// reclaimed by the fixture's reaper; dropped in <see cref="Dispose"/>.
/// </summary>
internal sealed class MigrationScratchDatabase : IDisposable
{
private const string DefaultServer = "10.100.0.35,14330";
private const string DefaultSaPassword = "OtOpcUaDev_2026!";
/// <summary>Gets the database name.</summary>
public string DatabaseName { get; }
/// <summary>Gets the connection string to the scratch database.</summary>
public string ConnectionString { get; }
/// <summary>Creates the (empty) database; nothing is migrated until <see cref="MigrateTo"/>.</summary>
public MigrationScratchDatabase()
{
var server = Environment.GetEnvironmentVariable("OTOPCUA_CONFIG_TEST_SERVER") ?? DefaultServer;
var saPassword = Environment.GetEnvironmentVariable("OTOPCUA_CONFIG_TEST_SA_PASSWORD") ?? DefaultSaPassword;
DatabaseName = $"{SchemaComplianceFixture.TestDatabasePrefix}{DateTime.UtcNow:yyyyMMddHHmmss}_{Guid.NewGuid():N}";
ConnectionString =
$"Server={server};Database={DatabaseName};User Id=sa;Password={saPassword};TrustServerCertificate=True;Encrypt=False;";
}
/// <summary>Opens a context on the scratch database.</summary>
/// <returns>A new context.</returns>
public OtOpcUaConfigDbContext NewContext() =>
new(new DbContextOptionsBuilder<OtOpcUaConfigDbContext>().UseSqlServer(ConnectionString).Options);
/// <summary>Migrates (up) to <paramref name="targetMigration"/>, or to the latest when null.</summary>
/// <param name="targetMigration">The migration id or name to stop at.</param>
public void MigrateTo(string? targetMigration = null)
{
using var db = NewContext();
db.GetService<IMigrator>().Migrate(targetMigration);
}
/// <summary>The most recently applied migration id.</summary>
/// <returns>The id, or null when none is applied.</returns>
public string? LastAppliedMigration()
{
using var db = NewContext();
return db.Database.GetAppliedMigrations().LastOrDefault();
}
/// <summary>Runs one non-query statement.</summary>
/// <param name="sql">The T-SQL.</param>
public void Execute(string sql)
{
using var conn = new SqlConnection(ConnectionString);
conn.Open();
using var cmd = conn.CreateCommand();
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
/// <summary>Runs one scalar query.</summary>
/// <param name="sql">The T-SQL.</param>
/// <returns>The scalar.</returns>
public object? Scalar(string sql)
{
using var conn = new SqlConnection(ConnectionString);
conn.Open();
using var cmd = conn.CreateCommand();
cmd.CommandText = sql;
return cmd.ExecuteScalar();
}
/// <inheritdoc />
public void Dispose()
{
SqlConnection.ClearAllPools();
var master = new SqlConnectionStringBuilder(ConnectionString) { InitialCatalog = "master" }.ConnectionString;
SqlTestDatabaseReaper.TryDropDatabase(master, DatabaseName);
}
}
@@ -1,63 +0,0 @@
using Microsoft.EntityFrameworkCore;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Configuration.Queries;
namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests;
/// <summary>lmxopcua#996 / review A-8: the /reservations page read is active-only by default, projected and capped.</summary>
[Trait("Category", "Unit")]
public sealed class ReservationListQueryTests
{
private static OtOpcUaConfigDbContext InMemory() =>
new(new DbContextOptionsBuilder<OtOpcUaConfigDbContext>().UseInMemoryDatabase($"resv-{Guid.NewGuid():N}").Options);
private static void Seed(OtOpcUaConfigDbContext db, int active, int released)
{
for (var i = 0; i < active + released; i++)
db.ExternalIdReservations.Add(new ExternalIdReservation
{
ReservationId = Guid.NewGuid(), Kind = i % 2 == 0 ? ReservationKind.ZTag : ReservationKind.SAPID,
Value = $"v{i:0000}", EquipmentUuid = Guid.NewGuid(), ClusterId = "MAIN", FirstPublishedBy = "t",
ReleasedAt = i < active ? null : DateTime.UtcNow, ReleasedBy = i < active ? null : "t",
});
db.SaveChanges();
}
/// <summary>1,000 rows render at most the page size and the total is reported; released rows are hidden by default.</summary>
[Fact]
public async Task Page_is_capped_and_defaults_to_active_rows()
{
using var db = InMemory();
Seed(db, active: 700, released: 300);
var page = await ReservationListQuery.LoadAsync(db, includeReleased: false, ct: TestContext.Current.CancellationToken);
page.Rows.Count.ShouldBe(ReservationListQuery.DefaultPageSize);
page.Total.ShouldBe(700);
page.Rows.ShouldAllBe(r => r.ReleasedAt == null);
// Positive control: asking for released rows too changes the total (so the filter was what hid them).
var all = await ReservationListQuery.LoadAsync(db, includeReleased: true, pageSize: 50, ct: TestContext.Current.CancellationToken);
all.Total.ShouldBe(1000);
all.Rows.Count.ShouldBe(50);
}
/// <summary>The SQL selects only the displayed columns (no audit columns) and filters released rows server-side.</summary>
[Fact]
public void Query_projects_displayed_columns_and_filters_released_rows_in_sql()
{
using var db = new OtOpcUaConfigDbContext(new DbContextOptionsBuilder<OtOpcUaConfigDbContext>()
.UseSqlServer("Server=127.0.0.1,1;Database=never;Connect Timeout=1").Options);
var sql = ReservationListQuery.Query(db, includeReleased: false).ToQueryString();
sql.ShouldContain("[ReleasedAt] IS NULL");
sql.ShouldNotContain("FirstPublishedBy");
sql.ShouldNotContain("LastPublishedAt");
ReservationListQuery.Query(db, includeReleased: true).ToQueryString().ShouldNotContain("IS NULL");
// Positive control: the whole-entity read does select the audit columns.
db.ExternalIdReservations.AsNoTracking().ToQueryString().ShouldContain("FirstPublishedBy");
}
}
@@ -34,7 +34,9 @@ public sealed class SchemaComplianceTests
"DriverInstance", "Device", "Equipment", "Tag", "PollGroup", "VirtualTag",
// ApiKey added in Gitea #520 — the OPC UA data plane is machine-to-machine, so a consuming
// system authenticates with a key resolving to a Principal that NodeAcl rows grant to.
"NodeAcl", "ApiKey", "ExternalIdReservation",
"NodeAcl", "ApiKey",
// ExternalIdReservation was dropped by lmxopcua#1049 — no writer since the generation model retired;
// ZTag/SAPID uniqueness is the deploy gate plus UX_Equipment_ZTag / UX_Equipment_SAPID below.
// DriverHostStatus was dropped in Gitea #521 — nothing ever wrote a row, and per-cluster
// mesh Phase 4 made the publisher its entity doc described unbuildable (a driver-only node
// has no ConfigDb connection). Per-host connectivity now rides DriverHealthChanged to /hosts.
@@ -69,7 +71,8 @@ SELECT name FROM sys.tables WHERE name <> '__EFMigrationsHistory' ORDER BY name;
var expected = new[]
{
("UX_ClusterNodeCredential_Value", "([Enabled]=(1))"),
("UX_ExternalIdReservation_KindValue_Active", "([ReleasedAt] IS NULL)"),
("UX_Equipment_ZTag", "([ZTag] IS NOT NULL AND [ZTag]<>N'')"),
("UX_Equipment_SAPID", "([SAPID] IS NOT NULL AND [SAPID]<>N'')"),
// v3 sibling-name filtered unique indexes over nullable parent columns.
("UX_RawFolder_Parent_Name", "([ParentRawFolderId] IS NOT NULL)"),
("UX_RawFolder_ClusterRoot_Name", "([ParentRawFolderId] IS NULL)"),
@@ -0,0 +1,108 @@
using Microsoft.Data.SqlClient;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests;
/// <summary>
/// lmxopcua#1040 / #1049: migration <c>ScriptForeignKeysAndExternalIdUniqueness</c> must refuse — loudly, naming the
/// rows, and changing NOTHING — a populated ConfigDb holding data its constraints cannot hold (dangling script
/// references, duplicated ZTag / SAPID, reservation history it would drop); and apply cleanly once they are fixed.
/// Each test migrates its own scratch database to the previous migration, seeds, then migrates up.
/// </summary>
[Trait("Category", "SchemaCompliance")]
[Collection(nameof(SchemaComplianceCollection))]
public sealed class ScriptForeignKeysAndExternalIdUniquenessMigrationTests
{
private const string Previous = "20261203154217_ConfigurationGapsIndexesAndRowVersions";
private static Equipment NewEquipment(string? zTag = null, string? sapId = null)
{
var uuid = Guid.NewGuid();
return new Equipment
{
EquipmentId = "EQ-" + uuid.ToString("N")[..12], EquipmentUuid = uuid, UnsLineId = "line-" + uuid.ToString("N"),
Name = "eq", MachineCode = "mc-" + uuid.ToString("N"), ZTag = zTag, SAPID = sapId,
};
}
/// <summary>Every offending row class is named in ONE refusal and the schema is left exactly as it was.</summary>
[Fact]
public void Offending_rows_refuse_the_migration_and_nothing_changes()
{
using var scratch = new MigrationScratchDatabase();
scratch.MigrateTo(Previous);
using (var db = scratch.NewContext())
{
db.VirtualTags.Add(new VirtualTag
{
VirtualTagId = "VT-dangling", EquipmentId = "EQ-x", Name = "V", DataType = "Int32", ScriptId = "SC-gone",
});
db.ScriptedAlarms.Add(new ScriptedAlarm
{
ScriptedAlarmId = "SA-dangling", EquipmentId = "EQ-x", Name = "A", AlarmType = "AlarmCondition",
MessageTemplate = "m", PredicateScriptId = "SC-also-gone",
});
db.Equipment.AddRange(NewEquipment(zTag: "ZT-1"), NewEquipment(zTag: "zt-1"), NewEquipment(sapId: "SAP-1"), NewEquipment(sapId: "SAP-1"));
db.SaveChanges();
}
scratch.Execute(
"INSERT ExternalIdReservation (Kind, Value, EquipmentUuid, ClusterId, FirstPublishedBy) VALUES ('ZTag', 'ZT-9', NEWID(), 'c', 't')");
var ex = Should.Throw<SqlException>(() => scratch.MigrateTo());
ex.Number.ShouldBe(51049);
ex.Message.ShouldContain("VT-dangling->SC-gone");
ex.Message.ShouldContain("SA-dangling->SC-also-gone");
ex.Message.ShouldContain("ZTag value(s)");
ex.Message.ShouldContain("SAPID value(s)");
ex.Message.ShouldContain("1 ExternalIdReservation row(s)");
scratch.LastAppliedMigration().ShouldBe(Previous);
scratch.Scalar("SELECT COUNT(*) FROM sys.indexes WHERE name = 'IX_Equipment_ZTag'").ShouldBe(1);
scratch.Scalar("SELECT COUNT(*) FROM ExternalIdReservation").ShouldBe(1);
scratch.Scalar("SELECT COUNT(*) FROM sys.foreign_keys WHERE name = 'FK_VirtualTag_Script'").ShouldBe(0);
}
/// <summary>Positive control: once the operator fixes the rows the same database migrates and the constraints exist.</summary>
[Fact]
public void A_clean_populated_database_migrates_and_gains_the_constraints()
{
using var scratch = new MigrationScratchDatabase();
scratch.MigrateTo(Previous);
using (var db = scratch.NewContext())
{
db.Scripts.Add(new Script { ScriptId = "SC-1", Name = "s", SourceCode = "return 1;", SourceHash = new string('a', 64) });
db.VirtualTags.Add(new VirtualTag
{
VirtualTagId = "VT-ok", EquipmentId = "EQ-x", Name = "V", DataType = "Int32", ScriptId = "SC-1",
});
db.ScriptedAlarms.Add(new ScriptedAlarm
{
ScriptedAlarmId = "SA-ok", EquipmentId = "EQ-x", Name = "A", AlarmType = "AlarmCondition",
MessageTemplate = "m", PredicateScriptId = "SC-1",
});
// Blank and NULL identifiers are "none" and may repeat; distinct values are fine.
db.Equipment.AddRange(NewEquipment(), NewEquipment(), NewEquipment(zTag: "", sapId: ""), NewEquipment(zTag: "", sapId: ""),
NewEquipment(zTag: "ZT-1", sapId: "SAP-1"), NewEquipment(zTag: "ZT-2", sapId: "SAP-2"));
db.SaveChanges();
}
Should.NotThrow(() => scratch.MigrateTo());
scratch.LastAppliedMigration().ShouldEndWith("_ScriptForeignKeysAndExternalIdUniqueness");
scratch.Scalar("SELECT COUNT(*) FROM sys.foreign_keys WHERE name IN ('FK_VirtualTag_Script', 'FK_ScriptedAlarm_Script')").ShouldBe(2);
scratch.Scalar("SELECT COUNT(*) FROM sys.indexes WHERE is_unique = 1 AND name IN ('UX_Equipment_ZTag', 'UX_Equipment_SAPID')").ShouldBe(2);
scratch.Scalar("SELECT OBJECT_ID(N'ExternalIdReservation')").ShouldBe(DBNull.Value);
scratch.Scalar("SELECT OBJECT_ID(N'dbo.sp_ReleaseExternalIdReservation')").ShouldBe(DBNull.Value);
scratch.Scalar("SELECT COUNT(*) FROM VirtualTag").ShouldBe(1);
// Down restores the previous shape (table, procedure, non-unique indexes) without touching the data.
Should.NotThrow(() => scratch.MigrateTo(Previous));
scratch.Scalar("SELECT COUNT(*) FROM sys.indexes WHERE is_unique = 0 AND name IN ('IX_Equipment_ZTag', 'IX_Equipment_SAPID')").ShouldBe(2);
scratch.Scalar("SELECT COUNT(*) FROM sys.foreign_keys WHERE name LIKE 'FK_%_Script'").ShouldBe(0);
scratch.Scalar("SELECT CASE WHEN OBJECT_ID(N'dbo.sp_ReleaseExternalIdReservation') IS NULL THEN 0 ELSE 1 END").ShouldBe(1);
scratch.Scalar("SELECT COUNT(*) FROM ExternalIdReservation").ShouldBe(0);
scratch.Scalar("SELECT COUNT(*) FROM Equipment").ShouldBe(6);
}
}
@@ -0,0 +1,170 @@
using Microsoft.EntityFrameworkCore;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests;
/// <summary>
/// lmxopcua#1040 (script FKs) and lmxopcua#1049 (Equipment ZTag / SAPID filtered unique indexes) against the real
/// SQL schema: the database itself now refuses a VirtualTag / ScriptedAlarm naming a missing script, the delete of an
/// in-use script, and a second equipment claiming a ZTag or SAPID — with positive controls for each.
/// </summary>
[Trait("Category", "SchemaCompliance")]
[Collection(nameof(SchemaComplianceCollection))]
public sealed class ScriptForeignKeysAndExternalIdUniquenessSchemaTests
{
private readonly SchemaComplianceFixture _fixture;
/// <summary>Initializes a new instance of the <see cref="ScriptForeignKeysAndExternalIdUniquenessSchemaTests"/> class.</summary>
/// <param name="fixture">The schema compliance fixture (real SQL DB).</param>
public ScriptForeignKeysAndExternalIdUniquenessSchemaTests(SchemaComplianceFixture fixture) => _fixture = fixture;
private OtOpcUaConfigDbContext NewContext() =>
new(new DbContextOptionsBuilder<OtOpcUaConfigDbContext>().UseSqlServer(_fixture.ConnectionString).Options);
private static string Id(string prefix) => $"{prefix}-{Guid.NewGuid():N}";
private static Script NewScript(string id) => new()
{
ScriptId = id, Name = id, SourceCode = "return 1;", SourceHash = new string('a', 64),
};
private static VirtualTag NewVirtualTag(string scriptId) => new()
{
VirtualTagId = Id("vt"), EquipmentId = Id("eq"), Name = "V", DataType = "Int32", ScriptId = scriptId,
};
private static ScriptedAlarm NewAlarm(string scriptId) => new()
{
ScriptedAlarmId = Id("sa"), EquipmentId = Id("eq"), Name = "A", AlarmType = "AlarmCondition",
MessageTemplate = "m", PredicateScriptId = scriptId,
};
private static Equipment NewEquipment(string? zTag = null, string? sapId = null)
{
var uuid = Guid.NewGuid();
return new Equipment
{
EquipmentId = "EQ-" + uuid.ToString("N")[..12], EquipmentUuid = uuid, UnsLineId = Id("line"),
Name = "eq", MachineCode = Id("mc"), ZTag = zTag, SAPID = sapId,
};
}
/// <summary>A VirtualTag naming a script that does not exist is refused by FK_VirtualTag_Script.</summary>
[Fact]
public void A_virtual_tag_naming_a_missing_script_is_refused()
{
using var db = NewContext();
db.VirtualTags.Add(NewVirtualTag(Id("missing")));
Should.Throw<DbUpdateException>(() => db.SaveChanges()).InnerException!.Message.ShouldContain("FK_VirtualTag_Script");
}
/// <summary>A ScriptedAlarm naming a missing predicate script is refused by FK_ScriptedAlarm_Script.</summary>
[Fact]
public void A_scripted_alarm_naming_a_missing_predicate_script_is_refused()
{
using var db = NewContext();
db.ScriptedAlarms.Add(NewAlarm(Id("missing")));
Should.Throw<DbUpdateException>(() => db.SaveChanges()).InnerException!.Message.ShouldContain("FK_ScriptedAlarm_Script");
}
/// <summary>Positive control: a script and the rows that use it, added in ONE SaveChanges, insert in FK order.</summary>
[Fact]
public void A_script_and_its_users_saved_together_are_accepted()
{
var scriptId = Id("sc");
using var db = NewContext();
db.VirtualTags.Add(NewVirtualTag(scriptId));
db.ScriptedAlarms.Add(NewAlarm(scriptId));
db.Scripts.Add(NewScript(scriptId));
Should.NotThrow(() => db.SaveChanges());
}
/// <summary>Deleting a script a VirtualTag still uses is refused (Restrict, never a cascade).</summary>
[Fact]
public void Deleting_an_in_use_script_is_refused()
{
var scriptId = Id("sc");
using (var seed = NewContext())
{
seed.Scripts.Add(NewScript(scriptId));
seed.VirtualTags.Add(NewVirtualTag(scriptId));
seed.SaveChanges();
}
using var db = NewContext();
db.Scripts.Remove(db.Scripts.Single(s => s.ScriptId == scriptId));
Should.Throw<DbUpdateException>(() => db.SaveChanges());
using var check = NewContext();
check.VirtualTags.Count(v => v.ScriptId == scriptId).ShouldBe(1);
}
/// <summary>Positive control: an unused script deletes; and a script plus its last user delete together.</summary>
[Fact]
public void Deleting_an_unused_script_or_a_script_with_its_users_is_accepted()
{
var unused = Id("sc");
var used = Id("sc");
using (var seed = NewContext())
{
seed.Scripts.Add(NewScript(unused));
seed.Scripts.Add(NewScript(used));
seed.VirtualTags.Add(NewVirtualTag(used));
seed.SaveChanges();
}
using var db = NewContext();
db.Scripts.Remove(db.Scripts.Single(s => s.ScriptId == unused));
db.Scripts.Remove(db.Scripts.Single(s => s.ScriptId == used));
db.VirtualTags.RemoveRange(db.VirtualTags.Where(v => v.ScriptId == used).ToList());
Should.NotThrow(() => db.SaveChanges());
}
/// <summary>Two equipment rows with one ZTag (differing only in case) are refused by UX_Equipment_ZTag.</summary>
[Fact]
public void A_duplicate_ZTag_is_refused_case_insensitively()
{
var zTag = Id("ZT");
using var db = NewContext();
db.Equipment.Add(NewEquipment(zTag: zTag));
db.Equipment.Add(NewEquipment(zTag: zTag.ToLowerInvariant()));
Should.Throw<DbUpdateException>(() => db.SaveChanges()).InnerException!.Message.ShouldContain("UX_Equipment_ZTag");
}
/// <summary>The same for SAPID.</summary>
[Fact]
public void A_duplicate_SAPID_is_refused()
{
var sapId = Id("SAP");
using var db = NewContext();
db.Equipment.Add(NewEquipment(sapId: sapId));
db.Equipment.Add(NewEquipment(sapId: sapId));
Should.Throw<DbUpdateException>(() => db.SaveChanges()).InnerException!.Message.ShouldContain("UX_Equipment_SAPID");
}
/// <summary>
/// Positive control: NULL and blank identifiers mean "none" (the deploy gate's rule), so any number of them
/// coexist, and distinct values are fine.
/// </summary>
[Fact]
public void Null_blank_and_distinct_identifiers_are_accepted()
{
using var db = NewContext();
db.Equipment.Add(NewEquipment());
db.Equipment.Add(NewEquipment());
db.Equipment.Add(NewEquipment(zTag: "", sapId: ""));
db.Equipment.Add(NewEquipment(zTag: " ", sapId: " "));
db.Equipment.Add(NewEquipment(zTag: Id("ZT"), sapId: Id("SAP")));
db.Equipment.Add(NewEquipment(zTag: Id("ZT"), sapId: Id("SAP")));
Should.NotThrow(() => db.SaveChanges());
}
}
@@ -54,7 +54,11 @@ public sealed class ScriptingEntitiesTests
// v2 live-edit dropped the per-generation qualifier; Script.ScriptId is globally unique.
using var ctx = BuildCtx();
var entity = ctx.Model.FindEntityType(typeof(Script)).ShouldNotBeNull();
entity.GetIndexes().Any(i => i.IsUnique).ShouldBeTrue("Script needs at least one unique index");
// lmxopcua#1040: the logical id is the principal key of the VirtualTag / ScriptedAlarm FKs, so it is an
// alternate key (a unique constraint) named as the unique index it replaced.
var key = entity.GetKeys().SingleOrDefault(k => k.Properties.Select(p => p.Name).SequenceEqual([nameof(Script.ScriptId)]));
key.ShouldNotBeNull("Script.ScriptId must be a unique (alternate) key");
key.GetName().ShouldBe("UX_Script_LogicalId");
}
/// <summary>Verifies that the VirtualTag entity is registered with the expected trigger check constraint.</summary>
@@ -71,7 +71,6 @@ public class PageAuthorizationGuardTests
[typeof(AlarmsHistorian)] = AdminUiPolicies.AuthenticatedRead,
[typeof(Account)] = AdminUiPolicies.AuthenticatedRead,
[typeof(global::ZB.MOM.WW.OtOpcUa.AdminUI.Components.Pages.Certificates)] = AdminUiPolicies.AuthenticatedRead,
[typeof(Reservations)] = AdminUiPolicies.AuthenticatedRead,
[typeof(ClustersList)] = AdminUiPolicies.AuthenticatedRead,
[typeof(ClusterOverview)] = AdminUiPolicies.AuthenticatedRead,
[typeof(ClusterAudit)] = AdminUiPolicies.AuthenticatedRead,
@@ -65,7 +65,6 @@ public sealed class DataConnectionsNarrowLoadTests
narrow.Scripts.ShouldBeEmpty();
narrow.NodeAcls.ShouldBeEmpty();
narrow.PollGroups.ShouldBeEmpty();
narrow.ActiveReservations.ShouldBeEmpty();
narrow.Tags.Select(t => t.TagId).ShouldBe(full.Tags.Select(t => t.TagId));
narrow.Tags.Single(t => t.TagId == "TAG-bulky").TagConfig.ShouldBe("{}");
@@ -0,0 +1,202 @@
using Bunit;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Pages.Clusters;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Pages;
/// <summary>
/// lmxopcua#1049 (#998 C-9 follow-up): the NodeEdit / ClusterEdit pages against a REAL SQL Server, where
/// <c>rowversion</c> is generated and the Restrict FKs exist (the InMemory provider has neither). A save carrying
/// the token the page loaded is refused once another user has changed the row — the other user's edit survives —
/// and a save with a current token succeeds; a node that was deployed to deletes together with its
/// <c>NodeDeploymentState</c> rows; a cluster that still has nodes is not deleted and the page says why.
/// </summary>
[Collection(nameof(AdminUiSqlServerCollection))]
public sealed class ClusterNodeEditConcurrencySqlServerTests : BunitContext
{
private const string ModalSelector = ".modal-dialog";
private readonly AdminUiSqlServerFixture _sql;
/// <summary>Registers the fixture's SQL-backed context factory (when the server is available).</summary>
/// <param name="sql">The AdminUI SQL Server fixture.</param>
public ClusterNodeEditConcurrencySqlServerTests(AdminUiSqlServerFixture sql)
{
_sql = sql;
JSInterop.Setup<bool>("otDialog.activate", _ => true).SetResult(true);
JSInterop.SetupVoid("otDialog.update", _ => true).SetVoidResult();
JSInterop.SetupVoid("otDialog.deactivate", _ => true).SetVoidResult();
if (sql.SkipReason is null) Services.AddSingleton(sql.Factory);
Services.AddSingleton<AuthenticationStateProvider>(new FakeAuth());
}
private static string Id(string prefix) => $"{prefix}-{Guid.NewGuid():N}"[..(prefix.Length + 21)];
private string SeedCluster()
{
var clusterId = Id("C");
using var db = _sql.Factory.CreateDbContext();
db.ServerClusters.Add(new ServerCluster
{
ClusterId = clusterId, Name = Id("Cluster"), Enterprise = "zb", Site = "s1", NodeCount = 1,
RedundancyMode = RedundancyMode.None, CreatedBy = "t1049",
});
db.SaveChanges();
return clusterId;
}
private string SeedNode(string clusterId)
{
var nodeId = Id("n");
using var db = _sql.Factory.CreateDbContext();
db.ClusterNodes.Add(new ClusterNode
{
NodeId = nodeId, ClusterId = clusterId, Host = "h-original", ApplicationUri = "urn:" + nodeId, CreatedBy = "t1049",
});
db.SaveChanges();
return nodeId;
}
/// <summary>Another user's committed edit, on its own context.</summary>
private void ConcurrentEdit(Action<OtOpcUaConfigDbContext> edit)
{
using var db = _sql.Factory.CreateDbContext();
edit(db);
db.SaveChanges();
}
/// <summary>NodeEdit: a stale token is refused with the concurrency message; the other user's edit survives.</summary>
[SqlServerFact]
public void NodeEdit_save_with_a_stale_token_is_refused()
{
var clusterId = SeedCluster();
var nodeId = SeedNode(clusterId);
var cut = Render<NodeEdit>(p => p.Add(x => x.ClusterId, clusterId).Add(x => x.NodeId, nodeId));
cut.WaitForAssertion(() => cut.Find("#host").GetAttribute("value").ShouldBe("h-original"));
ConcurrentEdit(db => db.ClusterNodes.Single(n => n.NodeId == nodeId).Host = "h-other-user");
cut.Find("#host").Change("h-stale");
cut.Find("form").Submit();
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Another user changed this node"));
using var db = _sql.Factory.CreateDbContext();
db.ClusterNodes.AsNoTracking().Single(n => n.NodeId == nodeId).Host.ShouldBe("h-other-user");
}
/// <summary>Positive control: with no concurrent edit the same save goes through.</summary>
[SqlServerFact]
public void NodeEdit_save_with_a_current_token_succeeds()
{
var clusterId = SeedCluster();
var nodeId = SeedNode(clusterId);
var cut = Render<NodeEdit>(p => p.Add(x => x.ClusterId, clusterId).Add(x => x.NodeId, nodeId));
cut.WaitForAssertion(() => cut.Find("#host").GetAttribute("value").ShouldBe("h-original"));
cut.Find("#host").Change("h-saved");
cut.Find("form").Submit();
cut.WaitForAssertion(() =>
{
using var db = _sql.Factory.CreateDbContext();
db.ClusterNodes.AsNoTracking().Single(n => n.NodeId == nodeId).Host.ShouldBe("h-saved");
});
cut.Markup.ShouldNotContain("Another user changed this node");
}
/// <summary>ClusterEdit: a stale token is refused; positive control on the same page after a reload-equivalent re-render.</summary>
[SqlServerFact]
public void ClusterEdit_save_with_a_stale_token_is_refused()
{
var clusterId = SeedCluster();
var cut = Render<ClusterEdit>(p => p.Add(x => x.ClusterId, clusterId));
cut.WaitForAssertion(() => cut.Find("#notes"));
ConcurrentEdit(db => db.ServerClusters.Single(c => c.ClusterId == clusterId).Notes = "other user");
cut.Find("#notes").Change("stale");
cut.Find("form").Submit();
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Another user changed this cluster"));
using (var db = _sql.Factory.CreateDbContext())
db.ServerClusters.AsNoTracking().Single(c => c.ClusterId == clusterId).Notes.ShouldBe("other user");
var fresh = Render<ClusterEdit>(p => p.Add(x => x.ClusterId, clusterId));
fresh.WaitForAssertion(() => fresh.Find("#notes"));
fresh.Find("#notes").Change("current");
fresh.Find("form").Submit();
fresh.WaitForAssertion(() =>
{
using var db = _sql.Factory.CreateDbContext();
db.ServerClusters.AsNoTracking().Single(c => c.ClusterId == clusterId).Notes.ShouldBe("current");
});
}
/// <summary>A node with NodeDeploymentState rows (Restrict FK) deletes together with them — no raw FK error.</summary>
[SqlServerFact]
public void NodeEdit_delete_of_a_deployed_node_removes_its_deployment_states()
{
var clusterId = SeedCluster();
var nodeId = SeedNode(clusterId);
var deploymentId = Guid.NewGuid();
using (var seed = _sql.Factory.CreateDbContext())
{
seed.Deployments.Add(new Deployment { DeploymentId = deploymentId, RevisionHash = new string('a', 64), CreatedBy = "t1049" });
seed.NodeDeploymentStates.Add(new NodeDeploymentState { NodeId = nodeId, DeploymentId = deploymentId, Status = NodeDeploymentStatus.Applied });
seed.SaveChanges();
}
var cut = Render<NodeEdit>(p => p.Add(x => x.ClusterId, clusterId).Add(x => x.NodeId, nodeId));
cut.WaitForAssertion(() => cut.Find("button.btn-outline-danger"));
cut.Find("button.btn-outline-danger").Click();
cut.Find(".modal-footer .btn-danger").Click();
cut.WaitForAssertion(() =>
{
using var db = _sql.Factory.CreateDbContext();
db.ClusterNodes.Any(n => n.NodeId == nodeId).ShouldBeFalse();
db.NodeDeploymentStates.Any(s => s.NodeId == nodeId).ShouldBeFalse();
db.Deployments.Any(d => d.DeploymentId == deploymentId).ShouldBeTrue(); // the deployment itself is history, kept
});
}
/// <summary>A cluster that still has nodes is not deleted (Restrict FK) and the page names the reason; positive control: an empty one deletes.</summary>
[SqlServerFact]
public void ClusterEdit_delete_of_a_cluster_with_nodes_is_refused_with_a_reason()
{
var busy = SeedCluster();
SeedNode(busy);
var cut = Render<ClusterEdit>(p => p.Add(x => x.ClusterId, busy));
cut.WaitForAssertion(() => cut.Find("button.btn-outline-danger"));
cut.Find("button.btn-outline-danger").Click();
cut.Find(".modal-footer .btn-danger").Click();
cut.WaitForAssertion(() => cut.Markup.ShouldContain("remove them first"));
using (var db = _sql.Factory.CreateDbContext())
db.ServerClusters.Any(c => c.ClusterId == busy).ShouldBeTrue();
var empty = SeedCluster();
var cut2 = Render<ClusterEdit>(p => p.Add(x => x.ClusterId, empty));
cut2.WaitForAssertion(() => cut2.Find("button.btn-outline-danger"));
cut2.Find("button.btn-outline-danger").Click();
cut2.Find(".modal-footer .btn-danger").Click();
cut2.WaitForAssertion(() =>
{
using var db = _sql.Factory.CreateDbContext();
db.ServerClusters.Any(c => c.ClusterId == empty).ShouldBeFalse();
});
}
private sealed class FakeAuth : AuthenticationStateProvider
{
public override Task<AuthenticationState> GetAuthenticationStateAsync() =>
Task.FromResult(new AuthenticationState(new System.Security.Claims.ClaimsPrincipal(
new System.Security.Claims.ClaimsIdentity("test"))));
}
}
@@ -0,0 +1,148 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.AdminUI.Uns;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Uns;
/// <summary>
/// lmxopcua#1049 / #1040: the authoring mirrors of the new database constraints. A ZTag / SAPID another equipment
/// holds (case-insensitive, trimmed) is refused on create, update and CSV import with the owner named — not left
/// to <c>UX_Equipment_ZTag</c> / <c>UX_Equipment_SAPID</c> to fail the save (or a whole import batch) with no row
/// named; a VirtualTag / scripted alarm naming a script that does not exist is refused before
/// <c>FK_VirtualTag_Script</c> / <c>FK_ScriptedAlarm_Script</c> would.
/// </summary>
[Trait("Category", "Unit")]
public sealed class UnsTreeServiceExternalIdAndScriptReferenceTests
{
private static (UnsTreeService Service, string DbName) Fresh()
{
var dbName = $"uns-extid-{Guid.NewGuid():N}";
using var db = UnsTreeTestDb.CreateNamed(dbName);
db.UnsAreas.Add(new UnsArea { UnsAreaId = "AREA-1", ClusterId = "MAIN", Name = "a" });
db.UnsLines.Add(new UnsLine { UnsLineId = "LINE-1", UnsAreaId = "AREA-1", Name = "l" });
db.SaveChanges();
return (new UnsTreeService(UnsTreeTestDb.Factory(dbName)), dbName);
}
private static EquipmentInput Input(string name, string machineCode, string? zTag = null, string? sapId = null) =>
new(name, machineCode, "LINE-1",
ZTag: zTag, SAPID: sapId, Manufacturer: null, Model: null, SerialNumber: null,
HardwareRevision: null, SoftwareRevision: null, YearOfConstruction: null,
AssetLocation: null, ManufacturerUri: null, DeviceManualUri: null, Enabled: true);
/// <summary>Create refuses a ZTag another equipment holds and names it; a trimmed copy counts as the same value.</summary>
[Fact]
public async Task Create_refuses_a_ZTag_another_equipment_holds()
{
var (svc, dbName) = Fresh();
var ct = TestContext.Current.CancellationToken;
(await svc.CreateEquipmentAsync(Input("m1", "MC1", zTag: "ZT-1"), ct)).Ok.ShouldBeTrue();
using var db = UnsTreeTestDb.CreateNamed(dbName);
var owner = db.Equipment.Single().EquipmentId;
var dup = await svc.CreateEquipmentAsync(Input("m2", "MC2", zTag: " ZT-1 "), ct);
dup.Ok.ShouldBeFalse();
dup.Error.ShouldNotBeNull().ShouldContain("ZTag 'ZT-1'");
dup.Error.ShouldContain(owner);
}
/// <summary>Update refuses a SAPID another equipment holds, but keeping its OWN value is fine.</summary>
[Fact]
public async Task Update_refuses_another_equipments_SAPID_but_keeps_its_own()
{
var (svc, dbName) = Fresh();
var ct = TestContext.Current.CancellationToken;
(await svc.CreateEquipmentAsync(Input("m1", "MC1", sapId: "SAP-1"), ct)).Ok.ShouldBeTrue();
(await svc.CreateEquipmentAsync(Input("m2", "MC2", sapId: "SAP-2"), ct)).Ok.ShouldBeTrue();
using var db = UnsTreeTestDb.CreateNamed(dbName);
var second = db.Equipment.Single(e => e.MachineCode == "MC2");
var clash = await svc.UpdateEquipmentAsync(second.EquipmentId, Input("m2", "MC2", sapId: "SAP-1"), second.RowVersion, ct);
clash.Ok.ShouldBeFalse();
clash.Error.ShouldNotBeNull().ShouldContain("SAPID 'SAP-1'");
var own = await svc.UpdateEquipmentAsync(second.EquipmentId, Input("m2-renamed", "MC2", sapId: "SAP-2"), second.RowVersion, ct);
own.Ok.ShouldBeTrue();
}
/// <summary>Blank identifiers are stored as NULL and never clash; values are stored trimmed.</summary>
[Fact]
public async Task Blank_identifiers_are_none_and_values_are_stored_trimmed()
{
var (svc, dbName) = Fresh();
var ct = TestContext.Current.CancellationToken;
(await svc.CreateEquipmentAsync(Input("m1", "MC1", zTag: " ", sapId: ""), ct)).Ok.ShouldBeTrue();
(await svc.CreateEquipmentAsync(Input("m2", "MC2", zTag: " ", sapId: ""), ct)).Ok.ShouldBeTrue();
(await svc.CreateEquipmentAsync(Input("m3", "MC3", zTag: " ZT-3 "), ct)).Ok.ShouldBeTrue();
using var db = UnsTreeTestDb.CreateNamed(dbName);
db.Equipment.Count(e => e.ZTag == null && e.SAPID == null).ShouldBe(2);
db.Equipment.Single(e => e.MachineCode == "MC3").ZTag.ShouldBe("ZT-3");
}
/// <summary>
/// Import names each clashing row — against the DB and against an earlier row of the same file — and still
/// imports the clean rows (the clash no longer fails the whole batch at SaveChanges).
/// </summary>
[Fact]
public async Task Import_names_clashing_rows_and_imports_the_rest()
{
var (svc, dbName) = Fresh();
var ct = TestContext.Current.CancellationToken;
(await svc.CreateEquipmentAsync(Input("m1", "MC1", zTag: "ZT-1"), ct)).Ok.ShouldBeTrue();
var result = await svc.ImportEquipmentAsync(
[
Input("m2", "MC2", zTag: "zt-1"),
Input("m3", "MC3", sapId: "SAP-3"),
Input("m4", "MC4", sapId: "SAP-3"),
Input("m5", "MC5", zTag: "ZT-5", sapId: "SAP-5"),
], ct);
result.Inserted.ShouldBe(2);
result.Errors.Count.ShouldBe(2);
result.Errors.ShouldContain(e => e.Contains("'MC2'") && e.Contains("ZTag"));
result.Errors.ShouldContain(e => e.Contains("'MC4'") && e.Contains("SAPID 'SAP-3'"));
using var db = UnsTreeTestDb.CreateNamed(dbName);
db.Equipment.Select(e => e.MachineCode).ToList().ShouldBe(["MC1", "MC3", "MC5"], ignoreOrder: true);
}
/// <summary>A VirtualTag naming a missing script is refused with the script named; positive control binds SCRIPT-1.</summary>
[Fact]
public async Task A_virtual_tag_naming_a_missing_script_is_refused()
{
var dbName = $"uns-vtscript-{Guid.NewGuid():N}";
UnsTreeTestDb.SeedNamed(dbName);
var svc = new UnsTreeService(UnsTreeTestDb.Factory(dbName));
var ct = TestContext.Current.CancellationToken;
var missing = await svc.CreateVirtualTagAsync(UnsTreeTestDb.SeededEquipmentId,
new VirtualTagInput("VT-X", "x", DataType: "Double", ScriptId: "SCRIPT-GONE", ChangeTriggered: true,
TimerIntervalMs: null, Historize: false, Enabled: true), ct);
missing.Ok.ShouldBeFalse();
missing.Error.ShouldNotBeNull().ShouldContain("SCRIPT-GONE");
var ok = await svc.CreateVirtualTagAsync(UnsTreeTestDb.SeededEquipmentId,
new VirtualTagInput("VT-Y", "y", DataType: "Double", ScriptId: "SCRIPT-1", ChangeTriggered: true,
TimerIntervalMs: null, Historize: false, Enabled: true), ct);
ok.Ok.ShouldBeTrue();
}
/// <summary>A scripted alarm naming a missing predicate script is refused.</summary>
[Fact]
public async Task A_scripted_alarm_naming_a_missing_predicate_script_is_refused()
{
var dbName = $"uns-sascript-{Guid.NewGuid():N}";
UnsTreeTestDb.SeedNamed(dbName);
var svc = new UnsTreeService(UnsTreeTestDb.Factory(dbName));
var result = await svc.CreateScriptedAlarmAsync(UnsTreeTestDb.SeededEquipmentId,
new ScriptedAlarmInput("SA-X", "x", "LimitAlarm", 700, "m", "SCRIPT-GONE", HistorizeToAveva: true, Retain: true, Enabled: true),
TestContext.Current.CancellationToken);
result.Ok.ShouldBeFalse();
result.Error.ShouldNotBeNull().ShouldContain("SCRIPT-GONE");
}
}
@@ -117,6 +117,13 @@ internal static class UnsTreeTestDb
TagConfig = "{}",
});
// The script the seeded virtual tag (and the scripted-alarm tests) name — FK_VirtualTag_Script /
// FK_ScriptedAlarm_Script (lmxopcua#1040) and the service's script-existence check require it.
db.Scripts.Add(new Script
{
ScriptId = "SCRIPT-1", Name = "seeded", SourceCode = "return 1;", SourceHash = new string('0', 64),
});
// One virtual tag on the seeded equipment → per-equipment virtual-tag ChildCount 1.
db.VirtualTags.Add(new VirtualTag
{
@@ -1,5 +1,6 @@
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using ZB.MOM.WW.OtOpcUa.Configuration;
namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.Harness;
@@ -23,7 +24,13 @@ public sealed class SqlServerTestDatabase : IDisposable
private readonly string _databaseName;
/// <summary>Creates and migrates the database.</summary>
public SqlServerTestDatabase()
public SqlServerTestDatabase() : this(null)
{
}
/// <summary>Creates the database migrated up to <paramref name="targetMigration"/> (latest when null).</summary>
/// <param name="targetMigration">A migration id or name to stop at — e.g. to seed rows a later migration refuses.</param>
public SqlServerTestDatabase(string? targetMigration)
{
var server = Environment.GetEnvironmentVariable("OTOPCUA_CONFIG_TEST_SERVER") ?? DefaultServer;
var saPassword = Environment.GetEnvironmentVariable("OTOPCUA_CONFIG_TEST_SA_PASSWORD") ?? DefaultSaPassword;
@@ -31,7 +38,8 @@ public sealed class SqlServerTestDatabase : IDisposable
ConnectionString =
$"Server={server};Database={_databaseName};User Id=sa;Password={saPassword};TrustServerCertificate=True;Encrypt=False;";
using var ctx = NewContext();
ctx.Database.Migrate();
if (targetMigration is null) ctx.Database.Migrate();
else ctx.GetService<Microsoft.EntityFrameworkCore.Migrations.IMigrator>().Migrate(targetMigration);
}
/// <summary>A new context on the database.</summary>
@@ -0,0 +1,190 @@
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.ControlPlane.Preflight;
using ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.Harness;
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Tests;
/// <summary>
/// lmxopcua#1013 / #1015 / #1021 / #1058: the read-only upgrade preflight against real SQL Server. A ConfigDb still
/// on an OLDER schema (pending migrations add tables and columns) is read through this build's model, and every row
/// a pending migration or the next deploy would refuse is named — with nothing written. Positive controls: a clean
/// database reports no blocking finding; a database that is not a v3 ConfigDb is refused, not guessed at.
/// </summary>
[Trait("Category", "SchemaCompliance")]
public sealed class UpgradePreflightSqlServerTests
{
/// <summary>Before the gRPC data-connection tables, the #998 RowVersion columns and the #1040/#1049 constraints.</summary>
private const string OldSchema = "20261022102459_EnableSnapshotIsolation";
private static readonly RoslynDeployScriptChecker Checker = new();
private static async Task ExecAsync(SqlServerTestDatabase sql, string text)
{
await using var conn = new SqlConnection(sql.ConnectionString);
await conn.OpenAsync(TestContext.Current.CancellationToken);
await using var cmd = conn.CreateCommand();
cmd.CommandText = text;
await cmd.ExecuteNonQueryAsync(TestContext.Current.CancellationToken);
}
private static async Task<long> RowCountAsync(SqlServerTestDatabase sql)
{
await using var conn = new SqlConnection(sql.ConnectionString);
await conn.OpenAsync(TestContext.Current.CancellationToken);
await using var cmd = conn.CreateCommand();
cmd.CommandText = "SELECT SUM(p.rows) FROM sys.partitions p JOIN sys.tables t ON t.object_id = p.object_id WHERE p.index_id IN (0, 1)";
return Convert.ToInt64(await cmd.ExecuteScalarAsync(TestContext.Current.CancellationToken));
}
private static Equipment NewEquipment(string lineId, string name, string? zTag)
{
var uuid = Guid.NewGuid();
return new Equipment
{
EquipmentId = "EQ-" + uuid.ToString("N")[..12], EquipmentUuid = uuid, UnsLineId = lineId, Name = name,
MachineCode = "mc-" + uuid.ToString("N"), ZTag = zTag,
};
}
/// <summary>
/// Every class of finding on one old-schema database: the migration pre-checks (#1021), the new VirtualTag /
/// script-reference / ZTag gate rules (#1015), the Sql named-query rule (#1058) and the script compile gate (#1013).
/// </summary>
[Fact]
public async Task An_old_schema_database_is_read_and_every_blocking_row_is_named_without_writing()
{
var ct = TestContext.Current.CancellationToken;
using var sql = new SqlServerTestDatabase(OldSchema);
// Rows the old schema allows and the new one refuses. ServerCluster / NodeAcl by SQL: this build's model has
// columns (RowVersion) the old tables do not.
await ExecAsync(sql, """
INSERT ServerCluster (ClusterId, Name, Enterprise, Site, NodeCount, RedundancyMode, Enabled, CreatedBy)
VALUES ('C1', 'Cluster one', 'zb', 's1', 1, 'None', 1, 't');
INSERT NodeAcl (NodeAclId, ClusterId, Principal, ScopeKind, ScopeId, PermissionFlags)
VALUES ('acl-1', 'C1', 'ops', 'Cluster', NULL, 1), ('acl-2', 'C1', 'ops', 'Cluster', NULL, 1);
INSERT ExternalIdReservation (Kind, Value, EquipmentUuid, ClusterId, FirstPublishedBy)
VALUES ('ZTag', 'ZT-OLD', NEWID(), 'C1', 't');
""");
await using (var db = sql.NewContext())
{
db.UnsAreas.Add(new UnsArea { UnsAreaId = "AREA-1", ClusterId = "C1", Name = "area" });
db.UnsLines.Add(new UnsLine { UnsLineId = "LINE-1", UnsAreaId = "AREA-1", Name = "line" });
var eq1 = NewEquipment("LINE-1", "press1", "ZT-1");
db.Equipment.AddRange(eq1, NewEquipment("LINE-1", "press2", "zt-1"));
db.Scripts.Add(new Script { ScriptId = "SC-ok", Name = "ok", SourceCode = "return 1;", SourceHash = new string('a', 64) });
db.Scripts.Add(new Script
{
ScriptId = "SC-file", Name = "reads a file", SourceHash = new string('b', 64),
SourceCode = "return System.IO.File.ReadAllText(\"c:/x\");",
});
db.VirtualTags.AddRange(
new VirtualTag { VirtualTagId = "VT-dangling", EquipmentId = eq1.EquipmentId, Name = "dangling", DataType = "Int32", ScriptId = "SC-gone" },
new VirtualTag { VirtualTagId = "VT-slash", EquipmentId = eq1.EquipmentId, Name = "a/b", DataType = "Int32", ScriptId = "SC-ok" },
new VirtualTag { VirtualTagId = "VT-file", EquipmentId = eq1.EquipmentId, Name = "file", DataType = "String", ScriptId = "SC-file" });
db.DriverInstances.Add(new DriverInstance
{
DriverInstanceId = "DRV-odbc", ClusterId = "C1", Name = "odbc", DriverType = "Sql",
DriverConfig = """{"provider":"Odbc","queries":{"line":{"sql":"SELECT v FROM t WHERE v ILIKE 'a%'"}}}""",
});
await db.SaveChangesAsync(ct);
}
var before = await RowCountAsync(sql);
var report = await UpgradePreflight.RunAsync(sql.ConnectionString, Checker, ct: ct);
report.PendingMigrations.ShouldContain(m => m.EndsWith("_ConfigurationGapsIndexesAndRowVersions", StringComparison.Ordinal));
report.PendingMigrations.ShouldContain(m => m.EndsWith("_ScriptForeignKeysAndExternalIdUniqueness", StringComparison.Ordinal));
report.Findings.ShouldContain(f => f.Check == "schema" && f.Code == "ReadAsEmpty" && f.Message.Contains("DataConnection"));
void Blocking(string check, string code, string text) =>
report.Findings.ShouldContain(f => f.Check == check && f.Code == code && f.Severity == PreflightSeverity.Blocking && f.Message.Contains(text),
$"expected {check}/{code} naming '{text}'");
// #1021: the migrations' own pre-checks, row-named.
Blocking("migration:ConfigurationGapsIndexesAndRowVersions", "DuplicateNodeAcl", "acl-1, acl-2");
Blocking("migration:ScriptForeignKeysAndExternalIdUniqueness", "VirtualTagScriptDangling", "VT-dangling");
Blocking("migration:ScriptForeignKeysAndExternalIdUniqueness", "DuplicateZTag", "ZT-1");
Blocking("migration:ScriptForeignKeysAndExternalIdUniqueness", "ExternalIdReservationRows", "ZT-OLD");
// #1015: the new deploy-gate rules.
Blocking("deploy-gate", "VirtualTagScriptNotFound", "VT-dangling");
Blocking("deploy-gate", "VirtualTagNameInvalid", "VT-slash");
Blocking("deploy-gate", "BadDuplicateExternalIdentifier", "ZT-1");
// #1058: an Odbc named query that does not parse as T-SQL.
Blocking("deploy-gate", "SqlNamedQueryInvalid", "DRV-odbc");
// #1013: the sandbox analyzer over the scripts in use.
Blocking("script-gate", "ScriptCompileFailed", "SC-file");
report.HasBlocking.ShouldBeTrue();
// Read-only: nothing written, no migration applied.
(await RowCountAsync(sql)).ShouldBe(before);
await using var verify = sql.NewContext();
verify.Database.GetAppliedMigrations().Last().ShouldBe(OldSchema);
}
/// <summary>Positive control: a clean, current database has no blocking finding; an unused broken script is a Warning only.</summary>
[Fact]
public async Task A_clean_current_database_has_no_blocking_finding()
{
var ct = TestContext.Current.CancellationToken;
using var sql = new SqlServerTestDatabase();
await using (var db = sql.NewContext())
{
db.Scripts.Add(new Script { ScriptId = "SC-unused", Name = "unused", SourceHash = new string('c', 64), SourceCode = "this is not C#" });
await db.SaveChangesAsync(ct);
}
var report = await UpgradePreflight.RunAsync(sql.ConnectionString, Checker, ct: ct);
report.PendingMigrations.ShouldBeEmpty();
report.HasBlocking.ShouldBeFalse(string.Join("\n", report.Findings.Select(f => $"{f.Check}/{f.Code}: {f.Message}")));
report.Findings.ShouldContain(f => f.Check == "deploy-gate" && f.Code == "Clean");
report.Findings.ShouldContain(f => f.Code == "UnusedScriptDoesNotCompile" && f.Severity == PreflightSeverity.Warning && f.Subject == "SC-unused");
}
/// <summary>Positive control for the migration pre-checks: an old schema with clean data reports each pending check Clean.</summary>
[Fact]
public async Task An_old_schema_database_with_clean_data_reports_the_migrations_will_apply()
{
using var sql = new SqlServerTestDatabase(OldSchema);
var report = await UpgradePreflight.RunAsync(sql.ConnectionString, Checker, ct: TestContext.Current.CancellationToken);
report.HasBlocking.ShouldBeFalse(string.Join("\n", report.Findings.Select(f => $"{f.Check}/{f.Code}: {f.Message}")));
report.Findings.Count(f => f.Check.StartsWith("migration:", StringComparison.Ordinal) && f.Code == "Clean").ShouldBe(2);
}
/// <summary>
/// A NULL <c>Script.ScriptId</c> (legal in the old schema) is named by the migration pre-check, and the snapshot
/// this build cannot read is reported as Blocking instead of crashing the tool.
/// </summary>
[Fact]
public async Task A_null_script_id_is_named_and_the_unreadable_snapshot_is_reported()
{
using var sql = new SqlServerTestDatabase(OldSchema);
await ExecAsync(sql, "INSERT Script (ScriptId, Name, SourceCode, SourceHash, Language) VALUES (NULL, 'orphan', 'return 1;', 'h', 'CSharp')");
var report = await UpgradePreflight.RunAsync(sql.ConnectionString, Checker, ct: TestContext.Current.CancellationToken);
report.Findings.ShouldContain(f => f.Code == "ScriptIdNull" && f.Severity == PreflightSeverity.Blocking && f.Message.Contains("orphan"));
report.Findings.ShouldContain(f => f.Code == "SnapshotUnreadable" && f.Severity == PreflightSeverity.Blocking);
report.HasBlocking.ShouldBeTrue();
}
/// <summary>A database without the v3 migration history is refused, never checked against the wrong model.</summary>
[Fact]
public async Task A_database_that_is_not_a_v3_ConfigDb_is_refused()
{
using var sql = new SqlServerTestDatabase("0"); // created, nothing applied
var ex = await Should.ThrowAsync<PreflightUnsupportedException>(() =>
UpgradePreflight.RunAsync(sql.ConnectionString, Checker, ct: TestContext.Current.CancellationToken));
ex.Message.ShouldContain("is not a v3 OtOpcUa ConfigDb");
}
}