Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| cc33b063fa | |||
| 2e6645ef92 | |||
| 13e9a26d39 | |||
| 7a41d9edea | |||
| 54367e7408 | |||
| 256b5c1bfc |
+5
-3
@@ -88,9 +88,11 @@ of items per round trip while preserving MXAccess parity per entry.
|
|||||||
`was_successful`, `was_cached`, `value`, `quality`, `source_timestamp`,
|
`was_successful`, `was_cached`, `value`, `quality`, `source_timestamp`,
|
||||||
`repeated MxStatusProxy statuses`, and `error_message`. MXAccess has no
|
`repeated MxStatusProxy statuses`, and `error_message`. MXAccess has no
|
||||||
synchronous `Read`, so `ReadBulk` is dual-mode per entry: when a tag is
|
synchronous `Read`, so `ReadBulk` is dual-mode per entry: when a tag is
|
||||||
already advised in the session the worker returns the cached
|
already advised in the session and has a cached value the worker returns
|
||||||
`OnDataChange` payload without touching the subscription
|
the cached `OnDataChange` payload without touching the subscription
|
||||||
(`was_cached = true`); otherwise the worker takes a full
|
(`was_cached = true`); a tag the session has advised without a cached
|
||||||
|
value yet is read by waiting on that existing subscription; otherwise the
|
||||||
|
worker takes a full
|
||||||
`AddItem` + `Advise` + wait-for-first-`OnDataChange` + `UnAdvise` +
|
`AddItem` + `Advise` + wait-for-first-`OnDataChange` + `UnAdvise` +
|
||||||
`RemoveItem` snapshot lifecycle and returns the result
|
`RemoveItem` snapshot lifecycle and returns the result
|
||||||
(`was_cached = false`). The asymmetry that `BulkReadResult` has no
|
(`was_cached = false`). The asymmetry that `BulkReadResult` has no
|
||||||
|
|||||||
+25
-6
@@ -532,7 +532,23 @@ choices were considered:
|
|||||||
(`was_cached = true`). Otherwise it takes the full `AddItem + Advise +
|
(`was_cached = true`). Otherwise it takes the full `AddItem + Advise +
|
||||||
wait-for-first-OnDataChange + UnAdvise + RemoveItem` lifecycle itself
|
wait-for-first-OnDataChange + UnAdvise + RemoveItem` lifecycle itself
|
||||||
(`was_cached = false`) and leaves the session exactly as it was before
|
(`was_cached = false`) and leaves the session exactly as it was before
|
||||||
the call. The cache lives on a per-session `MxAccessValueCache`,
|
the call. "Exactly as it was" is enforced by ownership, not by
|
||||||
|
symmetry: teardown undoes only the `AddItem` and `Advise` calls the read
|
||||||
|
itself made (#238). An advised tag whose first `OnDataChange` is not
|
||||||
|
cached yet is read by waiting on the caller's own subscription, with no
|
||||||
|
`AddItem` at all. Any other tag gets a snapshot `AddItem`. The installed
|
||||||
|
MXAccess on windev hands a re-added address a new handle (observed
|
||||||
|
2026-12-01), so a caller's added-but-not-advised item is not touched and
|
||||||
|
the snapshot item is torn down on its own. The worker does not rely on
|
||||||
|
that: when the snapshot `AddItem` returns a handle the registry already
|
||||||
|
tracks, the handle is the caller's, and a symmetric teardown would
|
||||||
|
unadvise and remove the caller's item — a subscription that delivered
|
||||||
|
one value and went silent. Such a handle is advised for the read only
|
||||||
|
if nothing advises it yet, unadvised afterwards (back to the caller's
|
||||||
|
added-not-advised state), and never removed; at worst one extra
|
||||||
|
`AddItem` reference outlives the read until the caller removes the item
|
||||||
|
or unregisters, which is preferable to deleting a live subscription.
|
||||||
|
The cache lives on a per-session `MxAccessValueCache`,
|
||||||
populated by `MxAccessBaseEventSink` on every `OnDataChange` after the
|
populated by `MxAccessBaseEventSink` on every `OnDataChange` after the
|
||||||
event clears the outbound queue.
|
event clears the outbound queue.
|
||||||
|
|
||||||
@@ -543,12 +559,15 @@ choices were considered:
|
|||||||
|
|
||||||
The chosen behavior matches what callers actually want from "current
|
The chosen behavior matches what callers actually want from "current
|
||||||
value" — a free read of an already-streaming tag, and a one-shot snapshot
|
value" — a free read of an already-streaming tag, and a one-shot snapshot
|
||||||
otherwise — and never disturbs subscriptions the caller did not create.
|
otherwise — and never disturbs subscriptions the caller already holds.
|
||||||
The decision intentionally does NOT synthesize an `OnDataChange` event
|
The decision intentionally does NOT synthesize an `OnDataChange` event
|
||||||
from the snapshot path: the snapshot value reaches the caller through
|
from the snapshot path: the worker adds no event of its own for the
|
||||||
`ReadBulk`'s reply payload only, not through the event stream. This
|
snapshot value, which reaches the caller through `ReadBulk`'s reply
|
||||||
preserves the "Don't synthesize events" rule that scopes the rest of the
|
payload. The native `OnDataChange` MXAccess raises for a handle the read
|
||||||
worker.
|
advised still flows through the event sink like any other (under the
|
||||||
|
snapshot item handle, or under the caller's own handle in the fallback
|
||||||
|
above where `AddItem` returned it). This preserves the "Don't
|
||||||
|
synthesize events" rule that scopes the rest of the worker.
|
||||||
|
|
||||||
`ReadBulk`'s wait loop pumps Windows messages on the worker STA
|
`ReadBulk`'s wait loop pumps Windows messages on the worker STA
|
||||||
(`StaRuntime.PumpPendingMessages`) on every poll iteration so the inbound
|
(`StaRuntime.PumpPendingMessages`) on every poll iteration so the inbound
|
||||||
|
|||||||
@@ -355,10 +355,21 @@ timeout.
|
|||||||
|
|
||||||
`ReadBulk` runs its snapshot lifecycle in phases so the STA is held for at most
|
`ReadBulk` runs its snapshot lifecycle in phases so the STA is held for at most
|
||||||
one `timeout_ms` per command, not one per tag: (1) every tag is validated and
|
one `timeout_ms` per command, not one per tag: (1) every tag is validated and
|
||||||
probed against the cached-and-advised fast path; (2) every remaining tag is
|
probed against the registry and the cached-and-advised fast path; (2) every
|
||||||
added and advised; (3) one wait with a shared deadline collects the first
|
remaining tag gets an advised handle — a tag the caller has advised keeps the
|
||||||
`OnDataChange` per snapshot handle and returns as soon as all have delivered;
|
caller's item handle and its existing subscription, any other tag gets the
|
||||||
(4) every snapshot handle is unadvised and removed, best-effort. Per-tag
|
read's own `AddItem`, and a handle is advised only when nothing advises it
|
||||||
|
yet; (3) one wait with a shared deadline collects the first `OnDataChange` per
|
||||||
|
handle and returns as soon as all have delivered; (4) teardown, best-effort
|
||||||
|
and ownership-scoped, unadvises only the advices phase 2 created and removes
|
||||||
|
only the items phase 2 added. The caller's items are therefore never removed
|
||||||
|
and the caller's subscriptions never unadvised (#238). A snapshot `AddItem`
|
||||||
|
that returns a handle the registry already tracks is the caller's item: it is
|
||||||
|
advised for the read only if nothing advises it yet, unadvised afterwards,
|
||||||
|
and never removed. (The windev MXAccess install returns a new handle for a
|
||||||
|
re-added address, so in practice an added-only caller item is not touched;
|
||||||
|
the ownership check covers an install or address spelling that resolves to
|
||||||
|
the caller's handle.) Per-tag
|
||||||
results are unchanged: request order, the blank-address failure, the cached
|
results are unchanged: request order, the blank-address failure, the cached
|
||||||
result, an `AddItem` failure (item handle 0) or `Advise` failure (its own item
|
result, an `AddItem` failure (item handle 0) or `Advise` failure (its own item
|
||||||
handle) failing only that tag, and the `ReadBulk timed out after <n> ms waiting
|
handle) failing only that tag, and the `ReadBulk timed out after <n> ms waiting
|
||||||
@@ -737,7 +748,12 @@ the handle they receive when the registry does not already track it. An
|
|||||||
`Unregister` ran is dispatched after the eviction and recreates the entry;
|
`Unregister` ran is dispatched after the eviction and recreates the entry;
|
||||||
when MXAccess later reuses that item id, `ReadBulk`'s cached path would
|
when MXAccess later reuses that item id, `ReadBulk`'s cached path would
|
||||||
otherwise serve the stale value as `was_cached = true`. A handle the
|
otherwise serve the stale value as `was_cached = true`. A handle the
|
||||||
registry still tracks belongs to a live item, so its entries are kept. Failed advice and cleanup calls
|
registry still tracks belongs to a live item, so its entries are kept.
|
||||||
|
Successful `UnAdvise` drops the handle pair's `MxAccessValueCache` entry too:
|
||||||
|
the item stays added, but its value stops updating, so without the eviction a
|
||||||
|
later re-advise would let `ReadBulk`'s cached path answer with the previous
|
||||||
|
advice's value (including one a `ReadBulk`'s temporary advice on a caller's
|
||||||
|
handle captured) before the new advice's first `OnDataChange` lands. Failed advice and cleanup calls
|
||||||
leave registry state unchanged so diagnostics continue to reflect the last
|
leave registry state unchanged so diagnostics continue to reflect the last
|
||||||
successful MXAccess-owned state transition.
|
successful MXAccess-owned state transition.
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,136 @@
|
|||||||
|
# 2026-11-22: PROD install of MxAccessGateway `e74918cc` on wonder-par-vp03 / wonder-par-vp04 (site-par)
|
||||||
|
|
||||||
|
Owner: "keep checking par-vp04 every minute. when its ready then execute the par server updates (both)". This follows the
|
||||||
|
2026-11-20 app-box install ([`2026-11-20-prod-e74918cc.md`](2026-11-20-prod-e74918cc.md)); the build, stage pack and env
|
||||||
|
are the same. Driven from the Mac with the `winrm` CLI (profiles `parvp03`/`parvp04`, NAM\adm_dohertj2). No firewall changes, and no
|
||||||
|
ScadaBridge service was touched.
|
||||||
|
|
||||||
|
## Gate: WinPlatform / MXAccess on the PAR boxes
|
||||||
|
|
||||||
|
Checked over SMB only.
|
||||||
|
- **par-vp03** already had `LmxProxy.dll` at 12:0xZ: 318,496 bytes, sha256 `bd75a2fd…7ef15459`, the same file as vp03. Its
|
||||||
|
`ArchestrA\Framework\Bin` held the full platform runtime (102 entries).
|
||||||
|
- **par-vp04** started with 49 entries and no MXAccess. It was polled every minute. `LmxProxy.dll` appeared at about
|
||||||
|
12:19Z (101 entries), and the folder was stable at 102 entries from 12:21Z. The poller declared it ready at 12:23:45Z
|
||||||
|
with the same sha256 `bd75a2fde222…`.
|
||||||
|
|
||||||
|
## Stage fixes (by SMB, before anything ran)
|
||||||
|
|
||||||
|
- **PATCH 4 (`Install-MxGatewayService.ps1`, nssm status probe under `Continue`; mxaccessgw#234):** both PAR boxes still had
|
||||||
|
the PATCH 3 copy (`11a23e9f…`). The patched copy (`fb6f0f47…`) was pushed, the old one kept as
|
||||||
|
`Install-MxGatewayService.ps1.patch3`, and the `SHA256SUMS.txt` line updated on both boxes.
|
||||||
|
- **Value files:** `_values\mxgw-<box>\` on each box held three files, all from the Keychain, never printed and never on argv:
|
||||||
|
- `MxGateway__ApiKeyPepper.txt`: `zb-prod/mxgw-pepper`, the same as vp03/vp04;
|
||||||
|
- `MxGateway__Galaxy__ConnectionString.txt`:
|
||||||
|
`Server=wonder-app-vp03.zmr.zimmer.com;Database=ZB;Integrated Security=True;TrustServerCertificate=True;Encrypt=False;`;
|
||||||
|
- the LDAP seed file `nam-ldap-mxgw.txt`.
|
||||||
|
- **API-key store:** vp03's gateway could not be stopped for a clean copy, because site-app runs on it. So vp04's
|
||||||
|
`gateway-auth.db` (+wal/shm) was pulled live; it is vp03's store as copied on 2026-11-20. Checked on the Mac:
|
||||||
|
- consolidated (the WAL held 0 frames);
|
||||||
|
- `integrity_check` ok;
|
||||||
|
- one key, `scadabridge-prod`, scopes `events:read invoke:read invoke:write metadata:read session:close session:open`,
|
||||||
|
not revoked;
|
||||||
|
- single-file sha256 `3c5705d7…43bffe55`.
|
||||||
|
|
||||||
|
## Install (UTC)
|
||||||
|
|
||||||
|
| Step | par-vp03 | par-vp04 |
|
||||||
|
|---|---|---|
|
||||||
|
| dry | 12:06:28 DONE (LmxProxy `6000.0045.2657.1` / `BD75A2FDE222`, 38 env entries, Server and Worker `0.1.2+e74918cc`, one benign WorkerDir WARN); `dry\` removed | 12:23:54 DONE, same output; `dry\` removed |
|
||||||
|
| real | 12:24:00 DONE; KEK generated `AA55B221`; service `MxAccessGw` Stopped, Automatic, LocalSystem | 12:24:09 DONE; KEK `01F9EE28`; Stopped, Automatic, LocalSystem |
|
||||||
|
| seed | 12:24:21 `nam-ldap-svc-password` → `data\secrets.db`, `readback-match=True`, value file removed | 12:24:26 same |
|
||||||
|
| key store | 12:24:25 `data\gateway-auth.db` = `3C5705D78769` (no earlier store existed) | 12:24:30 same |
|
||||||
|
| start | 12:24:35; Running; listening on 5120 and 5130; stderr empty | 12:26:11; same |
|
||||||
|
| `/health/ready` | **503**: auth-store Healthy, worker-executable Healthy, **galaxy-sql Unhealthy** | **503**, same |
|
||||||
|
|
||||||
|
**galaxy-sql: expected, same cause as vp04 (scadaproj#60).** The log shows
|
||||||
|
`Login failed for user 'ZMR\WONDER-PAR-VP03$'` / `'ZMR\WONDER-PAR-VP04$'`, `Error Number:4060`. The machine accounts reach
|
||||||
|
vp03's SQL Server but have no access to `ZB`. The gateway retries every 30 s and turns ready without a restart once the DBA
|
||||||
|
grants it (T-SQL on #60). MXAccess sessions do not depend on it.
|
||||||
|
|
||||||
|
## Consumer: ScadaBridge site-par
|
||||||
|
|
||||||
|
The site-par node on par-vp03 logged `[MxGateway] Reconnected successfully on "Primary" endpoint` → `Entering Connected
|
||||||
|
state` at **12:24:56Z**, 20 s after par-vp03's gateway started. There was no ScadaBridge change; the copied store makes the
|
||||||
|
existing `scadabridge-prod` token valid. (A no-op `deploy artifacts --site-id 1` at 12:29Z applied nothing; it was not needed.)
|
||||||
|
|
||||||
|
## Unrelated event in the same window: app-box services restarted at 12:31Z
|
||||||
|
|
||||||
|
Every ScadaBridge and mxgw service on **wonder-app-vp03 and vp04** (centrals, site-app nodes, mxgw) received a process
|
||||||
|
termination ("CLR termination hook") at 12:31:03–12:31:43Z. They came back at about 12:34:30Z. The central pair re-formed
|
||||||
|
(vp03 active), and all health endpoints were 200 by 12:35:58Z. Nothing in this run touched those boxes (SMB reads only). The
|
||||||
|
pattern looks like an external restart or reboot of both app boxes. The cause was not investigated: that would need
|
||||||
|
remote diagnostics, which the deploy-only WinRM scope does not cover.
|
||||||
|
|
||||||
|
Separately, at 10:51Z vp03 stalled for about 47.6 s ("heartbeat delayed 47592 ms", which looks like a VM freeze). vp04
|
||||||
|
downed it under `leader-auto-down`, and vp03 restarted with exit 75 as designed.
|
||||||
|
|
||||||
|
After the restart, site-app's `MxGateway` connection was not rebuilt. This is by design: on boot the site builds only the
|
||||||
|
connections a deployed instance references, and PROD has no instances yet. `deploy artifacts --site-id 2` at 12:43:13Z
|
||||||
|
rebuilt it: **Connected at 12:43:17Z**.
|
||||||
|
|
||||||
|
## Clean-up
|
||||||
|
|
||||||
|
- `_values\mxgw-par*`, `_values\mxgw-store` and the seed file were deleted on both boxes (verified; only the empty `_values\seed` folder is left).
|
||||||
|
- The local value files and key-store copies on the Mac were deleted.
|
||||||
|
|
||||||
|
## Open
|
||||||
|
|
||||||
|
- **scadaproj#60:** `ZB` read access for `ZMR\WONDER-APP-VP04$`, `ZMR\WONDER-PAR-VP03$` and `ZMR\WONDER-PAR-VP04$`.
|
||||||
|
- **Alarms are off on all four gateways** until the owner picks an area.
|
||||||
|
- **mxaccessgw#234:** the repo copy of the install script still needs PATCH 4.
|
||||||
|
|
||||||
|
## Rollback
|
||||||
|
|
||||||
|
On each PAR box: `nssm stop MxAccessGw; nssm remove MxAccessGw confirm`, then delete `E:\ApiInstall\MxAccessGateway` and
|
||||||
|
`C:\ProgramData\ZB\kek\mxgateway.kek`. site-par's connection then goes back to retrying. To serve it from the app-box
|
||||||
|
gateways instead: `data-connection update --id 1` with `10.220.153.205:5120` / `10.220.153.210:5120`, then
|
||||||
|
`deploy artifacts --site-id 1`.
|
||||||
|
|
||||||
|
## Later 2026-11-22: alarms on the PAR gateways; all four PROD gateways moved to a SQL login for Galaxy
|
||||||
|
|
||||||
|
The owner asked for two changes:
|
||||||
|
- "make sure the par servers mxaccessgw's are configured to listen to alarms for NAM / NewJersey area (and subareas)";
|
||||||
|
- "swap all mxaccesgw on all 4 prod to use the galaxy_prod_sql login".
|
||||||
|
|
||||||
|
Each change was made in the service's `AppEnvironmentExtra` registry value through WinRM. Before the edit, each box
|
||||||
|
kept a backup copy of the old value in the same key:
|
||||||
|
- `AppEnvironmentExtra.bak-20261122-prealarms` (par-vp04 only);
|
||||||
|
- `AppEnvironmentExtra.bak-20261122-pregalaxysql` (all four).
|
||||||
|
|
||||||
|
**Alarms (PAR):**
|
||||||
|
- `MxGateway__Alarms__Enabled=true`.
|
||||||
|
- `MxGateway__Alarms__SubscriptionExpression=\\<own box>\Galaxy!NewJersey`, i.e. `\\WONDER-PAR-VP03\…` and
|
||||||
|
`\\WONDER-PAR-VP04\…`. Each box subscribes on its own name, which is the QA pattern (`\\wonder-app-vq03\Galaxy!NAM`).
|
||||||
|
- Galaxy facts: `NewJersey` (gobject 6614) is the area under `NAM`. Its sub-areas are `CVDAisle_1` (6762, the nine
|
||||||
|
reactors) and `Gas_Service` (tag `Gas_Service`, contained name `Gas_Service_1`). All of them are hosted by
|
||||||
|
`AppEnginePAR` on `WinPlatformPAR01`, with a redundant engine on `WinPlatformPAR02`.
|
||||||
|
- Alarm references carry the sub-area tag name, e.g. `Galaxy!CVDAisle_1.Z28063.HeartbeatTimeoutAlarm`.
|
||||||
|
- par-vp04 was done at 16:54Z. Its first restart still had the old Windows-auth login, so the monitor came up on the
|
||||||
|
alarm manager but degraded: Repository discovery failed with 4060. par-vp03 was done at 17:01Z, together with the SQL
|
||||||
|
swap.
|
||||||
|
- vp03/vp04 were already set to `\\WONDER-APP-VP03\Galaxy!ControlSystem` by someone outside this run. That was left
|
||||||
|
unchanged.
|
||||||
|
|
||||||
|
**Galaxy SQL login (all four):**
|
||||||
|
- `MxGateway__Galaxy__ConnectionString` now uses the SQL login `wwpdgdbro` (`db_datareader` on `ZB`,
|
||||||
|
WONDER-APP-VP03; from the owner's `GALAXY_PROD_SQL_*`):
|
||||||
|
`Server=wonder-app-vp03.zmr.zimmer.com;Database=ZB;User Id=wwpdgdbro;Password=***;TrustServerCertificate=True;Encrypt=False;`.
|
||||||
|
The string was staged by SMB to `_values\galaxy-sql.txt`, read on the box and deleted there. The local copy was
|
||||||
|
deleted too, and the string was never printed.
|
||||||
|
- Previously: vp03 used `Data Source=localhost` with Integrated Security; the other three used Integrated Security,
|
||||||
|
i.e. the machine accounts, which `ZB` refused (scadaproj#60).
|
||||||
|
- Order: par-vp04 17:00:22Z, par-vp03 17:00:57Z, vp04 17:01:44Z, vp03 17:02:09Z. Each box restarted once, and each
|
||||||
|
was ready (200) within 3 s of the service coming up.
|
||||||
|
|
||||||
|
**Result:**
|
||||||
|
- `/health/ready` is **200 on all four for the first time**, with galaxy-sql Healthy.
|
||||||
|
- Alarm discovery `watchList=5659` on all four.
|
||||||
|
- par-vp03/04 feeds: `ALARM_PROVIDER_MODE_ALARMMGR`, not degraded, 7 active alarms, all in `CVDAisle_1`. Those are
|
||||||
|
the `HeartbeatTimeoutAlarm` of Z28061, Z28063–Z28067 and Z28069.
|
||||||
|
- ScadaBridge site-par mirrors exactly those 7 through each instance's `ReactorAlarms` source. Each alarm appears on
|
||||||
|
its own instance, and every instance still reads 244/244 Good.
|
||||||
|
- **This makes the scadaproj#60 DBA grant unnecessary** for the gateways.
|
||||||
|
|
||||||
|
**Rollback (per box):** copy the `.bak-20261122-pregalaxysql` value back to `AppEnvironmentExtra`, then
|
||||||
|
`Restart-Service MxAccessGw`.
|
||||||
+11
-4
@@ -570,11 +570,18 @@ returns one result per requested entry — per-entry failures populate
|
|||||||
last cached `OnDataChange` payload when the requested tag is already
|
last cached `OnDataChange` payload when the requested tag is already
|
||||||
advised (`was_cached = true`, no subscription side-effects), or by
|
advised (`was_cached = true`, no subscription side-effects), or by
|
||||||
taking a full `AddItem` + `Advise` + wait-for-first-OnDataChange +
|
taking a full `AddItem` + `Advise` + wait-for-first-OnDataChange +
|
||||||
`UnAdvise` + `RemoveItem` snapshot lifecycle when no live subscription
|
`UnAdvise` + `RemoveItem` snapshot lifecycle otherwise
|
||||||
exists (`was_cached = false`). `timeout_ms` is one shared deadline for
|
(`was_cached = false`). A tag the session has advised whose first
|
||||||
|
`OnDataChange` is not cached yet is read by waiting on the caller's own
|
||||||
|
subscription, with no COM call (`was_cached = false`). Teardown only
|
||||||
|
undoes the `AddItem` and `Advise` calls the read itself made: if a
|
||||||
|
snapshot `AddItem` returns a handle the session already holds, that
|
||||||
|
handle is never removed, and is unadvised only if the read advised it,
|
||||||
|
so a seed read issued right after subscribing cannot cancel the
|
||||||
|
subscription (#238). `timeout_ms` is one shared deadline for
|
||||||
the whole command, not a per-tag budget: the worker adds and advises
|
the whole command, not a per-tag budget: the worker adds and advises
|
||||||
every uncached tag first, waits once for all of them, then tears them
|
every tag that needs it first, waits once for all of them, then tears
|
||||||
all down, so the STA is held for at most one `timeout_ms` (plus the
|
down its own snapshot state, so the STA is held for at most one `timeout_ms` (plus the
|
||||||
add/advise and teardown COM calls, during which it pumps every 16 tags).
|
add/advise and teardown COM calls, during which it pumps every 16 tags).
|
||||||
Each tag that has not delivered by the deadline surfaces its own
|
Each tag that has not delivered by the deadline surfaces its own
|
||||||
`was_successful = false` timeout rather than throwing. Duplicate
|
`was_successful = false` timeout rather than throwing. Duplicate
|
||||||
|
|||||||
@@ -647,6 +647,200 @@ public sealed class WorkerLiveMxAccessSmokeTests(ITestOutputHelper output)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Issue #238: a <c>ReadBulk</c> of a tag the client already holds must not tear down the
|
||||||
|
/// client's item or subscription. Step 1 reads an added-but-not-advised item, after which
|
||||||
|
/// the client must still be able to advise its own handle. Step 2 reads the tag right
|
||||||
|
/// after that advise — the window a subscribe-then-seed-read client hits, where the first
|
||||||
|
/// OnDataChange may not be cached yet — and must read through the client's own handle
|
||||||
|
/// rather than a snapshot item; the test then proves the subscription still delivers by
|
||||||
|
/// writing a fresh value and waiting for its OnDataChange. The step 1 snapshot handle is
|
||||||
|
/// logged: on the windev install (2026-12-01) MXAccess returned a new handle for the
|
||||||
|
/// re-added address, so the pre-fix worker's teardown never reached the client's item
|
||||||
|
/// there; only the step 2 handle assertion distinguishes the fixed worker.
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
[LiveMxAccessFact]
|
||||||
|
public async Task GatewaySession_WithLiveWorker_ReadBulkOfClientHeldTag_LeavesTheClientSubscriptionLive()
|
||||||
|
{
|
||||||
|
string workerExecutablePath = IntegrationTestEnvironment.ResolveLiveMxAccessWorkerExecutablePath();
|
||||||
|
Assert.True(
|
||||||
|
File.Exists(workerExecutablePath),
|
||||||
|
$"Live MXAccess worker executable was not found at {workerExecutablePath}. Build the worker or set {IntegrationTestEnvironment.LiveMxAccessWorkerExecutableVariableName}.");
|
||||||
|
|
||||||
|
TestWorkerProcessFactory processFactory = new(output);
|
||||||
|
await using GatewayServiceFixture fixture = new(workerExecutablePath, processFactory, output);
|
||||||
|
using RecordingServerStreamWriter<MxEvent> eventWriter = new();
|
||||||
|
|
||||||
|
string? sessionId = null;
|
||||||
|
Task? streamTask = null;
|
||||||
|
int serverHandle = 0;
|
||||||
|
int itemHandle = 0;
|
||||||
|
MxValue? originalValue = null;
|
||||||
|
bool restored = false;
|
||||||
|
using CancellationTokenSource streamCancellation = new();
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
OpenSessionReply openReply = await fixture.Service.OpenSession(
|
||||||
|
new OpenSessionRequest
|
||||||
|
{
|
||||||
|
ClientSessionName = "live-mxaccess-readbulk-held",
|
||||||
|
ClientCorrelationId = "live-open-readbulk-held",
|
||||||
|
CommandTimeout = Duration.FromTimeSpan(CommandTimeout),
|
||||||
|
},
|
||||||
|
new TestServerCallContext()).ConfigureAwait(false);
|
||||||
|
|
||||||
|
sessionId = openReply.SessionId;
|
||||||
|
Assert.Equal(ProtocolStatusCode.Ok, openReply.ProtocolStatus.Code);
|
||||||
|
|
||||||
|
streamTask = fixture.Service.StreamEvents(
|
||||||
|
new StreamEventsRequest { SessionId = sessionId },
|
||||||
|
eventWriter,
|
||||||
|
new TestServerCallContext(streamCancellation.Token));
|
||||||
|
|
||||||
|
MxCommandReply registerReply = await fixture.Service.Invoke(
|
||||||
|
CreateRegisterRequest(sessionId),
|
||||||
|
new TestServerCallContext()).ConfigureAwait(false);
|
||||||
|
LogReply("Register", registerReply);
|
||||||
|
Assert.Equal(ProtocolStatusCode.Ok, registerReply.ProtocolStatus.Code);
|
||||||
|
serverHandle = registerReply.Register.ServerHandle;
|
||||||
|
|
||||||
|
MxCommandReply addItemReply = await fixture.Service.Invoke(
|
||||||
|
CreateAddItemRequest(sessionId, serverHandle),
|
||||||
|
new TestServerCallContext()).ConfigureAwait(false);
|
||||||
|
LogReply("AddItem", addItemReply);
|
||||||
|
Assert.Equal(ProtocolStatusCode.Ok, addItemReply.ProtocolStatus.Code);
|
||||||
|
itemHandle = addItemReply.AddItem.ItemHandle;
|
||||||
|
|
||||||
|
// Step 1: added but not advised.
|
||||||
|
BulkReadResult addedOnlyRead = await ReadBulkSingleAsync(fixture, sessionId, serverHandle, "added-only").ConfigureAwait(false);
|
||||||
|
Assert.True(addedOnlyRead.WasSuccessful, addedOnlyRead.ErrorMessage);
|
||||||
|
output.WriteLine(
|
||||||
|
$"Snapshot AddItem for a client-held address returned {(addedOnlyRead.ItemHandle == itemHandle ? "the client's handle" : "a new handle")} ({addedOnlyRead.ItemHandle} vs client {itemHandle}).");
|
||||||
|
originalValue = addedOnlyRead.Value;
|
||||||
|
ulong sequenceAfterFirstRead = LastWorkerSequence(eventWriter);
|
||||||
|
|
||||||
|
// Supervisory so the user-id-0 write in step 2 applies (#212). This fails with an
|
||||||
|
// invalid-handle MXAccess status if the read removed the client's item.
|
||||||
|
MxCommandReply adviseReply = await fixture.Service.Invoke(
|
||||||
|
CreateAdviseSupervisoryRequest(sessionId, serverHandle, itemHandle),
|
||||||
|
new TestServerCallContext()).ConfigureAwait(false);
|
||||||
|
LogReply("AdviseSupervisory", adviseReply);
|
||||||
|
Assert.Equal(ProtocolStatusCode.Ok, adviseReply.ProtocolStatus.Code);
|
||||||
|
|
||||||
|
// Step 2: advised, read immediately (cached or not, depending on the race with the
|
||||||
|
// first OnDataChange — logged so a run shows which path it exercised).
|
||||||
|
BulkReadResult advisedRead = await ReadBulkSingleAsync(fixture, sessionId, serverHandle, "advised").ConfigureAwait(false);
|
||||||
|
Assert.True(advisedRead.WasSuccessful, advisedRead.ErrorMessage);
|
||||||
|
Assert.Equal(itemHandle, advisedRead.ItemHandle);
|
||||||
|
|
||||||
|
MxEvent firstAdvisedChange = await eventWriter
|
||||||
|
.WaitForMessageAsync(
|
||||||
|
candidate => candidate.Family == MxEventFamily.OnDataChange
|
||||||
|
&& candidate.ItemHandle == itemHandle
|
||||||
|
&& candidate.WorkerSequence > sequenceAfterFirstRead,
|
||||||
|
IntegrationTestEnvironment.LiveMxAccessEventTimeout,
|
||||||
|
streamCancellation.Token)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
LogEvent(firstAdvisedChange);
|
||||||
|
|
||||||
|
int freshValue = originalValue is { DataType: MxDataType.Integer }
|
||||||
|
? unchecked(originalValue.Int32Value + 1)
|
||||||
|
: 238;
|
||||||
|
MxCommandReply writeReply = await fixture.Service.Invoke(
|
||||||
|
CreateWriteRequest(
|
||||||
|
sessionId,
|
||||||
|
serverHandle,
|
||||||
|
itemHandle,
|
||||||
|
new MxValue { DataType = MxDataType.Integer, Int32Value = freshValue }),
|
||||||
|
new TestServerCallContext()).ConfigureAwait(false);
|
||||||
|
LogReply("Write", writeReply);
|
||||||
|
Assert.Equal(ProtocolStatusCode.Ok, writeReply.ProtocolStatus.Code);
|
||||||
|
|
||||||
|
MxEvent writtenChange = await eventWriter
|
||||||
|
.WaitForMessageAsync(
|
||||||
|
candidate => candidate.Family == MxEventFamily.OnDataChange
|
||||||
|
&& candidate.ItemHandle == itemHandle
|
||||||
|
&& candidate.Value is { DataType: MxDataType.Integer } value
|
||||||
|
&& value.Int32Value == freshValue,
|
||||||
|
IntegrationTestEnvironment.LiveMxAccessEventTimeout,
|
||||||
|
streamCancellation.Token)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
LogEvent(writtenChange);
|
||||||
|
|
||||||
|
if (originalValue is not null)
|
||||||
|
{
|
||||||
|
MxCommandReply restoreReply = await fixture.Service.Invoke(
|
||||||
|
CreateWriteRequest(sessionId, serverHandle, itemHandle, originalValue),
|
||||||
|
new TestServerCallContext()).ConfigureAwait(false);
|
||||||
|
LogReply("Write (restore)", restoreReply);
|
||||||
|
restored = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.False(
|
||||||
|
streamTask.IsFaulted,
|
||||||
|
streamTask.Exception?.ToString() ?? "Event stream task faulted without an exception.");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
if (!restored && originalValue is not null && sessionId is not null && itemHandle != 0)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
MxCommandReply restoreReply = await fixture.Service.Invoke(
|
||||||
|
CreateWriteRequest(sessionId, serverHandle, itemHandle, originalValue),
|
||||||
|
new TestServerCallContext()).ConfigureAwait(false);
|
||||||
|
LogReply("Write (restore after failure)", restoreReply);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
output.WriteLine($"Restore after failure threw {ex.GetType().Name}: {ex.Message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
streamCancellation.Cancel();
|
||||||
|
await ShutDownAsync(fixture, processFactory, sessionId, streamTask, propagateStreamFaults: true).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<BulkReadResult> ReadBulkSingleAsync(
|
||||||
|
GatewayServiceFixture fixture,
|
||||||
|
string sessionId,
|
||||||
|
int serverHandle,
|
||||||
|
string label)
|
||||||
|
{
|
||||||
|
MxCommandReply reply = await fixture.Service.Invoke(
|
||||||
|
new MxCommandRequest
|
||||||
|
{
|
||||||
|
SessionId = sessionId,
|
||||||
|
ClientCorrelationId = "live-read-bulk-" + label,
|
||||||
|
Command = new MxCommand
|
||||||
|
{
|
||||||
|
Kind = MxCommandKind.ReadBulk,
|
||||||
|
ReadBulk = new ReadBulkCommand
|
||||||
|
{
|
||||||
|
ServerHandle = serverHandle,
|
||||||
|
TagAddresses = { IntegrationTestEnvironment.LiveMxAccessItem },
|
||||||
|
TimeoutMs = 5000,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
new TestServerCallContext()).ConfigureAwait(false);
|
||||||
|
LogReply("ReadBulk(" + label + ")", reply);
|
||||||
|
Assert.Equal(ProtocolStatusCode.Ok, reply.ProtocolStatus.Code);
|
||||||
|
BulkReadResult result = Assert.Single(reply.ReadBulk.Results);
|
||||||
|
output.WriteLine(
|
||||||
|
$"ReadBulk({label}) success={result.WasSuccessful} cached={result.WasCached} item_handle={result.ItemHandle} error={result.ErrorMessage}");
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ulong LastWorkerSequence(RecordingServerStreamWriter<MxEvent> eventWriter)
|
||||||
|
{
|
||||||
|
IReadOnlyList<MxEvent> messages = eventWriter.Messages;
|
||||||
|
return messages.Count == 0 ? 0UL : messages.Max(message => message.WorkerSequence);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Verifies the MXAccess <c>WriteSecured</c> path: <c>AuthenticateUser</c> resolves a
|
/// Verifies the MXAccess <c>WriteSecured</c> path: <c>AuthenticateUser</c> resolves a
|
||||||
/// user id, then <c>WriteSecured</c> against the advised item completes its round-trip
|
/// user id, then <c>WriteSecured</c> against the advised item completes its round-trip
|
||||||
|
|||||||
@@ -715,8 +715,8 @@ public sealed class MxAccessCommandExecutorTests
|
|||||||
new ZB.MOM.WW.MxGateway.Worker.Conversion.VariantConverter());
|
new ZB.MOM.WW.MxGateway.Worker.Conversion.VariantConverter());
|
||||||
|
|
||||||
// Registry half of the fast path: the tag must resolve to a live item
|
// Registry half of the fast path: the tag must resolve to a live item
|
||||||
// handle on this server AND carry an advice, or TryGetCachedReadFor
|
// handle on this server AND carry an advice and a cached value, or
|
||||||
// falls through to the AddItem/Advise snapshot lifecycle.
|
// FindExistingItem sends the tag to the wait/snapshot path.
|
||||||
MxCommandReply registerReply = executor.Execute(
|
MxCommandReply registerReply = executor.Execute(
|
||||||
CreateRegisterCommand("register-before-cached-read", "client-a"));
|
CreateRegisterCommand("register-before-cached-read", "client-a"));
|
||||||
MxCommandReply addItemReply = executor.Execute(
|
MxCommandReply addItemReply = executor.Execute(
|
||||||
|
|||||||
@@ -257,11 +257,11 @@ public sealed class MxAccessHandleRegistryTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Pins the registry half of <c>MxAccessSession.TryGetCachedReadFor</c>'s fall-through
|
/// Pins the registry half of <c>MxAccessSession.FindExistingItem</c>'s cached-read
|
||||||
/// contract. That scan walks <see cref="MxAccessHandleRegistry.GetItemHandlesForDefinition"/>
|
/// contract. That scan walks <see cref="MxAccessHandleRegistry.GetItemHandlesForDefinition"/>
|
||||||
/// in order and skips any candidate carrying neither a plain nor a supervisory advice,
|
/// in order and never serves the cache of a candidate carrying neither a plain nor a
|
||||||
/// because an added-but-unadvised item will never receive a fresh <c>OnDataChange</c> and so
|
/// supervisory advice, because an added-but-unadvised item will never receive a fresh
|
||||||
/// can only serve a stale cache entry. The registry has to make that skip possible: the
|
/// <c>OnDataChange</c> and so can only serve a stale cache entry. The registry has to make that skip possible: the
|
||||||
/// duplicate registrations of one tag must come back in a stable ascending order, and the
|
/// duplicate registrations of one tag must come back in a stable ascending order, and the
|
||||||
/// advice index must answer per item handle rather than per tag. Asserted here rather than
|
/// advice index must answer per item handle rather than per tag. Asserted here rather than
|
||||||
/// on the session because the session's read path needs a live MXAccess COM instance.
|
/// on the session because the session's read path needs a live MXAccess COM instance.
|
||||||
|
|||||||
@@ -428,6 +428,343 @@ public sealed class MxAccessSessionTests
|
|||||||
Assert.Contains(pumpAtOperation, at => at > firstUnAdvise);
|
Assert.Contains(pumpAtOperation, at => at > firstUnAdvise);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Issue #238: a tag the caller has added and advised whose first
|
||||||
|
/// OnDataChange has not been cached yet must be read through the
|
||||||
|
/// caller's own subscription. The read makes no AddItem, Advise,
|
||||||
|
/// UnAdvise, or RemoveItem call, and the caller's item and advice
|
||||||
|
/// survive it. The fake reuses the handle for a re-added address, so
|
||||||
|
/// the pre-fix snapshot path would have torn down the caller's item.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public void ReadBulk_AdvisedTagWithNoCachedValue_WaitsOnTheCallersSubscriptionWithoutTearingItDown()
|
||||||
|
{
|
||||||
|
RecordingMxAccessServer server = new() { ReuseHandleForSameTag = true };
|
||||||
|
MxAccessValueCache valueCache = new();
|
||||||
|
using MxAccessSession session = MxAccessSession.CreateForTesting(server, new NoopEventSink(), valueCache: valueCache);
|
||||||
|
int serverHandle = session.Register("client");
|
||||||
|
int callerHandle = session.AddItem(serverHandle, "Tag.Subscribed");
|
||||||
|
session.Advise(serverHandle, callerHandle);
|
||||||
|
int operationsBeforeRead = server.Operations.Count;
|
||||||
|
|
||||||
|
// The caller's subscription delivers its first OnDataChange mid-wait.
|
||||||
|
Action pumpStep = () =>
|
||||||
|
{
|
||||||
|
if (!valueCache.TryGet(serverHandle, callerHandle, out _))
|
||||||
|
{
|
||||||
|
valueCache.Set(serverHandle, callerHandle, BuildDataChange(serverHandle, callerHandle, 61));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
BulkReadResult result = Assert.Single(
|
||||||
|
session.ReadBulk(serverHandle, new[] { "Tag.Subscribed" }, TimeSpan.FromSeconds(5), pumpStep));
|
||||||
|
|
||||||
|
Assert.True(result.WasSuccessful);
|
||||||
|
Assert.False(result.WasCached);
|
||||||
|
Assert.Equal(callerHandle, result.ItemHandle);
|
||||||
|
Assert.Equal(61, result.Value.Int32Value);
|
||||||
|
Assert.Empty(server.Operations.Skip(operationsBeforeRead));
|
||||||
|
AssertCallerItemIntact(session, serverHandle, callerHandle, "Tag.Subscribed", expectAdvised: true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The same advised-but-uncached tag that never delivers within the
|
||||||
|
/// timeout reports its own timeout and still leaves the caller's
|
||||||
|
/// subscription alone.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public void ReadBulk_AdvisedTagThatNeverDelivers_TimesOutWithoutTearingDownTheCallersSubscription()
|
||||||
|
{
|
||||||
|
RecordingMxAccessServer server = new() { ReuseHandleForSameTag = true };
|
||||||
|
using MxAccessSession session = MxAccessSession.CreateForTesting(server, new NoopEventSink());
|
||||||
|
int serverHandle = session.Register("client");
|
||||||
|
int callerHandle = session.AddItem(serverHandle, "Tag.Quiet");
|
||||||
|
session.AdviseSupervisory(serverHandle, callerHandle);
|
||||||
|
int operationsBeforeRead = server.Operations.Count;
|
||||||
|
|
||||||
|
BulkReadResult result = Assert.Single(
|
||||||
|
session.ReadBulk(serverHandle, new[] { "Tag.Quiet" }, TimeSpan.FromMilliseconds(60), () => { }));
|
||||||
|
|
||||||
|
Assert.False(result.WasSuccessful);
|
||||||
|
Assert.Equal(callerHandle, result.ItemHandle);
|
||||||
|
Assert.Contains(ReadBulkTimeoutText, result.ErrorMessage, StringComparison.OrdinalIgnoreCase);
|
||||||
|
Assert.Empty(server.Operations.Skip(operationsBeforeRead));
|
||||||
|
Assert.True(session.HandleRegistry.ContainsAdviceHandle(serverHandle, callerHandle, MxAccessAdviceKind.Supervisory));
|
||||||
|
Assert.True(session.HandleRegistry.ContainsItemHandle(serverHandle, callerHandle));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A tag the caller has added but not advised takes a snapshot AddItem.
|
||||||
|
/// The installed MXAccess hands that AddItem a new handle (observed
|
||||||
|
/// live on windev), so the snapshot item is advised, read, and torn
|
||||||
|
/// down on its own and the caller's item sees no call at all.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public void ReadBulk_AddedButNotAdvisedTag_WhenAddItemReturnsANewHandle_LeavesTheCallersItemUntouched()
|
||||||
|
{
|
||||||
|
RecordingMxAccessServer server = new();
|
||||||
|
MxAccessValueCache valueCache = new();
|
||||||
|
using MxAccessSession session = MxAccessSession.CreateForTesting(server, new NoopEventSink(), valueCache: valueCache);
|
||||||
|
int serverHandle = session.Register("client");
|
||||||
|
int callerHandle = session.AddItem(serverHandle, "Tag.AddedOnly");
|
||||||
|
int operationsBeforeRead = server.Operations.Count;
|
||||||
|
|
||||||
|
Action pumpStep = () =>
|
||||||
|
{
|
||||||
|
if (server.TryGetAdvisedHandle("Tag.AddedOnly", out int handle) && !valueCache.TryGet(serverHandle, handle, out _))
|
||||||
|
{
|
||||||
|
valueCache.Set(serverHandle, handle, BuildDataChange(serverHandle, handle, 23));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
BulkReadResult result = Assert.Single(
|
||||||
|
session.ReadBulk(serverHandle, new[] { "Tag.AddedOnly" }, TimeSpan.FromSeconds(5), pumpStep));
|
||||||
|
|
||||||
|
int snapshotHandle = server.HandleForTag("Tag.AddedOnly");
|
||||||
|
Assert.NotEqual(callerHandle, snapshotHandle);
|
||||||
|
Assert.True(result.WasSuccessful);
|
||||||
|
Assert.Equal(snapshotHandle, result.ItemHandle);
|
||||||
|
Assert.Equal(23, result.Value.Int32Value);
|
||||||
|
Assert.Equal(
|
||||||
|
new[]
|
||||||
|
{
|
||||||
|
$"AddItem:{serverHandle}:Tag.AddedOnly",
|
||||||
|
$"Advise:{serverHandle}:{snapshotHandle}",
|
||||||
|
$"UnAdvise:{serverHandle}:{snapshotHandle}",
|
||||||
|
$"RemoveItem:{serverHandle}:{snapshotHandle}",
|
||||||
|
},
|
||||||
|
server.Operations.Skip(operationsBeforeRead));
|
||||||
|
AssertCallerItemIntact(session, serverHandle, callerHandle, "Tag.AddedOnly", expectAdvised: false);
|
||||||
|
Assert.False(session.HandleRegistry.ContainsItemHandle(serverHandle, snapshotHandle));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// When the snapshot AddItem for a caller's added-but-not-advised tag
|
||||||
|
/// returns the caller's own handle, the read advises that handle and
|
||||||
|
/// unadvises it afterwards — returning the caller's item to its prior
|
||||||
|
/// added-not-advised state — but never removes it.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public void ReadBulk_AddedButNotAdvisedTag_WhenAddItemReturnsTheCallersHandle_AdvisesForTheReadButNeverRemovesIt()
|
||||||
|
{
|
||||||
|
RecordingMxAccessServer server = new() { ReuseHandleForSameTag = true };
|
||||||
|
MxAccessValueCache valueCache = new();
|
||||||
|
using MxAccessSession session = MxAccessSession.CreateForTesting(server, new NoopEventSink(), valueCache: valueCache);
|
||||||
|
int serverHandle = session.Register("client");
|
||||||
|
int callerHandle = session.AddItem(serverHandle, "Tag.AddedOnly");
|
||||||
|
int operationsBeforeRead = server.Operations.Count;
|
||||||
|
|
||||||
|
Action pumpStep = () =>
|
||||||
|
{
|
||||||
|
if (server.TryGetAdvisedHandle("Tag.AddedOnly", out int handle) && !valueCache.TryGet(serverHandle, handle, out _))
|
||||||
|
{
|
||||||
|
valueCache.Set(serverHandle, handle, BuildDataChange(serverHandle, handle, 17));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
BulkReadResult result = Assert.Single(
|
||||||
|
session.ReadBulk(serverHandle, new[] { "Tag.AddedOnly" }, TimeSpan.FromSeconds(5), pumpStep));
|
||||||
|
|
||||||
|
Assert.True(result.WasSuccessful);
|
||||||
|
Assert.False(result.WasCached);
|
||||||
|
Assert.Equal(callerHandle, result.ItemHandle);
|
||||||
|
Assert.Equal(17, result.Value.Int32Value);
|
||||||
|
Assert.Equal(
|
||||||
|
new[]
|
||||||
|
{
|
||||||
|
$"AddItem:{serverHandle}:Tag.AddedOnly",
|
||||||
|
$"Advise:{serverHandle}:{callerHandle}",
|
||||||
|
$"UnAdvise:{serverHandle}:{callerHandle}",
|
||||||
|
},
|
||||||
|
server.Operations.Skip(operationsBeforeRead));
|
||||||
|
AssertCallerItemIntact(session, serverHandle, callerHandle, "Tag.AddedOnly", expectAdvised: false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// UnAdvise drops the item's cached value: the item stays added but the
|
||||||
|
/// value stops updating, so a later re-advise must not be answered from
|
||||||
|
/// the previous advice's cache before its own first OnDataChange.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public void UnAdvise_EvictsTheItemsCachedValueButKeepsTheItem()
|
||||||
|
{
|
||||||
|
RecordingMxAccessServer server = new();
|
||||||
|
MxAccessValueCache valueCache = new();
|
||||||
|
using MxAccessSession session = MxAccessSession.CreateForTesting(server, new NoopEventSink(), valueCache: valueCache);
|
||||||
|
int serverHandle = session.Register("client");
|
||||||
|
int handle = session.AddItem(serverHandle, "Tag.Readvise");
|
||||||
|
session.Advise(serverHandle, handle);
|
||||||
|
valueCache.Set(serverHandle, handle, BuildDataChange(serverHandle, handle, 3));
|
||||||
|
|
||||||
|
session.UnAdvise(serverHandle, handle);
|
||||||
|
|
||||||
|
Assert.False(valueCache.TryGet(serverHandle, handle, out _));
|
||||||
|
Assert.True(session.HandleRegistry.ContainsItemHandle(serverHandle, handle));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The value a ReadBulk's temporary advice on a caller's added-only item
|
||||||
|
/// produced (AddItem returning the caller's handle) must not be served
|
||||||
|
/// as cached once the caller advises the item itself: the next read
|
||||||
|
/// waits for the caller's own first value.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public void ReadBulk_AfterTemporaryAdviceOnAddedOnlyItem_LaterAdviseIsNotServedTheTemporaryValue()
|
||||||
|
{
|
||||||
|
RecordingMxAccessServer server = new() { ReuseHandleForSameTag = true };
|
||||||
|
MxAccessValueCache valueCache = new();
|
||||||
|
using MxAccessSession session = MxAccessSession.CreateForTesting(server, new NoopEventSink(), valueCache: valueCache);
|
||||||
|
int serverHandle = session.Register("client");
|
||||||
|
int callerHandle = session.AddItem(serverHandle, "Tag.Seed");
|
||||||
|
int nextValue = 17;
|
||||||
|
Action pumpStep = () =>
|
||||||
|
{
|
||||||
|
if (server.TryGetAdvisedHandle("Tag.Seed", out int handle) && !valueCache.TryGet(serverHandle, handle, out _))
|
||||||
|
{
|
||||||
|
valueCache.Set(serverHandle, handle, BuildDataChange(serverHandle, handle, nextValue));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
BulkReadResult seed = Assert.Single(
|
||||||
|
session.ReadBulk(serverHandle, new[] { "Tag.Seed" }, TimeSpan.FromSeconds(5), pumpStep));
|
||||||
|
Assert.Equal(17, seed.Value.Int32Value);
|
||||||
|
|
||||||
|
session.Advise(serverHandle, callerHandle);
|
||||||
|
nextValue = 99;
|
||||||
|
BulkReadResult afterAdvise = Assert.Single(
|
||||||
|
session.ReadBulk(serverHandle, new[] { "Tag.Seed" }, TimeSpan.FromSeconds(5), pumpStep));
|
||||||
|
|
||||||
|
Assert.True(afterAdvise.WasSuccessful);
|
||||||
|
Assert.False(afterAdvise.WasCached);
|
||||||
|
Assert.Equal(99, afterAdvise.Value.Int32Value);
|
||||||
|
AssertCallerItemIntact(session, serverHandle, callerHandle, "Tag.Seed", expectAdvised: true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Defence in depth for the ordinal registry lookup: when a snapshot
|
||||||
|
/// AddItem for an address the registry does not know comes back with a
|
||||||
|
/// handle the caller already holds (MXAccess resolving a differently
|
||||||
|
/// spelled address to the caller's item), the read never removes that
|
||||||
|
/// item. Advised, it is waited on untouched; added only, it is advised
|
||||||
|
/// and unadvised for the read. The caller's registration keeps its own
|
||||||
|
/// item definition.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="callerAdvised">Whether the caller has advised its item.</param>
|
||||||
|
[Theory]
|
||||||
|
[InlineData(true)]
|
||||||
|
[InlineData(false)]
|
||||||
|
public void ReadBulk_SnapshotAddItemReturningACallersHandle_NeverRemovesTheCallersItem(bool callerAdvised)
|
||||||
|
{
|
||||||
|
RecordingMxAccessServer server = new();
|
||||||
|
MxAccessValueCache valueCache = new();
|
||||||
|
using MxAccessSession session = MxAccessSession.CreateForTesting(server, new NoopEventSink(), valueCache: valueCache);
|
||||||
|
int serverHandle = session.Register("client");
|
||||||
|
int callerHandle = session.AddItem(serverHandle, "Area.Tank.PV");
|
||||||
|
if (callerAdvised)
|
||||||
|
{
|
||||||
|
session.Advise(serverHandle, callerHandle);
|
||||||
|
}
|
||||||
|
|
||||||
|
int operationsBeforeRead = server.Operations.Count;
|
||||||
|
server.NextItemHandleOverride = callerHandle;
|
||||||
|
Action pumpStep = () =>
|
||||||
|
{
|
||||||
|
if (!valueCache.TryGet(serverHandle, callerHandle, out _))
|
||||||
|
{
|
||||||
|
valueCache.Set(serverHandle, callerHandle, BuildDataChange(serverHandle, callerHandle, 5));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
BulkReadResult result = Assert.Single(
|
||||||
|
session.ReadBulk(serverHandle, new[] { "AREA.TANK.PV" }, TimeSpan.FromSeconds(5), pumpStep));
|
||||||
|
|
||||||
|
Assert.True(result.WasSuccessful);
|
||||||
|
Assert.Equal(callerHandle, result.ItemHandle);
|
||||||
|
Assert.Equal("AREA.TANK.PV", result.TagAddress);
|
||||||
|
List<string> readOperations = server.Operations.Skip(operationsBeforeRead).ToList();
|
||||||
|
Assert.Contains($"AddItem:{serverHandle}:AREA.TANK.PV", readOperations);
|
||||||
|
Assert.DoesNotContain($"RemoveItem:{serverHandle}:{callerHandle}", readOperations);
|
||||||
|
Assert.Equal(callerAdvised ? 0 : 1, readOperations.Count(op => op == $"Advise:{serverHandle}:{callerHandle}"));
|
||||||
|
Assert.Equal(callerAdvised ? 0 : 1, readOperations.Count(op => op == $"UnAdvise:{serverHandle}:{callerHandle}"));
|
||||||
|
AssertCallerItemIntact(session, serverHandle, callerHandle, "Area.Tank.PV", expectAdvised: callerAdvised);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The ScadaBridge reconnect shape (subscribe, then seed-read in one
|
||||||
|
/// batch): cached, advised-but-uncached, added-only, and never-held
|
||||||
|
/// tags in one request, with a duplicate of the advised tag. Only the
|
||||||
|
/// never-held tag's own snapshot item is removed; every caller item
|
||||||
|
/// survives with exactly the advice it had before the read. The fake
|
||||||
|
/// reuses handles for re-added addresses, the worst case for teardown.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public void ReadBulk_MixedCallerAndSnapshotTags_TearsDownOnlyItsOwnSnapshotState()
|
||||||
|
{
|
||||||
|
RecordingMxAccessServer server = new() { ReuseHandleForSameTag = true };
|
||||||
|
MxAccessValueCache valueCache = new();
|
||||||
|
using MxAccessSession session = MxAccessSession.CreateForTesting(server, new NoopEventSink(), valueCache: valueCache);
|
||||||
|
int serverHandle = session.Register("client");
|
||||||
|
int cached = session.AddItem(serverHandle, "Tag.Cached");
|
||||||
|
session.Advise(serverHandle, cached);
|
||||||
|
valueCache.Set(serverHandle, cached, BuildDataChange(serverHandle, cached, 1));
|
||||||
|
int advised = session.AddItem(serverHandle, "Tag.Advised");
|
||||||
|
session.Advise(serverHandle, advised);
|
||||||
|
int addedOnly = session.AddItem(serverHandle, "Tag.AddedOnly");
|
||||||
|
int operationsBeforeRead = server.Operations.Count;
|
||||||
|
|
||||||
|
Action pumpStep = () =>
|
||||||
|
{
|
||||||
|
foreach (string tag in new[] { "Tag.Advised", "Tag.AddedOnly", "Tag.Fresh" })
|
||||||
|
{
|
||||||
|
if (server.TryGetAdvisedHandle(tag, out int handle) && !valueCache.TryGet(serverHandle, handle, out _))
|
||||||
|
{
|
||||||
|
valueCache.Set(serverHandle, handle, BuildDataChange(serverHandle, handle, handle));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
string[] tags = { "Tag.Cached", "Tag.Advised", "Tag.AddedOnly", "Tag.Fresh", "Tag.Advised" };
|
||||||
|
IReadOnlyList<BulkReadResult> results = session.ReadBulk(serverHandle, tags, TimeSpan.FromSeconds(5), pumpStep);
|
||||||
|
|
||||||
|
Assert.All(results, result => Assert.True(result.WasSuccessful, result.TagAddress + ": " + result.ErrorMessage));
|
||||||
|
Assert.True(results[0].WasCached);
|
||||||
|
Assert.Equal(advised, results[1].ItemHandle);
|
||||||
|
Assert.Equal(addedOnly, results[2].ItemHandle);
|
||||||
|
Assert.Equal(advised, results[4].ItemHandle);
|
||||||
|
int fresh = server.HandleForTag("Tag.Fresh");
|
||||||
|
Assert.Equal(fresh, results[3].ItemHandle);
|
||||||
|
|
||||||
|
List<string> readOperations = server.Operations.Skip(operationsBeforeRead).ToList();
|
||||||
|
Assert.Equal(
|
||||||
|
new[]
|
||||||
|
{
|
||||||
|
$"AddItem:{serverHandle}:Tag.AddedOnly",
|
||||||
|
$"Advise:{serverHandle}:{addedOnly}",
|
||||||
|
$"AddItem:{serverHandle}:Tag.Fresh",
|
||||||
|
$"Advise:{serverHandle}:{fresh}",
|
||||||
|
$"UnAdvise:{serverHandle}:{addedOnly}",
|
||||||
|
$"UnAdvise:{serverHandle}:{fresh}",
|
||||||
|
$"RemoveItem:{serverHandle}:{fresh}",
|
||||||
|
},
|
||||||
|
readOperations);
|
||||||
|
AssertCallerItemIntact(session, serverHandle, cached, "Tag.Cached", expectAdvised: true);
|
||||||
|
AssertCallerItemIntact(session, serverHandle, advised, "Tag.Advised", expectAdvised: true);
|
||||||
|
AssertCallerItemIntact(session, serverHandle, addedOnly, "Tag.AddedOnly", expectAdvised: false);
|
||||||
|
Assert.False(session.HandleRegistry.ContainsItemHandle(serverHandle, fresh));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void AssertCallerItemIntact(
|
||||||
|
MxAccessSession session,
|
||||||
|
int serverHandle,
|
||||||
|
int itemHandle,
|
||||||
|
string itemDefinition,
|
||||||
|
bool expectAdvised)
|
||||||
|
{
|
||||||
|
Assert.True(session.HandleRegistry.ContainsItemHandle(serverHandle, itemHandle));
|
||||||
|
Assert.Contains(itemHandle, session.HandleRegistry.GetItemHandlesForDefinition(serverHandle, itemDefinition));
|
||||||
|
Assert.Equal(expectAdvised, session.HandleRegistry.ContainsAdviceHandle(serverHandle, itemHandle, MxAccessAdviceKind.Plain));
|
||||||
|
}
|
||||||
|
|
||||||
private static void RecordCompletion(MxAccessWriteCompletionCache cache, int serverHandle, int itemHandle)
|
private static void RecordCompletion(MxAccessWriteCompletionCache cache, int serverHandle, int itemHandle)
|
||||||
{
|
{
|
||||||
RepeatedField<MxStatusProxy> statuses = new() { new MxStatusProxy { Category = MxStatusCategory.Ok } };
|
RepeatedField<MxStatusProxy> statuses = new() { new MxStatusProxy { Category = MxStatusCategory.Ok } };
|
||||||
|
|||||||
@@ -350,6 +350,12 @@ public sealed class MxAccessSession : IDisposable
|
|||||||
|
|
||||||
mxAccessServer.UnAdvise(serverHandle, itemHandle);
|
mxAccessServer.UnAdvise(serverHandle, itemHandle);
|
||||||
handleRegistry.RemoveAdviceHandles(serverHandle, itemHandle);
|
handleRegistry.RemoveAdviceHandles(serverHandle, itemHandle);
|
||||||
|
// The item stays added but its last value stops updating. Drop it so
|
||||||
|
// a later re-advise is not answered by ReadBulk's cached fast path
|
||||||
|
// with the value from the previous advice (including a ReadBulk's
|
||||||
|
// own temporary advice on a caller's added-only item) before the new
|
||||||
|
// advice's first OnDataChange lands.
|
||||||
|
valueCache.Remove(serverHandle, itemHandle);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Advises on item changes with supervisory subscription.</summary>
|
/// <summary>Advises on item changes with supervisory subscription.</summary>
|
||||||
@@ -927,26 +933,49 @@ public sealed class MxAccessSession : IDisposable
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Bulk read snapshot. For each requested tag, returns the most recent
|
/// Bulk read snapshot. For each requested tag, returns the most recent
|
||||||
/// OnDataChange value if the tag is already advised AND a cached value
|
/// OnDataChange value if the tag is already advised AND a cached value
|
||||||
/// exists (no subscription side effects); otherwise takes the AddItem
|
/// exists (no subscription side effects); waits on the caller's own
|
||||||
/// + Advise + wait + UnAdvise + RemoveItem snapshot lifecycle itself.
|
/// subscription when the tag is advised but its first OnDataChange has
|
||||||
/// <paramref name="timeout"/> bounds the wait for every snapshot tag;
|
/// not been cached yet; otherwise takes a snapshot lifecycle itself.
|
||||||
|
/// <paramref name="timeout"/> bounds the wait for every waiting tag;
|
||||||
/// <paramref name="pumpStep"/> is invoked on every poll iteration so the
|
/// <paramref name="pumpStep"/> is invoked on every poll iteration so the
|
||||||
/// worker's STA can dispatch the incoming MXAccess message that carries
|
/// worker's STA can dispatch the incoming MXAccess message that carries
|
||||||
/// the value.
|
/// the value.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <remarks>
|
/// <remarks>
|
||||||
/// The snapshot tags are processed in phases rather than one at a time:
|
/// <para>
|
||||||
/// every cache probe runs first, then every uncached tag is added and
|
/// The waiting tags are processed in phases rather than one at a
|
||||||
/// advised, then one wait with a single shared deadline collects the
|
/// time: every registry and cache probe runs first, then every tag
|
||||||
/// first OnDataChange per handle, then every snapshot handle is torn
|
/// that needs a subscription is added and/or advised, then one wait
|
||||||
/// down. A serial lifecycle held the STA for up to N x timeout when N
|
/// with a single shared deadline collects the first OnDataChange per
|
||||||
/// tags never produced a value; the phased form holds it for at most
|
/// handle, then the snapshot state this call created is torn down.
|
||||||
/// one timeout. Each tag's result is still its own: a tag that never
|
/// A serial lifecycle held the STA for up to N x timeout when N tags
|
||||||
/// delivered fails with the same timed-out diagnostic and its own item
|
/// never produced a value; the phased form holds it for at most one
|
||||||
/// handle, an AddItem or Advise failure fails only that tag, and results
|
/// timeout. Each tag's result is still its own: a tag that never
|
||||||
/// keep request order. The cache probes run before any snapshot AddItem
|
/// delivered fails with the same timed-out diagnostic and its own
|
||||||
/// so a later tag can never be served from an earlier tag's own
|
/// item handle, an AddItem or Advise failure fails only that tag,
|
||||||
/// snapshot subscription.
|
/// and results keep request order. The cache probes run before any
|
||||||
|
/// snapshot AddItem so a later tag can never be served from an
|
||||||
|
/// earlier tag's own snapshot subscription.
|
||||||
|
/// </para>
|
||||||
|
/// <para>
|
||||||
|
/// ReadBulk never removes or unadvises state it did not create
|
||||||
|
/// (issue #238). Teardown is ownership-scoped: it unadvises only the
|
||||||
|
/// advices this call's own Advise created and removes only the items
|
||||||
|
/// this call's own AddItem created. A tag the caller has advised but
|
||||||
|
/// whose first OnDataChange is not cached yet is read through the
|
||||||
|
/// caller's own subscription with no COM call at all. Any other tag
|
||||||
|
/// gets a snapshot AddItem. The installed MXAccess hands that
|
||||||
|
/// AddItem a new handle even when the caller already holds the
|
||||||
|
/// address (observed live on windev, 2026-12-01), so a caller's
|
||||||
|
/// added-but-not-advised item is left untouched and the snapshot
|
||||||
|
/// item is torn down as before. When AddItem instead returns a
|
||||||
|
/// handle the registry already tracks, that handle is the caller's:
|
||||||
|
/// it is advised for the read only if nothing advises it yet,
|
||||||
|
/// unadvised afterwards (back to its prior added-not-advised state),
|
||||||
|
/// and never removed — an extra AddItem reference may then outlive
|
||||||
|
/// the read until the caller removes the item or unregisters, but
|
||||||
|
/// the caller's item can never be deleted from under it.
|
||||||
|
/// </para>
|
||||||
/// </remarks>
|
/// </remarks>
|
||||||
/// <param name="serverHandle">The MXAccess server handle.</param>
|
/// <param name="serverHandle">The MXAccess server handle.</param>
|
||||||
/// <param name="tagAddresses">The tag addresses to read.</param>
|
/// <param name="tagAddresses">The tag addresses to read.</param>
|
||||||
@@ -974,10 +1003,13 @@ public sealed class MxAccessSession : IDisposable
|
|||||||
BulkReadResult?[] results = new BulkReadResult?[tagCount];
|
BulkReadResult?[] results = new BulkReadResult?[tagCount];
|
||||||
List<SnapshotRead> snapshots = new();
|
List<SnapshotRead> snapshots = new();
|
||||||
|
|
||||||
// Phase 1: validation and the cached-and-advised fast path. A tag
|
// Phase 1: validation, the cached-and-advised fast path, and the
|
||||||
// already advised by the caller with a cached value is answered without
|
// registry probe. A tag already advised by the caller with a cached
|
||||||
// touching the existing subscription — the caller didn't create it, so
|
// value is answered without touching the existing subscription — the
|
||||||
// ReadBulk must not tear it down.
|
// caller created it, so ReadBulk must not tear it down. A tag the
|
||||||
|
// caller has advised without a cached value yet keeps the caller's
|
||||||
|
// item handle, so phase 2 waits on that subscription instead of
|
||||||
|
// re-adding the address and phase 4 never touches it.
|
||||||
for (int index = 0; index < tagCount; index++)
|
for (int index = 0; index < tagCount; index++)
|
||||||
{
|
{
|
||||||
string? tagAddress = tagAddresses[index];
|
string? tagAddress = tagAddresses[index];
|
||||||
@@ -987,13 +1019,25 @@ public sealed class MxAccessSession : IDisposable
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (TryGetCachedReadFor(serverHandle, tagAddress!, out int cachedItemHandle, out MxAccessValueCache.CachedValue cachedValue))
|
ExistingItemState existing = FindExistingItem(
|
||||||
|
serverHandle,
|
||||||
|
tagAddress!,
|
||||||
|
out int existingItemHandle,
|
||||||
|
out MxAccessValueCache.CachedValue cachedValue);
|
||||||
|
if (existing == ExistingItemState.AdvisedAndCached)
|
||||||
{
|
{
|
||||||
results[index] = SucceededRead(serverHandle, tagAddress!, cachedItemHandle, wasCached: true, cachedValue);
|
results[index] = SucceededRead(serverHandle, tagAddress!, existingItemHandle, wasCached: true, cachedValue);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
snapshots.Add(new SnapshotRead(index, tagAddress!));
|
SnapshotRead snapshot = new(index, tagAddress!);
|
||||||
|
if (existing == ExistingItemState.Advised)
|
||||||
|
{
|
||||||
|
snapshot.ItemHandle = existingItemHandle;
|
||||||
|
snapshot.IsCallerItem = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
snapshots.Add(snapshot);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (snapshots.Count > 0)
|
if (snapshots.Count > 0)
|
||||||
@@ -1035,14 +1079,18 @@ public sealed class MxAccessSession : IDisposable
|
|||||||
TimeSpan timeout,
|
TimeSpan timeout,
|
||||||
Action pumpStep)
|
Action pumpStep)
|
||||||
{
|
{
|
||||||
// Phase 2: reserve our own item handle and advise for every uncached
|
// Phase 2: get an advised item handle for every tag that needs one. A
|
||||||
// tag. A per-tag AddItem/Advise failure fails only that tag. When
|
// tag the caller does not hold gets this call's own AddItem; a tag the
|
||||||
// MXAccess hands back a handle an earlier tag in this batch already
|
// caller holds keeps the caller's handle. The handle is advised only
|
||||||
// advised (a duplicate address), that tag shares the earlier tag's
|
// when nothing advises it yet — an advised caller item is waited on
|
||||||
// subscription instead of advising the handle a second time, and gets
|
// through the caller's own subscription. A per-tag AddItem/Advise
|
||||||
// the same outcome fanned out to it after the wait.
|
// failure fails only that tag. When a handle is already waited on by
|
||||||
|
// an earlier tag in this batch (a duplicate address), the later tag
|
||||||
|
// shares that subscription instead of advising the handle a second
|
||||||
|
// time, and gets the same outcome fanned out to it after the wait.
|
||||||
List<SnapshotRead> waiting = new(snapshots.Count);
|
List<SnapshotRead> waiting = new(snapshots.Count);
|
||||||
Dictionary<int, SnapshotRead> advisedByHandle = new();
|
Dictionary<int, SnapshotRead> waitingByHandle = new();
|
||||||
|
HashSet<int> addedHandles = new();
|
||||||
List<SnapshotRead> sharing = new();
|
List<SnapshotRead> sharing = new();
|
||||||
for (int position = 0; position < snapshots.Count; position++)
|
for (int position = 0; position < snapshots.Count; position++)
|
||||||
{
|
{
|
||||||
@@ -1054,18 +1102,52 @@ public sealed class MxAccessSession : IDisposable
|
|||||||
pumpStep();
|
pumpStep();
|
||||||
}
|
}
|
||||||
|
|
||||||
snapshot.ItemHandle = AddItem(serverHandle, snapshot.TagAddress);
|
if (!snapshot.IsCallerItem)
|
||||||
if (advisedByHandle.TryGetValue(snapshot.ItemHandle, out SnapshotRead? owner))
|
{
|
||||||
|
snapshot.ItemHandle = AddSnapshotItem(serverHandle, snapshot.TagAddress, out bool alreadyRegistered);
|
||||||
|
if (!alreadyRegistered)
|
||||||
|
{
|
||||||
|
snapshot.OwnsItem = true;
|
||||||
|
addedHandles.Add(snapshot.ItemHandle);
|
||||||
|
}
|
||||||
|
else if (!addedHandles.Contains(snapshot.ItemHandle))
|
||||||
|
{
|
||||||
|
// MXAccess returned an item the caller already holds
|
||||||
|
// (the same address added but not advised, or a
|
||||||
|
// differently spelled one the ordinal registry lookup
|
||||||
|
// missed). It is the caller's item: never remove it.
|
||||||
|
snapshot.IsCallerItem = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (waitingByHandle.TryGetValue(snapshot.ItemHandle, out SnapshotRead? owner))
|
||||||
{
|
{
|
||||||
snapshot.SharedWith = owner;
|
snapshot.SharedWith = owner;
|
||||||
sharing.Add(snapshot);
|
sharing.Add(snapshot);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (IsAdvised(serverHandle, snapshot.ItemHandle))
|
||||||
|
{
|
||||||
|
// The caller's subscription already delivers OnDataChange
|
||||||
|
// for this handle. Serve a value that landed since phase 1,
|
||||||
|
// otherwise wait on that subscription without touching it.
|
||||||
|
if (valueCache.TryGet(serverHandle, snapshot.ItemHandle, out MxAccessValueCache.CachedValue cachedValue))
|
||||||
|
{
|
||||||
|
results[snapshot.Index] = SucceededRead(serverHandle, snapshot.TagAddress, snapshot.ItemHandle, wasCached: true, cachedValue);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
snapshot.Baseline = valueCache.CurrentVersion(serverHandle, snapshot.ItemHandle);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
snapshot.Baseline = valueCache.CurrentVersion(serverHandle, snapshot.ItemHandle);
|
snapshot.Baseline = valueCache.CurrentVersion(serverHandle, snapshot.ItemHandle);
|
||||||
Advise(serverHandle, snapshot.ItemHandle);
|
Advise(serverHandle, snapshot.ItemHandle);
|
||||||
snapshot.Advised = true;
|
snapshot.OwnsAdvice = true;
|
||||||
advisedByHandle[snapshot.ItemHandle] = snapshot;
|
}
|
||||||
|
|
||||||
|
waitingByHandle[snapshot.ItemHandle] = snapshot;
|
||||||
waiting.Add(snapshot);
|
waiting.Add(snapshot);
|
||||||
}
|
}
|
||||||
catch (Exception exception)
|
catch (Exception exception)
|
||||||
@@ -1156,15 +1238,18 @@ public sealed class MxAccessSession : IDisposable
|
|||||||
List<SnapshotRead> snapshots,
|
List<SnapshotRead> snapshots,
|
||||||
Action pumpStep)
|
Action pumpStep)
|
||||||
{
|
{
|
||||||
// Phase 4: snapshot teardown — best-effort, never re-throws. Each
|
// Phase 4: snapshot teardown — best-effort, never re-throws, and
|
||||||
// distinct handle is unadvised and removed exactly once, even when
|
// ownership-scoped: only an advice this call's own Advise created is
|
||||||
|
// unadvised, and only an item this call's own AddItem created is
|
||||||
|
// removed. A caller's item or subscription is never torn down (#238).
|
||||||
|
// Each owned handle is unadvised and removed exactly once, even when
|
||||||
// MXAccess handed the same id to several tags in the batch.
|
// MXAccess handed the same id to several tags in the batch.
|
||||||
HashSet<int> unadvised = new();
|
HashSet<int> unadvised = new();
|
||||||
HashSet<int> removed = new();
|
HashSet<int> removed = new();
|
||||||
int calls = 0;
|
int calls = 0;
|
||||||
foreach (SnapshotRead snapshot in snapshots)
|
foreach (SnapshotRead snapshot in snapshots)
|
||||||
{
|
{
|
||||||
if (snapshot.Advised && unadvised.Add(snapshot.ItemHandle))
|
if (snapshot.OwnsAdvice && unadvised.Add(snapshot.ItemHandle))
|
||||||
{
|
{
|
||||||
PumpEvery(ref calls, pumpStep);
|
PumpEvery(ref calls, pumpStep);
|
||||||
try { UnAdvise(serverHandle, snapshot.ItemHandle); } catch { /* swallow — best effort */ }
|
try { UnAdvise(serverHandle, snapshot.ItemHandle); } catch { /* swallow — best effort */ }
|
||||||
@@ -1173,7 +1258,7 @@ public sealed class MxAccessSession : IDisposable
|
|||||||
|
|
||||||
foreach (SnapshotRead snapshot in snapshots)
|
foreach (SnapshotRead snapshot in snapshots)
|
||||||
{
|
{
|
||||||
if (snapshot.ItemHandle != 0 && removed.Add(snapshot.ItemHandle))
|
if (snapshot.OwnsItem && removed.Add(snapshot.ItemHandle))
|
||||||
{
|
{
|
||||||
PumpEvery(ref calls, pumpStep);
|
PumpEvery(ref calls, pumpStep);
|
||||||
try { RemoveItem(serverHandle, snapshot.ItemHandle); } catch { /* swallow — best effort */ }
|
try { RemoveItem(serverHandle, snapshot.ItemHandle); } catch { /* swallow — best effort */ }
|
||||||
@@ -1191,7 +1276,21 @@ public sealed class MxAccessSession : IDisposable
|
|||||||
calls++;
|
calls++;
|
||||||
}
|
}
|
||||||
|
|
||||||
private bool TryGetCachedReadFor(
|
/// <summary>
|
||||||
|
/// Classifies the caller's advised items for a tag: none, an advised
|
||||||
|
/// item with no cached value yet, or an advised item with a cached
|
||||||
|
/// value. Added-but-not-advised items are skipped: they receive no
|
||||||
|
/// OnDataChange to wait on, so the tag takes a snapshot AddItem.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="serverHandle">The MXAccess server handle.</param>
|
||||||
|
/// <param name="tagAddress">The tag address, matched ordinally.</param>
|
||||||
|
/// <param name="itemHandle">
|
||||||
|
/// The caller's item handle to read through, or 0 for
|
||||||
|
/// <see cref="ExistingItemState.None"/>.
|
||||||
|
/// </param>
|
||||||
|
/// <param name="cachedValue">The cached value for <see cref="ExistingItemState.AdvisedAndCached"/>.</param>
|
||||||
|
/// <returns>The strongest state among the tag's advised items.</returns>
|
||||||
|
private ExistingItemState FindExistingItem(
|
||||||
int serverHandle,
|
int serverHandle,
|
||||||
string tagAddress,
|
string tagAddress,
|
||||||
out int itemHandle,
|
out int itemHandle,
|
||||||
@@ -1202,32 +1301,77 @@ public sealed class MxAccessSession : IDisposable
|
|||||||
// no longer walks the whole item table once per tag. The index matches
|
// no longer walks the whole item table once per tag. The index matches
|
||||||
// the tag ordinally and hands the handles back in ascending order — the
|
// the tag ordinally and hands the handles back in ascending order — the
|
||||||
// same order the previous linear scan over the sorted ItemHandles view
|
// same order the previous linear scan over the sorted ItemHandles view
|
||||||
// visited them — so the first advised-and-cached candidate still wins.
|
// visited them — so the first advised-and-cached candidate still wins,
|
||||||
|
// then the first advised one.
|
||||||
IReadOnlyList<int> candidates = handleRegistry.GetItemHandlesForDefinition(serverHandle, tagAddress);
|
IReadOnlyList<int> candidates = handleRegistry.GetItemHandlesForDefinition(serverHandle, tagAddress);
|
||||||
|
|
||||||
|
int firstAdvised = 0;
|
||||||
for (int index = 0; index < candidates.Count; index++)
|
for (int index = 0; index < candidates.Count; index++)
|
||||||
{
|
{
|
||||||
int candidate = candidates[index];
|
int candidate = candidates[index];
|
||||||
|
if (!IsAdvised(serverHandle, candidate))
|
||||||
if (!handleRegistry.ContainsAdviceHandle(serverHandle, candidate, MxAccessAdviceKind.Plain)
|
|
||||||
&& !handleRegistry.ContainsAdviceHandle(serverHandle, candidate, MxAccessAdviceKind.Supervisory))
|
|
||||||
{
|
{
|
||||||
// Tag is added but not advised — no fresh OnDataChange will
|
|
||||||
// arrive without us advising. Fall through to the snapshot
|
|
||||||
// path which advises explicitly.
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (valueCache.TryGet(serverHandle, candidate, out cachedValue))
|
if (valueCache.TryGet(serverHandle, candidate, out cachedValue))
|
||||||
{
|
{
|
||||||
itemHandle = candidate;
|
itemHandle = candidate;
|
||||||
return true;
|
return ExistingItemState.AdvisedAndCached;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (firstAdvised == 0)
|
||||||
|
{
|
||||||
|
firstAdvised = candidate;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
itemHandle = 0;
|
|
||||||
cachedValue = default;
|
cachedValue = default;
|
||||||
return false;
|
itemHandle = firstAdvised;
|
||||||
|
return firstAdvised != 0 ? ExistingItemState.Advised : ExistingItemState.None;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool IsAdvised(
|
||||||
|
int serverHandle,
|
||||||
|
int itemHandle)
|
||||||
|
{
|
||||||
|
return handleRegistry.ContainsAdviceHandle(serverHandle, itemHandle, MxAccessAdviceKind.Plain)
|
||||||
|
|| handleRegistry.ContainsAdviceHandle(serverHandle, itemHandle, MxAccessAdviceKind.Supervisory);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ReadBulk's own AddItem. Unlike <see cref="AddItem"/> it reports
|
||||||
|
/// whether MXAccess handed back a handle the registry already tracks,
|
||||||
|
/// and in that case leaves the existing registration (and its item
|
||||||
|
/// definition and context) untouched, so the caller can tell its own
|
||||||
|
/// snapshot item from an item someone else holds.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="serverHandle">The MXAccess server handle.</param>
|
||||||
|
/// <param name="tagAddress">The tag address to add.</param>
|
||||||
|
/// <param name="alreadyRegistered">
|
||||||
|
/// <see langword="true"/> when the returned handle was already in the
|
||||||
|
/// registry before this AddItem.
|
||||||
|
/// </param>
|
||||||
|
/// <returns>The item handle MXAccess returned.</returns>
|
||||||
|
private int AddSnapshotItem(
|
||||||
|
int serverHandle,
|
||||||
|
string tagAddress,
|
||||||
|
out bool alreadyRegistered)
|
||||||
|
{
|
||||||
|
int itemHandle = mxAccessServer.AddItem(serverHandle, tagAddress);
|
||||||
|
alreadyRegistered = handleRegistry.ContainsItemHandle(serverHandle, itemHandle);
|
||||||
|
if (!alreadyRegistered)
|
||||||
|
{
|
||||||
|
EvictStaleHandleState(serverHandle, itemHandle);
|
||||||
|
handleRegistry.RegisterItemHandle(
|
||||||
|
serverHandle,
|
||||||
|
itemHandle,
|
||||||
|
tagAddress,
|
||||||
|
string.Empty,
|
||||||
|
hasItemContext: false);
|
||||||
|
}
|
||||||
|
|
||||||
|
return itemHandle;
|
||||||
}
|
}
|
||||||
|
|
||||||
private BulkWriteResult ExecuteBulkWriteEntry(
|
private BulkWriteResult ExecuteBulkWriteEntry(
|
||||||
@@ -1597,14 +1741,33 @@ public sealed class MxAccessSession : IDisposable
|
|||||||
/// <summary>Gets the requested tag address.</summary>
|
/// <summary>Gets the requested tag address.</summary>
|
||||||
public string TagAddress { get; }
|
public string TagAddress { get; }
|
||||||
|
|
||||||
/// <summary>Gets or sets the snapshot item handle, 0 until AddItem succeeds.</summary>
|
/// <summary>
|
||||||
|
/// Gets or sets the item handle the read goes through: the caller's
|
||||||
|
/// own handle, or the snapshot handle (0 until AddItem succeeds).
|
||||||
|
/// </summary>
|
||||||
public int ItemHandle { get; set; }
|
public int ItemHandle { get; set; }
|
||||||
|
|
||||||
/// <summary>Gets or sets the value-cache version captured before Advise.</summary>
|
/// <summary>Gets or sets the value-cache version captured before the wait.</summary>
|
||||||
public ulong Baseline { get; set; }
|
public ulong Baseline { get; set; }
|
||||||
|
|
||||||
/// <summary>Gets or sets a value indicating whether Advise succeeded.</summary>
|
/// <summary>
|
||||||
public bool Advised { get; set; }
|
/// Gets or sets a value indicating whether <see cref="ItemHandle"/>
|
||||||
|
/// is an item the session held before this ReadBulk, which teardown
|
||||||
|
/// must never remove.
|
||||||
|
/// </summary>
|
||||||
|
public bool IsCallerItem { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets or sets a value indicating whether this ReadBulk's own
|
||||||
|
/// AddItem created the item, so teardown removes it.
|
||||||
|
/// </summary>
|
||||||
|
public bool OwnsItem { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets or sets a value indicating whether this ReadBulk's own
|
||||||
|
/// Advise created the advice, so teardown unadvises it.
|
||||||
|
/// </summary>
|
||||||
|
public bool OwnsAdvice { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets or sets the earlier snapshot in the same batch whose
|
/// Gets or sets the earlier snapshot in the same batch whose
|
||||||
@@ -1613,6 +1776,19 @@ public sealed class MxAccessSession : IDisposable
|
|||||||
public SnapshotRead? SharedWith { get; set; }
|
public SnapshotRead? SharedWith { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>What the caller has advised for a ReadBulk tag before the read.</summary>
|
||||||
|
private enum ExistingItemState
|
||||||
|
{
|
||||||
|
/// <summary>No advised item for the tag: the read takes a snapshot AddItem.</summary>
|
||||||
|
None,
|
||||||
|
|
||||||
|
/// <summary>An advised item with no cached value: the read waits on that subscription.</summary>
|
||||||
|
Advised,
|
||||||
|
|
||||||
|
/// <summary>An advised item with a cached value: the read is served from the cache.</summary>
|
||||||
|
AdvisedAndCached,
|
||||||
|
}
|
||||||
|
|
||||||
private void ThrowIfDisposed()
|
private void ThrowIfDisposed()
|
||||||
{
|
{
|
||||||
if (disposed)
|
if (disposed)
|
||||||
|
|||||||
Reference in New Issue
Block a user