Compare commits
92 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8e0e232fd6 | |||
| cfaacf7485 | |||
| 8fe50f7cad | |||
| f2720d4e56 | |||
| c102f881b7 | |||
| 3bb6182f91 | |||
| 04655b78fa | |||
| 8045afe174 | |||
| 9293c4c913 | |||
| dbc5ea0c25 | |||
| d1769f81ff | |||
| 00a597b08b | |||
| 1a44b5ac31 | |||
| 30ac3f3225 | |||
| 659bb831a2 | |||
| 08a9cfd68a | |||
| 57d5b7c364 | |||
| e74918ccfb | |||
| 26a90883fa | |||
| b06921ce85 | |||
| c9a6c31cb8 | |||
| 5a1daab9ce | |||
| 260d58afa1 | |||
| 3e004708d4 | |||
| 2cc0d57541 | |||
| 9e4be25807 | |||
| 4890a3d16e | |||
| 453fe01525 | |||
| d9d9ff489b | |||
| 31f7f9fc6e | |||
| 76a71bc82d | |||
| 9ef6fc8489 | |||
| 7481b95905 | |||
| ebbfaa4c03 | |||
| 04a40f2c1a | |||
| 447070a532 | |||
| afd504d5ae | |||
| 892bdc1a19 | |||
| 2b13564e04 | |||
| 9c6ac0cdbc | |||
| 53562ddc17 | |||
| ace12f81ad | |||
| e1656f214b | |||
| 7a7ef3b89f | |||
| 477fa55998 | |||
| 259d375022 | |||
| fccc21ba8e | |||
| 716c845fc7 | |||
| de86f8b80e | |||
| 09b3ecddf2 | |||
| 22964e192b | |||
| 381e772766 | |||
| 2e52f9f5e8 | |||
| 29d9510b4e | |||
| 7d44ecd62d | |||
| 2a91e2b083 | |||
| bc28e1436b | |||
| b47a168a2c | |||
| 82d29beafd | |||
| 0c0c7b86f2 | |||
| d9c60a78eb | |||
| f49b7a0cc1 | |||
| cf575bfca8 | |||
| 0609e810f4 | |||
| 8c21678cb4 | |||
| b5d11e5869 | |||
| 21bab1a982 | |||
| 2f6e480a41 | |||
| f77062f097 | |||
| 07badd139e | |||
| 7b21f304e9 | |||
| 101bda7073 | |||
| 11d8f76c5f | |||
| d56353bf08 | |||
| f829df8087 | |||
| 9906d7e57c | |||
| ad7d2cbef0 | |||
| 7c377cac7b | |||
| e69cd0321e | |||
| f3a452810e | |||
| 417b9e5a19 | |||
| be0d585f8c | |||
| 0d156b56cc | |||
| 8ba5667b7a | |||
| 6130b1338e | |||
| 42f69e4f00 | |||
| fad1c11e44 | |||
| 20138b60cc | |||
| 58e9b6a05a | |||
| 9007966292 | |||
| 0ec247e88c | |||
| f13a747084 |
@@ -3,19 +3,29 @@
|
||||
# Scope note: the x86 Worker (src/ZB.MOM.WW.MxGateway.Worker) and Worker.Tests target
|
||||
# .NET Framework 4.8 / x86 and need MXAccess COM installed, so they build ONLY on a Windows host.
|
||||
# They are out of scope for this Linux `portable` job — the `windows-x86` job below builds and
|
||||
# tests them on windev (10.100.0.48) over SSH (see scripts/ci/run-windev-ci.sh), and the nightly
|
||||
# `nightly-windev` job additionally runs the full solution build, gateway suite, and live-MXAccess
|
||||
# smoke, which are scheduled-only so they never gate a push.
|
||||
# tests them on windev (10.100.0.48) over SSH (see scripts/ci/run-windev-ci.sh).
|
||||
#
|
||||
# There is no scheduled run. The deep windev tier (full-slnx build, gateway suite, live-MXAccess
|
||||
# smoke) is on demand, the same way the clients are packed and published on demand: either
|
||||
# dispatch this workflow by hand with `windev_mode: live`, or run
|
||||
# `CI_SHA=<sha> scripts/ci/run-windev-ci.sh live` from a machine with SSH access to windev.
|
||||
# The old `nightly-windev` cron job failed on most nights for host reasons and filed an issue
|
||||
# each time, so it was removed (2026-11-15).
|
||||
name: ci
|
||||
|
||||
on:
|
||||
push:
|
||||
pull_request:
|
||||
schedule:
|
||||
# 06:00 UTC nightly: x86 Worker build + Worker.Tests, full-slnx build, gateway tests, then the
|
||||
# live-MXAccess smoke (MXGATEWAY_RUN_LIVE_MXACCESS_TESTS=1), serialized on windev's host lock.
|
||||
# Push/PR runs skip it — the job is gated `if: github.event_name == 'schedule'`.
|
||||
- cron: '0 6 * * *'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
windev_mode:
|
||||
description: 'windev tier for the windows-x86 job (test = x86 Worker build + Worker.Tests; live = test + full slnx + gateway suite + live-MXAccess smoke)'
|
||||
type: choice
|
||||
options:
|
||||
- test
|
||||
- build
|
||||
- live
|
||||
default: test
|
||||
|
||||
jobs:
|
||||
portable:
|
||||
@@ -177,47 +187,13 @@ jobs:
|
||||
WINDEV_SSH_KEY: ${{ secrets.WINDEV_SSH_KEY }}
|
||||
WINDEV_SSH_USER: ${{ vars.WINDEV_SSH_USER }}
|
||||
CI_SHA: ${{ github.sha }}
|
||||
# Push/PR runs have no inputs, so they fall back to `test`; a manual dispatch picks the mode.
|
||||
WINDEV_MODE: ${{ inputs.windev_mode || 'test' }}
|
||||
# `test` = x86 build + Worker.Tests (~50s measured on windev). Demote to `build` only if the
|
||||
# test step ever exceeds ~10 min; the x86 build alone still guards the net48/CS0246/x86 class.
|
||||
run: ./scripts/ci/run-windev-ci.sh test
|
||||
|
||||
nightly-windev:
|
||||
# TST-35: scheduled deep run — Worker, full-slnx, gateway, and live-smoke tiers on windev.
|
||||
# Gated to the schedule event via `if:` (not an unsatisfiable `runs-on`), so push/PR runs mark it
|
||||
# skipped, not queued. Never gates a push. On failure it opens a Gitea issue so a red nightly is
|
||||
# visible even though nobody watches the Actions page.
|
||||
if: github.event_name == 'schedule'
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
# `github.server_url` is the URL Gitea hands the runner — the docker-network-internal
|
||||
# `http://gitea:3000`. That is the right base for the issue-creation API call below (the job
|
||||
# container resolves `gitea` only on that network, and has no LAN egress to the public origin),
|
||||
# but it is useless as a link a human clicks out of the issue. So browser-facing URLs in the
|
||||
# issue body use the public origin instead. TST-25 acceptance Check 6 caught this: every
|
||||
# nightly issue since #126 carried an unreachable `http://gitea:3000/...` run link.
|
||||
PUBLIC_SERVER_URL: https://gitea.dohertylan.com
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Worker + gateway tests + live-MXAccess smoke on windev
|
||||
env:
|
||||
# WINDEV_SSH_KEY is stored base64-encoded (single line) so Gitea's line-oriented secret
|
||||
# masker redacts it in the step env echo; run-windev-ci.sh decodes it. A raw multiline PEM
|
||||
# would leak in cleartext here (TST-25 acceptance: no key material in logs). Known-hosts is
|
||||
# public and comes from the committed scripts/ci/windev.known_hosts pin (no secret needed).
|
||||
WINDEV_SSH_KEY: ${{ secrets.WINDEV_SSH_KEY }}
|
||||
WINDEV_SSH_USER: ${{ vars.WINDEV_SSH_USER }}
|
||||
CI_SHA: ${{ github.sha }}
|
||||
run: ./scripts/ci/run-windev-ci.sh live
|
||||
- name: Report a red nightly as a Gitea issue
|
||||
if: failure()
|
||||
run: |
|
||||
curl -sSf -X POST \
|
||||
-H "Authorization: token ${{ github.token }}" \
|
||||
-H "Content-Type: application/json" \
|
||||
"${{ github.server_url }}/api/v1/repos/${{ github.repository }}/issues" \
|
||||
-d "{\"title\":\"nightly-windev failed on ${{ github.sha }}\",\"body\":\"The scheduled windev Worker + live-MXAccess run failed: ${PUBLIC_SERVER_URL}/${{ github.repository }}/actions/runs/${{ github.run_id }} . A red nightly may mean the Windows tier is down rather than the change — see docs/GatewayTesting.md (Continuous Integration).\"}"
|
||||
run: ./scripts/ci/run-windev-ci.sh "$WINDEV_MODE"
|
||||
|
||||
# NOTE: there is intentionally no native `windows` runner job. act_runner v0.6.1 host-mode on
|
||||
# Windows is broken and Windows containers are impractical for the net48/x86/MXAccess Worker, so the
|
||||
# Windows tier runs via the SSH-driven `windows-x86` (per-push) and `nightly-windev` (scheduled)
|
||||
# jobs above. Restore a native job only alongside a Windows runner that actually works.
|
||||
# Windows tier runs via the SSH-driven `windows-x86` job above (per push/PR, or on demand with a
|
||||
# chosen mode via workflow_dispatch). Restore a native job only alongside a Windows runner that actually works.
|
||||
|
||||
@@ -55,12 +55,13 @@ per-project narrative in `../scadaproj/.claude/skills/sister-project-history/<pr
|
||||
(create `mxaccessgateway.md` there if this gateway ever needs one) and shared-library history
|
||||
in `../scadaproj/<lib>/CLAUDE.md`.
|
||||
|
||||
> ⛔ **Wonder box remote access (2026-09-11): no `psbridge`, no `winrm`.** Both skills are retired/disabled —
|
||||
> the WinRM remote-exec channel set off the security software on the wonder boxes (vd03/vq03/vq04). Do not
|
||||
> run remote commands (service control, publish/swap, PowerShell) on those boxes and do not stand up a
|
||||
> replacement channel until the user clears one. Still allowed: UNC/SMB file copies and logging directly
|
||||
> into the SQL Servers. Deploy steps that need a command on the box are blocked; see the umbrella
|
||||
> [`../scadaproj/CLAUDE.md`](../scadaproj/CLAUDE.md) for the current hold.
|
||||
> ⛔ **Wonder box remote access: deployment activities only (re-enabled 2026-09-28).** The `winrm` skill
|
||||
> was disabled 2026-09-11 (WinRM exec set off the security software on vd03/vq03/vq04) and re-enabled
|
||||
> 2026-09-28 scoped to deploys the user asked for: preflight, backup, stop/swap/start, migration,
|
||||
> post-deploy verify, rollback. No ad-hoc diagnostics, log grepping or version checks over WinRM — use
|
||||
> SMB, HTTP or SQL. Always allowed: UNC/SMB file copies and logging directly into the SQL Servers. See
|
||||
> the umbrella [`../scadaproj/CLAUDE.md`](../scadaproj/CLAUDE.md) and
|
||||
> [`docs/runbooks/DeployUpgradeNssmService.md`](docs/runbooks/DeployUpgradeNssmService.md).
|
||||
|
||||
## Build, Test, Run
|
||||
|
||||
|
||||
@@ -137,6 +137,46 @@ gateway's own sentinel observable. Normal events pass through with
|
||||
`IsReplayGap == false` and `ReplayGap == null`. The gap is only ever produced by
|
||||
`StreamEvents`; the diagnostic drain path never emits it. If you already consume
|
||||
the raw `StreamEventsAsync` (or the client-level stream), the
|
||||
### Waiting For The Stream To Attach
|
||||
|
||||
A fresh stream (`afterWorkerSequence == 0`) is never replayed, so an initial value
|
||||
the session publishes before the gateway has registered the stream is lost. That
|
||||
matters for an advise whose only interesting event is its first one (a slow-changing
|
||||
attribute such as `ScanState`). Opening the stream and then waiting an arbitrary
|
||||
interval only narrows the race. `OpenEventStreamAsync` closes it: it asks the
|
||||
gateway for the opt-in **stream-attached sentinel** (`emit_stream_attached`, #227)
|
||||
and completes only when that sentinel arrives, which the gateway sends after it has
|
||||
registered the stream.
|
||||
|
||||
```csharp
|
||||
await using MxGatewayEventStream stream = await session.OpenEventStreamAsync(
|
||||
attachTimeout: TimeSpan.FromSeconds(5));
|
||||
|
||||
// The stream is attached: an advise issued now cannot lose its initial value.
|
||||
await session.SubscribeBulkAsync(addresses);
|
||||
|
||||
await foreach (MxEvent gatewayEvent in stream.ReadAllAsync(cancellationToken))
|
||||
{
|
||||
HandleEvent(gatewayEvent);
|
||||
}
|
||||
```
|
||||
|
||||
The sentinel is consumed by `OpenEventStreamAsync`; `ReadAllAsync` yields only what
|
||||
follows it (a replay-gap sentinel on a resumed stream is still yielded). The method
|
||||
throws `NotSupportedException` without streaming when the session's
|
||||
`OpenSessionReply` lists capabilities but not `stream-events-attached-ack`
|
||||
(`SupportsStreamAttachedAck` is `false`), i.e. the gateway predates #227. A session
|
||||
bound with `AttachSession` carries no capability list, so the request is sent anyway;
|
||||
an older gateway then answers with a normal event (`NotSupportedException`) or nothing
|
||||
(`TimeoutException` once `attachTimeout` elapses).
|
||||
|
||||
Callers that run their own stream loop can use
|
||||
`StreamEventsAsync(afterWorkerSequence, emitStreamAttached: true)` or the typed
|
||||
`StreamEventItemsAsync(afterWorkerSequence, emitStreamAttached: true)` and watch for
|
||||
`MxEvent.StreamAttached` / `MxEventStreamItem.IsStreamAttached`. The sentinel's
|
||||
`WorkerSequence` is `0`: do not store it as the resume cursor. Without
|
||||
`emitStreamAttached` the stream is exactly the pre-#227 shape.
|
||||
|
||||
### Caller-owned channels, resuming sessions, diagnostics
|
||||
|
||||
`MxGatewayClient.Create(GrpcChannel, MxGatewayClientOptions)` and
|
||||
@@ -554,7 +594,7 @@ dotnet nuget add source https://gitea.dohertylan.com/api/packages/dohertj2/nuget
|
||||
Then add the package to your project:
|
||||
|
||||
````bash
|
||||
dotnet add package ZB.MOM.WW.MxGateway.Client --version 0.3.0
|
||||
dotnet add package ZB.MOM.WW.MxGateway.Client --version 0.4.0
|
||||
````
|
||||
|
||||
The `ZB.MOM.WW.MxGateway.Contracts` package is pulled in transitively.
|
||||
|
||||
@@ -126,18 +126,29 @@ internal sealed class FakeGatewayTransport(MxGatewayClientOptions options) : IMx
|
||||
return Task.FromResult(CloseSessionReply);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets an optional behaviour run (before any queued exception) on each InvokeAsync call;
|
||||
/// receives the 1-based attempt number and the call options.
|
||||
/// </summary>
|
||||
public Func<int, CallOptions, Task>? InvokeBehavior { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<MxCommandReply> InvokeAsync(
|
||||
public async Task<MxCommandReply> InvokeAsync(
|
||||
MxCommandRequest request,
|
||||
CallOptions callOptions)
|
||||
{
|
||||
InvokeCalls.Add((request, callOptions));
|
||||
if (InvokeBehavior is not null)
|
||||
{
|
||||
await InvokeBehavior(InvokeCalls.Count, callOptions).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (InvokeExceptions.TryDequeue(out Exception? exception))
|
||||
{
|
||||
throw exception;
|
||||
}
|
||||
|
||||
return Task.FromResult(_invokeReplies.Dequeue());
|
||||
return _invokeReplies.Dequeue();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
using System.Threading.Channels;
|
||||
using Google.Protobuf.WellKnownTypes;
|
||||
using Xunit.Abstractions;
|
||||
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
||||
|
||||
namespace ZB.MOM.WW.MxGateway.Client.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Live proof that <c>Write2</c> applies a value and timestamp through a real gateway (#212).
|
||||
/// The item is advised <b>supervisory</b> first: MXAccess only accepts a user-id-0 write on a
|
||||
/// supervisory-advised item, and a plain advise gets the write refused (or never completed).
|
||||
/// The original value is restored with a plain <c>Write</c> before the test returns.
|
||||
/// </summary>
|
||||
public sealed class LiveGatewayWrite2Tests(ITestOutputHelper output)
|
||||
{
|
||||
private static readonly TimeSpan EventTimeout = TimeSpan.FromSeconds(20);
|
||||
|
||||
/// <summary>Write2 on a supervisory-advised item applies the value; the original is restored.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[LiveGatewayWriteFact]
|
||||
public async Task Write2_SupervisoryAdvise_AppliesValue()
|
||||
{
|
||||
Write2Outcome outcome = await RunWrite2RoundTripAsync();
|
||||
|
||||
Assert.Equal(outcome.WrittenValue, outcome.ObservedValue);
|
||||
Assert.Equal(outcome.OriginalValue, outcome.RestoredValue);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The source timestamp after Write2 equals the timestamp sent. MXAccess reads the VT_DATE
|
||||
/// time argument as box-local time; a worker without the mxaccessgw#228 fix sends UTC clock
|
||||
/// fields, so on a host whose clock is not UTC this fails by the host's UTC offset.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[LiveGatewayWriteFact(requireTimestampOptIn: true)]
|
||||
public async Task Write2_SupervisoryAdvise_KeepsSentTimestamp()
|
||||
{
|
||||
Write2Outcome outcome = await RunWrite2RoundTripAsync();
|
||||
|
||||
Assert.Equal(outcome.WrittenValue, outcome.ObservedValue);
|
||||
Assert.Equal(outcome.SentTimestampUtc, outcome.ObservedTimestampUtc);
|
||||
}
|
||||
|
||||
private async Task<Write2Outcome> RunWrite2RoundTripAsync()
|
||||
{
|
||||
string item = LiveGatewayWriteFactAttribute.WriteItem;
|
||||
await using MxGatewayClient client = MxGatewayClient.Create(new MxGatewayClientOptions
|
||||
{
|
||||
Endpoint = new Uri(LiveGatewayWriteFactAttribute.Endpoint),
|
||||
ApiKey = LiveGatewayWriteFactAttribute.ApiKey,
|
||||
});
|
||||
|
||||
MxGatewaySession session = await client.OpenSessionAsync(new OpenSessionRequest
|
||||
{
|
||||
ClientSessionName = "live-gateway-write2",
|
||||
CommandTimeout = Duration.FromTimeSpan(TimeSpan.FromSeconds(30)),
|
||||
});
|
||||
output.WriteLine($"session {session.SessionId}, item {item}");
|
||||
|
||||
Channel<MxEvent> events = Channel.CreateUnbounded<MxEvent>();
|
||||
using CancellationTokenSource streamCancellation = new();
|
||||
Task streamTask = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
await foreach (MxEvent mxEvent in session.StreamEventsAsync(0, streamCancellation.Token))
|
||||
{
|
||||
events.Writer.TryWrite(mxEvent);
|
||||
}
|
||||
}
|
||||
catch (Exception) when (streamCancellation.IsCancellationRequested)
|
||||
{
|
||||
// Expected at teardown.
|
||||
}
|
||||
});
|
||||
|
||||
int serverHandle = 0;
|
||||
int itemHandle = 0;
|
||||
int? originalValue = null;
|
||||
bool restored = false;
|
||||
try
|
||||
{
|
||||
serverHandle = await session.RegisterAsync("live-gateway-write2");
|
||||
itemHandle = await session.AddItemAsync(serverHandle, item);
|
||||
await session.AdviseSupervisoryAsync(serverHandle, itemHandle);
|
||||
|
||||
MxEvent initial = await WaitForAsync(events, MxEventFamily.OnDataChange, itemHandle);
|
||||
Assert.Equal(MxValue.KindOneofCase.Int32Value, initial.Value.KindCase);
|
||||
originalValue = initial.Value.Int32Value;
|
||||
int writtenValue = originalValue == 212212 ? 212213 : 212212;
|
||||
|
||||
DateTime sent = DateTime.UtcNow.AddSeconds(-30);
|
||||
sent = new DateTime(sent.Ticks - (sent.Ticks % TimeSpan.TicksPerSecond), DateTimeKind.Utc);
|
||||
output.WriteLine($"before: {originalValue} @ {Format(initial.SourceTimestamp)}; Write2 {writtenValue} @ {sent:O}");
|
||||
|
||||
MxCommandReply write2Reply = await session.Write2RawAsync(
|
||||
serverHandle,
|
||||
itemHandle,
|
||||
new MxValue { DataType = MxDataType.Integer, Int32Value = writtenValue },
|
||||
new MxValue { DataType = MxDataType.Time, VariantType = "VT_DATE", TimestampValue = Timestamp.FromDateTime(sent) },
|
||||
userId: 0);
|
||||
Assert.Equal(ProtocolStatusCode.Ok, write2Reply.ProtocolStatus.Code);
|
||||
Assert.Equal(MxCommandKind.Write2, write2Reply.Kind);
|
||||
|
||||
(MxEvent written, MxEvent completion) = await WaitForWriteAsync(events, itemHandle);
|
||||
Assert.All(completion.Statuses, status => Assert.Equal(MxStatusCategory.Ok, status.Category));
|
||||
output.WriteLine($"after Write2: {written.Value.Int32Value} @ {Format(written.SourceTimestamp)}");
|
||||
|
||||
MxCommandReply restoreReply = await session.WriteRawAsync(
|
||||
serverHandle,
|
||||
itemHandle,
|
||||
new MxValue { DataType = MxDataType.Integer, Int32Value = originalValue.Value },
|
||||
userId: 0);
|
||||
Assert.Equal(ProtocolStatusCode.Ok, restoreReply.ProtocolStatus.Code);
|
||||
(MxEvent restoredEvent, _) = await WaitForWriteAsync(events, itemHandle);
|
||||
restored = true;
|
||||
output.WriteLine($"restored: {restoredEvent.Value.Int32Value} @ {Format(restoredEvent.SourceTimestamp)}");
|
||||
|
||||
return new Write2Outcome(
|
||||
originalValue.Value,
|
||||
writtenValue,
|
||||
written.Value.Int32Value,
|
||||
sent,
|
||||
written.SourceTimestamp?.ToDateTime(),
|
||||
restoredEvent.Value.Int32Value);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (!restored && originalValue is not null && itemHandle != 0)
|
||||
{
|
||||
// Best effort: never leave the test value behind when an assertion failed
|
||||
// mid-way. Logged, not thrown, so the original failure is not masked.
|
||||
try
|
||||
{
|
||||
MxCommandReply reply = await session.WriteRawAsync(
|
||||
serverHandle,
|
||||
itemHandle,
|
||||
new MxValue { DataType = MxDataType.Integer, Int32Value = originalValue.Value },
|
||||
userId: 0);
|
||||
output.WriteLine($"restore after failure: {originalValue} -> {reply.ProtocolStatus.Code}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
output.WriteLine($"restore after failure threw {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
await session.CloseAsync();
|
||||
streamCancellation.Cancel();
|
||||
await streamTask;
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<MxEvent> WaitForAsync(Channel<MxEvent> events, MxEventFamily family, int itemHandle)
|
||||
{
|
||||
using CancellationTokenSource timeout = new(EventTimeout);
|
||||
while (true)
|
||||
{
|
||||
MxEvent mxEvent = await events.Reader.ReadAsync(timeout.Token);
|
||||
if (mxEvent.Family == family && mxEvent.ItemHandle == itemHandle)
|
||||
{
|
||||
return mxEvent;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Waits for the OnDataChange and OnWriteComplete a write raises, in either order.</summary>
|
||||
private static async Task<(MxEvent DataChange, MxEvent Completion)> WaitForWriteAsync(Channel<MxEvent> events, int itemHandle)
|
||||
{
|
||||
using CancellationTokenSource timeout = new(EventTimeout);
|
||||
MxEvent? dataChange = null;
|
||||
MxEvent? completion = null;
|
||||
while (dataChange is null || completion is null)
|
||||
{
|
||||
MxEvent mxEvent = await events.Reader.ReadAsync(timeout.Token);
|
||||
if (mxEvent.ItemHandle != itemHandle)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (mxEvent.Family == MxEventFamily.OnDataChange)
|
||||
{
|
||||
dataChange = mxEvent;
|
||||
}
|
||||
else if (mxEvent.Family == MxEventFamily.OnWriteComplete)
|
||||
{
|
||||
completion = mxEvent;
|
||||
}
|
||||
}
|
||||
|
||||
return (dataChange, completion);
|
||||
}
|
||||
|
||||
private static string Format(Timestamp? timestamp) =>
|
||||
timestamp is null ? "-" : timestamp.ToDateTime().ToString("O");
|
||||
|
||||
private sealed record Write2Outcome(
|
||||
int OriginalValue,
|
||||
int WrittenValue,
|
||||
int ObservedValue,
|
||||
DateTime SentTimestampUtc,
|
||||
DateTime? ObservedTimestampUtc,
|
||||
int RestoredValue);
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
namespace ZB.MOM.WW.MxGateway.Client.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Marks a test that writes to a real Galaxy attribute through a running gateway.
|
||||
/// The test is skipped unless an endpoint, an API key and a write item are all set,
|
||||
/// so it never runs (or writes) by accident. See <c>docs/GatewayTesting.md</c>, "Live gateway write".
|
||||
/// </summary>
|
||||
public sealed class LiveGatewayWriteFactAttribute : FactAttribute
|
||||
{
|
||||
/// <summary>Gateway gRPC endpoint, e.g. <c>http://host:5120</c>.</summary>
|
||||
public const string EndpointVariableName = "MXGATEWAY_LIVE_GATEWAY_ENDPOINT";
|
||||
|
||||
/// <summary>API key (<c>mxgw_<id>_<secret></c>). Prefer the file variant so the key stays out of the environment.</summary>
|
||||
public const string ApiKeyVariableName = "MXGATEWAY_LIVE_GATEWAY_API_KEY";
|
||||
|
||||
/// <summary>Path to a file holding the API key. Takes precedence over <see cref="ApiKeyVariableName"/>.</summary>
|
||||
public const string ApiKeyFileVariableName = "MXGATEWAY_LIVE_GATEWAY_API_KEY_FILE";
|
||||
|
||||
/// <summary>A writable, test-only Int32 attribute. It is written and then restored. No default on purpose.</summary>
|
||||
public const string WriteItemVariableName = "MXGATEWAY_LIVE_GATEWAY_WRITE_ITEM";
|
||||
|
||||
/// <summary>Set to <c>1</c> to also run the Write2 timestamp-parity test (fails on a non-UTC host until #228 is fixed).</summary>
|
||||
public const string AssertWrite2TimestampVariableName = "MXGATEWAY_LIVE_GATEWAY_ASSERT_WRITE2_TIMESTAMP";
|
||||
|
||||
/// <summary>Initializes the attribute, skipping unless the live gateway write variables are set.</summary>
|
||||
/// <param name="requireTimestampOptIn">When true, also require <see cref="AssertWrite2TimestampVariableName"/>=1.</param>
|
||||
public LiveGatewayWriteFactAttribute(bool requireTimestampOptIn = false)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(EndpointVariableName))
|
||||
|| string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(WriteItemVariableName))
|
||||
|| (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(ApiKeyVariableName))
|
||||
&& string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(ApiKeyFileVariableName))))
|
||||
{
|
||||
Skip = $"Set {EndpointVariableName}, {WriteItemVariableName} and {ApiKeyFileVariableName} (or {ApiKeyVariableName}) to run live gateway write tests.";
|
||||
}
|
||||
else if (requireTimestampOptIn
|
||||
&& Environment.GetEnvironmentVariable(AssertWrite2TimestampVariableName) != "1")
|
||||
{
|
||||
Skip = $"Set {AssertWrite2TimestampVariableName}=1 to assert Write2 timestamp parity (mxaccessgw#228).";
|
||||
}
|
||||
}
|
||||
|
||||
internal static string Endpoint => Environment.GetEnvironmentVariable(EndpointVariableName)!;
|
||||
|
||||
internal static string WriteItem => Environment.GetEnvironmentVariable(WriteItemVariableName)!;
|
||||
|
||||
internal static string ApiKey
|
||||
{
|
||||
get
|
||||
{
|
||||
string? path = Environment.GetEnvironmentVariable(ApiKeyFileVariableName);
|
||||
return !string.IsNullOrWhiteSpace(path)
|
||||
? File.ReadAllText(path).Trim()
|
||||
: Environment.GetEnvironmentVariable(ApiKeyVariableName)!.Trim();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -223,6 +223,47 @@ public sealed class MxGatewayClientSessionTests
|
||||
Assert.Equal("session-fixture", request.SessionId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #227: the default stream call leaves emit_stream_attached unset (the pre-#227 wire shape);
|
||||
/// the opt-in overload sets it and surfaces the sentinel as a typed item.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task StreamEventItemsAsync_OptIn_SurfacesStreamAttachedSentinel()
|
||||
{
|
||||
FakeGatewayTransport transport = CreateTransport();
|
||||
transport.AddEvent(new MxEvent
|
||||
{
|
||||
SessionId = "session-fixture",
|
||||
StreamAttached = new StreamAttached { LiveAfterSequence = 0 },
|
||||
});
|
||||
transport.AddEvent(new MxEvent
|
||||
{
|
||||
SessionId = "session-fixture",
|
||||
Family = MxEventFamily.OnDataChange,
|
||||
WorkerSequence = 1,
|
||||
});
|
||||
await using MxGatewayClient client = CreateClient(transport);
|
||||
MxGatewaySession session = await client.OpenSessionAsync();
|
||||
|
||||
await foreach (MxEvent _ in session.StreamEventsAsync())
|
||||
{
|
||||
}
|
||||
|
||||
List<MxEventStreamItem> items = [];
|
||||
await foreach (MxEventStreamItem item in session.StreamEventItemsAsync(0, emitStreamAttached: true))
|
||||
{
|
||||
items.Add(item);
|
||||
}
|
||||
|
||||
Assert.False(transport.StreamEventsCalls[0].Request.EmitStreamAttached);
|
||||
Assert.True(transport.StreamEventsCalls[1].Request.EmitStreamAttached);
|
||||
Assert.True(items[0].IsStreamAttached);
|
||||
Assert.False(items[0].IsReplayGap);
|
||||
Assert.False(items[1].IsStreamAttached);
|
||||
Assert.Equal(1UL, items[1].Event.WorkerSequence);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that a reconnect-replay gap sentinel is surfaced as a typed
|
||||
/// <see cref="MxEventStreamItem"/> with the gap populated, while normal
|
||||
@@ -315,6 +356,80 @@ public sealed class MxGatewayClientSessionTests
|
||||
Assert.Equal(2, transport.InvokeCalls.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that a first attempt which runs to its own call deadline and fails with DeadlineExceeded
|
||||
/// does not exhaust the retry budget (mxaccessgw#197): the retry still runs and succeeds.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task InvokeAsync_RetriesAfterFirstAttemptRunsToItsDeadline()
|
||||
{
|
||||
FakeGatewayTransport transport = new(new MxGatewayClientOptions
|
||||
{
|
||||
Endpoint = new Uri("http://localhost:5000"),
|
||||
ApiKey = "test-api-key",
|
||||
DefaultCallTimeout = TimeSpan.FromMilliseconds(400),
|
||||
Retry = new MxGatewayClientRetryOptions
|
||||
{
|
||||
MaxAttempts = 2,
|
||||
Delay = TimeSpan.FromMilliseconds(10),
|
||||
MaxDelay = TimeSpan.FromMilliseconds(20),
|
||||
},
|
||||
});
|
||||
transport.AddInvokeReply(new MxCommandReply
|
||||
{
|
||||
SessionId = "session-fixture",
|
||||
Kind = MxCommandKind.Ping,
|
||||
ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok },
|
||||
});
|
||||
transport.InvokeBehavior = async (attempt, callOptions) =>
|
||||
{
|
||||
if (attempt != 1)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Simulate a gateway that never answers: block until this attempt's own deadline,
|
||||
// then fail the way gRPC does.
|
||||
TimeSpan remaining = callOptions.Deadline!.Value - DateTime.UtcNow;
|
||||
if (remaining > TimeSpan.Zero)
|
||||
{
|
||||
await Task.Delay(remaining + TimeSpan.FromMilliseconds(20));
|
||||
}
|
||||
|
||||
throw new RpcException(new Status(StatusCode.DeadlineExceeded, "deadline"));
|
||||
};
|
||||
await using MxGatewayClient client = CreateClient(transport);
|
||||
MxGatewaySession session = await client.OpenSessionAsync();
|
||||
|
||||
await session.InvokeAsync(new MxCommandRequest
|
||||
{
|
||||
SessionId = session.SessionId,
|
||||
Command = new MxCommand { Kind = MxCommandKind.Ping, Ping = new PingCommand() },
|
||||
});
|
||||
|
||||
Assert.Equal(2, transport.InvokeCalls.Count);
|
||||
}
|
||||
|
||||
/// <summary>Verifies the overall retry budget spans every attempt plus back-off.</summary>
|
||||
[Fact]
|
||||
public void ComputeOverallBudget_CoversAllAttemptsAndBackoff()
|
||||
{
|
||||
MxGatewayClientRetryOptions retry = new()
|
||||
{
|
||||
MaxAttempts = 3,
|
||||
Delay = TimeSpan.FromSeconds(1),
|
||||
MaxDelay = TimeSpan.FromSeconds(2),
|
||||
};
|
||||
|
||||
Assert.Equal(
|
||||
TimeSpan.FromSeconds((3 * 30) + (2 * 2)),
|
||||
MxGatewayClientRetryPolicy.ComputeOverallBudget(retry, TimeSpan.FromSeconds(30)));
|
||||
Assert.Equal(
|
||||
TimeSpan.FromSeconds(30),
|
||||
MxGatewayClientRetryPolicy.ComputeOverallBudget(new MxGatewayClientRetryOptions { MaxAttempts = 1 }, TimeSpan.FromSeconds(30)));
|
||||
}
|
||||
|
||||
/// <summary>Verifies that open session does not retry on transient RPC failure.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
|
||||
@@ -130,6 +130,87 @@ public sealed class MxGatewayClientWireTests
|
||||
Assert.Equal(3ul, server.Service.StreamEventsRequest?.AfterWorkerSequence);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #227: <see cref="MxGatewaySession.OpenEventStreamAsync"/> asks for the attach
|
||||
/// acknowledgement, completes on the sentinel, and yields only the events after it.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task OpenEventStreamAsync_AwaitsTheAttachSentinel_ThenYieldsLaterEvents()
|
||||
{
|
||||
await using WireFakeGatewayServer server = await WireFakeGatewayServer.StartAsync(service =>
|
||||
service.SupportsStreamAttached = true);
|
||||
await using MxGatewayClient client = server.CreateClient(ApiKey);
|
||||
MxGatewaySession session = await client.OpenSessionAsync(new OpenSessionRequest());
|
||||
Assert.True(session.SupportsStreamAttachedAck);
|
||||
|
||||
await using MxGatewayEventStream stream = await session.OpenEventStreamAsync(
|
||||
attachTimeout: TimeSpan.FromSeconds(10));
|
||||
|
||||
Assert.True(server.Service.StreamEventsRequest?.EmitStreamAttached);
|
||||
Assert.Equal(0ul, stream.Attached.LiveAfterSequence);
|
||||
|
||||
List<MxEvent> events = [];
|
||||
await foreach (MxEvent gatewayEvent in stream.ReadAllAsync())
|
||||
{
|
||||
events.Add(gatewayEvent);
|
||||
}
|
||||
|
||||
MxEvent only = Assert.Single(events);
|
||||
Assert.Null(only.StreamAttached);
|
||||
Assert.Equal(9ul, only.WorkerSequence);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #227: a session whose gateway does not advertise the capability fails fast with
|
||||
/// <see cref="NotSupportedException"/> and never opens a stream.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task OpenEventStreamAsync_OnGatewayWithoutCapability_ThrowsWithoutStreaming()
|
||||
{
|
||||
await using WireFakeGatewayServer server = await WireFakeGatewayServer.StartAsync();
|
||||
await using MxGatewayClient client = server.CreateClient(ApiKey);
|
||||
MxGatewaySession session = await client.OpenSessionAsync(new OpenSessionRequest());
|
||||
Assert.False(session.SupportsStreamAttachedAck);
|
||||
|
||||
await Assert.ThrowsAsync<NotSupportedException>(() => session.OpenEventStreamAsync());
|
||||
Assert.Null(server.Service.StreamEventsRequest);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #227: a session bound with AttachSession (no capability list) against an older gateway
|
||||
/// sees a normal event first and is refused rather than handed an unacknowledged stream.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task OpenEventStreamAsync_AttachedSessionOnOlderGateway_RejectsNonSentinelFirstMessage()
|
||||
{
|
||||
await using WireFakeGatewayServer server = await WireFakeGatewayServer.StartAsync();
|
||||
await using MxGatewayClient client = server.CreateClient(ApiKey);
|
||||
MxGatewaySession session = client.AttachSession(WireFakeGatewayServer.FakeGatewayService.SessionId);
|
||||
|
||||
await Assert.ThrowsAsync<NotSupportedException>(
|
||||
() => session.OpenEventStreamAsync(attachTimeout: TimeSpan.FromSeconds(10)));
|
||||
Assert.True(server.Service.StreamEventsRequest?.EmitStreamAttached);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #227: against a quiet older gateway nothing arrives; the attach timeout bounds the wait.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task OpenEventStreamAsync_WhenNoSentinelArrives_TimesOut()
|
||||
{
|
||||
await using WireFakeGatewayServer server = await WireFakeGatewayServer.StartAsync(service =>
|
||||
service.StallStream = true);
|
||||
await using MxGatewayClient client = server.CreateClient(ApiKey);
|
||||
MxGatewaySession session = client.AttachSession(WireFakeGatewayServer.FakeGatewayService.SessionId);
|
||||
|
||||
await Assert.ThrowsAsync<TimeoutException>(
|
||||
() => session.OpenEventStreamAsync(attachTimeout: TimeSpan.FromMilliseconds(200)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies a genuine <c>PERMISSION_DENIED</c> status maps to the typed client
|
||||
/// exception rather than a bare RpcException.
|
||||
@@ -149,6 +230,57 @@ public sealed class MxGatewayClientWireTests
|
||||
() => session.RegisterAsync("wire-test-client"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A <c>RESOURCE_EXHAUSTED</c> status carrying the <c>mxgw-reason</c> trailer surfaces the
|
||||
/// reason as a typed property, so overflow and limit rejections can be told apart.
|
||||
/// </summary>
|
||||
/// <param name="reason">The reason code the fake gateway attaches.</param>
|
||||
/// <param name="overflow">Whether the client should classify it as an overflow.</param>
|
||||
/// <param name="limit">Whether the client should classify it as a subscriber-limit rejection.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Theory]
|
||||
[InlineData("event-queue-overflow", true, false)]
|
||||
[InlineData("subscriber-limit", false, true)]
|
||||
public async Task ResourceExhaustedStatus_ExposesReasonFromTrailer(string reason, bool overflow, bool limit)
|
||||
{
|
||||
await using WireFakeGatewayServer server = await WireFakeGatewayServer.StartAsync(
|
||||
service =>
|
||||
{
|
||||
service.ExhaustInvoke = true;
|
||||
service.ExhaustedReason = reason;
|
||||
});
|
||||
await using MxGatewayClient client = server.CreateClient(ApiKey);
|
||||
MxGatewaySession session = await client.OpenSessionAsync(
|
||||
new OpenSessionRequest { ClientSessionName = "wire-test" });
|
||||
|
||||
MxGatewayResourceExhaustedException exception =
|
||||
await Assert.ThrowsAsync<MxGatewayResourceExhaustedException>(
|
||||
() => session.RegisterAsync("wire-test-client"));
|
||||
|
||||
Assert.Equal(reason, exception.Reason);
|
||||
Assert.Equal(overflow, exception.IsOverflow);
|
||||
Assert.Equal(limit, exception.IsSubscriberLimit);
|
||||
Assert.IsAssignableFrom<MxGatewayException>(exception);
|
||||
}
|
||||
|
||||
/// <summary>A <c>RESOURCE_EXHAUSTED</c> from an older gateway (no trailer) has a null reason.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task ResourceExhaustedStatus_WithoutTrailer_HasNullReason()
|
||||
{
|
||||
await using WireFakeGatewayServer server = await WireFakeGatewayServer.StartAsync(
|
||||
service => service.ExhaustInvoke = true);
|
||||
await using MxGatewayClient client = server.CreateClient(ApiKey);
|
||||
MxGatewaySession session = await client.OpenSessionAsync(
|
||||
new OpenSessionRequest { ClientSessionName = "wire-test" });
|
||||
|
||||
MxGatewayResourceExhaustedException exception =
|
||||
await Assert.ThrowsAsync<MxGatewayResourceExhaustedException>(
|
||||
() => session.RegisterAsync("wire-test-client"));
|
||||
|
||||
Assert.Null(exception.Reason);
|
||||
}
|
||||
|
||||
private static async Task<List<MxEvent>> CollectAsync(IAsyncEnumerable<MxEvent> stream)
|
||||
{
|
||||
List<MxEvent> events = [];
|
||||
|
||||
@@ -140,11 +140,34 @@ internal sealed class WireFakeGatewayServer : IAsyncDisposable
|
||||
/// </summary>
|
||||
public bool DenyInvoke { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether <c>Invoke</c> fails with
|
||||
/// <see cref="StatusCode.ResourceExhausted"/>; <see cref="ExhaustedReason"/> (when set) rides the
|
||||
/// <c>mxgw-reason</c> trailer the way the real gateway attaches it.
|
||||
/// </summary>
|
||||
public bool ExhaustInvoke { get; set; }
|
||||
|
||||
/// <summary>Gets or sets the reason-code trailer value sent with the exhausted failure.</summary>
|
||||
public string? ExhaustedReason { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the replay-gap sentinel emitted at the head of the event stream.
|
||||
/// </summary>
|
||||
public ReplayGap? ReplayGap { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether this fake behaves as a #227 gateway: it advertises the
|
||||
/// attach-acknowledgement capability and, when a request asks for it, writes the
|
||||
/// stream-attached sentinel first. False models a gateway that predates #227.
|
||||
/// </summary>
|
||||
public bool SupportsStreamAttached { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether the stream stalls (until the call is cancelled) instead of
|
||||
/// writing the canned data-change event — a quiet session on an older gateway.
|
||||
/// </summary>
|
||||
public bool StallStream { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the last <c>Invoke</c> request the client sent, as decoded from the wire.
|
||||
/// </summary>
|
||||
@@ -166,7 +189,7 @@ internal sealed class WireFakeGatewayServer : IAsyncDisposable
|
||||
ServerCallContext context)
|
||||
{
|
||||
Record(context);
|
||||
return Task.FromResult(new OpenSessionReply
|
||||
OpenSessionReply reply = new()
|
||||
{
|
||||
SessionId = SessionId,
|
||||
BackendName = "fake-backend",
|
||||
@@ -175,7 +198,13 @@ internal sealed class WireFakeGatewayServer : IAsyncDisposable
|
||||
GatewayProtocolVersion = 3,
|
||||
Capabilities = { "events", "invoke" },
|
||||
ProtocolStatus = Ok(),
|
||||
});
|
||||
};
|
||||
if (SupportsStreamAttached)
|
||||
{
|
||||
reply.Capabilities.Add(ZB.MOM.WW.MxGateway.Contracts.GatewayCapabilities.StreamEventsAttachedAck);
|
||||
}
|
||||
|
||||
return Task.FromResult(reply);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
@@ -189,6 +218,17 @@ internal sealed class WireFakeGatewayServer : IAsyncDisposable
|
||||
throw new RpcException(new Status(StatusCode.PermissionDenied, "invoke scope required"));
|
||||
}
|
||||
|
||||
if (ExhaustInvoke)
|
||||
{
|
||||
Metadata trailers = [];
|
||||
if (ExhaustedReason is not null)
|
||||
{
|
||||
trailers.Add(ZB.MOM.WW.MxGateway.Contracts.ResourceExhaustedReasons.TrailerKey, ExhaustedReason);
|
||||
}
|
||||
|
||||
throw new RpcException(new Status(StatusCode.ResourceExhausted, "exhausted"), trailers);
|
||||
}
|
||||
|
||||
return Task.FromResult(new MxCommandReply
|
||||
{
|
||||
SessionId = request.SessionId,
|
||||
@@ -209,6 +249,21 @@ internal sealed class WireFakeGatewayServer : IAsyncDisposable
|
||||
Record(context);
|
||||
StreamEventsRequest = request;
|
||||
|
||||
if (SupportsStreamAttached && request.EmitStreamAttached)
|
||||
{
|
||||
// The #227 sentinel shape: family unspecified, body unset, worker_sequence 0.
|
||||
await responseStream.WriteAsync(new MxEvent
|
||||
{
|
||||
SessionId = request.SessionId,
|
||||
StreamAttached = new StreamAttached { LiveAfterSequence = request.AfterWorkerSequence },
|
||||
}).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (StallStream)
|
||||
{
|
||||
await Task.Delay(Timeout.InfiniteTimeSpan, context.CancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (ReplayGap is not null)
|
||||
{
|
||||
// The sentinel shape the gateway emits: family unspecified, body unset,
|
||||
|
||||
@@ -518,7 +518,10 @@ public sealed class GalaxyRepositoryClient : IAsyncDisposable
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
using CancellationTokenSource timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
timeout.CancelAfter(Options.DefaultCallTimeout);
|
||||
// Outer budget covers every attempt (each carries its own DefaultCallTimeout deadline)
|
||||
// plus back-off; capping it at one DefaultCallTimeout starved retries of a
|
||||
// DeadlineExceeded first attempt (mxaccessgw#197).
|
||||
timeout.CancelAfter(MxGatewayClientRetryPolicy.ComputeOverallBudget(Options.Retry, Options.DefaultCallTimeout));
|
||||
|
||||
return await _safeUnaryRetryPipeline.ExecuteAsync(
|
||||
async token => await call(token).ConfigureAwait(false),
|
||||
|
||||
@@ -255,6 +255,10 @@ internal sealed class GrpcMxGatewayClientTransport(
|
||||
StatusCode.PermissionDenied => new MxGatewayAuthorizationException(
|
||||
exception.Status.Detail,
|
||||
innerException: exception),
|
||||
StatusCode.ResourceExhausted => new MxGatewayResourceExhaustedException(
|
||||
exception.Status.Detail,
|
||||
MxGatewayResourceExhaustedException.ReadReason(exception),
|
||||
exception),
|
||||
_ => new MxGatewayException(exception.Status.Detail, exception),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ public static class MxEventStreamExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Projects a raw <see cref="MxEvent"/> stream (e.g.
|
||||
/// <see cref="MxGatewaySession.StreamEventsAsync"/> or
|
||||
/// <see cref="MxGatewaySession.StreamEventsAsync(ulong, CancellationToken)"/> or
|
||||
/// <see cref="MxGatewayClient.StreamEventsAsync"/>) into typed
|
||||
/// <see cref="MxEventStreamItem"/> values. Normal events pass through with
|
||||
/// <see cref="MxEventStreamItem.IsReplayGap"/> false; the gateway's
|
||||
|
||||
@@ -4,7 +4,8 @@ namespace ZB.MOM.WW.MxGateway.Client;
|
||||
|
||||
/// <summary>
|
||||
/// One item yielded by the typed event stream. It is either a normal MXAccess
|
||||
/// <see cref="MxEvent"/> or a reconnect-replay <em>gap sentinel</em>.
|
||||
/// <see cref="MxEvent"/>, a reconnect-replay <em>gap sentinel</em>, or — only on a stream
|
||||
/// that asked for it — the <em>stream-attached sentinel</em> (#227).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
@@ -30,13 +31,21 @@ namespace ZB.MOM.WW.MxGateway.Client;
|
||||
/// incurring another gap, reconnect with
|
||||
/// <c>after_worker_sequence = ReplayGap.OldestAvailableSequence - 1</c>.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// When the stream was opened with <c>emit_stream_attached</c>, its first item is the
|
||||
/// stream-attached sentinel: <see cref="IsStreamAttached"/> is <see langword="true"/> and
|
||||
/// <see cref="StreamAttached"/> is populated. It means the gateway has registered the stream,
|
||||
/// so every event published from then on is delivered. Its <c>worker_sequence</c> is 0 and
|
||||
/// must not be used as a resume cursor.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class MxEventStreamItem
|
||||
{
|
||||
private MxEventStreamItem(MxEvent gatewayEvent, ReplayGap? replayGap)
|
||||
private MxEventStreamItem(MxEvent gatewayEvent, ReplayGap? replayGap, StreamAttached? streamAttached)
|
||||
{
|
||||
Event = gatewayEvent;
|
||||
ReplayGap = replayGap;
|
||||
StreamAttached = streamAttached;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -64,6 +73,20 @@ public sealed class MxEventStreamItem
|
||||
/// </summary>
|
||||
public bool IsReplayGap => ReplayGap is not null;
|
||||
|
||||
/// <summary>
|
||||
/// The attach acknowledgement when this item is the stream-attached sentinel (#227);
|
||||
/// otherwise <see langword="null"/>. Only a stream opened with
|
||||
/// <c>emit_stream_attached</c> carries it, and only as its first item.
|
||||
/// </summary>
|
||||
public StreamAttached? StreamAttached { get; }
|
||||
|
||||
/// <summary>
|
||||
/// <see langword="true"/> when this item is the stream-attached sentinel: the gateway has
|
||||
/// registered the stream, so an advise issued after this point cannot lose its initial value
|
||||
/// to the attach race.
|
||||
/// </summary>
|
||||
public bool IsStreamAttached => StreamAttached is not null;
|
||||
|
||||
/// <summary>
|
||||
/// Wraps a raw stream <see cref="MxEvent"/> as a typed item, classifying it
|
||||
/// as a replay-gap sentinel when <c>MxEvent.replay_gap</c> is present.
|
||||
@@ -75,8 +98,6 @@ public sealed class MxEventStreamItem
|
||||
ArgumentNullException.ThrowIfNull(gatewayEvent);
|
||||
|
||||
// For a message-typed proto3 field, presence is a non-null reference.
|
||||
return gatewayEvent.ReplayGap is { } replayGap
|
||||
? new MxEventStreamItem(gatewayEvent, replayGap)
|
||||
: new MxEventStreamItem(gatewayEvent, replayGap: null);
|
||||
return new MxEventStreamItem(gatewayEvent, gatewayEvent.ReplayGap, gatewayEvent.StreamAttached);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,7 +123,7 @@ public sealed class MxGatewayClient : IAsyncDisposable
|
||||
/// <summary>
|
||||
/// Binds a session object to an existing gateway session id without calling
|
||||
/// OpenSession, so a reconnecting process can resume
|
||||
/// <see cref="MxGatewaySession.StreamEventsAsync"/> with <c>afterWorkerSequence</c>.
|
||||
/// <see cref="MxGatewaySession.StreamEventsAsync(ulong, CancellationToken)"/> with <c>afterWorkerSequence</c>.
|
||||
/// The gateway only allows the API key that opened the session to stream its events
|
||||
/// or invoke commands on it; any other key is rejected with PermissionDenied. The
|
||||
/// returned session's <see cref="MxGatewaySession.OpenSessionReply"/> carries only the
|
||||
@@ -376,7 +376,10 @@ public sealed class MxGatewayClient : IAsyncDisposable
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
using CancellationTokenSource timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
timeout.CancelAfter(Options.DefaultCallTimeout);
|
||||
// Outer budget covers every attempt (each carries its own DefaultCallTimeout deadline)
|
||||
// plus back-off; capping it at one DefaultCallTimeout starved retries of a
|
||||
// DeadlineExceeded first attempt (mxaccessgw#197).
|
||||
timeout.CancelAfter(MxGatewayClientRetryPolicy.ComputeOverallBudget(Options.Retry, Options.DefaultCallTimeout));
|
||||
|
||||
return await _safeUnaryRetryPipeline.ExecuteAsync(
|
||||
async token => await call(token).ConfigureAwait(false),
|
||||
|
||||
@@ -41,6 +41,29 @@ internal static class MxGatewayClientRetryPolicy
|
||||
.Build();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes the overall time budget for a retried unary call: every attempt gets its own
|
||||
/// <paramref name="callTimeout"/> deadline, plus the worst-case back-off between attempts.
|
||||
/// An outer cap equal to a single <paramref name="callTimeout"/> would let a
|
||||
/// <c>DeadlineExceeded</c> first attempt consume the whole budget so no retry could ever run.
|
||||
/// </summary>
|
||||
/// <param name="options">Retry configuration.</param>
|
||||
/// <param name="callTimeout">The per-attempt call timeout.</param>
|
||||
/// <returns>The overall budget, or <see cref="Timeout.InfiniteTimeSpan"/> if it exceeds the timer range.</returns>
|
||||
public static TimeSpan ComputeOverallBudget(MxGatewayClientRetryOptions options, TimeSpan callTimeout)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
|
||||
int attempts = Math.Max(1, options.MaxAttempts);
|
||||
double totalMs = (callTimeout.TotalMilliseconds * attempts)
|
||||
+ (options.MaxDelay.TotalMilliseconds * (attempts - 1));
|
||||
|
||||
// CancellationTokenSource.CancelAfter accepts at most int.MaxValue milliseconds.
|
||||
return totalMs >= int.MaxValue
|
||||
? Timeout.InfiniteTimeSpan
|
||||
: TimeSpan.FromMilliseconds(totalMs);
|
||||
}
|
||||
|
||||
/// <summary>Returns whether a command kind is eligible for automatic retry on transient failures.</summary>
|
||||
/// <param name="kind">The command kind to check.</param>
|
||||
/// <returns><see langword="true"/> if the command kind may be automatically retried; otherwise, <see langword="false"/>.</returns>
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
||||
|
||||
namespace ZB.MOM.WW.MxGateway.Client;
|
||||
|
||||
/// <summary>
|
||||
/// An event stream the gateway has confirmed attached (#227), returned by
|
||||
/// <see cref="MxGatewaySession.OpenEventStreamAsync"/>. Its existence is the attach signal:
|
||||
/// every event the session publishes after it was created reaches <see cref="ReadAllAsync"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The stream-attached sentinel is consumed when the stream opens and is not yielded again.
|
||||
/// A replay-gap sentinel on a resumed stream is a normal stream item and is yielded as-is
|
||||
/// (inspect <see cref="MxEvent.ReplayGap"/>, or wrap with
|
||||
/// <see cref="MxEventStreamExtensions.AsStreamItemsAsync"/>). Dispose to end the call.
|
||||
/// </remarks>
|
||||
public sealed class MxGatewayEventStream : IAsyncDisposable
|
||||
{
|
||||
private readonly IAsyncEnumerator<MxEvent> _enumerator;
|
||||
private readonly CancellationTokenSource _lifetime;
|
||||
private int _readStarted;
|
||||
private int _disposed;
|
||||
|
||||
private MxGatewayEventStream(
|
||||
IAsyncEnumerator<MxEvent> enumerator,
|
||||
CancellationTokenSource lifetime,
|
||||
StreamAttached attached)
|
||||
{
|
||||
_enumerator = enumerator;
|
||||
_lifetime = lifetime;
|
||||
Attached = attached;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The gateway's attach acknowledgement. Live events on this stream have a
|
||||
/// <c>worker_sequence</c> strictly greater than <see cref="StreamAttached.LiveAfterSequence"/>.
|
||||
/// </summary>
|
||||
public StreamAttached Attached { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Reads the events that follow the attach acknowledgement. May be enumerated once.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Cancels the enumeration and ends the stream.</param>
|
||||
/// <returns>The remaining events, in gateway order.</returns>
|
||||
/// <exception cref="InvalidOperationException">The stream was already enumerated.</exception>
|
||||
public async IAsyncEnumerable<MxEvent> ReadAllAsync(
|
||||
[EnumeratorCancellation] CancellationToken cancellationToken = default)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this);
|
||||
if (Interlocked.Exchange(ref _readStarted, 1) != 0)
|
||||
{
|
||||
throw new InvalidOperationException("The event stream can be enumerated only once.");
|
||||
}
|
||||
|
||||
using CancellationTokenRegistration registration = cancellationToken.Register(
|
||||
static state => ((CancellationTokenSource)state!).Cancel(),
|
||||
_lifetime);
|
||||
|
||||
while (await _enumerator.MoveNextAsync().ConfigureAwait(false))
|
||||
{
|
||||
yield return _enumerator.Current;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Cancels the underlying call and releases it.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) != 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await _lifetime.CancelAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await _enumerator.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_lifetime.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
// Opens the stream and consumes the first message, which must be the stream-attached
|
||||
// sentinel. Anything else means the gateway ignored the request (it predates #227): the
|
||||
// stream is closed rather than handed out, because it cannot keep the attach promise.
|
||||
internal static async Task<MxGatewayEventStream> OpenAsync(
|
||||
Func<CancellationToken, IAsyncEnumerable<MxEvent>> openStream,
|
||||
string sessionId,
|
||||
TimeSpan? attachTimeout,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
CancellationTokenSource lifetime = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
IAsyncEnumerator<MxEvent> enumerator = openStream(lifetime.Token).GetAsyncEnumerator(lifetime.Token);
|
||||
Task<bool>? first = null;
|
||||
bool handedOff = false;
|
||||
try
|
||||
{
|
||||
first = enumerator.MoveNextAsync().AsTask();
|
||||
bool hasFirst;
|
||||
try
|
||||
{
|
||||
hasFirst = attachTimeout is { } timeout
|
||||
? await first.WaitAsync(timeout, cancellationToken).ConfigureAwait(false)
|
||||
: await first.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (TimeoutException) when (!first.IsCompleted)
|
||||
{
|
||||
throw new TimeoutException(
|
||||
$"The gateway did not acknowledge the event-stream attach for session {sessionId} within {attachTimeout}.");
|
||||
}
|
||||
|
||||
if (!hasFirst)
|
||||
{
|
||||
throw new MxGatewayException(
|
||||
$"The gateway ended the event stream for session {sessionId} before acknowledging the attach.");
|
||||
}
|
||||
|
||||
if (enumerator.Current.StreamAttached is not { } attached)
|
||||
{
|
||||
throw new NotSupportedException(
|
||||
$"The gateway's first event-stream message for session {sessionId} was not the attach "
|
||||
+ "acknowledgement; the gateway does not support emit_stream_attached.");
|
||||
}
|
||||
|
||||
MxGatewayEventStream stream = new(enumerator, lifetime, attached);
|
||||
handedOff = true;
|
||||
return stream;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (!handedOff)
|
||||
{
|
||||
await lifetime.CancelAsync().ConfigureAwait(false);
|
||||
|
||||
// An async iterator cannot be disposed while a MoveNext is in flight (the timeout
|
||||
// and caller-cancel paths leave one pending), so let the cancelled read unwind first.
|
||||
// Its outcome is irrelevant: the failure being thrown is what the caller needs.
|
||||
if (first is not null)
|
||||
{
|
||||
try
|
||||
{
|
||||
await first.ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// Swallowed deliberately; see above.
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await enumerator.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
lifetime.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
using Grpc.Core;
|
||||
using ZB.MOM.WW.MxGateway.Contracts;
|
||||
|
||||
namespace ZB.MOM.WW.MxGateway.Client;
|
||||
|
||||
/// <summary>
|
||||
/// Exception thrown when the gateway answers gRPC <c>ResourceExhausted</c>. The
|
||||
/// <see cref="Reason"/> distinguishes "you fell behind and events were lost" (re-subscribe and
|
||||
/// resync) from "a limit was reached" (back off, do not retry immediately). It derives from
|
||||
/// <see cref="MxGatewayException"/>, so existing catch blocks keep working.
|
||||
/// </summary>
|
||||
public sealed class MxGatewayResourceExhaustedException : MxGatewayException
|
||||
{
|
||||
/// <summary>Initializes a new instance.</summary>
|
||||
/// <param name="message">Diagnostic message describing the failure.</param>
|
||||
/// <param name="reason">The gateway's machine-readable reason code, or null when absent (older gateway).</param>
|
||||
/// <param name="innerException">The underlying <see cref="RpcException"/>.</param>
|
||||
public MxGatewayResourceExhaustedException(string message, string? reason, Exception? innerException = null)
|
||||
: base(message, innerException)
|
||||
{
|
||||
Reason = reason;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the reason code from the <c>mxgw-reason</c> trailer (see <see cref="ResourceExhaustedReasons"/>),
|
||||
/// or null when the gateway sent none.
|
||||
/// </summary>
|
||||
public string? Reason { get; }
|
||||
|
||||
/// <summary>Gets a value indicating whether events were lost because the subscriber fell behind (event-stream or alarm-feed overflow); the caller should re-subscribe and resync.</summary>
|
||||
public bool IsOverflow =>
|
||||
Reason is ResourceExhaustedReasons.EventQueueOverflow or ResourceExhaustedReasons.AlarmFeedOverflow;
|
||||
|
||||
/// <summary>Gets a value indicating whether the failure was a subscriber-count limit rejection.</summary>
|
||||
public bool IsSubscriberLimit =>
|
||||
Reason is ResourceExhaustedReasons.SubscriberLimit or ResourceExhaustedReasons.SubscriberAlreadyActive;
|
||||
|
||||
internal static string? ReadReason(RpcException exception)
|
||||
{
|
||||
foreach (Metadata.Entry entry in exception.Trailers)
|
||||
{
|
||||
if (!entry.IsBinary
|
||||
&& string.Equals(entry.Key, ResourceExhaustedReasons.TrailerKey, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return entry.Value;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using Grpc.Core;
|
||||
using ZB.MOM.WW.MxGateway.Contracts;
|
||||
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
||||
|
||||
namespace ZB.MOM.WW.MxGateway.Client;
|
||||
@@ -1518,7 +1519,7 @@ public sealed class MxGatewaySession : IAsyncDisposable
|
||||
|
||||
/// <summary>
|
||||
/// Drains events queued in the worker through the diagnostic command path. This removes
|
||||
/// events from the worker queue; it is not a substitute for <see cref="StreamEventsAsync"/>
|
||||
/// events from the worker queue; it is not a substitute for <see cref="StreamEventsAsync(ulong, CancellationToken)"/>
|
||||
/// and is not retried automatically. The reply is bounded by server-side caps, so call
|
||||
/// repeatedly until it returns an empty list.
|
||||
/// </summary>
|
||||
@@ -1572,6 +1573,111 @@ public sealed class MxGatewaySession : IAsyncDisposable
|
||||
cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Streams events, optionally asking the gateway for the stream-attached sentinel (#227).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// With <paramref name="emitStreamAttached"/> set, a gateway that advertises
|
||||
/// <see cref="SupportsStreamAttachedAck"/> sends one sentinel <see cref="MxEvent"/> first, with
|
||||
/// <see cref="MxEvent.StreamAttached"/> populated, after it has registered the stream. Consumers
|
||||
/// that advise items only after seeing it cannot lose an initial value to the attach race. The
|
||||
/// sentinel's <c>worker_sequence</c> is 0 and must not be used as a resume cursor. Use
|
||||
/// <see cref="OpenEventStreamAsync"/> to await the sentinel instead of inspecting the stream.
|
||||
/// </remarks>
|
||||
/// <param name="afterWorkerSequence">The sequence number to stream from; 0 for a fresh stream.</param>
|
||||
/// <param name="emitStreamAttached">Whether to ask the gateway for the stream-attached sentinel.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>An async enumerable of events.</returns>
|
||||
public IAsyncEnumerable<MxEvent> StreamEventsAsync(
|
||||
ulong afterWorkerSequence,
|
||||
bool emitStreamAttached,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
return _client.StreamEventsAsync(
|
||||
new StreamEventsRequest
|
||||
{
|
||||
SessionId = SessionId,
|
||||
AfterWorkerSequence = afterWorkerSequence,
|
||||
EmitStreamAttached = emitStreamAttached,
|
||||
},
|
||||
cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Typed-item variant of <see cref="StreamEventsAsync(ulong, bool, CancellationToken)"/>: the
|
||||
/// stream-attached sentinel arrives as an item with <see cref="MxEventStreamItem.IsStreamAttached"/> set.
|
||||
/// </summary>
|
||||
/// <param name="afterWorkerSequence">The sequence number to stream from; 0 for a fresh stream.</param>
|
||||
/// <param name="emitStreamAttached">Whether to ask the gateway for the stream-attached sentinel.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>An async enumerable of typed event items.</returns>
|
||||
public IAsyncEnumerable<MxEventStreamItem> StreamEventItemsAsync(
|
||||
ulong afterWorkerSequence,
|
||||
bool emitStreamAttached,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
return StreamEventsAsync(afterWorkerSequence, emitStreamAttached, cancellationToken)
|
||||
.AsStreamItemsAsync(cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see langword="true"/> when the gateway listed
|
||||
/// <see cref="GatewayCapabilities.StreamEventsAttachedAck"/> in this session's
|
||||
/// <see cref="OpenSessionReply"/>, i.e. it honours the stream-attached request (#227).
|
||||
/// <see langword="false"/> for an older gateway, and also for a session bound with
|
||||
/// <see cref="MxGatewayClient.AttachSession"/>, whose reply carries no capabilities.
|
||||
/// </summary>
|
||||
public bool SupportsStreamAttachedAck =>
|
||||
OpenSessionReply.Capabilities.Contains(GatewayCapabilities.StreamEventsAttachedAck);
|
||||
|
||||
/// <summary>
|
||||
/// Opens the session's event stream and completes once the gateway confirms it is attached
|
||||
/// (#227). Advise items after this returns: every event the session publishes from then on
|
||||
/// reaches the returned stream, so no initial value is lost to the attach race.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// The returned <see cref="MxGatewayEventStream"/> owns the call; read the remaining events
|
||||
/// with <see cref="MxGatewayEventStream.ReadAllAsync"/> (the sentinel itself is consumed here)
|
||||
/// and dispose it to end the stream. <paramref name="cancellationToken"/> governs the whole
|
||||
/// stream's lifetime, not only the wait; bound the wait with <paramref name="attachTimeout"/>.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// When the session's reply lists capabilities but not the attach acknowledgement, the gateway
|
||||
/// predates #227 and this throws <see cref="NotSupportedException"/> without opening a stream.
|
||||
/// A session bound with <see cref="MxGatewayClient.AttachSession"/> has no capability list, so
|
||||
/// the request is sent anyway; against an older gateway the first message is then a normal
|
||||
/// event (or nothing), which ends the stream with <see cref="NotSupportedException"/> or
|
||||
/// <see cref="TimeoutException"/>.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <param name="afterWorkerSequence">The sequence number to stream from; 0 for a fresh stream.</param>
|
||||
/// <param name="attachTimeout">Upper bound on the wait for the sentinel; <see langword="null"/> waits indefinitely.</param>
|
||||
/// <param name="cancellationToken">Cancels the wait and, afterwards, the stream.</param>
|
||||
/// <returns>The attached stream.</returns>
|
||||
/// <exception cref="NotSupportedException">The gateway does not send the attach acknowledgement.</exception>
|
||||
/// <exception cref="TimeoutException">No sentinel arrived within <paramref name="attachTimeout"/>.</exception>
|
||||
public async Task<MxGatewayEventStream> OpenEventStreamAsync(
|
||||
ulong afterWorkerSequence = 0,
|
||||
TimeSpan? attachTimeout = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (OpenSessionReply.Capabilities.Count > 0 && !SupportsStreamAttachedAck)
|
||||
{
|
||||
throw new NotSupportedException(
|
||||
$"The gateway for session {SessionId} does not advertise "
|
||||
+ $"'{GatewayCapabilities.StreamEventsAttachedAck}'; it cannot acknowledge an event-stream attach.");
|
||||
}
|
||||
|
||||
return await MxGatewayEventStream
|
||||
.OpenAsync(
|
||||
token => StreamEventsAsync(afterWorkerSequence, emitStreamAttached: true, token),
|
||||
SessionId,
|
||||
attachTimeout,
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Streams events as typed <see cref="MxEventStreamItem"/> values, surfacing
|
||||
/// the gateway's reconnect-replay gap sentinel as an observable, typed signal.
|
||||
@@ -1586,7 +1692,7 @@ public sealed class MxGatewaySession : IAsyncDisposable
|
||||
/// incurring another gap, reconnect with
|
||||
/// <c>afterWorkerSequence = item.ReplayGap.OldestAvailableSequence - 1</c>.
|
||||
/// All other events pass through with <see cref="MxEventStreamItem.IsReplayGap"/>
|
||||
/// false. Use <see cref="StreamEventsAsync"/> when raw generated
|
||||
/// false. Use <see cref="StreamEventsAsync(ulong, CancellationToken)"/> when raw generated
|
||||
/// <see cref="MxEvent"/> messages are needed instead.
|
||||
/// </remarks>
|
||||
/// <param name="afterWorkerSequence">The sequence number to stream from. Defaults to 0.</param>
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
[assembly: InternalsVisibleTo("ZB.MOM.WW.MxGateway.Client.Tests")]
|
||||
@@ -19,7 +19,7 @@
|
||||
<PropertyGroup>
|
||||
<IsPackable>true</IsPackable>
|
||||
<PackageId>ZB.MOM.WW.MxGateway.Client</PackageId>
|
||||
<Version>0.3.0</Version>
|
||||
<Version>0.4.0</Version>
|
||||
<Description>.NET 10 gRPC client for the MxAccessGateway service. Provides typed wrappers, retry, and a lazy-browse walker over the Galaxy Repository hierarchy.</Description>
|
||||
<PackageReadmeFile>README.md</PackageReadmeFile>
|
||||
<!-- Only the shipped library generates XML docs (matching src/Contracts). The Cli and
|
||||
|
||||
@@ -92,7 +92,11 @@ returned subscription owns cancellation and exposes `Close` for deterministic
|
||||
goroutine cleanup. Raw protobuf messages remain available through the
|
||||
`mxgateway` package aliases and the `Raw` helper methods. Typed errors support
|
||||
`errors.As` for `GatewayError`, `CommandError`, and `MxAccessError`; command
|
||||
errors preserve the raw reply.
|
||||
errors preserve the raw reply. Authentication failures are distinguishable with
|
||||
`errors.Is(err, mxgateway.ErrUnauthenticated)` (missing/rejected API key) and
|
||||
`errors.Is(err, mxgateway.ErrPermissionDenied)` (valid key, not authorised);
|
||||
both match a `*GatewayError` by its gRPC status code and leave the message
|
||||
(and its credential redaction) unchanged.
|
||||
|
||||
`EnsureMxAccessSuccess` follows COM semantics: only a **negative** HRESULT is a
|
||||
failure, so positive success codes such as `S_FALSE` (1) pass. `StatusSucceeded`
|
||||
@@ -497,7 +501,10 @@ buffer is widened to 16 MiB so a single long command line (e.g. a bulk write wit
|
||||
thousands of handles) does not trip bufio's default 64 KiB token-too-long limit;
|
||||
a line that still exceeds 16 MiB surfaces as a framed error and ends the session.
|
||||
|
||||
Use TLS options for a secured gateway:
|
||||
Use TLS options for a secured gateway. Over TLS (no `-plaintext`) with
|
||||
no `-ca-cert`, `mxgw-go` skips certificate verification by default (self-signed
|
||||
gateway certs); pass `-require-certificate-validation` to verify against the
|
||||
system trust roots instead:
|
||||
|
||||
```powershell
|
||||
go run ./cmd/mxgw-go smoke -endpoint mxgateway.example.local:5001 -ca-cert C:\certs\mxgateway-ca.pem -server-name-override mxgateway.example.local -api-key-env MXGATEWAY_API_KEY -item Area001.Tag.Value -json
|
||||
|
||||
@@ -33,13 +33,15 @@ type versionOutput struct {
|
||||
}
|
||||
|
||||
type commonOptions struct {
|
||||
Endpoint string `json:"endpoint"`
|
||||
APIKey string `json:"apiKey"`
|
||||
APIKeyEnv string `json:"apiKeyEnv,omitempty"`
|
||||
Plaintext bool `json:"plaintext"`
|
||||
CACertFile string `json:"caCertFile,omitempty"`
|
||||
ServerName string `json:"serverNameOverride,omitempty"`
|
||||
CallTimeout string `json:"callTimeout,omitempty"`
|
||||
Endpoint string `json:"endpoint"`
|
||||
APIKey string `json:"apiKey"`
|
||||
APIKeyEnv string `json:"apiKeyEnv,omitempty"`
|
||||
Plaintext bool `json:"plaintext"`
|
||||
CACertFile string `json:"caCertFile,omitempty"`
|
||||
ServerName string `json:"serverNameOverride,omitempty"`
|
||||
|
||||
RequireCertificateValidation bool `json:"requireCertificateValidation,omitempty"`
|
||||
CallTimeout string `json:"callTimeout,omitempty"`
|
||||
|
||||
apiKeyValue string
|
||||
timeout time.Duration
|
||||
@@ -1295,6 +1297,7 @@ func bindCommonFlags(flags *flag.FlagSet) *commonOptions {
|
||||
flags.StringVar(&common.APIKeyEnv, "api-key-env", "MXGATEWAY_API_KEY", "environment variable containing the API key")
|
||||
flags.BoolVar(&common.Plaintext, "plaintext", false, "use plaintext transport")
|
||||
flags.StringVar(&common.CACertFile, "ca-cert", "", "CA certificate file")
|
||||
flags.BoolVar(&common.RequireCertificateValidation, "require-certificate-validation", false, "verify the gateway TLS certificate against system roots (default skips verification when no -ca-cert is given)")
|
||||
flags.StringVar(&common.ServerName, "server-name-override", "", "TLS server name override")
|
||||
flags.StringVar(&common.CallTimeout, "call-timeout", "30s", "per-call timeout")
|
||||
return common
|
||||
@@ -1307,12 +1310,13 @@ func dialForCommand(ctx context.Context, common *commonOptions) (*mxgateway.Clie
|
||||
}
|
||||
|
||||
client, err := mxgateway.Dial(ctx, mxgateway.Options{
|
||||
Endpoint: options.Endpoint,
|
||||
APIKey: options.apiKeyValue,
|
||||
Plaintext: options.Plaintext,
|
||||
CACertFile: options.CACertFile,
|
||||
ServerNameOverride: options.ServerName,
|
||||
CallTimeout: options.timeout,
|
||||
Endpoint: options.Endpoint,
|
||||
APIKey: options.apiKeyValue,
|
||||
Plaintext: options.Plaintext,
|
||||
CACertFile: options.CACertFile,
|
||||
ServerNameOverride: options.ServerName,
|
||||
RequireCertificateValidation: options.RequireCertificateValidation,
|
||||
CallTimeout: options.timeout,
|
||||
})
|
||||
return client, options, err
|
||||
}
|
||||
@@ -1523,12 +1527,13 @@ func dialGalaxyForCommand(ctx context.Context, common *commonOptions) (*mxgatewa
|
||||
}
|
||||
|
||||
client, err := mxgateway.DialGalaxy(ctx, mxgateway.Options{
|
||||
Endpoint: options.Endpoint,
|
||||
APIKey: options.apiKeyValue,
|
||||
Plaintext: options.Plaintext,
|
||||
CACertFile: options.CACertFile,
|
||||
ServerNameOverride: options.ServerName,
|
||||
CallTimeout: options.timeout,
|
||||
Endpoint: options.Endpoint,
|
||||
APIKey: options.apiKeyValue,
|
||||
Plaintext: options.Plaintext,
|
||||
CACertFile: options.CACertFile,
|
||||
ServerNameOverride: options.ServerName,
|
||||
RequireCertificateValidation: options.RequireCertificateValidation,
|
||||
CallTimeout: options.timeout,
|
||||
})
|
||||
return client, options, err
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"net"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -859,3 +860,24 @@ func TestRunStreamEventsPrintsReplayGap(t *testing.T) {
|
||||
t.Fatalf("stream-events -json gap cursors must be JSON numbers, got: %s", lines[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequireCertificateValidationFlag(t *testing.T) {
|
||||
parse := func(args ...string) commonOptions {
|
||||
flags := flag.NewFlagSet("t", flag.ContinueOnError)
|
||||
common := bindCommonFlags(flags)
|
||||
if err := flags.Parse(args); err != nil {
|
||||
t.Fatalf("parse: %v", err)
|
||||
}
|
||||
resolved, err := common.resolved()
|
||||
if err != nil {
|
||||
t.Fatalf("resolved: %v", err)
|
||||
}
|
||||
return resolved
|
||||
}
|
||||
if parse().RequireCertificateValidation {
|
||||
t.Fatal("default must stay lenient")
|
||||
}
|
||||
if !parse("-require-certificate-validation").RequireCertificateValidation {
|
||||
t.Fatal("flag must set RequireCertificateValidation")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,7 +93,11 @@ func (WorkerState) EnumDescriptor() ([]byte, []int) {
|
||||
type WorkerFaultCategory int32
|
||||
|
||||
const (
|
||||
WorkerFaultCategory_WORKER_FAULT_CATEGORY_UNSPECIFIED WorkerFaultCategory = 0
|
||||
WorkerFaultCategory_WORKER_FAULT_CATEGORY_UNSPECIFIED WorkerFaultCategory = 0
|
||||
// Values 1 and 2 are reserved: never emitted. Bootstrap failures (bad
|
||||
// arguments, gateway authentication) exit via WorkerExitCode before the pipe
|
||||
// exists, so there is no channel to carry a fault. Names kept so the numbers
|
||||
// are not reused.
|
||||
WorkerFaultCategory_WORKER_FAULT_CATEGORY_INVALID_ARGUMENTS WorkerFaultCategory = 1
|
||||
WorkerFaultCategory_WORKER_FAULT_CATEGORY_GATEWAY_AUTHENTICATION_FAILED WorkerFaultCategory = 2
|
||||
WorkerFaultCategory_WORKER_FAULT_CATEGORY_PROTOCOL_MISMATCH WorkerFaultCategory = 3
|
||||
@@ -576,8 +580,15 @@ type WorkerReady struct {
|
||||
MxaccessProgid string `protobuf:"bytes,2,opt,name=mxaccess_progid,json=mxaccessProgid,proto3" json:"mxaccess_progid,omitempty"`
|
||||
MxaccessClsid string `protobuf:"bytes,3,opt,name=mxaccess_clsid,json=mxaccessClsid,proto3" json:"mxaccess_clsid,omitempty"`
|
||||
ReadyTimestamp *timestamppb.Timestamp `protobuf:"bytes,4,opt,name=ready_timestamp,json=readyTimestamp,proto3" json:"ready_timestamp,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
// Outcome of the worker's process-wide MXSTATUS_PROXY record-info pin
|
||||
// (MxStatusProxyRecordInfoPin): "pinned {library-guid} vM.m record {record-guid}" on
|
||||
// success, or the failing call and HRESULT / exception type otherwise. Empty when the
|
||||
// worker made no attempt (an older worker, or a runtime that never created the
|
||||
// MXAccess COM object). Diagnostic only: the gateway logs it and shows it on the
|
||||
// dashboard, and never gates readiness on it, because the pin is a cache warm-up.
|
||||
RecordInfoPinStatus string `protobuf:"bytes,5,opt,name=record_info_pin_status,json=recordInfoPinStatus,proto3" json:"record_info_pin_status,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *WorkerReady) Reset() {
|
||||
@@ -638,6 +649,13 @@ func (x *WorkerReady) GetReadyTimestamp() *timestamppb.Timestamp {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *WorkerReady) GetRecordInfoPinStatus() string {
|
||||
if x != nil {
|
||||
return x.RecordInfoPinStatus
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type WorkerCommand struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Command *MxCommand `protobuf:"bytes,1,opt,name=command,proto3" json:"command,omitempty"`
|
||||
@@ -1135,12 +1153,13 @@ const file_mxaccess_worker_proto_rawDesc = "" +
|
||||
"\x10protocol_version\x18\x01 \x01(\rR\x0fprotocolVersion\x12\x14\n" +
|
||||
"\x05nonce\x18\x02 \x01(\tR\x05nonce\x12*\n" +
|
||||
"\x11worker_process_id\x18\x03 \x01(\x05R\x0fworkerProcessId\x12%\n" +
|
||||
"\x0eworker_version\x18\x04 \x01(\tR\rworkerVersion\"\xce\x01\n" +
|
||||
"\x0eworker_version\x18\x04 \x01(\tR\rworkerVersion\"\x83\x02\n" +
|
||||
"\vWorkerReady\x12*\n" +
|
||||
"\x11worker_process_id\x18\x01 \x01(\x05R\x0fworkerProcessId\x12'\n" +
|
||||
"\x0fmxaccess_progid\x18\x02 \x01(\tR\x0emxaccessProgid\x12%\n" +
|
||||
"\x0emxaccess_clsid\x18\x03 \x01(\tR\rmxaccessClsid\x12C\n" +
|
||||
"\x0fready_timestamp\x18\x04 \x01(\v2\x1a.google.protobuf.TimestampR\x0ereadyTimestamp\"\x92\x01\n" +
|
||||
"\x0fready_timestamp\x18\x04 \x01(\v2\x1a.google.protobuf.TimestampR\x0ereadyTimestamp\x123\n" +
|
||||
"\x16record_info_pin_status\x18\x05 \x01(\tR\x13recordInfoPinStatus\"\x92\x01\n" +
|
||||
"\rWorkerCommand\x128\n" +
|
||||
"\acommand\x18\x01 \x01(\v2\x1e.mxaccess_gateway.v1.MxCommandR\acommand\x12G\n" +
|
||||
"\x11enqueue_timestamp\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\x10enqueueTimestamp\"\x9c\x01\n" +
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package mxgateway
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type failingReader struct{}
|
||||
|
||||
func (failingReader) Read([]byte) (int, error) { return 0, errors.New("entropy unavailable") }
|
||||
|
||||
func TestNewCorrelationIDFallsBackWhenRandFails(t *testing.T) {
|
||||
a := newCorrelationIDFrom(failingReader{})
|
||||
b := newCorrelationIDFrom(failingReader{})
|
||||
if a == "" || b == "" {
|
||||
t.Fatal("fallback id must not be empty")
|
||||
}
|
||||
if a == b {
|
||||
t.Fatalf("fallback ids must be unique, got %q twice", a)
|
||||
}
|
||||
if !strings.HasPrefix(a, "fallback-") {
|
||||
t.Fatalf("unexpected fallback shape %q", a)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewCorrelationIDRandomIsHex32(t *testing.T) {
|
||||
if id := newCorrelationID(); len(id) != 32 {
|
||||
t.Fatalf("expected 32 hex chars, got %q", id)
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,8 @@ import (
|
||||
"strings"
|
||||
|
||||
pb "gitea.dohertylan.com/dohertj2/mxaccessgw/clients/go/internal/generated"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
@@ -199,6 +201,32 @@ func (e *GatewayError) Error() string {
|
||||
return fmt.Sprintf("mxgateway: %s failed: %v", e.Op, e.Err)
|
||||
}
|
||||
|
||||
// ErrUnauthenticated is matched (via errors.Is) by any GatewayError whose gRPC
|
||||
// status code is Unauthenticated: the API key was missing, malformed or
|
||||
// rejected. Fix the credential rather than retrying.
|
||||
var ErrUnauthenticated = errors.New("mxgateway: unauthenticated")
|
||||
|
||||
// ErrPermissionDenied is matched (via errors.Is) by any GatewayError whose gRPC
|
||||
// status code is PermissionDenied: the API key is valid but not authorised for
|
||||
// the operation. This is distinct from ErrUnauthenticated.
|
||||
var ErrPermissionDenied = errors.New("mxgateway: permission denied")
|
||||
|
||||
// Is lets errors.Is(err, ErrUnauthenticated) and errors.Is(err,
|
||||
// ErrPermissionDenied) classify a transport failure by its gRPC status code.
|
||||
// It adds no text to the error message, so credential redaction is unaffected.
|
||||
func (e *GatewayError) Is(target error) bool {
|
||||
if e == nil || e.Err == nil {
|
||||
return false
|
||||
}
|
||||
switch target {
|
||||
case ErrUnauthenticated:
|
||||
return status.Code(e.Err) == codes.Unauthenticated
|
||||
case ErrPermissionDenied:
|
||||
return status.Code(e.Err) == codes.PermissionDenied
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Unwrap returns the wrapped transport error.
|
||||
func (e *GatewayError) Unwrap() error {
|
||||
if e == nil {
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
package mxgateway
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
func TestGatewayErrorClassifiesAuthCodes(t *testing.T) {
|
||||
unauth := &GatewayError{Op: "invoke", Err: status.Error(codes.Unauthenticated, "bad key")}
|
||||
denied := &GatewayError{Op: "invoke", Err: status.Error(codes.PermissionDenied, "no")}
|
||||
other := &GatewayError{Op: "invoke", Err: status.Error(codes.Unavailable, "down")}
|
||||
|
||||
if !errors.Is(unauth, ErrUnauthenticated) || errors.Is(unauth, ErrPermissionDenied) {
|
||||
t.Fatal("Unauthenticated misclassified")
|
||||
}
|
||||
if !errors.Is(denied, ErrPermissionDenied) || errors.Is(denied, ErrUnauthenticated) {
|
||||
t.Fatal("PermissionDenied misclassified")
|
||||
}
|
||||
if errors.Is(other, ErrUnauthenticated) || errors.Is(other, ErrPermissionDenied) {
|
||||
t.Fatal("Unavailable must match neither")
|
||||
}
|
||||
var ge *GatewayError
|
||||
if !errors.As(error(unauth), &ge) {
|
||||
t.Fatal("errors.As to *GatewayError must still work")
|
||||
}
|
||||
wrapped := redactSecrets(unauth, "x")
|
||||
if !errors.Is(wrapped, ErrUnauthenticated) {
|
||||
t.Fatal("classification must survive the redaction wrapper")
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"io"
|
||||
"sort"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
pb "gitea.dohertylan.com/dohertj2/mxaccessgw/clients/go/internal/generated"
|
||||
@@ -1241,10 +1242,21 @@ func (s *Session) invokeCommand(ctx context.Context, command *MxCommand) (*MxCom
|
||||
})
|
||||
}
|
||||
|
||||
// correlationFallbackCounter backs correlation ids when crypto/rand fails, so a
|
||||
// request never goes out with an empty ClientCorrelationId.
|
||||
var correlationFallbackCounter atomic.Uint64
|
||||
|
||||
// newCorrelationID returns a random 128-bit hex id, falling back to a
|
||||
// process-unique counter-based id ("fallback-<unixnano>-<n>") if crypto/rand
|
||||
// fails.
|
||||
func newCorrelationID() string {
|
||||
return newCorrelationIDFrom(rand.Reader)
|
||||
}
|
||||
|
||||
func newCorrelationIDFrom(reader io.Reader) string {
|
||||
var buffer [16]byte
|
||||
if _, err := rand.Read(buffer[:]); err != nil {
|
||||
return ""
|
||||
if _, err := io.ReadFull(reader, buffer[:]); err != nil {
|
||||
return fmt.Sprintf("fallback-%d-%d", time.Now().UnixNano(), correlationFallbackCounter.Add(1))
|
||||
}
|
||||
return hex.EncodeToString(buffer[:])
|
||||
}
|
||||
|
||||
@@ -5477,6 +5477,36 @@ public final class MxaccessWorker extends com.google.protobuf.GeneratedFile {
|
||||
* <code>.google.protobuf.Timestamp ready_timestamp = 4;</code>
|
||||
*/
|
||||
com.google.protobuf.TimestampOrBuilder getReadyTimestampOrBuilder();
|
||||
|
||||
/**
|
||||
* <pre>
|
||||
* Outcome of the worker's process-wide MXSTATUS_PROXY record-info pin
|
||||
* (MxStatusProxyRecordInfoPin): "pinned {library-guid} vM.m record {record-guid}" on
|
||||
* success, or the failing call and HRESULT / exception type otherwise. Empty when the
|
||||
* worker made no attempt (an older worker, or a runtime that never created the
|
||||
* MXAccess COM object). Diagnostic only: the gateway logs it and shows it on the
|
||||
* dashboard, and never gates readiness on it, because the pin is a cache warm-up.
|
||||
* </pre>
|
||||
*
|
||||
* <code>string record_info_pin_status = 5;</code>
|
||||
* @return The recordInfoPinStatus.
|
||||
*/
|
||||
java.lang.String getRecordInfoPinStatus();
|
||||
/**
|
||||
* <pre>
|
||||
* Outcome of the worker's process-wide MXSTATUS_PROXY record-info pin
|
||||
* (MxStatusProxyRecordInfoPin): "pinned {library-guid} vM.m record {record-guid}" on
|
||||
* success, or the failing call and HRESULT / exception type otherwise. Empty when the
|
||||
* worker made no attempt (an older worker, or a runtime that never created the
|
||||
* MXAccess COM object). Diagnostic only: the gateway logs it and shows it on the
|
||||
* dashboard, and never gates readiness on it, because the pin is a cache warm-up.
|
||||
* </pre>
|
||||
*
|
||||
* <code>string record_info_pin_status = 5;</code>
|
||||
* @return The bytes for recordInfoPinStatus.
|
||||
*/
|
||||
com.google.protobuf.ByteString
|
||||
getRecordInfoPinStatusBytes();
|
||||
}
|
||||
/**
|
||||
* Protobuf type {@code mxaccess_worker.v1.WorkerReady}
|
||||
@@ -5502,6 +5532,7 @@ public final class MxaccessWorker extends com.google.protobuf.GeneratedFile {
|
||||
private WorkerReady() {
|
||||
mxaccessProgid_ = "";
|
||||
mxaccessClsid_ = "";
|
||||
recordInfoPinStatus_ = "";
|
||||
}
|
||||
|
||||
public static final com.google.protobuf.Descriptors.Descriptor
|
||||
@@ -5633,6 +5664,63 @@ public final class MxaccessWorker extends com.google.protobuf.GeneratedFile {
|
||||
return readyTimestamp_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : readyTimestamp_;
|
||||
}
|
||||
|
||||
public static final int RECORD_INFO_PIN_STATUS_FIELD_NUMBER = 5;
|
||||
@SuppressWarnings("serial")
|
||||
private volatile java.lang.Object recordInfoPinStatus_ = "";
|
||||
/**
|
||||
* <pre>
|
||||
* Outcome of the worker's process-wide MXSTATUS_PROXY record-info pin
|
||||
* (MxStatusProxyRecordInfoPin): "pinned {library-guid} vM.m record {record-guid}" on
|
||||
* success, or the failing call and HRESULT / exception type otherwise. Empty when the
|
||||
* worker made no attempt (an older worker, or a runtime that never created the
|
||||
* MXAccess COM object). Diagnostic only: the gateway logs it and shows it on the
|
||||
* dashboard, and never gates readiness on it, because the pin is a cache warm-up.
|
||||
* </pre>
|
||||
*
|
||||
* <code>string record_info_pin_status = 5;</code>
|
||||
* @return The recordInfoPinStatus.
|
||||
*/
|
||||
@java.lang.Override
|
||||
public java.lang.String getRecordInfoPinStatus() {
|
||||
java.lang.Object ref = recordInfoPinStatus_;
|
||||
if (ref instanceof java.lang.String) {
|
||||
return (java.lang.String) ref;
|
||||
} else {
|
||||
com.google.protobuf.ByteString bs =
|
||||
(com.google.protobuf.ByteString) ref;
|
||||
java.lang.String s = bs.toStringUtf8();
|
||||
recordInfoPinStatus_ = s;
|
||||
return s;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* <pre>
|
||||
* Outcome of the worker's process-wide MXSTATUS_PROXY record-info pin
|
||||
* (MxStatusProxyRecordInfoPin): "pinned {library-guid} vM.m record {record-guid}" on
|
||||
* success, or the failing call and HRESULT / exception type otherwise. Empty when the
|
||||
* worker made no attempt (an older worker, or a runtime that never created the
|
||||
* MXAccess COM object). Diagnostic only: the gateway logs it and shows it on the
|
||||
* dashboard, and never gates readiness on it, because the pin is a cache warm-up.
|
||||
* </pre>
|
||||
*
|
||||
* <code>string record_info_pin_status = 5;</code>
|
||||
* @return The bytes for recordInfoPinStatus.
|
||||
*/
|
||||
@java.lang.Override
|
||||
public com.google.protobuf.ByteString
|
||||
getRecordInfoPinStatusBytes() {
|
||||
java.lang.Object ref = recordInfoPinStatus_;
|
||||
if (ref instanceof java.lang.String) {
|
||||
com.google.protobuf.ByteString b =
|
||||
com.google.protobuf.ByteString.copyFromUtf8(
|
||||
(java.lang.String) ref);
|
||||
recordInfoPinStatus_ = b;
|
||||
return b;
|
||||
} else {
|
||||
return (com.google.protobuf.ByteString) ref;
|
||||
}
|
||||
}
|
||||
|
||||
private byte memoizedIsInitialized = -1;
|
||||
@java.lang.Override
|
||||
public final boolean isInitialized() {
|
||||
@@ -5659,6 +5747,9 @@ public final class MxaccessWorker extends com.google.protobuf.GeneratedFile {
|
||||
if (((bitField0_ & 0x00000001) != 0)) {
|
||||
output.writeMessage(4, getReadyTimestamp());
|
||||
}
|
||||
if (!com.google.protobuf.GeneratedMessage.isStringEmpty(recordInfoPinStatus_)) {
|
||||
com.google.protobuf.GeneratedMessage.writeString(output, 5, recordInfoPinStatus_);
|
||||
}
|
||||
getUnknownFields().writeTo(output);
|
||||
}
|
||||
|
||||
@@ -5682,6 +5773,9 @@ public final class MxaccessWorker extends com.google.protobuf.GeneratedFile {
|
||||
size += com.google.protobuf.CodedOutputStream
|
||||
.computeMessageSize(4, getReadyTimestamp());
|
||||
}
|
||||
if (!com.google.protobuf.GeneratedMessage.isStringEmpty(recordInfoPinStatus_)) {
|
||||
size += com.google.protobuf.GeneratedMessage.computeStringSize(5, recordInfoPinStatus_);
|
||||
}
|
||||
size += getUnknownFields().getSerializedSize();
|
||||
memoizedSize = size;
|
||||
return size;
|
||||
@@ -5708,6 +5802,8 @@ public final class MxaccessWorker extends com.google.protobuf.GeneratedFile {
|
||||
if (!getReadyTimestamp()
|
||||
.equals(other.getReadyTimestamp())) return false;
|
||||
}
|
||||
if (!getRecordInfoPinStatus()
|
||||
.equals(other.getRecordInfoPinStatus())) return false;
|
||||
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
|
||||
return true;
|
||||
}
|
||||
@@ -5729,6 +5825,8 @@ public final class MxaccessWorker extends com.google.protobuf.GeneratedFile {
|
||||
hash = (37 * hash) + READY_TIMESTAMP_FIELD_NUMBER;
|
||||
hash = (53 * hash) + getReadyTimestamp().hashCode();
|
||||
}
|
||||
hash = (37 * hash) + RECORD_INFO_PIN_STATUS_FIELD_NUMBER;
|
||||
hash = (53 * hash) + getRecordInfoPinStatus().hashCode();
|
||||
hash = (29 * hash) + getUnknownFields().hashCode();
|
||||
memoizedHashCode = hash;
|
||||
return hash;
|
||||
@@ -5874,6 +5972,7 @@ public final class MxaccessWorker extends com.google.protobuf.GeneratedFile {
|
||||
readyTimestampBuilder_.dispose();
|
||||
readyTimestampBuilder_ = null;
|
||||
}
|
||||
recordInfoPinStatus_ = "";
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -5923,6 +6022,9 @@ public final class MxaccessWorker extends com.google.protobuf.GeneratedFile {
|
||||
: readyTimestampBuilder_.build();
|
||||
to_bitField0_ |= 0x00000001;
|
||||
}
|
||||
if (((from_bitField0_ & 0x00000010) != 0)) {
|
||||
result.recordInfoPinStatus_ = recordInfoPinStatus_;
|
||||
}
|
||||
result.bitField0_ |= to_bitField0_;
|
||||
}
|
||||
|
||||
@@ -5954,6 +6056,11 @@ public final class MxaccessWorker extends com.google.protobuf.GeneratedFile {
|
||||
if (other.hasReadyTimestamp()) {
|
||||
mergeReadyTimestamp(other.getReadyTimestamp());
|
||||
}
|
||||
if (!other.getRecordInfoPinStatus().isEmpty()) {
|
||||
recordInfoPinStatus_ = other.recordInfoPinStatus_;
|
||||
bitField0_ |= 0x00000010;
|
||||
onChanged();
|
||||
}
|
||||
this.mergeUnknownFields(other.getUnknownFields());
|
||||
onChanged();
|
||||
return this;
|
||||
@@ -6002,6 +6109,11 @@ public final class MxaccessWorker extends com.google.protobuf.GeneratedFile {
|
||||
bitField0_ |= 0x00000008;
|
||||
break;
|
||||
} // case 34
|
||||
case 42: {
|
||||
recordInfoPinStatus_ = input.readStringRequireUtf8();
|
||||
bitField0_ |= 0x00000010;
|
||||
break;
|
||||
} // case 42
|
||||
default: {
|
||||
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
|
||||
done = true; // was an endgroup tag
|
||||
@@ -6316,6 +6428,123 @@ public final class MxaccessWorker extends com.google.protobuf.GeneratedFile {
|
||||
return readyTimestampBuilder_;
|
||||
}
|
||||
|
||||
private java.lang.Object recordInfoPinStatus_ = "";
|
||||
/**
|
||||
* <pre>
|
||||
* Outcome of the worker's process-wide MXSTATUS_PROXY record-info pin
|
||||
* (MxStatusProxyRecordInfoPin): "pinned {library-guid} vM.m record {record-guid}" on
|
||||
* success, or the failing call and HRESULT / exception type otherwise. Empty when the
|
||||
* worker made no attempt (an older worker, or a runtime that never created the
|
||||
* MXAccess COM object). Diagnostic only: the gateway logs it and shows it on the
|
||||
* dashboard, and never gates readiness on it, because the pin is a cache warm-up.
|
||||
* </pre>
|
||||
*
|
||||
* <code>string record_info_pin_status = 5;</code>
|
||||
* @return The recordInfoPinStatus.
|
||||
*/
|
||||
public java.lang.String getRecordInfoPinStatus() {
|
||||
java.lang.Object ref = recordInfoPinStatus_;
|
||||
if (!(ref instanceof java.lang.String)) {
|
||||
com.google.protobuf.ByteString bs =
|
||||
(com.google.protobuf.ByteString) ref;
|
||||
java.lang.String s = bs.toStringUtf8();
|
||||
recordInfoPinStatus_ = s;
|
||||
return s;
|
||||
} else {
|
||||
return (java.lang.String) ref;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* <pre>
|
||||
* Outcome of the worker's process-wide MXSTATUS_PROXY record-info pin
|
||||
* (MxStatusProxyRecordInfoPin): "pinned {library-guid} vM.m record {record-guid}" on
|
||||
* success, or the failing call and HRESULT / exception type otherwise. Empty when the
|
||||
* worker made no attempt (an older worker, or a runtime that never created the
|
||||
* MXAccess COM object). Diagnostic only: the gateway logs it and shows it on the
|
||||
* dashboard, and never gates readiness on it, because the pin is a cache warm-up.
|
||||
* </pre>
|
||||
*
|
||||
* <code>string record_info_pin_status = 5;</code>
|
||||
* @return The bytes for recordInfoPinStatus.
|
||||
*/
|
||||
public com.google.protobuf.ByteString
|
||||
getRecordInfoPinStatusBytes() {
|
||||
java.lang.Object ref = recordInfoPinStatus_;
|
||||
if (ref instanceof String) {
|
||||
com.google.protobuf.ByteString b =
|
||||
com.google.protobuf.ByteString.copyFromUtf8(
|
||||
(java.lang.String) ref);
|
||||
recordInfoPinStatus_ = b;
|
||||
return b;
|
||||
} else {
|
||||
return (com.google.protobuf.ByteString) ref;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* <pre>
|
||||
* Outcome of the worker's process-wide MXSTATUS_PROXY record-info pin
|
||||
* (MxStatusProxyRecordInfoPin): "pinned {library-guid} vM.m record {record-guid}" on
|
||||
* success, or the failing call and HRESULT / exception type otherwise. Empty when the
|
||||
* worker made no attempt (an older worker, or a runtime that never created the
|
||||
* MXAccess COM object). Diagnostic only: the gateway logs it and shows it on the
|
||||
* dashboard, and never gates readiness on it, because the pin is a cache warm-up.
|
||||
* </pre>
|
||||
*
|
||||
* <code>string record_info_pin_status = 5;</code>
|
||||
* @param value The recordInfoPinStatus to set.
|
||||
* @return This builder for chaining.
|
||||
*/
|
||||
public Builder setRecordInfoPinStatus(
|
||||
java.lang.String value) {
|
||||
if (value == null) { throw new NullPointerException(); }
|
||||
recordInfoPinStatus_ = value;
|
||||
bitField0_ |= 0x00000010;
|
||||
onChanged();
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* <pre>
|
||||
* Outcome of the worker's process-wide MXSTATUS_PROXY record-info pin
|
||||
* (MxStatusProxyRecordInfoPin): "pinned {library-guid} vM.m record {record-guid}" on
|
||||
* success, or the failing call and HRESULT / exception type otherwise. Empty when the
|
||||
* worker made no attempt (an older worker, or a runtime that never created the
|
||||
* MXAccess COM object). Diagnostic only: the gateway logs it and shows it on the
|
||||
* dashboard, and never gates readiness on it, because the pin is a cache warm-up.
|
||||
* </pre>
|
||||
*
|
||||
* <code>string record_info_pin_status = 5;</code>
|
||||
* @return This builder for chaining.
|
||||
*/
|
||||
public Builder clearRecordInfoPinStatus() {
|
||||
recordInfoPinStatus_ = getDefaultInstance().getRecordInfoPinStatus();
|
||||
bitField0_ = (bitField0_ & ~0x00000010);
|
||||
onChanged();
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* <pre>
|
||||
* Outcome of the worker's process-wide MXSTATUS_PROXY record-info pin
|
||||
* (MxStatusProxyRecordInfoPin): "pinned {library-guid} vM.m record {record-guid}" on
|
||||
* success, or the failing call and HRESULT / exception type otherwise. Empty when the
|
||||
* worker made no attempt (an older worker, or a runtime that never created the
|
||||
* MXAccess COM object). Diagnostic only: the gateway logs it and shows it on the
|
||||
* dashboard, and never gates readiness on it, because the pin is a cache warm-up.
|
||||
* </pre>
|
||||
*
|
||||
* <code>string record_info_pin_status = 5;</code>
|
||||
* @param value The bytes for recordInfoPinStatus to set.
|
||||
* @return This builder for chaining.
|
||||
*/
|
||||
public Builder setRecordInfoPinStatusBytes(
|
||||
com.google.protobuf.ByteString value) {
|
||||
if (value == null) { throw new NullPointerException(); }
|
||||
checkByteStringIsUtf8(value);
|
||||
recordInfoPinStatus_ = value;
|
||||
bitField0_ |= 0x00000010;
|
||||
onChanged();
|
||||
return this;
|
||||
}
|
||||
|
||||
// @@protoc_insertion_point(builder_scope:mxaccess_worker.v1.WorkerReady)
|
||||
}
|
||||
|
||||
@@ -12698,60 +12927,61 @@ public final class MxaccessWorker extends com.google.protobuf.GeneratedFile {
|
||||
"ay_version\030\003 \001(\t\022\027\n\017max_frame_bytes\030\004 \001(" +
|
||||
"\r\"i\n\013WorkerHello\022\030\n\020protocol_version\030\001 \001" +
|
||||
"(\r\022\r\n\005nonce\030\002 \001(\t\022\031\n\021worker_process_id\030\003" +
|
||||
" \001(\005\022\026\n\016worker_version\030\004 \001(\t\"\216\001\n\013WorkerR" +
|
||||
" \001(\005\022\026\n\016worker_version\030\004 \001(\t\"\256\001\n\013WorkerR" +
|
||||
"eady\022\031\n\021worker_process_id\030\001 \001(\005\022\027\n\017mxacc" +
|
||||
"ess_progid\030\002 \001(\t\022\026\n\016mxaccess_clsid\030\003 \001(\t" +
|
||||
"\0223\n\017ready_timestamp\030\004 \001(\0132\032.google.proto" +
|
||||
"buf.Timestamp\"w\n\rWorkerCommand\022/\n\007comman" +
|
||||
"d\030\001 \001(\0132\036.mxaccess_gateway.v1.MxCommand\022" +
|
||||
"5\n\021enqueue_timestamp\030\002 \001(\0132\032.google.prot" +
|
||||
"obuf.Timestamp\"\201\001\n\022WorkerCommandReply\0222\n" +
|
||||
"\005reply\030\001 \001(\0132#.mxaccess_gateway.v1.MxCom" +
|
||||
"mandReply\0227\n\023completed_timestamp\030\002 \001(\0132\032" +
|
||||
".google.protobuf.Timestamp\"\036\n\014WorkerCanc" +
|
||||
"el\022\016\n\006reason\030\001 \001(\t\"Q\n\016WorkerShutdown\022/\n\014" +
|
||||
"grace_period\030\001 \001(\0132\031.google.protobuf.Dur" +
|
||||
"ation\022\016\n\006reason\030\002 \001(\t\"H\n\021WorkerShutdownA" +
|
||||
"ck\0223\n\006status\030\001 \001(\0132#.mxaccess_gateway.v1" +
|
||||
".ProtocolStatus\":\n\013WorkerEvent\022+\n\005event\030" +
|
||||
"\001 \001(\0132\034.mxaccess_gateway.v1.MxEvent\"\245\002\n\017" +
|
||||
"WorkerHeartbeat\022\031\n\021worker_process_id\030\001 \001" +
|
||||
"(\005\022.\n\005state\030\002 \001(\0162\037.mxaccess_worker.v1.W" +
|
||||
"orkerState\022?\n\033last_sta_activity_timestam" +
|
||||
"p\030\003 \001(\0132\032.google.protobuf.Timestamp\022\035\n\025p" +
|
||||
"ending_command_count\030\004 \001(\r\022\"\n\032outbound_e" +
|
||||
"vent_queue_depth\030\005 \001(\r\022\033\n\023last_event_seq" +
|
||||
"uence\030\006 \001(\004\022&\n\036current_command_correlati" +
|
||||
"on_id\030\007 \001(\t\"\364\001\n\013WorkerFault\0229\n\010category\030" +
|
||||
"\001 \001(\0162\'.mxaccess_worker.v1.WorkerFaultCa" +
|
||||
"tegory\022\026\n\016command_method\030\002 \001(\t\022\024\n\007hresul" +
|
||||
"t\030\003 \001(\005H\000\210\001\001\022\026\n\016exception_type\030\004 \001(\t\022\032\n\022" +
|
||||
"diagnostic_message\030\005 \001(\t\022<\n\017protocol_sta" +
|
||||
"tus\030\006 \001(\0132#.mxaccess_gateway.v1.Protocol" +
|
||||
"StatusB\n\n\010_hresult*\227\002\n\013WorkerState\022\034\n\030WO" +
|
||||
"RKER_STATE_UNSPECIFIED\020\000\022\031\n\025WORKER_STATE" +
|
||||
"_STARTING\020\001\022\034\n\030WORKER_STATE_HANDSHAKING\020" +
|
||||
"\002\022!\n\035WORKER_STATE_INITIALIZING_STA\020\003\022\026\n\022" +
|
||||
"WORKER_STATE_READY\020\004\022\"\n\036WORKER_STATE_EXE" +
|
||||
"CUTING_COMMAND\020\005\022\036\n\032WORKER_STATE_SHUTTIN" +
|
||||
"G_DOWN\020\006\022\030\n\024WORKER_STATE_STOPPED\020\007\022\030\n\024WO" +
|
||||
"RKER_STATE_FAULTED\020\010*\307\004\n\023WorkerFaultCate" +
|
||||
"gory\022%\n!WORKER_FAULT_CATEGORY_UNSPECIFIE" +
|
||||
"D\020\000\022+\n\'WORKER_FAULT_CATEGORY_INVALID_ARG" +
|
||||
"UMENTS\020\001\0227\n3WORKER_FAULT_CATEGORY_GATEWA" +
|
||||
"Y_AUTHENTICATION_FAILED\020\002\022+\n\'WORKER_FAUL" +
|
||||
"T_CATEGORY_PROTOCOL_MISMATCH\020\003\022,\n(WORKER" +
|
||||
"_FAULT_CATEGORY_PROTOCOL_VIOLATION\020\004\022+\n\'" +
|
||||
"WORKER_FAULT_CATEGORY_PIPE_DISCONNECTED\020" +
|
||||
"\005\0222\n.WORKER_FAULT_CATEGORY_MXACCESS_CREA" +
|
||||
"TION_FAILED\020\006\0221\n-WORKER_FAULT_CATEGORY_M" +
|
||||
"XACCESS_COMMAND_FAILED\020\007\022:\n6WORKER_FAULT" +
|
||||
"_CATEGORY_MXACCESS_EVENT_CONVERSION_FAIL" +
|
||||
"ED\020\010\022\"\n\036WORKER_FAULT_CATEGORY_STA_HUNG\020\t" +
|
||||
"\022(\n$WORKER_FAULT_CATEGORY_QUEUE_OVERFLOW" +
|
||||
"\020\n\022*\n&WORKER_FAULT_CATEGORY_SHUTDOWN_TIM" +
|
||||
"EOUT\020\013B&\252\002#ZB.MOM.WW.MxGateway.Contracts" +
|
||||
".Protob\006proto3"
|
||||
"buf.Timestamp\022\036\n\026record_info_pin_status\030" +
|
||||
"\005 \001(\t\"w\n\rWorkerCommand\022/\n\007command\030\001 \001(\0132" +
|
||||
"\036.mxaccess_gateway.v1.MxCommand\0225\n\021enque" +
|
||||
"ue_timestamp\030\002 \001(\0132\032.google.protobuf.Tim" +
|
||||
"estamp\"\201\001\n\022WorkerCommandReply\0222\n\005reply\030\001" +
|
||||
" \001(\0132#.mxaccess_gateway.v1.MxCommandRepl" +
|
||||
"y\0227\n\023completed_timestamp\030\002 \001(\0132\032.google." +
|
||||
"protobuf.Timestamp\"\036\n\014WorkerCancel\022\016\n\006re" +
|
||||
"ason\030\001 \001(\t\"Q\n\016WorkerShutdown\022/\n\014grace_pe" +
|
||||
"riod\030\001 \001(\0132\031.google.protobuf.Duration\022\016\n" +
|
||||
"\006reason\030\002 \001(\t\"H\n\021WorkerShutdownAck\0223\n\006st" +
|
||||
"atus\030\001 \001(\0132#.mxaccess_gateway.v1.Protoco" +
|
||||
"lStatus\":\n\013WorkerEvent\022+\n\005event\030\001 \001(\0132\034." +
|
||||
"mxaccess_gateway.v1.MxEvent\"\245\002\n\017WorkerHe" +
|
||||
"artbeat\022\031\n\021worker_process_id\030\001 \001(\005\022.\n\005st" +
|
||||
"ate\030\002 \001(\0162\037.mxaccess_worker.v1.WorkerSta" +
|
||||
"te\022?\n\033last_sta_activity_timestamp\030\003 \001(\0132" +
|
||||
"\032.google.protobuf.Timestamp\022\035\n\025pending_c" +
|
||||
"ommand_count\030\004 \001(\r\022\"\n\032outbound_event_que" +
|
||||
"ue_depth\030\005 \001(\r\022\033\n\023last_event_sequence\030\006 " +
|
||||
"\001(\004\022&\n\036current_command_correlation_id\030\007 " +
|
||||
"\001(\t\"\364\001\n\013WorkerFault\0229\n\010category\030\001 \001(\0162\'." +
|
||||
"mxaccess_worker.v1.WorkerFaultCategory\022\026" +
|
||||
"\n\016command_method\030\002 \001(\t\022\024\n\007hresult\030\003 \001(\005H" +
|
||||
"\000\210\001\001\022\026\n\016exception_type\030\004 \001(\t\022\032\n\022diagnost" +
|
||||
"ic_message\030\005 \001(\t\022<\n\017protocol_status\030\006 \001(" +
|
||||
"\0132#.mxaccess_gateway.v1.ProtocolStatusB\n" +
|
||||
"\n\010_hresult*\227\002\n\013WorkerState\022\034\n\030WORKER_STA" +
|
||||
"TE_UNSPECIFIED\020\000\022\031\n\025WORKER_STATE_STARTIN" +
|
||||
"G\020\001\022\034\n\030WORKER_STATE_HANDSHAKING\020\002\022!\n\035WOR" +
|
||||
"KER_STATE_INITIALIZING_STA\020\003\022\026\n\022WORKER_S" +
|
||||
"TATE_READY\020\004\022\"\n\036WORKER_STATE_EXECUTING_C" +
|
||||
"OMMAND\020\005\022\036\n\032WORKER_STATE_SHUTTING_DOWN\020\006" +
|
||||
"\022\030\n\024WORKER_STATE_STOPPED\020\007\022\030\n\024WORKER_STA" +
|
||||
"TE_FAULTED\020\010*\307\004\n\023WorkerFaultCategory\022%\n!" +
|
||||
"WORKER_FAULT_CATEGORY_UNSPECIFIED\020\000\022+\n\'W" +
|
||||
"ORKER_FAULT_CATEGORY_INVALID_ARGUMENTS\020\001" +
|
||||
"\0227\n3WORKER_FAULT_CATEGORY_GATEWAY_AUTHEN" +
|
||||
"TICATION_FAILED\020\002\022+\n\'WORKER_FAULT_CATEGO" +
|
||||
"RY_PROTOCOL_MISMATCH\020\003\022,\n(WORKER_FAULT_C" +
|
||||
"ATEGORY_PROTOCOL_VIOLATION\020\004\022+\n\'WORKER_F" +
|
||||
"AULT_CATEGORY_PIPE_DISCONNECTED\020\005\0222\n.WOR" +
|
||||
"KER_FAULT_CATEGORY_MXACCESS_CREATION_FAI" +
|
||||
"LED\020\006\0221\n-WORKER_FAULT_CATEGORY_MXACCESS_" +
|
||||
"COMMAND_FAILED\020\007\022:\n6WORKER_FAULT_CATEGOR" +
|
||||
"Y_MXACCESS_EVENT_CONVERSION_FAILED\020\010\022\"\n\036" +
|
||||
"WORKER_FAULT_CATEGORY_STA_HUNG\020\t\022(\n$WORK" +
|
||||
"ER_FAULT_CATEGORY_QUEUE_OVERFLOW\020\n\022*\n&WO" +
|
||||
"RKER_FAULT_CATEGORY_SHUTDOWN_TIMEOUT\020\013B&" +
|
||||
"\252\002#ZB.MOM.WW.MxGateway.Contracts.Protob\006" +
|
||||
"proto3"
|
||||
};
|
||||
descriptor = com.google.protobuf.Descriptors.FileDescriptor
|
||||
.internalBuildGeneratedFileFrom(descriptorData,
|
||||
@@ -12783,7 +13013,7 @@ public final class MxaccessWorker extends com.google.protobuf.GeneratedFile {
|
||||
internal_static_mxaccess_worker_v1_WorkerReady_fieldAccessorTable = new
|
||||
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
|
||||
internal_static_mxaccess_worker_v1_WorkerReady_descriptor,
|
||||
new java.lang.String[] { "WorkerProcessId", "MxaccessProgid", "MxaccessClsid", "ReadyTimestamp", });
|
||||
new java.lang.String[] { "WorkerProcessId", "MxaccessProgid", "MxaccessClsid", "ReadyTimestamp", "RecordInfoPinStatus", });
|
||||
internal_static_mxaccess_worker_v1_WorkerCommand_descriptor =
|
||||
getDescriptor().getMessageType(4);
|
||||
internal_static_mxaccess_worker_v1_WorkerCommand_fieldAccessorTable = new
|
||||
|
||||
@@ -103,6 +103,10 @@ async with await GatewayClient.connect(
|
||||
await session.close()
|
||||
```
|
||||
|
||||
`Session.close()` is concurrency-safe and idempotent: concurrent or repeated
|
||||
calls issue a single `CloseSession` RPC and return the gateway's real reply (a
|
||||
failed RPC is not cached, so a later call may retry).
|
||||
|
||||
`GatewayClient.open_session_raw`, `GatewayClient.invoke_raw`, and
|
||||
`GatewayClient.stream_events_raw` keep the generated protobuf replies and
|
||||
events available for parity tests. `Session` helpers call the method-specific
|
||||
|
||||
@@ -27,7 +27,7 @@ from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__
|
||||
import mxaccess_gateway_pb2 as mxaccess__gateway__pb2
|
||||
|
||||
|
||||
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x15mxaccess_worker.proto\x12\x12mxaccess_worker.v1\x1a\x1egoogle/protobuf/duration.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x16mxaccess_gateway.proto\"\x95\x06\n\x0eWorkerEnvelope\x12\x18\n\x10protocol_version\x18\x01 \x01(\r\x12\x12\n\nsession_id\x18\x02 \x01(\t\x12\x10\n\x08sequence\x18\x03 \x01(\x04\x12\x16\n\x0e\x63orrelation_id\x18\x04 \x01(\t\x12\x39\n\rgateway_hello\x18\n \x01(\x0b\x32 .mxaccess_worker.v1.GatewayHelloH\x00\x12\x37\n\x0cworker_hello\x18\x0b \x01(\x0b\x32\x1f.mxaccess_worker.v1.WorkerHelloH\x00\x12\x37\n\x0cworker_ready\x18\x0c \x01(\x0b\x32\x1f.mxaccess_worker.v1.WorkerReadyH\x00\x12;\n\x0eworker_command\x18\r \x01(\x0b\x32!.mxaccess_worker.v1.WorkerCommandH\x00\x12\x46\n\x14worker_command_reply\x18\x0e \x01(\x0b\x32&.mxaccess_worker.v1.WorkerCommandReplyH\x00\x12\x39\n\rworker_cancel\x18\x0f \x01(\x0b\x32 .mxaccess_worker.v1.WorkerCancelH\x00\x12=\n\x0fworker_shutdown\x18\x10 \x01(\x0b\x32\".mxaccess_worker.v1.WorkerShutdownH\x00\x12\x44\n\x13worker_shutdown_ack\x18\x11 \x01(\x0b\x32%.mxaccess_worker.v1.WorkerShutdownAckH\x00\x12\x37\n\x0cworker_event\x18\x12 \x01(\x0b\x32\x1f.mxaccess_worker.v1.WorkerEventH\x00\x12?\n\x10worker_heartbeat\x18\x13 \x01(\x0b\x32#.mxaccess_worker.v1.WorkerHeartbeatH\x00\x12\x37\n\x0cworker_fault\x18\x14 \x01(\x0b\x32\x1f.mxaccess_worker.v1.WorkerFaultH\x00\x42\x06\n\x04\x62ody\"s\n\x0cGatewayHello\x12\"\n\x1asupported_protocol_version\x18\x01 \x01(\r\x12\r\n\x05nonce\x18\x02 \x01(\t\x12\x17\n\x0fgateway_version\x18\x03 \x01(\t\x12\x17\n\x0fmax_frame_bytes\x18\x04 \x01(\r\"i\n\x0bWorkerHello\x12\x18\n\x10protocol_version\x18\x01 \x01(\r\x12\r\n\x05nonce\x18\x02 \x01(\t\x12\x19\n\x11worker_process_id\x18\x03 \x01(\x05\x12\x16\n\x0eworker_version\x18\x04 \x01(\t\"\x8e\x01\n\x0bWorkerReady\x12\x19\n\x11worker_process_id\x18\x01 \x01(\x05\x12\x17\n\x0fmxaccess_progid\x18\x02 \x01(\t\x12\x16\n\x0emxaccess_clsid\x18\x03 \x01(\t\x12\x33\n\x0fready_timestamp\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\"w\n\rWorkerCommand\x12/\n\x07\x63ommand\x18\x01 \x01(\x0b\x32\x1e.mxaccess_gateway.v1.MxCommand\x12\x35\n\x11\x65nqueue_timestamp\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\"\x81\x01\n\x12WorkerCommandReply\x12\x32\n\x05reply\x18\x01 \x01(\x0b\x32#.mxaccess_gateway.v1.MxCommandReply\x12\x37\n\x13\x63ompleted_timestamp\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\"\x1e\n\x0cWorkerCancel\x12\x0e\n\x06reason\x18\x01 \x01(\t\"Q\n\x0eWorkerShutdown\x12/\n\x0cgrace_period\x18\x01 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x0e\n\x06reason\x18\x02 \x01(\t\"H\n\x11WorkerShutdownAck\x12\x33\n\x06status\x18\x01 \x01(\x0b\x32#.mxaccess_gateway.v1.ProtocolStatus\":\n\x0bWorkerEvent\x12+\n\x05\x65vent\x18\x01 \x01(\x0b\x32\x1c.mxaccess_gateway.v1.MxEvent\"\xa5\x02\n\x0fWorkerHeartbeat\x12\x19\n\x11worker_process_id\x18\x01 \x01(\x05\x12.\n\x05state\x18\x02 \x01(\x0e\x32\x1f.mxaccess_worker.v1.WorkerState\x12?\n\x1blast_sta_activity_timestamp\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x1d\n\x15pending_command_count\x18\x04 \x01(\r\x12\"\n\x1aoutbound_event_queue_depth\x18\x05 \x01(\r\x12\x1b\n\x13last_event_sequence\x18\x06 \x01(\x04\x12&\n\x1e\x63urrent_command_correlation_id\x18\x07 \x01(\t\"\xf4\x01\n\x0bWorkerFault\x12\x39\n\x08\x63\x61tegory\x18\x01 \x01(\x0e\x32\'.mxaccess_worker.v1.WorkerFaultCategory\x12\x16\n\x0e\x63ommand_method\x18\x02 \x01(\t\x12\x14\n\x07hresult\x18\x03 \x01(\x05H\x00\x88\x01\x01\x12\x16\n\x0e\x65xception_type\x18\x04 \x01(\t\x12\x1a\n\x12\x64iagnostic_message\x18\x05 \x01(\t\x12<\n\x0fprotocol_status\x18\x06 \x01(\x0b\x32#.mxaccess_gateway.v1.ProtocolStatusB\n\n\x08_hresult*\x97\x02\n\x0bWorkerState\x12\x1c\n\x18WORKER_STATE_UNSPECIFIED\x10\x00\x12\x19\n\x15WORKER_STATE_STARTING\x10\x01\x12\x1c\n\x18WORKER_STATE_HANDSHAKING\x10\x02\x12!\n\x1dWORKER_STATE_INITIALIZING_STA\x10\x03\x12\x16\n\x12WORKER_STATE_READY\x10\x04\x12\"\n\x1eWORKER_STATE_EXECUTING_COMMAND\x10\x05\x12\x1e\n\x1aWORKER_STATE_SHUTTING_DOWN\x10\x06\x12\x18\n\x14WORKER_STATE_STOPPED\x10\x07\x12\x18\n\x14WORKER_STATE_FAULTED\x10\x08*\xc7\x04\n\x13WorkerFaultCategory\x12%\n!WORKER_FAULT_CATEGORY_UNSPECIFIED\x10\x00\x12+\n\'WORKER_FAULT_CATEGORY_INVALID_ARGUMENTS\x10\x01\x12\x37\n3WORKER_FAULT_CATEGORY_GATEWAY_AUTHENTICATION_FAILED\x10\x02\x12+\n\'WORKER_FAULT_CATEGORY_PROTOCOL_MISMATCH\x10\x03\x12,\n(WORKER_FAULT_CATEGORY_PROTOCOL_VIOLATION\x10\x04\x12+\n\'WORKER_FAULT_CATEGORY_PIPE_DISCONNECTED\x10\x05\x12\x32\n.WORKER_FAULT_CATEGORY_MXACCESS_CREATION_FAILED\x10\x06\x12\x31\n-WORKER_FAULT_CATEGORY_MXACCESS_COMMAND_FAILED\x10\x07\x12:\n6WORKER_FAULT_CATEGORY_MXACCESS_EVENT_CONVERSION_FAILED\x10\x08\x12\"\n\x1eWORKER_FAULT_CATEGORY_STA_HUNG\x10\t\x12(\n$WORKER_FAULT_CATEGORY_QUEUE_OVERFLOW\x10\n\x12*\n&WORKER_FAULT_CATEGORY_SHUTDOWN_TIMEOUT\x10\x0b\x42&\xaa\x02#ZB.MOM.WW.MxGateway.Contracts.Protob\x06proto3')
|
||||
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x15mxaccess_worker.proto\x12\x12mxaccess_worker.v1\x1a\x1egoogle/protobuf/duration.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x16mxaccess_gateway.proto\"\x95\x06\n\x0eWorkerEnvelope\x12\x18\n\x10protocol_version\x18\x01 \x01(\r\x12\x12\n\nsession_id\x18\x02 \x01(\t\x12\x10\n\x08sequence\x18\x03 \x01(\x04\x12\x16\n\x0e\x63orrelation_id\x18\x04 \x01(\t\x12\x39\n\rgateway_hello\x18\n \x01(\x0b\x32 .mxaccess_worker.v1.GatewayHelloH\x00\x12\x37\n\x0cworker_hello\x18\x0b \x01(\x0b\x32\x1f.mxaccess_worker.v1.WorkerHelloH\x00\x12\x37\n\x0cworker_ready\x18\x0c \x01(\x0b\x32\x1f.mxaccess_worker.v1.WorkerReadyH\x00\x12;\n\x0eworker_command\x18\r \x01(\x0b\x32!.mxaccess_worker.v1.WorkerCommandH\x00\x12\x46\n\x14worker_command_reply\x18\x0e \x01(\x0b\x32&.mxaccess_worker.v1.WorkerCommandReplyH\x00\x12\x39\n\rworker_cancel\x18\x0f \x01(\x0b\x32 .mxaccess_worker.v1.WorkerCancelH\x00\x12=\n\x0fworker_shutdown\x18\x10 \x01(\x0b\x32\".mxaccess_worker.v1.WorkerShutdownH\x00\x12\x44\n\x13worker_shutdown_ack\x18\x11 \x01(\x0b\x32%.mxaccess_worker.v1.WorkerShutdownAckH\x00\x12\x37\n\x0cworker_event\x18\x12 \x01(\x0b\x32\x1f.mxaccess_worker.v1.WorkerEventH\x00\x12?\n\x10worker_heartbeat\x18\x13 \x01(\x0b\x32#.mxaccess_worker.v1.WorkerHeartbeatH\x00\x12\x37\n\x0cworker_fault\x18\x14 \x01(\x0b\x32\x1f.mxaccess_worker.v1.WorkerFaultH\x00\x42\x06\n\x04\x62ody\"s\n\x0cGatewayHello\x12\"\n\x1asupported_protocol_version\x18\x01 \x01(\r\x12\r\n\x05nonce\x18\x02 \x01(\t\x12\x17\n\x0fgateway_version\x18\x03 \x01(\t\x12\x17\n\x0fmax_frame_bytes\x18\x04 \x01(\r\"i\n\x0bWorkerHello\x12\x18\n\x10protocol_version\x18\x01 \x01(\r\x12\r\n\x05nonce\x18\x02 \x01(\t\x12\x19\n\x11worker_process_id\x18\x03 \x01(\x05\x12\x16\n\x0eworker_version\x18\x04 \x01(\t\"\xae\x01\n\x0bWorkerReady\x12\x19\n\x11worker_process_id\x18\x01 \x01(\x05\x12\x17\n\x0fmxaccess_progid\x18\x02 \x01(\t\x12\x16\n\x0emxaccess_clsid\x18\x03 \x01(\t\x12\x33\n\x0fready_timestamp\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x1e\n\x16record_info_pin_status\x18\x05 \x01(\t\"w\n\rWorkerCommand\x12/\n\x07\x63ommand\x18\x01 \x01(\x0b\x32\x1e.mxaccess_gateway.v1.MxCommand\x12\x35\n\x11\x65nqueue_timestamp\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\"\x81\x01\n\x12WorkerCommandReply\x12\x32\n\x05reply\x18\x01 \x01(\x0b\x32#.mxaccess_gateway.v1.MxCommandReply\x12\x37\n\x13\x63ompleted_timestamp\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\"\x1e\n\x0cWorkerCancel\x12\x0e\n\x06reason\x18\x01 \x01(\t\"Q\n\x0eWorkerShutdown\x12/\n\x0cgrace_period\x18\x01 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x0e\n\x06reason\x18\x02 \x01(\t\"H\n\x11WorkerShutdownAck\x12\x33\n\x06status\x18\x01 \x01(\x0b\x32#.mxaccess_gateway.v1.ProtocolStatus\":\n\x0bWorkerEvent\x12+\n\x05\x65vent\x18\x01 \x01(\x0b\x32\x1c.mxaccess_gateway.v1.MxEvent\"\xa5\x02\n\x0fWorkerHeartbeat\x12\x19\n\x11worker_process_id\x18\x01 \x01(\x05\x12.\n\x05state\x18\x02 \x01(\x0e\x32\x1f.mxaccess_worker.v1.WorkerState\x12?\n\x1blast_sta_activity_timestamp\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x1d\n\x15pending_command_count\x18\x04 \x01(\r\x12\"\n\x1aoutbound_event_queue_depth\x18\x05 \x01(\r\x12\x1b\n\x13last_event_sequence\x18\x06 \x01(\x04\x12&\n\x1e\x63urrent_command_correlation_id\x18\x07 \x01(\t\"\xf4\x01\n\x0bWorkerFault\x12\x39\n\x08\x63\x61tegory\x18\x01 \x01(\x0e\x32\'.mxaccess_worker.v1.WorkerFaultCategory\x12\x16\n\x0e\x63ommand_method\x18\x02 \x01(\t\x12\x14\n\x07hresult\x18\x03 \x01(\x05H\x00\x88\x01\x01\x12\x16\n\x0e\x65xception_type\x18\x04 \x01(\t\x12\x1a\n\x12\x64iagnostic_message\x18\x05 \x01(\t\x12<\n\x0fprotocol_status\x18\x06 \x01(\x0b\x32#.mxaccess_gateway.v1.ProtocolStatusB\n\n\x08_hresult*\x97\x02\n\x0bWorkerState\x12\x1c\n\x18WORKER_STATE_UNSPECIFIED\x10\x00\x12\x19\n\x15WORKER_STATE_STARTING\x10\x01\x12\x1c\n\x18WORKER_STATE_HANDSHAKING\x10\x02\x12!\n\x1dWORKER_STATE_INITIALIZING_STA\x10\x03\x12\x16\n\x12WORKER_STATE_READY\x10\x04\x12\"\n\x1eWORKER_STATE_EXECUTING_COMMAND\x10\x05\x12\x1e\n\x1aWORKER_STATE_SHUTTING_DOWN\x10\x06\x12\x18\n\x14WORKER_STATE_STOPPED\x10\x07\x12\x18\n\x14WORKER_STATE_FAULTED\x10\x08*\xc7\x04\n\x13WorkerFaultCategory\x12%\n!WORKER_FAULT_CATEGORY_UNSPECIFIED\x10\x00\x12+\n\'WORKER_FAULT_CATEGORY_INVALID_ARGUMENTS\x10\x01\x12\x37\n3WORKER_FAULT_CATEGORY_GATEWAY_AUTHENTICATION_FAILED\x10\x02\x12+\n\'WORKER_FAULT_CATEGORY_PROTOCOL_MISMATCH\x10\x03\x12,\n(WORKER_FAULT_CATEGORY_PROTOCOL_VIOLATION\x10\x04\x12+\n\'WORKER_FAULT_CATEGORY_PIPE_DISCONNECTED\x10\x05\x12\x32\n.WORKER_FAULT_CATEGORY_MXACCESS_CREATION_FAILED\x10\x06\x12\x31\n-WORKER_FAULT_CATEGORY_MXACCESS_COMMAND_FAILED\x10\x07\x12:\n6WORKER_FAULT_CATEGORY_MXACCESS_EVENT_CONVERSION_FAILED\x10\x08\x12\"\n\x1eWORKER_FAULT_CATEGORY_STA_HUNG\x10\t\x12(\n$WORKER_FAULT_CATEGORY_QUEUE_OVERFLOW\x10\n\x12*\n&WORKER_FAULT_CATEGORY_SHUTDOWN_TIMEOUT\x10\x0b\x42&\xaa\x02#ZB.MOM.WW.MxGateway.Contracts.Protob\x06proto3')
|
||||
|
||||
_globals = globals()
|
||||
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
|
||||
@@ -35,10 +35,10 @@ _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'mxaccess_worker_pb2', _glob
|
||||
if not _descriptor._USE_C_DESCRIPTORS:
|
||||
_globals['DESCRIPTOR']._loaded_options = None
|
||||
_globals['DESCRIPTOR']._serialized_options = b'\252\002#ZB.MOM.WW.MxGateway.Contracts.Proto'
|
||||
_globals['_WORKERSTATE']._serialized_start=2341
|
||||
_globals['_WORKERSTATE']._serialized_end=2620
|
||||
_globals['_WORKERFAULTCATEGORY']._serialized_start=2623
|
||||
_globals['_WORKERFAULTCATEGORY']._serialized_end=3206
|
||||
_globals['_WORKERSTATE']._serialized_start=2373
|
||||
_globals['_WORKERSTATE']._serialized_end=2652
|
||||
_globals['_WORKERFAULTCATEGORY']._serialized_start=2655
|
||||
_globals['_WORKERFAULTCATEGORY']._serialized_end=3238
|
||||
_globals['_WORKERENVELOPE']._serialized_start=135
|
||||
_globals['_WORKERENVELOPE']._serialized_end=924
|
||||
_globals['_GATEWAYHELLO']._serialized_start=926
|
||||
@@ -46,21 +46,21 @@ if not _descriptor._USE_C_DESCRIPTORS:
|
||||
_globals['_WORKERHELLO']._serialized_start=1043
|
||||
_globals['_WORKERHELLO']._serialized_end=1148
|
||||
_globals['_WORKERREADY']._serialized_start=1151
|
||||
_globals['_WORKERREADY']._serialized_end=1293
|
||||
_globals['_WORKERCOMMAND']._serialized_start=1295
|
||||
_globals['_WORKERCOMMAND']._serialized_end=1414
|
||||
_globals['_WORKERCOMMANDREPLY']._serialized_start=1417
|
||||
_globals['_WORKERCOMMANDREPLY']._serialized_end=1546
|
||||
_globals['_WORKERCANCEL']._serialized_start=1548
|
||||
_globals['_WORKERCANCEL']._serialized_end=1578
|
||||
_globals['_WORKERSHUTDOWN']._serialized_start=1580
|
||||
_globals['_WORKERSHUTDOWN']._serialized_end=1661
|
||||
_globals['_WORKERSHUTDOWNACK']._serialized_start=1663
|
||||
_globals['_WORKERSHUTDOWNACK']._serialized_end=1735
|
||||
_globals['_WORKEREVENT']._serialized_start=1737
|
||||
_globals['_WORKEREVENT']._serialized_end=1795
|
||||
_globals['_WORKERHEARTBEAT']._serialized_start=1798
|
||||
_globals['_WORKERHEARTBEAT']._serialized_end=2091
|
||||
_globals['_WORKERFAULT']._serialized_start=2094
|
||||
_globals['_WORKERFAULT']._serialized_end=2338
|
||||
_globals['_WORKERREADY']._serialized_end=1325
|
||||
_globals['_WORKERCOMMAND']._serialized_start=1327
|
||||
_globals['_WORKERCOMMAND']._serialized_end=1446
|
||||
_globals['_WORKERCOMMANDREPLY']._serialized_start=1449
|
||||
_globals['_WORKERCOMMANDREPLY']._serialized_end=1578
|
||||
_globals['_WORKERCANCEL']._serialized_start=1580
|
||||
_globals['_WORKERCANCEL']._serialized_end=1610
|
||||
_globals['_WORKERSHUTDOWN']._serialized_start=1612
|
||||
_globals['_WORKERSHUTDOWN']._serialized_end=1693
|
||||
_globals['_WORKERSHUTDOWNACK']._serialized_start=1695
|
||||
_globals['_WORKERSHUTDOWNACK']._serialized_end=1767
|
||||
_globals['_WORKEREVENT']._serialized_start=1769
|
||||
_globals['_WORKEREVENT']._serialized_end=1827
|
||||
_globals['_WORKERHEARTBEAT']._serialized_start=1830
|
||||
_globals['_WORKERHEARTBEAT']._serialized_end=2123
|
||||
_globals['_WORKERFAULT']._serialized_start=2126
|
||||
_globals['_WORKERFAULT']._serialized_end=2370
|
||||
# @@protoc_insertion_point(module_scope)
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections.abc import AsyncIterator, Sequence
|
||||
from typing import Any
|
||||
|
||||
@@ -29,6 +30,8 @@ class Session:
|
||||
self.session_id = session_id
|
||||
self.open_reply = open_reply
|
||||
self._closed = False
|
||||
self._close_lock = asyncio.Lock()
|
||||
self._close_reply: pb.CloseSessionReply | None = None
|
||||
|
||||
async def __aenter__(self) -> "Session":
|
||||
"""Return self to support ``async with`` usage."""
|
||||
@@ -39,23 +42,26 @@ class Session:
|
||||
await self.close()
|
||||
|
||||
async def close(self, *, client_correlation_id: str = "") -> pb.CloseSessionReply:
|
||||
"""Close the gateway session. Repeated calls return a local closed reply."""
|
||||
"""Close the gateway session.
|
||||
|
||||
if self._closed:
|
||||
return pb.CloseSessionReply(
|
||||
session_id=self.session_id,
|
||||
final_state=pb.SESSION_STATE_CLOSED,
|
||||
protocol_status=pb.ProtocolStatus(code=pb.PROTOCOL_STATUS_CODE_OK),
|
||||
Concurrency-safe: concurrent and repeated calls issue a single
|
||||
CloseSession RPC and all return the gateway's real reply. If the RPC
|
||||
raises, nothing is cached and a later call may retry.
|
||||
"""
|
||||
|
||||
async with self._close_lock:
|
||||
if self._close_reply is not None:
|
||||
return self._close_reply
|
||||
|
||||
reply = await self.client.close_session_raw(
|
||||
pb.CloseSessionRequest(
|
||||
session_id=self.session_id,
|
||||
client_correlation_id=client_correlation_id,
|
||||
),
|
||||
)
|
||||
|
||||
reply = await self.client.close_session_raw(
|
||||
pb.CloseSessionRequest(
|
||||
session_id=self.session_id,
|
||||
client_correlation_id=client_correlation_id,
|
||||
),
|
||||
)
|
||||
self._closed = True
|
||||
return reply
|
||||
self._closed = True
|
||||
self._close_reply = reply
|
||||
return reply
|
||||
|
||||
async def invoke(self, command: pb.MxCommand, *, correlation_id: str = "") -> pb.MxCommandReply:
|
||||
"""Invoke a raw command and enforce gateway and MXAccess success."""
|
||||
|
||||
@@ -374,3 +374,34 @@ class FakeStream:
|
||||
|
||||
def cancel(self) -> None:
|
||||
self.cancelled = True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_session_close_is_concurrency_safe_and_caches_real_reply() -> None:
|
||||
stub = FakeGatewayStub()
|
||||
real = stub.close_session.replies[0]
|
||||
real.final_state = pb.SESSION_STATE_CLOSED
|
||||
original_call = stub.close_session.__call__
|
||||
|
||||
async def slow_close(request: Any, *, metadata: Any) -> Any:
|
||||
await asyncio.sleep(0.01)
|
||||
return await original_call(request, metadata=metadata)
|
||||
|
||||
class SlowUnary:
|
||||
requests = stub.close_session.requests
|
||||
|
||||
async def __call__(self, request: Any, *, metadata: Any) -> Any:
|
||||
return await slow_close(request, metadata=metadata)
|
||||
|
||||
stub.CloseSession = SlowUnary()
|
||||
client = await GatewayClient.connect(
|
||||
ClientOptions(endpoint="fake", api_key="k", plaintext=True),
|
||||
stub=stub,
|
||||
)
|
||||
session = await client.open_session(client_session_name="pytest")
|
||||
|
||||
replies = await asyncio.gather(*(session.close() for _ in range(5)))
|
||||
|
||||
assert len(stub.close_session.requests) == 1
|
||||
assert all(r is real for r in replies)
|
||||
assert (await session.close()) is real
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
//! `batch` command: stdin-driven multi-command session.
|
||||
|
||||
use std::io::{self, BufRead, Write};
|
||||
|
||||
use clap::Parser;
|
||||
use zb_mom_ww_mxgateway_client::Error;
|
||||
|
||||
use crate::cli::*;
|
||||
use crate::dispatch;
|
||||
|
||||
/// End-of-result sentinel written to stdout after every batch command.
|
||||
pub(crate) const BATCH_EOR: &str = "__MXGW_BATCH_EOR__";
|
||||
|
||||
/// Run the batch loop: read one command line at a time from stdin, dispatch
|
||||
/// each through the normal [`dispatch`] path, and write [`BATCH_EOR`] to
|
||||
/// stdout after every result. Errors are serialised as JSON to stdout so
|
||||
/// the harness can parse them without interleaving stderr. The loop never
|
||||
/// terminates on command error or accidental blank lines; only stdin EOF
|
||||
/// ends the session — empty lines log an empty-EOR-bracketed result and
|
||||
/// continue.
|
||||
///
|
||||
/// `std::io::Stdin::lock().lines()` is a blocking iterator and the dispatch
|
||||
/// future is spawned on a separate tokio task so the runtime's main worker
|
||||
/// stays free. When the runtime is multi-threaded the blocking read keeps
|
||||
/// one worker parked on `ReadFile`; that is acceptable here because no other
|
||||
/// future on the main task needs to run while we wait for the next command.
|
||||
pub(crate) async fn run_batch() -> Result<(), Error> {
|
||||
let stdin = io::stdin();
|
||||
let stdout = io::stdout();
|
||||
|
||||
for line in stdin.lock().lines() {
|
||||
let line = line.map_err(|e| Error::InvalidArgument {
|
||||
name: "stdin".to_owned(),
|
||||
detail: e.to_string(),
|
||||
})?;
|
||||
|
||||
let parts: Vec<&str> = line.split_ascii_whitespace().collect();
|
||||
if parts.is_empty() {
|
||||
// Empty / whitespace-only line: log an empty-EOR-bracketed
|
||||
// result and continue so accidental blank lines from the
|
||||
// PowerShell e2e harness do not silently end the session.
|
||||
println!("{BATCH_EOR}");
|
||||
stdout.lock().flush().ok();
|
||||
continue;
|
||||
}
|
||||
|
||||
// Re-parse the split arguments under a fresh Cli, prepending the
|
||||
// program-name placeholder so clap sees a complete argv[].
|
||||
let parse_result =
|
||||
Cli::try_parse_from(std::iter::once("mxgw-cli").chain(parts.iter().copied()));
|
||||
|
||||
let outcome: Result<(), Error> = match parse_result {
|
||||
Ok(cli) => {
|
||||
// Spawn on a new tokio task so each command runs with a fresh
|
||||
// stack, avoiding stack overflow from the large dispatch future.
|
||||
tokio::task::spawn(dispatch(cli.command))
|
||||
.await
|
||||
.unwrap_or_else(|join_err| {
|
||||
Err(Error::InvalidArgument {
|
||||
name: "task".to_owned(),
|
||||
detail: join_err.to_string(),
|
||||
})
|
||||
})
|
||||
}
|
||||
Err(clap_err) => Err(Error::InvalidArgument {
|
||||
name: "args".to_owned(),
|
||||
detail: clap_err.to_string(),
|
||||
}),
|
||||
};
|
||||
|
||||
if let Err(err) = outcome {
|
||||
// Write error as JSON to stdout so the harness sees it in the
|
||||
// same stream as normal output, framed by the EOR sentinel.
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::json!({ "error": err.to_string(), "type": "error" })
|
||||
);
|
||||
}
|
||||
|
||||
println!("{BATCH_EOR}");
|
||||
stdout.lock().flush().ok();
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
//! `bench-read-bulk` command: ReadBulk stress benchmark and latency statistics.
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde_json::json;
|
||||
use zb_mom_ww_mxgateway_client::generated::mxaccess_gateway::v1::{
|
||||
CloseSessionRequest, OpenSessionRequest,
|
||||
};
|
||||
use zb_mom_ww_mxgateway_client::{next_correlation_id, Error};
|
||||
|
||||
use crate::cli::*;
|
||||
use crate::connect::*;
|
||||
|
||||
/// Drive the cross-language ReadBulk stress benchmark from Rust: opens its
|
||||
/// own session, subscribes to `bulk_size` tags so the worker's per-session
|
||||
/// value cache populates from real OnDataChange events, hammers ReadBulk in
|
||||
/// a tight loop for `duration_seconds` with per-call latency capture, and
|
||||
/// emits the shared JSON stats schema the `scripts/bench-read-bulk.ps1`
|
||||
/// driver collates across all five clients.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) async fn run_bench_read_bulk(
|
||||
connection: ConnectionArgs,
|
||||
client_name: String,
|
||||
duration_seconds: u64,
|
||||
warmup_seconds: u64,
|
||||
bulk_size: usize,
|
||||
tag_start: i32,
|
||||
tag_prefix: String,
|
||||
tag_attribute: String,
|
||||
timeout_ms: u32,
|
||||
json: bool,
|
||||
) -> Result<(), Error> {
|
||||
if bulk_size == 0 {
|
||||
return Err(Error::InvalidArgument {
|
||||
name: "bulk-size".to_owned(),
|
||||
detail: "bulk-size must be positive".to_owned(),
|
||||
});
|
||||
}
|
||||
if duration_seconds == 0 {
|
||||
return Err(Error::InvalidArgument {
|
||||
name: "duration-seconds".to_owned(),
|
||||
detail: "duration-seconds must be positive".to_owned(),
|
||||
});
|
||||
}
|
||||
|
||||
// Build TestMachine_NNN.<attribute> tags with three-digit machine numbers
|
||||
// matching the existing cross-language tag-discovery convention.
|
||||
let tags: Vec<String> = (0..bulk_size)
|
||||
.map(|index| {
|
||||
format!(
|
||||
"{prefix}{number:03}.{attr}",
|
||||
prefix = tag_prefix,
|
||||
number = tag_start + index as i32,
|
||||
attr = tag_attribute,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let endpoint = connection.endpoint.clone();
|
||||
let client = connect(connection).await?;
|
||||
let session = client
|
||||
.open_session(OpenSessionRequest {
|
||||
client_session_name: client_name.clone(),
|
||||
..OpenSessionRequest::default()
|
||||
})
|
||||
.await?;
|
||||
let session_id = session.id().to_owned();
|
||||
|
||||
// Subscribe so the worker's MxAccessValueCache populates from real
|
||||
// OnDataChange events before the measurement window opens. Any per-tag
|
||||
// failures fall through silently; the bench is still meaningful for the
|
||||
// successfully-subscribed subset.
|
||||
let bench_outcome = async {
|
||||
let server_handle = session.register(&client_name).await?;
|
||||
let subscribe_results = session.subscribe_bulk(server_handle, tags.clone()).await?;
|
||||
let tags_ref: &[String] = &tags;
|
||||
let item_handles: Vec<i32> = subscribe_results
|
||||
.iter()
|
||||
.filter(|r| r.was_successful)
|
||||
.map(|r| r.item_handle)
|
||||
.collect();
|
||||
|
||||
let timeout_ms_param = timeout_ms;
|
||||
|
||||
// Warm-up: drive identical calls so any connection-pool / channel
|
||||
// setup is amortised before the measurement window opens.
|
||||
let warmup_deadline = Instant::now() + Duration::from_secs(warmup_seconds);
|
||||
while Instant::now() < warmup_deadline {
|
||||
let _ = session
|
||||
.read_bulk(server_handle, tags_ref, timeout_ms_param)
|
||||
.await;
|
||||
}
|
||||
|
||||
// Steady-state measurement window: capture per-call latency as
|
||||
// sub-millisecond f64 deltas from Instant::now() so the histogram
|
||||
// resolution matches the .NET Stopwatch / Go time.Now path.
|
||||
let mut latencies_ms: Vec<f64> = Vec::with_capacity(65_536);
|
||||
let mut total_read_results: i64 = 0;
|
||||
let mut cached_read_results: i64 = 0;
|
||||
let mut successful_calls: u64 = 0;
|
||||
let mut failed_calls: u64 = 0;
|
||||
let steady_start = Instant::now();
|
||||
let steady_deadline = steady_start + Duration::from_secs(duration_seconds);
|
||||
|
||||
while Instant::now() < steady_deadline {
|
||||
let call_start = Instant::now();
|
||||
let result = session
|
||||
.read_bulk(server_handle, tags_ref, timeout_ms_param)
|
||||
.await;
|
||||
let elapsed = call_start.elapsed();
|
||||
latencies_ms.push(elapsed.as_secs_f64() * 1000.0);
|
||||
match result {
|
||||
Ok(results) => {
|
||||
successful_calls += 1;
|
||||
for r in &results {
|
||||
total_read_results += 1;
|
||||
if r.was_cached {
|
||||
cached_read_results += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(_) => failed_calls += 1,
|
||||
}
|
||||
}
|
||||
let steady_elapsed = steady_start.elapsed();
|
||||
|
||||
// Best-effort cleanup: unsubscribe so the worker can release cache slots.
|
||||
if !item_handles.is_empty() {
|
||||
let _ = session.unsubscribe_bulk(server_handle, item_handles).await;
|
||||
}
|
||||
|
||||
let total_calls = successful_calls + failed_calls;
|
||||
let calls_per_second = if steady_elapsed.as_secs_f64() > 0.0 {
|
||||
total_calls as f64 / steady_elapsed.as_secs_f64()
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
Ok::<_, Error>(BenchStats {
|
||||
endpoint,
|
||||
client_name,
|
||||
bulk_size,
|
||||
duration_seconds,
|
||||
warmup_seconds,
|
||||
duration_ms: steady_elapsed.as_millis() as u64,
|
||||
tags: tags.clone(),
|
||||
total_calls,
|
||||
successful_calls,
|
||||
failed_calls,
|
||||
total_read_results,
|
||||
cached_read_results,
|
||||
calls_per_second,
|
||||
latencies_ms,
|
||||
})
|
||||
}
|
||||
.await;
|
||||
|
||||
// Always close the session, even if the bench loop returned an error.
|
||||
let close_result = client
|
||||
.close_session_raw(CloseSessionRequest {
|
||||
session_id: session_id.clone(),
|
||||
client_correlation_id: next_correlation_id("cli-bench-read-bulk-close"),
|
||||
})
|
||||
.await;
|
||||
|
||||
let stats = bench_outcome?;
|
||||
// Closing the session is best-effort; never let it mask a real bench error.
|
||||
let _ = close_result;
|
||||
|
||||
if json {
|
||||
let latency = percentile_summary(&stats.latencies_ms);
|
||||
let payload = json!({
|
||||
"language": "rust",
|
||||
"command": "bench-read-bulk",
|
||||
"endpoint": stats.endpoint,
|
||||
"clientName": stats.client_name,
|
||||
"bulkSize": stats.bulk_size,
|
||||
"durationSeconds": stats.duration_seconds,
|
||||
"warmupSeconds": stats.warmup_seconds,
|
||||
"durationMs": stats.duration_ms,
|
||||
"tags": stats.tags,
|
||||
"totalCalls": stats.total_calls,
|
||||
"successfulCalls": stats.successful_calls,
|
||||
"failedCalls": stats.failed_calls,
|
||||
"totalReadResults": stats.total_read_results,
|
||||
"cachedReadResults": stats.cached_read_results,
|
||||
"callsPerSecond": round_to(stats.calls_per_second, 2),
|
||||
"latencyMs": {
|
||||
"p50": round_to(latency.p50, 3),
|
||||
"p95": round_to(latency.p95, 3),
|
||||
"p99": round_to(latency.p99, 3),
|
||||
"max": round_to(latency.max, 3),
|
||||
"mean": round_to(latency.mean, 3),
|
||||
},
|
||||
});
|
||||
println!("{payload}");
|
||||
} else {
|
||||
println!("{}", stats.calls_per_second);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Collected bench-read-bulk measurements; carried in one struct so the
|
||||
/// async block can finish cleanup (unsubscribe, close-session) before the
|
||||
/// caller renders the JSON / plain output.
|
||||
pub(crate) struct BenchStats {
|
||||
endpoint: String,
|
||||
client_name: String,
|
||||
bulk_size: usize,
|
||||
duration_seconds: u64,
|
||||
warmup_seconds: u64,
|
||||
duration_ms: u64,
|
||||
tags: Vec<String>,
|
||||
total_calls: u64,
|
||||
successful_calls: u64,
|
||||
failed_calls: u64,
|
||||
total_read_results: i64,
|
||||
cached_read_results: i64,
|
||||
calls_per_second: f64,
|
||||
latencies_ms: Vec<f64>,
|
||||
}
|
||||
|
||||
/// The same `{ p50, p95, p99, max, mean }` shape every language bench emits.
|
||||
/// `p50`/`p95`/`p99` use nearest-rank with linear interpolation, matching the
|
||||
/// .NET / Go implementations so cross-language comparisons are apples-to-apples.
|
||||
pub(crate) struct LatencySummary {
|
||||
pub(crate) p50: f64,
|
||||
pub(crate) p95: f64,
|
||||
pub(crate) p99: f64,
|
||||
pub(crate) max: f64,
|
||||
pub(crate) mean: f64,
|
||||
}
|
||||
|
||||
pub(crate) fn percentile_summary(sample: &[f64]) -> LatencySummary {
|
||||
if sample.is_empty() {
|
||||
return LatencySummary {
|
||||
p50: 0.0,
|
||||
p95: 0.0,
|
||||
p99: 0.0,
|
||||
max: 0.0,
|
||||
mean: 0.0,
|
||||
};
|
||||
}
|
||||
let mut sorted: Vec<f64> = sample.to_vec();
|
||||
sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
|
||||
let max = sorted[sorted.len() - 1];
|
||||
let mean: f64 = sample.iter().copied().sum::<f64>() / sample.len() as f64;
|
||||
LatencySummary {
|
||||
p50: percentile(&sorted, 0.50),
|
||||
p95: percentile(&sorted, 0.95),
|
||||
p99: percentile(&sorted, 0.99),
|
||||
max,
|
||||
mean,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn percentile(sorted: &[f64], quantile: f64) -> f64 {
|
||||
if sorted.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
if sorted.len() == 1 {
|
||||
return sorted[0];
|
||||
}
|
||||
let rank = quantile * (sorted.len() - 1) as f64;
|
||||
let lower = rank.floor() as usize;
|
||||
let upper = lower + 1;
|
||||
if upper >= sorted.len() {
|
||||
return sorted[lower];
|
||||
}
|
||||
let fraction = rank - lower as f64;
|
||||
sorted[lower] + (sorted[upper] - sorted[lower]) * fraction
|
||||
}
|
||||
|
||||
pub(crate) fn round_to(value: f64, digits: u32) -> f64 {
|
||||
let shift = 10f64.powi(digits as i32);
|
||||
(value * shift).round() / shift
|
||||
}
|
||||
|
||||
/// Run the `bench` command group.
|
||||
pub(crate) async fn run(command: Command) -> Result<(), Error> {
|
||||
match command {
|
||||
Command::BenchReadBulk {
|
||||
connection,
|
||||
client_name,
|
||||
duration_seconds,
|
||||
warmup_seconds,
|
||||
bulk_size,
|
||||
tag_start,
|
||||
tag_prefix,
|
||||
tag_attribute,
|
||||
timeout_ms,
|
||||
json,
|
||||
} => {
|
||||
run_bench_read_bulk(
|
||||
connection,
|
||||
client_name,
|
||||
duration_seconds,
|
||||
warmup_seconds,
|
||||
bulk_size,
|
||||
tag_start,
|
||||
tag_prefix,
|
||||
tag_attribute,
|
||||
timeout_ms,
|
||||
json,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
_ => unreachable!("command routed to the wrong group"),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
//! Bulk item commands: subscribe, unsubscribe, read and write bulk.
|
||||
|
||||
use zb_mom_ww_mxgateway_client::generated::mxaccess_gateway::v1::{
|
||||
MxValue as ProtoMxValue, Write2BulkEntry, WriteBulkEntry, WriteSecured2BulkEntry,
|
||||
WriteSecuredBulkEntry,
|
||||
};
|
||||
use zb_mom_ww_mxgateway_client::{Error, MxValue};
|
||||
|
||||
use crate::cli::*;
|
||||
use crate::connect::*;
|
||||
use crate::output::*;
|
||||
use crate::parse::*;
|
||||
|
||||
/// Run the `bulk` command group.
|
||||
pub(crate) async fn run(command: Command) -> Result<(), Error> {
|
||||
match command {
|
||||
Command::SubscribeBulk {
|
||||
connection,
|
||||
session_id,
|
||||
server_handle,
|
||||
items,
|
||||
json,
|
||||
} => {
|
||||
let session = session_for(connection, session_id).await?;
|
||||
let results = session.subscribe_bulk(server_handle, items).await?;
|
||||
print_bulk_results("subscribe-bulk", &results, json);
|
||||
}
|
||||
Command::UnsubscribeBulk {
|
||||
connection,
|
||||
session_id,
|
||||
server_handle,
|
||||
item_handles,
|
||||
json,
|
||||
} => {
|
||||
let session = session_for(connection, session_id).await?;
|
||||
let results = session
|
||||
.unsubscribe_bulk(server_handle, item_handles)
|
||||
.await?;
|
||||
print_bulk_results("unsubscribe-bulk", &results, json);
|
||||
}
|
||||
Command::ReadBulk {
|
||||
connection,
|
||||
session_id,
|
||||
server_handle,
|
||||
items,
|
||||
timeout_ms,
|
||||
json,
|
||||
} => {
|
||||
let session = session_for(connection, session_id).await?;
|
||||
let results = session.read_bulk(server_handle, &items, timeout_ms).await?;
|
||||
print_read_bulk_results("read-bulk", &results, json);
|
||||
}
|
||||
Command::WriteBulk {
|
||||
connection,
|
||||
session_id,
|
||||
server_handle,
|
||||
item_handles,
|
||||
value_type,
|
||||
values,
|
||||
user_id,
|
||||
json,
|
||||
} => {
|
||||
let entries = build_write_bulk_entries(&item_handles, value_type, &values)?;
|
||||
let session = session_for(connection, session_id).await?;
|
||||
let results = session
|
||||
.write_bulk(
|
||||
server_handle,
|
||||
entries
|
||||
.into_iter()
|
||||
.map(|(item_handle, value)| WriteBulkEntry {
|
||||
item_handle,
|
||||
value: Some(value),
|
||||
user_id,
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
.await?;
|
||||
print_write_bulk_results("write-bulk", &results, json);
|
||||
}
|
||||
Command::Write2Bulk {
|
||||
connection,
|
||||
session_id,
|
||||
server_handle,
|
||||
item_handles,
|
||||
value_type,
|
||||
values,
|
||||
timestamp,
|
||||
user_id,
|
||||
json,
|
||||
} => {
|
||||
let entries = build_write_bulk_entries(&item_handles, value_type, &values)?;
|
||||
let timestamp_value: ProtoMxValue = MxValue::string(timestamp).into_proto();
|
||||
let session = session_for(connection, session_id).await?;
|
||||
let results = session
|
||||
.write2_bulk(
|
||||
server_handle,
|
||||
entries
|
||||
.into_iter()
|
||||
.map(|(item_handle, value)| Write2BulkEntry {
|
||||
item_handle,
|
||||
value: Some(value),
|
||||
timestamp_value: Some(timestamp_value.clone()),
|
||||
user_id,
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
.await?;
|
||||
print_write_bulk_results("write2-bulk", &results, json);
|
||||
}
|
||||
Command::WriteSecuredBulk {
|
||||
connection,
|
||||
session_id,
|
||||
server_handle,
|
||||
item_handles,
|
||||
value_type,
|
||||
values,
|
||||
current_user_id,
|
||||
verifier_user_id,
|
||||
json,
|
||||
} => {
|
||||
let entries = build_write_bulk_entries(&item_handles, value_type, &values)?;
|
||||
let session = session_for(connection, session_id).await?;
|
||||
let results = session
|
||||
.write_secured_bulk(
|
||||
server_handle,
|
||||
entries
|
||||
.into_iter()
|
||||
.map(|(item_handle, value)| WriteSecuredBulkEntry {
|
||||
item_handle,
|
||||
value: Some(value),
|
||||
current_user_id,
|
||||
verifier_user_id,
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
.await?;
|
||||
print_write_bulk_results("write-secured-bulk", &results, json);
|
||||
}
|
||||
Command::WriteSecured2Bulk {
|
||||
connection,
|
||||
session_id,
|
||||
server_handle,
|
||||
item_handles,
|
||||
value_type,
|
||||
values,
|
||||
timestamp,
|
||||
current_user_id,
|
||||
verifier_user_id,
|
||||
json,
|
||||
} => {
|
||||
let entries = build_write_bulk_entries(&item_handles, value_type, &values)?;
|
||||
let timestamp_value: ProtoMxValue = MxValue::string(timestamp).into_proto();
|
||||
let session = session_for(connection, session_id).await?;
|
||||
let results = session
|
||||
.write_secured2_bulk(
|
||||
server_handle,
|
||||
entries
|
||||
.into_iter()
|
||||
.map(|(item_handle, value)| WriteSecured2BulkEntry {
|
||||
item_handle,
|
||||
value: Some(value),
|
||||
timestamp_value: Some(timestamp_value.clone()),
|
||||
current_user_id,
|
||||
verifier_user_id,
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
.await?;
|
||||
print_write_bulk_results("write-secured2-bulk", &results, json);
|
||||
}
|
||||
_ => unreachable!("command routed to the wrong group"),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,582 @@
|
||||
//! The `clap` command-line definition: `Cli`, `Command`, `GalaxyCommand` and shared connection arguments.
|
||||
|
||||
use std::env;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
use clap::{Args, Parser, Subcommand, ValueEnum};
|
||||
use zb_mom_ww_mxgateway_client::{ApiKey, ClientOptions};
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
#[command(name = "mxgw")]
|
||||
#[command(about = "MXAccess Gateway Rust test CLI")]
|
||||
pub(crate) struct Cli {
|
||||
#[command(subcommand)]
|
||||
pub(crate) command: Command,
|
||||
}
|
||||
|
||||
#[derive(Debug, Subcommand)]
|
||||
pub(crate) enum Command {
|
||||
Version {
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
Ping {
|
||||
#[command(flatten)]
|
||||
connection: ConnectionArgs,
|
||||
#[arg(long, default_value = "ping")]
|
||||
message: String,
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
OpenSession {
|
||||
#[command(flatten)]
|
||||
connection: ConnectionArgs,
|
||||
#[arg(long, default_value = "mxgw-rust-cli")]
|
||||
client_name: String,
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
CloseSession {
|
||||
#[command(flatten)]
|
||||
connection: ConnectionArgs,
|
||||
#[arg(long)]
|
||||
session_id: String,
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
Register {
|
||||
#[command(flatten)]
|
||||
connection: ConnectionArgs,
|
||||
#[arg(long)]
|
||||
session_id: String,
|
||||
#[arg(long, default_value = "mxgw-rust-cli")]
|
||||
client_name: String,
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
AddItem {
|
||||
#[command(flatten)]
|
||||
connection: ConnectionArgs,
|
||||
#[arg(long)]
|
||||
session_id: String,
|
||||
#[arg(long)]
|
||||
server_handle: i32,
|
||||
#[arg(long)]
|
||||
item: String,
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
Advise {
|
||||
#[command(flatten)]
|
||||
connection: ConnectionArgs,
|
||||
#[arg(long)]
|
||||
session_id: String,
|
||||
#[arg(long)]
|
||||
server_handle: i32,
|
||||
#[arg(long)]
|
||||
item_handle: i32,
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
AdviseSupervisory {
|
||||
#[command(flatten)]
|
||||
connection: ConnectionArgs,
|
||||
#[arg(long)]
|
||||
session_id: String,
|
||||
#[arg(long)]
|
||||
server_handle: i32,
|
||||
#[arg(long)]
|
||||
item_handle: i32,
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
/// Release a `ServerHandle` (and the items advised under it) via
|
||||
/// MXAccess `Unregister`.
|
||||
Unregister {
|
||||
#[command(flatten)]
|
||||
connection: ConnectionArgs,
|
||||
#[arg(long)]
|
||||
session_id: String,
|
||||
#[arg(long)]
|
||||
server_handle: i32,
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
/// Resolve an MXAccess user id from a credential via `AuthenticateUser`.
|
||||
/// The password is read from `--password` or, if omitted, from the
|
||||
/// environment variable named by `--password-env`; it is never echoed to
|
||||
/// stdout/stderr.
|
||||
AuthenticateUser {
|
||||
#[command(flatten)]
|
||||
connection: ConnectionArgs,
|
||||
#[arg(long)]
|
||||
session_id: String,
|
||||
#[arg(long)]
|
||||
server_handle: i32,
|
||||
#[arg(long)]
|
||||
verify_user: String,
|
||||
/// Verifier password. Prefer `--password-env` so the secret never
|
||||
/// appears in the process command line.
|
||||
#[arg(long)]
|
||||
password: Option<String>,
|
||||
/// Name of the environment variable holding the verifier password.
|
||||
/// Used only when `--password` is not supplied.
|
||||
#[arg(long, default_value = "MXGATEWAY_VERIFY_PASSWORD")]
|
||||
password_env: String,
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
/// Single credential-verified write via MXAccess `WriteSecured`.
|
||||
///
|
||||
/// Parity note: this fails natively unless the session has first run
|
||||
/// `authenticate-user` + `advise-supervisory` and the item carries a
|
||||
/// value-bearing body — the native failure is surfaced, not hidden.
|
||||
WriteSecured {
|
||||
#[command(flatten)]
|
||||
connection: ConnectionArgs,
|
||||
#[arg(long)]
|
||||
session_id: String,
|
||||
#[arg(long)]
|
||||
server_handle: i32,
|
||||
#[arg(long)]
|
||||
item_handle: i32,
|
||||
#[arg(long, value_enum)]
|
||||
value_type: CliValueType,
|
||||
#[arg(long)]
|
||||
value: String,
|
||||
#[arg(long, default_value_t = 0)]
|
||||
current_user_id: i32,
|
||||
#[arg(long, default_value_t = 0)]
|
||||
verifier_user_id: i32,
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
SubscribeBulk {
|
||||
#[command(flatten)]
|
||||
connection: ConnectionArgs,
|
||||
#[arg(long)]
|
||||
session_id: String,
|
||||
#[arg(long)]
|
||||
server_handle: i32,
|
||||
#[arg(long, value_delimiter = ',')]
|
||||
items: Vec<String>,
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
UnsubscribeBulk {
|
||||
#[command(flatten)]
|
||||
connection: ConnectionArgs,
|
||||
#[arg(long)]
|
||||
session_id: String,
|
||||
#[arg(long)]
|
||||
server_handle: i32,
|
||||
#[arg(long, value_delimiter = ',')]
|
||||
item_handles: Vec<i32>,
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
/// Snapshot the current value for each requested tag. Cached
|
||||
/// OnDataChange values are returned for tags that are already advised
|
||||
/// without touching the existing subscription; otherwise the worker
|
||||
/// takes a one-shot AddItem + Advise + UnAdvise + RemoveItem lifecycle.
|
||||
ReadBulk {
|
||||
#[command(flatten)]
|
||||
connection: ConnectionArgs,
|
||||
#[arg(long)]
|
||||
session_id: String,
|
||||
#[arg(long)]
|
||||
server_handle: i32,
|
||||
#[arg(long, value_delimiter = ',')]
|
||||
items: Vec<String>,
|
||||
/// Snapshot deadline in milliseconds, shared by all tags in the command. `0` uses the worker default (1000 ms).
|
||||
#[arg(long, default_value_t = 0)]
|
||||
timeout_ms: u32,
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
/// Bulk Write — one MXAccess Write per (item_handle, value) pair.
|
||||
WriteBulk {
|
||||
#[command(flatten)]
|
||||
connection: ConnectionArgs,
|
||||
#[arg(long)]
|
||||
session_id: String,
|
||||
#[arg(long)]
|
||||
server_handle: i32,
|
||||
#[arg(long, value_delimiter = ',')]
|
||||
item_handles: Vec<i32>,
|
||||
#[arg(long, value_enum)]
|
||||
value_type: CliValueType,
|
||||
#[arg(long, value_delimiter = ',')]
|
||||
values: Vec<String>,
|
||||
#[arg(long, default_value_t = 0)]
|
||||
user_id: i32,
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
/// Bulk Write2 — timestamped variant; the timestamp applies to all entries.
|
||||
Write2Bulk {
|
||||
#[command(flatten)]
|
||||
connection: ConnectionArgs,
|
||||
#[arg(long)]
|
||||
session_id: String,
|
||||
#[arg(long)]
|
||||
server_handle: i32,
|
||||
#[arg(long, value_delimiter = ',')]
|
||||
item_handles: Vec<i32>,
|
||||
#[arg(long, value_enum)]
|
||||
value_type: CliValueType,
|
||||
#[arg(long, value_delimiter = ',')]
|
||||
values: Vec<String>,
|
||||
#[arg(long)]
|
||||
timestamp: String,
|
||||
#[arg(long, default_value_t = 0)]
|
||||
user_id: i32,
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
/// Bulk WriteSecured.
|
||||
WriteSecuredBulk {
|
||||
#[command(flatten)]
|
||||
connection: ConnectionArgs,
|
||||
#[arg(long)]
|
||||
session_id: String,
|
||||
#[arg(long)]
|
||||
server_handle: i32,
|
||||
#[arg(long, value_delimiter = ',')]
|
||||
item_handles: Vec<i32>,
|
||||
#[arg(long, value_enum)]
|
||||
value_type: CliValueType,
|
||||
#[arg(long, value_delimiter = ',')]
|
||||
values: Vec<String>,
|
||||
#[arg(long, default_value_t = 0)]
|
||||
current_user_id: i32,
|
||||
#[arg(long, default_value_t = 0)]
|
||||
verifier_user_id: i32,
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
/// Bulk WriteSecured2 — timestamped + verified.
|
||||
WriteSecured2Bulk {
|
||||
#[command(flatten)]
|
||||
connection: ConnectionArgs,
|
||||
#[arg(long)]
|
||||
session_id: String,
|
||||
#[arg(long)]
|
||||
server_handle: i32,
|
||||
#[arg(long, value_delimiter = ',')]
|
||||
item_handles: Vec<i32>,
|
||||
#[arg(long, value_enum)]
|
||||
value_type: CliValueType,
|
||||
#[arg(long, value_delimiter = ',')]
|
||||
values: Vec<String>,
|
||||
#[arg(long)]
|
||||
timestamp: String,
|
||||
#[arg(long, default_value_t = 0)]
|
||||
current_user_id: i32,
|
||||
#[arg(long, default_value_t = 0)]
|
||||
verifier_user_id: i32,
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
/// Cross-language stress benchmark for ReadBulk: opens its own session,
|
||||
/// subscribes to `--bulk-size` tags so the worker's per-session value cache
|
||||
/// populates from real OnDataChange events, then hammers ReadBulk in a
|
||||
/// tight loop for `--duration-seconds` with per-call latency capture. Emits
|
||||
/// a single JSON object on stdout matching the schema the
|
||||
/// `scripts/bench-read-bulk.ps1` driver collates across all five clients.
|
||||
BenchReadBulk {
|
||||
#[command(flatten)]
|
||||
connection: ConnectionArgs,
|
||||
#[arg(long, default_value = "mxgw-rust-bench")]
|
||||
client_name: String,
|
||||
#[arg(long, default_value_t = 30)]
|
||||
duration_seconds: u64,
|
||||
#[arg(long, default_value_t = 3)]
|
||||
warmup_seconds: u64,
|
||||
#[arg(long, default_value_t = 6)]
|
||||
bulk_size: usize,
|
||||
#[arg(long, default_value_t = 1)]
|
||||
tag_start: i32,
|
||||
#[arg(long, default_value = "TestMachine_")]
|
||||
tag_prefix: String,
|
||||
#[arg(long, default_value = "TestChangingInt")]
|
||||
tag_attribute: String,
|
||||
#[arg(long, default_value_t = 1500)]
|
||||
timeout_ms: u32,
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
StreamEvents {
|
||||
#[command(flatten)]
|
||||
connection: ConnectionArgs,
|
||||
#[arg(long)]
|
||||
session_id: String,
|
||||
#[arg(long, default_value_t = 0)]
|
||||
after_worker_sequence: u64,
|
||||
#[arg(long, default_value_t = 1)]
|
||||
max_events: usize,
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
#[arg(long)]
|
||||
jsonl: bool,
|
||||
},
|
||||
/// Attach to the gateway's session-less central alarm feed. The stream
|
||||
/// opens with one `active_alarm` per currently-active alarm, then a
|
||||
/// single `snapshot_complete`, then a `transition` for every subsequent
|
||||
/// raise / acknowledge / clear.
|
||||
StreamAlarms {
|
||||
#[command(flatten)]
|
||||
connection: ConnectionArgs,
|
||||
/// Optional alarm-reference prefix scoping the feed to an equipment
|
||||
/// sub-tree. Omit to stream every active alarm.
|
||||
#[arg(long)]
|
||||
filter_prefix: Option<String>,
|
||||
#[arg(long, default_value_t = 1)]
|
||||
max_events: usize,
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
#[arg(long)]
|
||||
jsonl: bool,
|
||||
},
|
||||
/// Acknowledge an active MXAccess alarm condition through the gateway's
|
||||
/// session-less AcknowledgeAlarm RPC.
|
||||
AcknowledgeAlarm {
|
||||
#[command(flatten)]
|
||||
connection: ConnectionArgs,
|
||||
#[arg(long)]
|
||||
reference: String,
|
||||
#[arg(long, default_value = "")]
|
||||
comment: String,
|
||||
/// Galaxy account of the acknowledging operator (required; the gateway
|
||||
/// rejects an empty operator so the real operator is recorded).
|
||||
#[arg(long)]
|
||||
operator: String,
|
||||
/// Galaxy domain of the operator; empty authenticates the bare user name.
|
||||
#[arg(long, default_value = "")]
|
||||
operator_domain: String,
|
||||
/// Operator password (prefer `--operator-password-env`; empty is allowed).
|
||||
#[arg(long)]
|
||||
operator_password: Option<String>,
|
||||
/// Environment variable holding the operator password.
|
||||
#[arg(long, default_value = "MXGATEWAY_OPERATOR_PASSWORD")]
|
||||
operator_password_env: String,
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
Write {
|
||||
#[command(flatten)]
|
||||
connection: ConnectionArgs,
|
||||
#[arg(long)]
|
||||
session_id: String,
|
||||
#[arg(long)]
|
||||
server_handle: i32,
|
||||
#[arg(long)]
|
||||
item_handle: i32,
|
||||
#[arg(long, value_enum)]
|
||||
value_type: CliValueType,
|
||||
#[arg(long)]
|
||||
value: String,
|
||||
#[arg(long, default_value_t = 0)]
|
||||
user_id: i32,
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
Write2 {
|
||||
#[command(flatten)]
|
||||
connection: ConnectionArgs,
|
||||
#[arg(long)]
|
||||
session_id: String,
|
||||
#[arg(long)]
|
||||
server_handle: i32,
|
||||
#[arg(long)]
|
||||
item_handle: i32,
|
||||
#[arg(long, value_enum)]
|
||||
value_type: CliValueType,
|
||||
#[arg(long)]
|
||||
value: String,
|
||||
#[arg(long)]
|
||||
timestamp: String,
|
||||
#[arg(long, default_value_t = 0)]
|
||||
user_id: i32,
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
Smoke {
|
||||
#[command(flatten)]
|
||||
connection: ConnectionArgs,
|
||||
#[arg(long)]
|
||||
item: String,
|
||||
#[arg(long, default_value = "mxgw-rust-smoke")]
|
||||
client_name: String,
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
/// Read commands from stdin, one per line, execute each in sequence, and
|
||||
/// write `__MXGW_BATCH_EOR__` to stdout after every result. Errors are
|
||||
/// written as `{"error":"…","type":"error"}` JSON to stdout (not stderr)
|
||||
/// so the harness can parse them without interleaving stderr. The loop
|
||||
/// never terminates on command error or accidental blank lines; only
|
||||
/// stdin EOF ends the session — empty lines log an empty-EOR-bracketed
|
||||
/// result and continue, matching the other four language CLIs.
|
||||
Batch,
|
||||
#[command(subcommand)]
|
||||
Galaxy(GalaxyCommand),
|
||||
}
|
||||
|
||||
#[derive(Debug, Subcommand)]
|
||||
pub(crate) enum GalaxyCommand {
|
||||
TestConnection {
|
||||
#[command(flatten)]
|
||||
connection: ConnectionArgs,
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
LastDeployTime {
|
||||
#[command(flatten)]
|
||||
connection: ConnectionArgs,
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
DiscoverHierarchy {
|
||||
#[command(flatten)]
|
||||
connection: ConnectionArgs,
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
/// Lazily browse the Galaxy hierarchy through `BrowseChildren`.
|
||||
///
|
||||
/// With no `--parent-gobject-id` the root objects are listed; pass a
|
||||
/// parent id to list that object's direct children. `--depth` controls
|
||||
/// how many further levels are eagerly expanded (0 = the requested level
|
||||
/// only). The filter flags map onto `BrowseChildrenOptions` and are reused
|
||||
/// at every expanded level, mirroring the lazy-browse library helper.
|
||||
Browse {
|
||||
#[command(flatten)]
|
||||
connection: ConnectionArgs,
|
||||
/// Parent gobject id whose children to browse. Omit for root objects.
|
||||
#[arg(long)]
|
||||
parent_gobject_id: Option<i32>,
|
||||
/// Restrict to objects whose `category_id` matches one of these ids.
|
||||
/// Repeatable.
|
||||
#[arg(long = "category-id")]
|
||||
category_ids: Vec<i32>,
|
||||
/// Restrict to objects whose template chain contains this entry.
|
||||
/// Repeatable (combined with AND).
|
||||
#[arg(long = "template-contains")]
|
||||
template_chain_contains: Vec<String>,
|
||||
/// Restrict to objects whose tag name matches this SQL `LIKE`-style glob.
|
||||
#[arg(long)]
|
||||
tag_name_glob: Option<String>,
|
||||
/// Populate `attributes` on the returned objects.
|
||||
#[arg(long)]
|
||||
include_attributes: bool,
|
||||
/// Only return objects that own at least one alarm-bearing attribute.
|
||||
#[arg(long)]
|
||||
alarm_bearing_only: bool,
|
||||
/// Only return objects that own at least one historized attribute.
|
||||
#[arg(long)]
|
||||
historized_only: bool,
|
||||
/// Number of additional levels to eagerly expand beneath each returned
|
||||
/// node. 0 (the default) prints only the requested level.
|
||||
/// Ignored when --parent-gobject-id is specified.
|
||||
#[arg(long, default_value_t = 0)]
|
||||
depth: usize,
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
/// Subscribe to the WatchDeployEvents server stream.
|
||||
///
|
||||
/// Prints one line per received event (or one JSON object with `--json`).
|
||||
/// Runs until the stream ends, the server fails the call, or the
|
||||
/// process is interrupted (Ctrl+C).
|
||||
#[command(alias = "watch-deploy-events")]
|
||||
Watch {
|
||||
#[command(flatten)]
|
||||
connection: ConnectionArgs,
|
||||
/// Optional RFC3339 timestamp (e.g. `2026-04-28T15:30:00Z`). When
|
||||
/// supplied, the server suppresses the bootstrap event if its
|
||||
/// cached deploy time matches this value.
|
||||
#[arg(long)]
|
||||
last_seen_deploy_time: Option<String>,
|
||||
/// Optional cap on the number of events to print before exiting.
|
||||
/// 0 (the default) means run until cancelled or the stream ends.
|
||||
#[arg(long, default_value_t = 0)]
|
||||
max_events: usize,
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Args, Clone)]
|
||||
pub(crate) struct ConnectionArgs {
|
||||
#[arg(long, default_value = "http://127.0.0.1:5000")]
|
||||
pub(crate) endpoint: String,
|
||||
#[arg(long)]
|
||||
api_key: Option<String>,
|
||||
/// Name of the environment variable holding the gateway API key. The
|
||||
/// variable's value must be a full gateway key of the form
|
||||
/// `mxgw_<key-id>_<secret>`; it is forwarded verbatim as the Bearer
|
||||
/// token, so do not point this at an unrelated credential.
|
||||
#[arg(long, default_value = "MXGATEWAY_API_KEY")]
|
||||
api_key_env: String,
|
||||
/// Use an unencrypted (plaintext h2c) channel. Mutually exclusive with
|
||||
/// `--tls`; supplying both is rejected so an explicit `--tls` cannot be
|
||||
/// silently downgraded.
|
||||
#[arg(long, conflicts_with = "tls")]
|
||||
plaintext: bool,
|
||||
#[arg(long)]
|
||||
tls: bool,
|
||||
#[arg(long)]
|
||||
ca_file: Option<PathBuf>,
|
||||
#[arg(long)]
|
||||
server_name_override: Option<String>,
|
||||
/// Verify the server certificate against the system trust roots even
|
||||
/// without a pinned CA. The Rust client's default is to require a CA
|
||||
/// file (see `--ca-file`); set this flag to use system roots instead.
|
||||
#[arg(long)]
|
||||
require_certificate_validation: bool,
|
||||
#[arg(long, default_value_t = 10)]
|
||||
connect_timeout_seconds: u64,
|
||||
#[arg(long, default_value_t = 30)]
|
||||
call_timeout_seconds: u64,
|
||||
}
|
||||
|
||||
impl ConnectionArgs {
|
||||
pub(crate) fn options(&self) -> ClientOptions {
|
||||
let mut options = ClientOptions::new(self.endpoint.clone())
|
||||
.with_plaintext(!self.tls || self.plaintext)
|
||||
.with_connect_timeout(Duration::from_secs(self.connect_timeout_seconds))
|
||||
.with_call_timeout(Duration::from_secs(self.call_timeout_seconds));
|
||||
|
||||
if let Some(api_key) = self
|
||||
.api_key
|
||||
.clone()
|
||||
.or_else(|| env::var(&self.api_key_env).ok())
|
||||
.filter(|value| !value.is_empty())
|
||||
{
|
||||
options = options.with_api_key(ApiKey::new(api_key));
|
||||
}
|
||||
if let Some(ca_file) = &self.ca_file {
|
||||
options = options.with_ca_file(ca_file);
|
||||
}
|
||||
if let Some(server_name_override) = &self.server_name_override {
|
||||
options = options.with_server_name_override(server_name_override);
|
||||
}
|
||||
if self.require_certificate_validation {
|
||||
options = options.with_require_certificate_validation(true);
|
||||
}
|
||||
|
||||
options
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, ValueEnum)]
|
||||
pub(crate) enum CliValueType {
|
||||
Bool,
|
||||
Int32,
|
||||
Int64,
|
||||
Float,
|
||||
Double,
|
||||
String,
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
//! Gateway and Galaxy client construction helpers.
|
||||
|
||||
use zb_mom_ww_mxgateway_client::{Error, GalaxyClient, GatewayClient};
|
||||
|
||||
use crate::cli::*;
|
||||
|
||||
pub(crate) async fn connect(connection: ConnectionArgs) -> Result<GatewayClient, Error> {
|
||||
GatewayClient::connect(connection.options()).await
|
||||
}
|
||||
|
||||
pub(crate) async fn connect_galaxy(connection: ConnectionArgs) -> Result<GalaxyClient, Error> {
|
||||
GalaxyClient::connect(connection.options()).await
|
||||
}
|
||||
|
||||
pub(crate) async fn session_for(
|
||||
connection: ConnectionArgs,
|
||||
session_id: String,
|
||||
) -> Result<zb_mom_ww_mxgateway_client::Session, Error> {
|
||||
let client = connect(connection).await?;
|
||||
Ok(client.session(session_id))
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
//! Event and alarm commands (`stream-events`, `stream-alarms`, `acknowledge-alarm`) and their JSON rendering.
|
||||
|
||||
use std::env;
|
||||
|
||||
use futures_util::StreamExt;
|
||||
use serde_json::json;
|
||||
use serde_json::Value;
|
||||
use zb_mom_ww_mxgateway_client::generated::mxaccess_gateway::v1::{
|
||||
alarm_feed_message, AcknowledgeAlarmRequest, AlarmFeedMessage, MxEvent, MxEventFamily,
|
||||
MxValue as ProtoMxValue, StreamAlarmsRequest, StreamEventsRequest,
|
||||
};
|
||||
use zb_mom_ww_mxgateway_client::{
|
||||
next_correlation_id, Error, EventItem, MxValue, MxValueProjection,
|
||||
};
|
||||
|
||||
use crate::cli::*;
|
||||
use crate::connect::*;
|
||||
|
||||
pub(crate) const MAX_AGGREGATE_EVENTS: usize = 10_000;
|
||||
|
||||
/// Render a streamed [`MxEvent`] as a JSON object. The scalar value is
|
||||
/// projected into protojson-style `*Value` keys so the cross-language e2e
|
||||
/// matrix can extract and compare event values uniformly across all five
|
||||
/// client CLIs.
|
||||
pub(crate) fn event_to_json(event: &MxEvent) -> Value {
|
||||
// Match the other four CLIs by rendering the family as its protobuf enum
|
||||
// name (e.g. MX_EVENT_FAMILY_ON_WRITE_COMPLETE). The e2e write round-trip
|
||||
// looks up this name to confirm the OnWriteComplete echo arrived; emitting
|
||||
// the raw i32 leaves it unable to recognise any event.
|
||||
let family = MxEventFamily::try_from(event.family)
|
||||
.map(|f| f.as_str_name())
|
||||
.unwrap_or("MX_EVENT_FAMILY_UNSPECIFIED");
|
||||
json!({
|
||||
"family": family,
|
||||
"sessionId": event.session_id,
|
||||
"serverHandle": event.server_handle,
|
||||
"itemHandle": event.item_handle,
|
||||
"quality": event.quality,
|
||||
"workerSequence": event.worker_sequence,
|
||||
"value": event.value.as_ref().map(event_value_to_json),
|
||||
})
|
||||
}
|
||||
|
||||
/// Project an [`MxValue`] into a protojson-shaped JSON object whose single
|
||||
/// key names the scalar kind (`int32Value`, `stringValue`, ...), matching
|
||||
/// the protobuf-JSON the .NET/Go/Java CLIs emit.
|
||||
pub(crate) fn event_value_to_json(value: &ProtoMxValue) -> Value {
|
||||
match MxValue::from_proto(value.clone()).projection() {
|
||||
MxValueProjection::Bool(inner) => json!({ "boolValue": inner }),
|
||||
MxValueProjection::Int32(inner) => json!({ "int32Value": inner }),
|
||||
// protojson renders 64-bit integers as strings; mirror that here.
|
||||
MxValueProjection::Int64(inner) => json!({ "int64Value": inner.to_string() }),
|
||||
MxValueProjection::Float(inner) => json!({ "floatValue": inner }),
|
||||
MxValueProjection::Double(inner) => json!({ "doubleValue": inner }),
|
||||
MxValueProjection::String(inner) => json!({ "stringValue": inner }),
|
||||
MxValueProjection::Timestamp(ts) => {
|
||||
json!({ "timestampValue": { "seconds": ts.seconds, "nanos": ts.nanos } })
|
||||
}
|
||||
MxValueProjection::Array(_) => json!({ "arrayValue": {} }),
|
||||
MxValueProjection::Raw(bytes) => json!({ "rawValue": { "byteCount": bytes.len() } }),
|
||||
MxValueProjection::Null => json!({ "isNull": true }),
|
||||
MxValueProjection::Unset => Value::Null,
|
||||
}
|
||||
}
|
||||
|
||||
/// Render a streamed [`AlarmFeedMessage`] as a terse one-line summary that
|
||||
/// distinguishes the five `payload` oneof cases.
|
||||
pub(crate) fn alarm_feed_message_summary(message: &AlarmFeedMessage) -> String {
|
||||
match &message.payload {
|
||||
Some(alarm_feed_message::Payload::ActiveAlarm(snapshot)) => {
|
||||
format!(
|
||||
"active-alarm {} state={}",
|
||||
snapshot.alarm_full_reference,
|
||||
AlarmEnumName::condition_state(snapshot.current_state)
|
||||
)
|
||||
}
|
||||
Some(alarm_feed_message::Payload::SnapshotComplete(complete)) => {
|
||||
format!("snapshot-complete {complete}")
|
||||
}
|
||||
Some(alarm_feed_message::Payload::Transition(transition)) => {
|
||||
format!(
|
||||
"transition {} kind={}",
|
||||
transition.alarm_full_reference,
|
||||
AlarmEnumName::transition_kind(transition.transition_kind)
|
||||
)
|
||||
}
|
||||
Some(alarm_feed_message::Payload::ProviderStatus(status)) => {
|
||||
format!(
|
||||
"provider-status mode={} degraded={} reason={:?}",
|
||||
AlarmEnumName::provider_mode(status.mode),
|
||||
status.degraded,
|
||||
status.reason
|
||||
)
|
||||
}
|
||||
Some(alarm_feed_message::Payload::SnapshotStatus(status)) => {
|
||||
format!("snapshot-status truncated={}", status.truncated)
|
||||
}
|
||||
None => "(empty)".to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Render a streamed [`AlarmFeedMessage`] as a JSON object whose single
|
||||
/// top-level key names the active `payload` oneof case, mirroring the
|
||||
/// protobuf-JSON the .NET/Go/Java/Python CLIs emit.
|
||||
pub(crate) fn alarm_feed_message_to_json(message: &AlarmFeedMessage) -> Value {
|
||||
match &message.payload {
|
||||
Some(alarm_feed_message::Payload::ActiveAlarm(snapshot)) => json!({
|
||||
"activeAlarm": {
|
||||
"alarmFullReference": snapshot.alarm_full_reference,
|
||||
"sourceObjectReference": snapshot.source_object_reference,
|
||||
"alarmTypeName": snapshot.alarm_type_name,
|
||||
"severity": snapshot.severity,
|
||||
"currentState": AlarmEnumName::condition_state(snapshot.current_state),
|
||||
"category": snapshot.category,
|
||||
"description": snapshot.description,
|
||||
"operatorUser": snapshot.operator_user,
|
||||
"operatorComment": snapshot.operator_comment,
|
||||
}
|
||||
}),
|
||||
Some(alarm_feed_message::Payload::SnapshotComplete(complete)) => json!({
|
||||
"snapshotComplete": complete,
|
||||
}),
|
||||
Some(alarm_feed_message::Payload::Transition(transition)) => json!({
|
||||
"transition": {
|
||||
"alarmFullReference": transition.alarm_full_reference,
|
||||
"sourceObjectReference": transition.source_object_reference,
|
||||
"alarmTypeName": transition.alarm_type_name,
|
||||
"transitionKind": AlarmEnumName::transition_kind(transition.transition_kind),
|
||||
"severity": transition.severity,
|
||||
"operatorUser": transition.operator_user,
|
||||
"operatorComment": transition.operator_comment,
|
||||
"category": transition.category,
|
||||
"description": transition.description,
|
||||
}
|
||||
}),
|
||||
Some(alarm_feed_message::Payload::ProviderStatus(status)) => json!({
|
||||
"providerStatus": {
|
||||
"mode": AlarmEnumName::provider_mode(status.mode),
|
||||
"degraded": status.degraded,
|
||||
"reason": status.reason,
|
||||
"since": status.since.as_ref().map(|ts| json!({
|
||||
"seconds": ts.seconds,
|
||||
"nanos": ts.nanos,
|
||||
})),
|
||||
}
|
||||
}),
|
||||
Some(alarm_feed_message::Payload::SnapshotStatus(status)) => json!({
|
||||
"snapshotStatus": {
|
||||
"truncated": status.truncated,
|
||||
}
|
||||
}),
|
||||
None => Value::Null,
|
||||
}
|
||||
}
|
||||
|
||||
/// Tiny namespace for alarm-enum name lookups used by the alarm-feed
|
||||
/// renderers; keeps the proto-enum imports off the `main.rs` top level.
|
||||
pub(crate) struct AlarmEnumName;
|
||||
|
||||
impl AlarmEnumName {
|
||||
fn condition_state(value: i32) -> String {
|
||||
use zb_mom_ww_mxgateway_client::generated::mxaccess_gateway::v1::AlarmConditionState;
|
||||
AlarmConditionState::try_from(value)
|
||||
.map(|state| state.as_str_name().to_owned())
|
||||
.unwrap_or_else(|_| value.to_string())
|
||||
}
|
||||
|
||||
fn transition_kind(value: i32) -> String {
|
||||
use zb_mom_ww_mxgateway_client::generated::mxaccess_gateway::v1::AlarmTransitionKind;
|
||||
AlarmTransitionKind::try_from(value)
|
||||
.map(|kind| kind.as_str_name().to_owned())
|
||||
.unwrap_or_else(|_| value.to_string())
|
||||
}
|
||||
|
||||
fn provider_mode(value: i32) -> String {
|
||||
use zb_mom_ww_mxgateway_client::generated::mxaccess_gateway::v1::AlarmProviderMode;
|
||||
AlarmProviderMode::try_from(value)
|
||||
.map(|mode| mode.as_str_name().to_owned())
|
||||
.unwrap_or_else(|_| value.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// Render an [`AcknowledgeAlarmReply`] as a terse line or a JSON document.
|
||||
pub(crate) fn print_acknowledge_alarm_reply(
|
||||
reply: &zb_mom_ww_mxgateway_client::generated::mxaccess_gateway::v1::AcknowledgeAlarmReply,
|
||||
use_json: bool,
|
||||
) {
|
||||
if use_json {
|
||||
println!(
|
||||
"{}",
|
||||
json!({
|
||||
"operation": "acknowledge-alarm",
|
||||
"correlationId": reply.correlation_id,
|
||||
"protocolStatus": reply.protocol_status.as_ref().map(|status| json!({
|
||||
"code": status.code,
|
||||
"message": status.message,
|
||||
})),
|
||||
"hresult": reply.hresult,
|
||||
"diagnosticMessage": reply.diagnostic_message,
|
||||
})
|
||||
);
|
||||
} else {
|
||||
println!("acknowledge-alarm completed");
|
||||
}
|
||||
}
|
||||
|
||||
/// Run the `events` command group.
|
||||
pub(crate) async fn run(command: Command) -> Result<(), Error> {
|
||||
match command {
|
||||
Command::StreamEvents {
|
||||
connection,
|
||||
session_id,
|
||||
after_worker_sequence,
|
||||
max_events,
|
||||
json,
|
||||
jsonl,
|
||||
} => {
|
||||
if max_events > MAX_AGGREGATE_EVENTS {
|
||||
return Err(Error::InvalidArgument {
|
||||
name: "max-events".to_owned(),
|
||||
detail: format!("must be less than or equal to {MAX_AGGREGATE_EVENTS}"),
|
||||
});
|
||||
}
|
||||
|
||||
let client = connect(connection).await?;
|
||||
let mut stream = client
|
||||
.stream_events(StreamEventsRequest {
|
||||
session_id,
|
||||
after_worker_sequence,
|
||||
// #227 attach acknowledgement is opt-in; this stream keeps the default wire shape.
|
||||
emit_stream_attached: false,
|
||||
})
|
||||
.await?;
|
||||
let mut events: Vec<Value> = Vec::new();
|
||||
let mut event_count = 0usize;
|
||||
while event_count < max_events {
|
||||
let Some(item) = stream.next().await else {
|
||||
break;
|
||||
};
|
||||
let item = item?;
|
||||
event_count += 1;
|
||||
match item {
|
||||
EventItem::Event(event) => {
|
||||
if jsonl {
|
||||
println!("{}", event_to_json(&event));
|
||||
} else if json {
|
||||
events.push(event_to_json(&event));
|
||||
} else {
|
||||
println!("{} {}", event.worker_sequence, event.family);
|
||||
}
|
||||
}
|
||||
// Reconnect-replay gap sentinel: recent history was evicted
|
||||
// before this resumed stream could replay it. Render it as a
|
||||
// distinct row so the caller can re-snapshot and resume with
|
||||
// `oldest_available_sequence - 1`.
|
||||
EventItem::ReplayGap(gap) => {
|
||||
let value = json!({
|
||||
"replayGap": {
|
||||
"requestedAfterSequence": gap.requested_after_sequence,
|
||||
"oldestAvailableSequence": gap.oldest_available_sequence,
|
||||
}
|
||||
});
|
||||
if jsonl {
|
||||
println!("{value}");
|
||||
} else if json {
|
||||
events.push(value);
|
||||
} else {
|
||||
println!(
|
||||
"REPLAY_GAP requested_after={} oldest_available={}",
|
||||
gap.requested_after_sequence, gap.oldest_available_sequence
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if json {
|
||||
// `eventCount` is preserved for back-compat; `events` carries
|
||||
// the per-event detail the cross-language e2e matrix compares.
|
||||
println!("{}", json!({ "eventCount": event_count, "events": events }));
|
||||
}
|
||||
}
|
||||
Command::StreamAlarms {
|
||||
connection,
|
||||
filter_prefix,
|
||||
max_events,
|
||||
json,
|
||||
jsonl,
|
||||
} => {
|
||||
if max_events > MAX_AGGREGATE_EVENTS {
|
||||
return Err(Error::InvalidArgument {
|
||||
name: "max-events".to_owned(),
|
||||
detail: format!("must be less than or equal to {MAX_AGGREGATE_EVENTS}"),
|
||||
});
|
||||
}
|
||||
|
||||
let client = connect(connection).await?;
|
||||
let mut stream = client
|
||||
.stream_alarms(StreamAlarmsRequest {
|
||||
client_correlation_id: next_correlation_id("cli-stream-alarms"),
|
||||
alarm_filter_prefix: filter_prefix.unwrap_or_default(),
|
||||
})
|
||||
.await?;
|
||||
let mut messages: Vec<Value> = Vec::new();
|
||||
let mut message_count = 0usize;
|
||||
while message_count < max_events {
|
||||
let Some(message) = stream.next().await else {
|
||||
break;
|
||||
};
|
||||
let message = message?;
|
||||
message_count += 1;
|
||||
if jsonl {
|
||||
println!("{}", alarm_feed_message_to_json(&message));
|
||||
} else if json {
|
||||
messages.push(alarm_feed_message_to_json(&message));
|
||||
} else {
|
||||
println!("{}", alarm_feed_message_summary(&message));
|
||||
}
|
||||
}
|
||||
if json {
|
||||
println!(
|
||||
"{}",
|
||||
json!({ "messageCount": message_count, "messages": messages })
|
||||
);
|
||||
}
|
||||
}
|
||||
Command::AcknowledgeAlarm {
|
||||
connection,
|
||||
reference,
|
||||
comment,
|
||||
operator,
|
||||
operator_domain,
|
||||
operator_password,
|
||||
operator_password_env,
|
||||
json,
|
||||
} => {
|
||||
// An empty password is allowed (Galaxy accounts may have one), so
|
||||
// an unset flag and env resolve to an empty string.
|
||||
let operator_password = operator_password
|
||||
.or_else(|| env::var(&operator_password_env).ok())
|
||||
.unwrap_or_default();
|
||||
let client = connect(connection).await?;
|
||||
let reply = client
|
||||
.acknowledge_alarm(AcknowledgeAlarmRequest {
|
||||
client_correlation_id: next_correlation_id("cli-acknowledge-alarm"),
|
||||
alarm_full_reference: reference,
|
||||
comment,
|
||||
operator_user: operator,
|
||||
operator_password,
|
||||
operator_domain,
|
||||
})
|
||||
.await?;
|
||||
print_acknowledge_alarm_reply(&reply, json);
|
||||
}
|
||||
_ => unreachable!("command routed to the wrong group"),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,448 @@
|
||||
//! `galaxy` command group: Galaxy Repository browse, discovery and deploy-watch.
|
||||
|
||||
use futures_util::StreamExt;
|
||||
use serde_json::json;
|
||||
use serde_json::Value;
|
||||
use zb_mom_ww_mxgateway_client::galaxy::{BrowseChildrenOptions, LazyBrowseNode};
|
||||
use zb_mom_ww_mxgateway_client::generated::galaxy_repository::v1::DeployEvent;
|
||||
use zb_mom_ww_mxgateway_client::{Error, GalaxyClient};
|
||||
|
||||
use crate::cli::*;
|
||||
use crate::connect::*;
|
||||
use crate::parse::*;
|
||||
|
||||
pub(crate) async fn run_galaxy(command: GalaxyCommand) -> Result<(), Error> {
|
||||
match command {
|
||||
GalaxyCommand::TestConnection { connection, json } => {
|
||||
let mut client = connect_galaxy(connection).await?;
|
||||
let ok = client.test_connection().await?;
|
||||
if json {
|
||||
println!("{}", json!({ "ok": ok }));
|
||||
} else if ok {
|
||||
println!("ok");
|
||||
} else {
|
||||
println!("not ok");
|
||||
}
|
||||
}
|
||||
GalaxyCommand::LastDeployTime { connection, json } => {
|
||||
let mut client = connect_galaxy(connection).await?;
|
||||
let timestamp = client.get_last_deploy_time().await?;
|
||||
match (json, timestamp) {
|
||||
(true, Some(ts)) => {
|
||||
println!(
|
||||
"{}",
|
||||
json!({
|
||||
"present": true,
|
||||
"seconds": ts.seconds,
|
||||
"nanos": ts.nanos,
|
||||
})
|
||||
);
|
||||
}
|
||||
(true, None) => {
|
||||
println!("{}", json!({ "present": false }));
|
||||
}
|
||||
(false, Some(ts)) => println!("{}.{:09}", ts.seconds, ts.nanos),
|
||||
(false, None) => println!("(absent)"),
|
||||
}
|
||||
}
|
||||
GalaxyCommand::Watch {
|
||||
connection,
|
||||
last_seen_deploy_time,
|
||||
max_events,
|
||||
json,
|
||||
} => {
|
||||
let mut client = connect_galaxy(connection).await?;
|
||||
let last_seen = last_seen_deploy_time
|
||||
.as_deref()
|
||||
.map(parse_rfc3339_timestamp)
|
||||
.transpose()?;
|
||||
let mut stream = client.watch_deploy_events(last_seen).await?;
|
||||
|
||||
let mut count = 0usize;
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
signal = tokio::signal::ctrl_c() => {
|
||||
signal.map_err(|err| Error::InvalidArgument {
|
||||
name: "ctrl_c".to_owned(),
|
||||
detail: err.to_string(),
|
||||
})?;
|
||||
// Drop the stream below by breaking; tonic tears the
|
||||
// gRPC call down cooperatively.
|
||||
break;
|
||||
}
|
||||
next = stream.next() => {
|
||||
let Some(event) = next else { break; };
|
||||
let event = event?;
|
||||
count += 1;
|
||||
print_deploy_event(&event, json);
|
||||
if max_events != 0 && count >= max_events {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
GalaxyCommand::DiscoverHierarchy { connection, json } => {
|
||||
let mut client = connect_galaxy(connection).await?;
|
||||
let objects = client.discover_hierarchy().await?;
|
||||
if json {
|
||||
let payload: Vec<_> = objects
|
||||
.iter()
|
||||
.map(|object| {
|
||||
json!({
|
||||
"gobjectId": object.gobject_id,
|
||||
"tagName": object.tag_name,
|
||||
"containedName": object.contained_name,
|
||||
"browseName": object.browse_name,
|
||||
"parentGobjectId": object.parent_gobject_id,
|
||||
"isArea": object.is_area,
|
||||
"categoryId": object.category_id,
|
||||
"hostedByGobjectId": object.hosted_by_gobject_id,
|
||||
"templateChain": object.template_chain,
|
||||
"attributes": object.attributes.iter().map(|attribute| json!({
|
||||
"attributeName": attribute.attribute_name,
|
||||
"fullTagReference": attribute.full_tag_reference,
|
||||
"mxDataType": attribute.mx_data_type,
|
||||
"dataTypeName": attribute.data_type_name,
|
||||
"isArray": attribute.is_array,
|
||||
"arrayDimension": attribute.array_dimension,
|
||||
"arrayDimensionPresent": attribute.array_dimension_present,
|
||||
"mxAttributeCategory": attribute.mx_attribute_category,
|
||||
"securityClassification": attribute.security_classification,
|
||||
"isHistorized": attribute.is_historized,
|
||||
"isAlarm": attribute.is_alarm,
|
||||
})).collect::<Vec<_>>(),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
println!("{}", json!({ "objects": payload }));
|
||||
} else {
|
||||
println!("{}", objects.len());
|
||||
for object in &objects {
|
||||
println!(
|
||||
"{} {} {} ({} attribute(s))",
|
||||
object.gobject_id,
|
||||
object.tag_name,
|
||||
object.browse_name,
|
||||
object.attributes.len()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
GalaxyCommand::Browse {
|
||||
connection,
|
||||
parent_gobject_id,
|
||||
category_ids,
|
||||
template_chain_contains,
|
||||
tag_name_glob,
|
||||
include_attributes,
|
||||
alarm_bearing_only,
|
||||
historized_only,
|
||||
depth,
|
||||
json,
|
||||
} => {
|
||||
if parent_gobject_id.is_some() && depth > 0 {
|
||||
eprintln!("warning: --depth is ignored when --parent-gobject-id is specified");
|
||||
}
|
||||
|
||||
let mut client = connect_galaxy(connection).await?;
|
||||
let options = BrowseChildrenOptions {
|
||||
category_ids,
|
||||
template_chain_contains,
|
||||
tag_name_glob,
|
||||
include_attributes: include_attributes.then_some(true),
|
||||
alarm_bearing_only,
|
||||
historized_only,
|
||||
};
|
||||
|
||||
match parent_gobject_id {
|
||||
// No parent → walk the lazy-browse tree from the root objects,
|
||||
// eagerly expanding `depth` further levels so the print walks
|
||||
// cached children without re-issuing RPCs.
|
||||
None => {
|
||||
let nodes = client.browse(Some(options)).await?;
|
||||
for node in &nodes {
|
||||
expand_to_depth(node, depth).await?;
|
||||
}
|
||||
if json {
|
||||
let mut payload = Vec::with_capacity(nodes.len());
|
||||
for node in &nodes {
|
||||
payload.push(lazy_node_to_json(node).await);
|
||||
}
|
||||
println!("{}", json!({ "nodes": payload }));
|
||||
} else {
|
||||
println!("{}", nodes.len());
|
||||
for node in &nodes {
|
||||
print_lazy_node(node, 0).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
// A specific parent → fetch exactly one level of children via
|
||||
// the raw paged RPC. `--depth` is not meaningful here; the
|
||||
// single-level children are returned as-is.
|
||||
Some(parent) => {
|
||||
let children = browse_children_one_level(&mut client, parent, &options).await?;
|
||||
print_browse_children(&children, json);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Page size used for the raw `BrowseChildren` RPC when fetching a single
|
||||
/// level via `--parent-gobject-id`. Mirrors `BROWSE_CHILDREN_PAGE_SIZE` in
|
||||
/// `galaxy.rs` (the library's lazy-browse helper uses the same value).
|
||||
pub(crate) const BROWSE_PAGE_SIZE: i32 = 500;
|
||||
|
||||
/// Drive `BrowseChildren` paging by hand for a single parent and return the
|
||||
/// flattened child list. Used by the `browse --parent-gobject-id` path, which
|
||||
/// surfaces one level of children rather than the lazy root-tree walk.
|
||||
/// Record a non-empty `next_page_token` in `seen` and reject a repeat. A
|
||||
/// server that returns the same continuation token twice would loop forever,
|
||||
/// so the second sighting is converted to an `InvalidArgument` error. Extracted
|
||||
/// from [`browse_children_one_level`] so the guard can be unit-tested without a
|
||||
/// network client.
|
||||
pub(crate) fn register_page_token(
|
||||
seen: &mut std::collections::HashSet<String>,
|
||||
token: &str,
|
||||
) -> Result<(), Error> {
|
||||
if !seen.insert(token.to_owned()) {
|
||||
return Err(Error::InvalidArgument {
|
||||
name: "page_token".to_owned(),
|
||||
detail: format!("galaxy browse children returned repeated page token `{token}`"),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn browse_children_one_level(
|
||||
client: &mut GalaxyClient,
|
||||
parent_gobject_id: i32,
|
||||
options: &BrowseChildrenOptions,
|
||||
) -> Result<Vec<GalaxyBrowseChild>, Error> {
|
||||
use std::collections::HashSet;
|
||||
use zb_mom_ww_mxgateway_client::generated::galaxy_repository::v1::{
|
||||
browse_children_request, BrowseChildrenRequest,
|
||||
};
|
||||
|
||||
let mut children = Vec::new();
|
||||
let mut page_token = String::new();
|
||||
let mut seen: HashSet<String> = HashSet::new();
|
||||
loop {
|
||||
let request = BrowseChildrenRequest {
|
||||
page_size: BROWSE_PAGE_SIZE,
|
||||
page_token: page_token.clone(),
|
||||
category_ids: options.category_ids.clone(),
|
||||
template_chain_contains: options.template_chain_contains.clone(),
|
||||
tag_name_glob: options.tag_name_glob.clone().unwrap_or_default(),
|
||||
include_attributes: options.include_attributes,
|
||||
alarm_bearing_only: options.alarm_bearing_only,
|
||||
historized_only: options.historized_only,
|
||||
parent: Some(browse_children_request::Parent::ParentGobjectId(
|
||||
parent_gobject_id,
|
||||
)),
|
||||
};
|
||||
let reply = client.browse_children_raw(request).await?;
|
||||
let hints = reply.child_has_children;
|
||||
for (index, object) in reply.children.into_iter().enumerate() {
|
||||
let has_children_hint = hints.get(index).copied().unwrap_or(false);
|
||||
children.push(GalaxyBrowseChild {
|
||||
object,
|
||||
has_children_hint,
|
||||
});
|
||||
}
|
||||
page_token = reply.next_page_token;
|
||||
if page_token.is_empty() {
|
||||
return Ok(children);
|
||||
}
|
||||
register_page_token(&mut seen, &page_token)?;
|
||||
}
|
||||
}
|
||||
|
||||
/// A single child returned by the raw `BrowseChildren` paging path, paired
|
||||
/// with its server-supplied `child_has_children` hint.
|
||||
pub(crate) struct GalaxyBrowseChild {
|
||||
object: zb_mom_ww_mxgateway_client::generated::galaxy_repository::v1::GalaxyObject,
|
||||
has_children_hint: bool,
|
||||
}
|
||||
|
||||
/// Print the one-level children of a browsed parent, mirroring the JSON node
|
||||
/// shape used by the root-tree walk (minus the recursive `children` array).
|
||||
pub(crate) fn print_browse_children(children: &[GalaxyBrowseChild], use_json: bool) {
|
||||
if use_json {
|
||||
let payload: Vec<_> = children.iter().map(browse_child_to_json).collect();
|
||||
println!("{}", json!({ "nodes": payload }));
|
||||
} else {
|
||||
println!("{}", children.len());
|
||||
for child in children {
|
||||
let object = &child.object;
|
||||
let marker = if child.has_children_hint { "+" } else { "-" };
|
||||
println!(
|
||||
"{marker} {} {} (gobject {})",
|
||||
object.tag_name, object.browse_name, object.gobject_id,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Render one raw browse child as a JSON object whose key set matches the
|
||||
/// lazy-node renderer (with an empty `children` array).
|
||||
pub(crate) fn browse_child_to_json(child: &GalaxyBrowseChild) -> Value {
|
||||
let object = &child.object;
|
||||
json!({
|
||||
"gobjectId": object.gobject_id,
|
||||
"tagName": object.tag_name,
|
||||
"containedName": object.contained_name,
|
||||
"browseName": object.browse_name,
|
||||
"parentGobjectId": object.parent_gobject_id,
|
||||
"isArea": object.is_area,
|
||||
"categoryId": object.category_id,
|
||||
"hostedByGobjectId": object.hosted_by_gobject_id,
|
||||
"templateChain": object.template_chain,
|
||||
"hasChildrenHint": child.has_children_hint,
|
||||
"attributes": object.attributes.iter().map(|attribute| json!({
|
||||
"attributeName": attribute.attribute_name,
|
||||
"fullTagReference": attribute.full_tag_reference,
|
||||
"mxDataType": attribute.mx_data_type,
|
||||
"dataTypeName": attribute.data_type_name,
|
||||
"isArray": attribute.is_array,
|
||||
"arrayDimension": attribute.array_dimension,
|
||||
"arrayDimensionPresent": attribute.array_dimension_present,
|
||||
"mxAttributeCategory": attribute.mx_attribute_category,
|
||||
"securityClassification": attribute.security_classification,
|
||||
"isHistorized": attribute.is_historized,
|
||||
"isAlarm": attribute.is_alarm,
|
||||
})).collect::<Vec<_>>(),
|
||||
"children": Vec::<Value>::new(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Recursively expand a [`LazyBrowseNode`] up to `depth` further levels. A
|
||||
/// `depth` of 0 leaves the node unexpanded so the caller prints only the
|
||||
/// requested level.
|
||||
pub(crate) fn expand_to_depth(
|
||||
node: &LazyBrowseNode,
|
||||
depth: usize,
|
||||
) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), Error>> + Send + '_>> {
|
||||
Box::pin(async move {
|
||||
if depth == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
node.expand().await?;
|
||||
for child in node.children().await {
|
||||
expand_to_depth(&child, depth - 1).await?;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Print a [`LazyBrowseNode`] and any already-expanded descendants as an
|
||||
/// indented tree. Indentation is two spaces per level.
|
||||
pub(crate) fn print_lazy_node(
|
||||
node: &LazyBrowseNode,
|
||||
indent: usize,
|
||||
) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send + '_>> {
|
||||
Box::pin(async move {
|
||||
let object = node.object();
|
||||
let marker = if node.has_children_hint() { "+" } else { "-" };
|
||||
println!(
|
||||
"{:indent$}{marker} {} {} (gobject {})",
|
||||
"",
|
||||
object.tag_name,
|
||||
object.browse_name,
|
||||
object.gobject_id,
|
||||
indent = indent,
|
||||
);
|
||||
if node.is_expanded().await {
|
||||
for child in node.children().await {
|
||||
print_lazy_node(&child, indent + 2).await;
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Render a [`LazyBrowseNode`] (and its already-expanded children) as a JSON
|
||||
/// object. Mirrors the `discover-hierarchy` object shape with an added
|
||||
/// `hasChildrenHint` flag and a nested `children` array.
|
||||
pub(crate) fn lazy_node_to_json(
|
||||
node: &LazyBrowseNode,
|
||||
) -> std::pin::Pin<Box<dyn std::future::Future<Output = Value> + Send + '_>> {
|
||||
Box::pin(async move {
|
||||
let object = node.object();
|
||||
let mut children = Vec::new();
|
||||
if node.is_expanded().await {
|
||||
for child in node.children().await {
|
||||
children.push(lazy_node_to_json(&child).await);
|
||||
}
|
||||
}
|
||||
json!({
|
||||
"gobjectId": object.gobject_id,
|
||||
"tagName": object.tag_name,
|
||||
"containedName": object.contained_name,
|
||||
"browseName": object.browse_name,
|
||||
"parentGobjectId": object.parent_gobject_id,
|
||||
"isArea": object.is_area,
|
||||
"categoryId": object.category_id,
|
||||
"hostedByGobjectId": object.hosted_by_gobject_id,
|
||||
"templateChain": object.template_chain,
|
||||
"hasChildrenHint": node.has_children_hint(),
|
||||
"attributes": object.attributes.iter().map(|attribute| json!({
|
||||
"attributeName": attribute.attribute_name,
|
||||
"fullTagReference": attribute.full_tag_reference,
|
||||
"mxDataType": attribute.mx_data_type,
|
||||
"dataTypeName": attribute.data_type_name,
|
||||
"isArray": attribute.is_array,
|
||||
"arrayDimension": attribute.array_dimension,
|
||||
"arrayDimensionPresent": attribute.array_dimension_present,
|
||||
"mxAttributeCategory": attribute.mx_attribute_category,
|
||||
"securityClassification": attribute.security_classification,
|
||||
"isHistorized": attribute.is_historized,
|
||||
"isAlarm": attribute.is_alarm,
|
||||
})).collect::<Vec<_>>(),
|
||||
"children": children,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn print_deploy_event(event: &DeployEvent, use_json: bool) {
|
||||
if use_json {
|
||||
println!(
|
||||
"{}",
|
||||
json!({
|
||||
"sequence": event.sequence,
|
||||
"observedAt": event.observed_at.as_ref().map(|ts| json!({
|
||||
"seconds": ts.seconds,
|
||||
"nanos": ts.nanos,
|
||||
})),
|
||||
"timeOfLastDeploy": event.time_of_last_deploy.as_ref().map(|ts| json!({
|
||||
"seconds": ts.seconds,
|
||||
"nanos": ts.nanos,
|
||||
})),
|
||||
"timeOfLastDeployPresent": event.time_of_last_deploy_present,
|
||||
"objectCount": event.object_count,
|
||||
"attributeCount": event.attribute_count,
|
||||
})
|
||||
);
|
||||
} else {
|
||||
let observed = event
|
||||
.observed_at
|
||||
.as_ref()
|
||||
.map(|ts| format!("{}.{:09}", ts.seconds, ts.nanos))
|
||||
.unwrap_or_else(|| "(absent)".to_owned());
|
||||
let last_deploy = if event.time_of_last_deploy_present {
|
||||
event
|
||||
.time_of_last_deploy
|
||||
.as_ref()
|
||||
.map(|ts| format!("{}.{:09}", ts.seconds, ts.nanos))
|
||||
.unwrap_or_else(|| "(absent)".to_owned())
|
||||
} else {
|
||||
"(absent)".to_owned()
|
||||
};
|
||||
println!(
|
||||
"seq={} observed={} lastDeploy={} objects={} attributes={}",
|
||||
event.sequence, observed, last_deploy, event.object_count, event.attribute_count,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
//! Shared terse/JSON output helpers.
|
||||
|
||||
use serde_json::json;
|
||||
use serde_json::Value;
|
||||
use zb_mom_ww_mxgateway_client::{
|
||||
CLIENT_VERSION, GATEWAY_PROTOCOL_VERSION, WORKER_PROTOCOL_VERSION,
|
||||
};
|
||||
|
||||
pub(crate) fn print_version(use_json: bool) {
|
||||
if use_json {
|
||||
println!("{}", version_json());
|
||||
return;
|
||||
}
|
||||
|
||||
println!("mxgw {CLIENT_VERSION}");
|
||||
println!("gateway protocol {GATEWAY_PROTOCOL_VERSION}");
|
||||
println!("worker protocol {WORKER_PROTOCOL_VERSION}");
|
||||
}
|
||||
|
||||
pub(crate) fn version_json() -> Value {
|
||||
json!({
|
||||
"clientVersion": CLIENT_VERSION,
|
||||
"gatewayProtocolVersion": GATEWAY_PROTOCOL_VERSION,
|
||||
"workerProtocolVersion": WORKER_PROTOCOL_VERSION,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn print_command_reply(
|
||||
operation: &str,
|
||||
reply: &zb_mom_ww_mxgateway_client::generated::mxaccess_gateway::v1::MxCommandReply,
|
||||
use_json: bool,
|
||||
) {
|
||||
if use_json {
|
||||
println!(
|
||||
"{}",
|
||||
json!({
|
||||
"operation": operation,
|
||||
"sessionId": reply.session_id,
|
||||
"correlationId": reply.correlation_id,
|
||||
"kind": reply.kind,
|
||||
})
|
||||
);
|
||||
} else {
|
||||
println!("{operation} completed");
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn print_handle(name: &str, handle: i32, use_json: bool) {
|
||||
if use_json {
|
||||
println!("{}", json!({ name: handle }));
|
||||
} else {
|
||||
println!("{handle}");
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn print_ok(operation: &str, use_json: bool) {
|
||||
if use_json {
|
||||
println!("{}", json!({ "operation": operation, "ok": true }));
|
||||
} else {
|
||||
println!("{operation} completed");
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn print_bulk_results(
|
||||
operation: &str,
|
||||
results: &[zb_mom_ww_mxgateway_client::generated::mxaccess_gateway::v1::SubscribeResult],
|
||||
use_json: bool,
|
||||
) {
|
||||
if use_json {
|
||||
let results_json: Vec<_> = results
|
||||
.iter()
|
||||
.map(|result| {
|
||||
json!({
|
||||
"serverHandle": result.server_handle,
|
||||
"tagAddress": result.tag_address,
|
||||
"itemHandle": result.item_handle,
|
||||
"wasSuccessful": result.was_successful,
|
||||
"errorMessage": result.error_message,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
println!(
|
||||
"{}",
|
||||
json!({ "operation": operation, "results": results_json })
|
||||
);
|
||||
} else {
|
||||
println!("{}", results.len());
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn print_write_bulk_results(
|
||||
operation: &str,
|
||||
results: &[zb_mom_ww_mxgateway_client::generated::mxaccess_gateway::v1::BulkWriteResult],
|
||||
use_json: bool,
|
||||
) {
|
||||
if use_json {
|
||||
let results_json: Vec<_> = results
|
||||
.iter()
|
||||
.map(|result| {
|
||||
json!({
|
||||
"serverHandle": result.server_handle,
|
||||
"itemHandle": result.item_handle,
|
||||
"wasSuccessful": result.was_successful,
|
||||
"hresult": result.hresult,
|
||||
"errorMessage": result.error_message,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
println!(
|
||||
"{}",
|
||||
json!({ "operation": operation, "results": results_json })
|
||||
);
|
||||
} else {
|
||||
println!("{}", results.len());
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn print_read_bulk_results(
|
||||
operation: &str,
|
||||
results: &[zb_mom_ww_mxgateway_client::generated::mxaccess_gateway::v1::BulkReadResult],
|
||||
use_json: bool,
|
||||
) {
|
||||
if use_json {
|
||||
let results_json: Vec<_> = results
|
||||
.iter()
|
||||
.map(|result| {
|
||||
json!({
|
||||
"serverHandle": result.server_handle,
|
||||
"tagAddress": result.tag_address,
|
||||
"itemHandle": result.item_handle,
|
||||
"wasSuccessful": result.was_successful,
|
||||
"wasCached": result.was_cached,
|
||||
"quality": result.quality,
|
||||
"errorMessage": result.error_message,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
println!(
|
||||
"{}",
|
||||
json!({ "operation": operation, "results": results_json })
|
||||
);
|
||||
} else {
|
||||
println!("{}", results.len());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
//! Argument and value parsing helpers (typed values, RFC3339 timestamps, credentials).
|
||||
|
||||
use std::env;
|
||||
|
||||
use zb_mom_ww_mxgateway_client::{Error, MxValue};
|
||||
|
||||
use crate::cli::*;
|
||||
|
||||
/// Resolves the `authenticate-user` credential from `--password`, falling back to
|
||||
/// the environment variable named by `--password-env` (default
|
||||
/// `MXGATEWAY_VERIFY_PASSWORD`).
|
||||
///
|
||||
/// An empty value from either source counts as missing (CLI-45): the CLI fails
|
||||
/// fast with a usage error rather than sending a fabricated empty credential to
|
||||
/// the wire. The error names the flag and the variable only — never the value,
|
||||
/// which is never echoed to stdout/stderr or embedded in an error message.
|
||||
pub(crate) fn resolve_verify_user_password(
|
||||
password: Option<String>,
|
||||
password_env: &str,
|
||||
) -> Result<String, Error> {
|
||||
password
|
||||
.filter(|value| !value.is_empty())
|
||||
.or_else(|| {
|
||||
env::var(password_env)
|
||||
.ok()
|
||||
.filter(|value| !value.is_empty())
|
||||
})
|
||||
.ok_or_else(|| Error::InvalidArgument {
|
||||
name: "password".to_owned(),
|
||||
detail: format!("supply --password or set the environment variable `{password_env}`"),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn parse_value(value_type: CliValueType, value: &str) -> Result<MxValue, Error> {
|
||||
let parsed = match value_type {
|
||||
CliValueType::Bool => MxValue::bool(parse_cli_value(value)?),
|
||||
CliValueType::Int32 => MxValue::int32(parse_cli_value(value)?),
|
||||
CliValueType::Int64 => MxValue::int64(parse_cli_value(value)?),
|
||||
CliValueType::Float => MxValue::float(parse_cli_value(value)?),
|
||||
CliValueType::Double => MxValue::double(parse_cli_value(value)?),
|
||||
CliValueType::String => MxValue::string(value),
|
||||
};
|
||||
Ok(parsed)
|
||||
}
|
||||
|
||||
/// Pairs each parsed item handle with its parsed MxValue (proto form) so a
|
||||
/// single helper can build the four bulk-write families without each branch
|
||||
/// repeating the length check and per-value parsing.
|
||||
pub(crate) fn build_write_bulk_entries(
|
||||
item_handles: &[i32],
|
||||
value_type: CliValueType,
|
||||
values: &[String],
|
||||
) -> Result<
|
||||
Vec<(
|
||||
i32,
|
||||
zb_mom_ww_mxgateway_client::generated::mxaccess_gateway::v1::MxValue,
|
||||
)>,
|
||||
Error,
|
||||
> {
|
||||
if item_handles.len() != values.len() {
|
||||
return Err(Error::InvalidArgument {
|
||||
name: "values".to_owned(),
|
||||
detail: format!(
|
||||
"item-handles count ({}) does not match values count ({})",
|
||||
item_handles.len(),
|
||||
values.len()
|
||||
),
|
||||
});
|
||||
}
|
||||
item_handles
|
||||
.iter()
|
||||
.zip(values.iter())
|
||||
.map(|(handle, value)| {
|
||||
parse_value(value_type, value).map(|wrapper| (*handle, wrapper.into_proto()))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Parse a small but practically-complete subset of RFC3339:
|
||||
/// `YYYY-MM-DDTHH:MM:SS[.fffffffff][Z|+HH:MM|-HH:MM]`. Returns the
|
||||
/// corresponding `prost_types::Timestamp` (Unix seconds + nanoseconds).
|
||||
pub(crate) fn parse_rfc3339_timestamp(input: &str) -> Result<prost_types::Timestamp, Error> {
|
||||
fn invalid(detail: impl Into<String>) -> Error {
|
||||
Error::InvalidArgument {
|
||||
name: "last-seen-deploy-time".to_owned(),
|
||||
detail: detail.into(),
|
||||
}
|
||||
}
|
||||
|
||||
let bytes = input.as_bytes();
|
||||
if bytes.len() < 20 || (bytes[10] != b'T' && bytes[10] != b't') {
|
||||
return Err(invalid(format!(
|
||||
"expected RFC3339 timestamp like 2026-04-28T15:30:00Z, got {input:?}"
|
||||
)));
|
||||
}
|
||||
|
||||
let read_u32 = |start: usize, len: usize| -> Result<u32, Error> {
|
||||
std::str::from_utf8(&bytes[start..start + len])
|
||||
.ok()
|
||||
.and_then(|slice| slice.parse::<u32>().ok())
|
||||
.ok_or_else(|| invalid(format!("non-numeric digits at byte {start}")))
|
||||
};
|
||||
|
||||
let year = read_u32(0, 4)? as i32;
|
||||
if bytes[4] != b'-' {
|
||||
return Err(invalid("expected '-' after year"));
|
||||
}
|
||||
let month = read_u32(5, 2)?;
|
||||
if bytes[7] != b'-' {
|
||||
return Err(invalid("expected '-' after month"));
|
||||
}
|
||||
let day = read_u32(8, 2)?;
|
||||
let hour = read_u32(11, 2)?;
|
||||
if bytes[13] != b':' {
|
||||
return Err(invalid("expected ':' after hour"));
|
||||
}
|
||||
let minute = read_u32(14, 2)?;
|
||||
if bytes[16] != b':' {
|
||||
return Err(invalid("expected ':' after minute"));
|
||||
}
|
||||
let second = read_u32(17, 2)?;
|
||||
|
||||
let mut cursor = 19usize;
|
||||
let mut nanos: u32 = 0;
|
||||
if cursor < bytes.len() && bytes[cursor] == b'.' {
|
||||
cursor += 1;
|
||||
let frac_start = cursor;
|
||||
while cursor < bytes.len() && bytes[cursor].is_ascii_digit() {
|
||||
cursor += 1;
|
||||
}
|
||||
let frac_len = cursor - frac_start;
|
||||
if frac_len == 0 {
|
||||
return Err(invalid("expected fractional digits after '.'"));
|
||||
}
|
||||
let take = frac_len.min(9);
|
||||
let frac = std::str::from_utf8(&bytes[frac_start..frac_start + take])
|
||||
.ok()
|
||||
.and_then(|slice| slice.parse::<u32>().ok())
|
||||
.ok_or_else(|| invalid("invalid fractional digits"))?;
|
||||
nanos = frac * 10u32.pow(9u32.saturating_sub(take as u32));
|
||||
}
|
||||
|
||||
let mut offset_seconds: i64 = 0;
|
||||
if cursor >= bytes.len() {
|
||||
return Err(invalid("missing timezone designator (Z or +HH:MM)"));
|
||||
}
|
||||
match bytes[cursor] {
|
||||
b'Z' | b'z' => cursor += 1,
|
||||
sign @ (b'+' | b'-') => {
|
||||
cursor += 1;
|
||||
if cursor + 5 > bytes.len() {
|
||||
return Err(invalid("offset must be ±HH:MM"));
|
||||
}
|
||||
let oh = std::str::from_utf8(&bytes[cursor..cursor + 2])
|
||||
.ok()
|
||||
.and_then(|slice| slice.parse::<i64>().ok())
|
||||
.ok_or_else(|| invalid("invalid offset hour"))?;
|
||||
if bytes[cursor + 2] != b':' {
|
||||
return Err(invalid("offset must contain ':' between HH and MM"));
|
||||
}
|
||||
let om = std::str::from_utf8(&bytes[cursor + 3..cursor + 5])
|
||||
.ok()
|
||||
.and_then(|slice| slice.parse::<i64>().ok())
|
||||
.ok_or_else(|| invalid("invalid offset minute"))?;
|
||||
cursor += 5;
|
||||
let signed = if sign == b'-' { -1 } else { 1 };
|
||||
offset_seconds = signed * (oh * 3600 + om * 60);
|
||||
}
|
||||
other => {
|
||||
return Err(invalid(format!(
|
||||
"unexpected timezone designator byte {other:?}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
if cursor != bytes.len() {
|
||||
return Err(invalid("trailing characters after timezone"));
|
||||
}
|
||||
|
||||
let unix = ymdhms_to_unix(year, month, day, hour, minute, second)?;
|
||||
let seconds = unix - offset_seconds;
|
||||
|
||||
Ok(prost_types::Timestamp {
|
||||
seconds,
|
||||
nanos: nanos as i32,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn ymdhms_to_unix(
|
||||
year: i32,
|
||||
month: u32,
|
||||
day: u32,
|
||||
hour: u32,
|
||||
minute: u32,
|
||||
second: u32,
|
||||
) -> Result<i64, Error> {
|
||||
if !(1..=12).contains(&month) || day < 1 || hour > 23 || minute > 59 || second > 60 {
|
||||
return Err(Error::InvalidArgument {
|
||||
name: "last-seen-deploy-time".to_owned(),
|
||||
detail: "calendar component out of range".to_owned(),
|
||||
});
|
||||
}
|
||||
fn is_leap(year: i32) -> bool {
|
||||
(year % 4 == 0 && year % 100 != 0) || year % 400 == 0
|
||||
}
|
||||
const DAYS: [u32; 12] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
||||
let mut max = DAYS[(month - 1) as usize];
|
||||
if month == 2 && is_leap(year) {
|
||||
max = 29;
|
||||
}
|
||||
if day > max {
|
||||
return Err(Error::InvalidArgument {
|
||||
name: "last-seen-deploy-time".to_owned(),
|
||||
detail: format!("day {day} out of range for month {month}/{year}"),
|
||||
});
|
||||
}
|
||||
|
||||
// Days from 1970-01-01 to year-month-day.
|
||||
let mut total_days: i64 = 0;
|
||||
if year >= 1970 {
|
||||
for y in 1970..year {
|
||||
total_days += if is_leap(y) { 366 } else { 365 };
|
||||
}
|
||||
} else {
|
||||
for y in year..1970 {
|
||||
total_days -= if is_leap(y) { 366 } else { 365 };
|
||||
}
|
||||
}
|
||||
for m in 1..month {
|
||||
let mut dim = DAYS[(m - 1) as usize];
|
||||
if m == 2 && is_leap(year) {
|
||||
dim = 29;
|
||||
}
|
||||
total_days += dim as i64;
|
||||
}
|
||||
total_days += (day - 1) as i64;
|
||||
|
||||
Ok(total_days * 86_400 + hour as i64 * 3600 + minute as i64 * 60 + second as i64)
|
||||
}
|
||||
|
||||
pub(crate) fn parse_cli_value<T>(value: &str) -> Result<T, Error>
|
||||
where
|
||||
T: std::str::FromStr,
|
||||
T::Err: std::fmt::Display,
|
||||
{
|
||||
value.parse::<T>().map_err(|source| Error::InvalidArgument {
|
||||
name: "value".to_owned(),
|
||||
detail: source.to_string(),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
//! Single-session commands: version, ping, session lifecycle, register/advise and single-item writes.
|
||||
|
||||
use serde_json::json;
|
||||
use zb_mom_ww_mxgateway_client::generated::mxaccess_gateway::v1::{
|
||||
CloseSessionRequest, MxCommand, MxCommandKind, MxCommandRequest, OpenSessionRequest,
|
||||
PingCommand,
|
||||
};
|
||||
use zb_mom_ww_mxgateway_client::{next_correlation_id, Error, MxValue};
|
||||
|
||||
use crate::cli::*;
|
||||
use crate::connect::*;
|
||||
use crate::output::*;
|
||||
use crate::parse::*;
|
||||
|
||||
/// Run the `session` command group.
|
||||
pub(crate) async fn run(command: Command) -> Result<(), Error> {
|
||||
match command {
|
||||
Command::Version { json } => print_version(json),
|
||||
Command::Ping {
|
||||
connection,
|
||||
message,
|
||||
json,
|
||||
} => {
|
||||
let client = connect(connection).await?;
|
||||
let reply = client
|
||||
.invoke(MxCommandRequest {
|
||||
client_correlation_id: next_correlation_id("cli-ping"),
|
||||
command: Some(MxCommand {
|
||||
kind: MxCommandKind::Ping as i32,
|
||||
payload: Some(zb_mom_ww_mxgateway_client::generated::mxaccess_gateway::v1::mx_command::Payload::Ping(
|
||||
PingCommand { message },
|
||||
)),
|
||||
}),
|
||||
..MxCommandRequest::default()
|
||||
})
|
||||
.await?;
|
||||
print_command_reply("ping", &reply, json);
|
||||
}
|
||||
Command::OpenSession {
|
||||
connection,
|
||||
client_name,
|
||||
json,
|
||||
} => {
|
||||
let client = connect(connection).await?;
|
||||
let reply = client
|
||||
.open_session_raw(OpenSessionRequest {
|
||||
client_session_name: client_name,
|
||||
..OpenSessionRequest::default()
|
||||
})
|
||||
.await?;
|
||||
if json {
|
||||
println!(
|
||||
"{}",
|
||||
json!({
|
||||
"sessionId": reply.session_id,
|
||||
"backendName": reply.backend_name,
|
||||
"gatewayProtocolVersion": reply.gateway_protocol_version,
|
||||
"workerProtocolVersion": reply.worker_protocol_version,
|
||||
})
|
||||
);
|
||||
} else {
|
||||
println!("{}", reply.session_id);
|
||||
}
|
||||
}
|
||||
Command::CloseSession {
|
||||
connection,
|
||||
session_id,
|
||||
json,
|
||||
} => {
|
||||
let client = connect(connection).await?;
|
||||
let reply = client
|
||||
.close_session_raw(CloseSessionRequest {
|
||||
session_id,
|
||||
client_correlation_id: next_correlation_id("cli-close-session"),
|
||||
})
|
||||
.await?;
|
||||
if json {
|
||||
println!("{}", json!({ "sessionId": reply.session_id }));
|
||||
} else {
|
||||
println!("closed {}", reply.session_id);
|
||||
}
|
||||
}
|
||||
Command::Register {
|
||||
connection,
|
||||
session_id,
|
||||
client_name,
|
||||
json,
|
||||
} => {
|
||||
let session = session_for(connection, session_id).await?;
|
||||
let server_handle = session.register(&client_name).await?;
|
||||
print_handle("serverHandle", server_handle, json);
|
||||
}
|
||||
Command::AddItem {
|
||||
connection,
|
||||
session_id,
|
||||
server_handle,
|
||||
item,
|
||||
json,
|
||||
} => {
|
||||
let session = session_for(connection, session_id).await?;
|
||||
let item_handle = session.add_item(server_handle, &item).await?;
|
||||
print_handle("itemHandle", item_handle, json);
|
||||
}
|
||||
Command::Advise {
|
||||
connection,
|
||||
session_id,
|
||||
server_handle,
|
||||
item_handle,
|
||||
json,
|
||||
} => {
|
||||
let session = session_for(connection, session_id).await?;
|
||||
session.advise(server_handle, item_handle).await?;
|
||||
print_ok("advise", json);
|
||||
}
|
||||
Command::AdviseSupervisory {
|
||||
connection,
|
||||
session_id,
|
||||
server_handle,
|
||||
item_handle,
|
||||
json,
|
||||
} => {
|
||||
let session = session_for(connection, session_id).await?;
|
||||
session
|
||||
.advise_supervisory(server_handle, item_handle)
|
||||
.await?;
|
||||
print_ok("advise-supervisory", json);
|
||||
}
|
||||
Command::Unregister {
|
||||
connection,
|
||||
session_id,
|
||||
server_handle,
|
||||
json,
|
||||
} => {
|
||||
let session = session_for(connection, session_id).await?;
|
||||
session.unregister(server_handle).await?;
|
||||
print_ok("unregister", json);
|
||||
}
|
||||
Command::AuthenticateUser {
|
||||
connection,
|
||||
session_id,
|
||||
server_handle,
|
||||
verify_user,
|
||||
password,
|
||||
password_env,
|
||||
json,
|
||||
} => {
|
||||
let verify_user_password = resolve_verify_user_password(password, &password_env)?;
|
||||
let session = session_for(connection, session_id).await?;
|
||||
let user_id = session
|
||||
.authenticate_user(server_handle, &verify_user, &verify_user_password)
|
||||
.await?;
|
||||
print_handle("userId", user_id, json);
|
||||
}
|
||||
Command::WriteSecured {
|
||||
connection,
|
||||
session_id,
|
||||
server_handle,
|
||||
item_handle,
|
||||
value_type,
|
||||
value,
|
||||
current_user_id,
|
||||
verifier_user_id,
|
||||
json,
|
||||
} => {
|
||||
let session = session_for(connection, session_id).await?;
|
||||
session
|
||||
.write_secured(
|
||||
server_handle,
|
||||
item_handle,
|
||||
current_user_id,
|
||||
verifier_user_id,
|
||||
parse_value(value_type, &value)?,
|
||||
)
|
||||
.await?;
|
||||
print_ok("write-secured", json);
|
||||
}
|
||||
Command::Write {
|
||||
connection,
|
||||
session_id,
|
||||
server_handle,
|
||||
item_handle,
|
||||
value_type,
|
||||
value,
|
||||
user_id,
|
||||
json,
|
||||
} => {
|
||||
let session = session_for(connection, session_id).await?;
|
||||
session
|
||||
.write(
|
||||
server_handle,
|
||||
item_handle,
|
||||
parse_value(value_type, &value)?,
|
||||
user_id,
|
||||
)
|
||||
.await?;
|
||||
print_ok("write", json);
|
||||
}
|
||||
Command::Write2 {
|
||||
connection,
|
||||
session_id,
|
||||
server_handle,
|
||||
item_handle,
|
||||
value_type,
|
||||
value,
|
||||
timestamp,
|
||||
user_id,
|
||||
json,
|
||||
} => {
|
||||
let session = session_for(connection, session_id).await?;
|
||||
session
|
||||
.write2(
|
||||
server_handle,
|
||||
item_handle,
|
||||
parse_value(value_type, &value)?,
|
||||
MxValue::string(timestamp),
|
||||
user_id,
|
||||
)
|
||||
.await?;
|
||||
print_ok("write2", json);
|
||||
}
|
||||
_ => unreachable!("command routed to the wrong group"),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
//! `smoke` command: open, register, add-item and close in one invocation.
|
||||
|
||||
use serde_json::json;
|
||||
use zb_mom_ww_mxgateway_client::generated::mxaccess_gateway::v1::OpenSessionRequest;
|
||||
use zb_mom_ww_mxgateway_client::Error;
|
||||
|
||||
use crate::cli::*;
|
||||
use crate::connect::*;
|
||||
|
||||
/// Run the `smoke` command group.
|
||||
pub(crate) async fn run(command: Command) -> Result<(), Error> {
|
||||
match command {
|
||||
Command::Smoke {
|
||||
connection,
|
||||
item,
|
||||
client_name,
|
||||
json,
|
||||
} => {
|
||||
let client = connect(connection).await?;
|
||||
let session = client
|
||||
.open_session(OpenSessionRequest {
|
||||
client_session_name: client_name.clone(),
|
||||
..OpenSessionRequest::default()
|
||||
})
|
||||
.await?;
|
||||
let result = async {
|
||||
let server_handle = session.register(&client_name).await?;
|
||||
let item_handle = session.add_item(server_handle, &item).await?;
|
||||
session.advise(server_handle, item_handle).await?;
|
||||
Ok::<_, Error>((server_handle, item_handle))
|
||||
}
|
||||
.await;
|
||||
let close_result = session.close().await;
|
||||
let (server_handle, item_handle) = result?;
|
||||
close_result?;
|
||||
if json {
|
||||
println!(
|
||||
"{}",
|
||||
json!({
|
||||
"sessionId": session.id(),
|
||||
"serverHandle": server_handle,
|
||||
"itemHandle": item_handle,
|
||||
"closed": true,
|
||||
})
|
||||
);
|
||||
} else {
|
||||
println!(
|
||||
"session {} registered server {server_handle}, item {item_handle}, closed",
|
||||
session.id()
|
||||
);
|
||||
}
|
||||
}
|
||||
_ => unreachable!("command routed to the wrong group"),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,455 @@
|
||||
//! Unit tests for the CLI.
|
||||
use clap::Parser;
|
||||
|
||||
use crate::cli::{Cli, Command};
|
||||
|
||||
/// Pull the flattened `ConnectionArgs` out of a parsed `ping` command so
|
||||
/// `ConnectionArgs::options()` can be exercised directly.
|
||||
fn connection_from_ping(args: &[&str]) -> crate::cli::ConnectionArgs {
|
||||
let mut full = vec!["mxgw", "ping"];
|
||||
full.extend_from_slice(args);
|
||||
match Cli::try_parse_from(full).expect("ping parse").command {
|
||||
Command::Ping { connection, .. } => connection,
|
||||
other => panic!("expected ping command, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_version_json_command() {
|
||||
let parsed = Cli::try_parse_from(["mxgw", "version", "--json"]);
|
||||
assert!(parsed.is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connection_defaults_to_plaintext() {
|
||||
let options = connection_from_ping(&[]).options();
|
||||
assert!(options.plaintext(), "default channel should be plaintext");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connection_tls_flag_disables_plaintext() {
|
||||
let options = connection_from_ping(&["--tls"]).options();
|
||||
assert!(
|
||||
!options.plaintext(),
|
||||
"--tls must select an encrypted channel"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connection_plaintext_flag_selects_plaintext() {
|
||||
let options = connection_from_ping(&["--plaintext"]).options();
|
||||
assert!(options.plaintext());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connection_rejects_tls_and_plaintext_together() {
|
||||
let parsed = Cli::try_parse_from(["mxgw", "ping", "--tls", "--plaintext"]);
|
||||
assert!(
|
||||
parsed.is_err(),
|
||||
"--tls and --plaintext must conflict so TLS cannot be silently downgraded"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_write_command() {
|
||||
let parsed = Cli::try_parse_from([
|
||||
"mxgw",
|
||||
"write",
|
||||
"--session-id",
|
||||
"session-1",
|
||||
"--server-handle",
|
||||
"12",
|
||||
"--item-handle",
|
||||
"34",
|
||||
"--value-type",
|
||||
"int32",
|
||||
"--value",
|
||||
"123",
|
||||
]);
|
||||
assert!(parsed.is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_json_output_has_protocol_versions() {
|
||||
let value = crate::output::version_json();
|
||||
|
||||
assert_eq!(value["gatewayProtocolVersion"], 3);
|
||||
assert_eq!(value["workerProtocolVersion"], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_authenticate_user_command_with_password_env() {
|
||||
let parsed = Cli::try_parse_from([
|
||||
"mxgw",
|
||||
"authenticate-user",
|
||||
"--session-id",
|
||||
"session-1",
|
||||
"--server-handle",
|
||||
"7",
|
||||
"--verify-user",
|
||||
"verifier",
|
||||
"--password-env",
|
||||
"MY_PW_VAR",
|
||||
]);
|
||||
assert!(parsed.is_ok(), "parse failed: {parsed:?}");
|
||||
}
|
||||
|
||||
/// CLI-45: `--password-env` must default to the canonical
|
||||
/// `MXGATEWAY_VERIFY_PASSWORD` shared by every official client CLI.
|
||||
#[test]
|
||||
fn authenticate_user_password_env_defaults_to_canonical_name() {
|
||||
let parsed = Cli::try_parse_from([
|
||||
"mxgw",
|
||||
"authenticate-user",
|
||||
"--session-id",
|
||||
"session-1",
|
||||
"--server-handle",
|
||||
"7",
|
||||
"--verify-user",
|
||||
"verifier",
|
||||
])
|
||||
.expect("parse");
|
||||
match parsed.command {
|
||||
Command::AuthenticateUser { password_env, .. } => {
|
||||
assert_eq!(password_env, "MXGATEWAY_VERIFY_PASSWORD");
|
||||
}
|
||||
other => panic!("expected authenticate-user, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// CLI-45: a credential that resolves to an empty string — whether from the
|
||||
/// flag or from the named environment variable — is treated as missing, so
|
||||
/// the CLI never sends a fabricated empty password to the wire. The usage
|
||||
/// error names the flag and the variable, never a value.
|
||||
#[test]
|
||||
fn resolve_verify_user_password_rejects_missing_and_empty_values() {
|
||||
const ABSENT: &str = "MXGW_CLI45_ABSENT_PASSWORD_VAR";
|
||||
const EMPTY: &str = "MXGW_CLI45_EMPTY_PASSWORD_VAR";
|
||||
const PRESENT: &str = "MXGW_CLI45_PRESENT_PASSWORD_VAR";
|
||||
std::env::remove_var(ABSENT);
|
||||
std::env::set_var(EMPTY, "");
|
||||
std::env::set_var(PRESENT, "env-sourced-credential");
|
||||
|
||||
for (password, env_name) in [
|
||||
(None, ABSENT),
|
||||
(Some(String::new()), ABSENT),
|
||||
(None, EMPTY),
|
||||
(Some(String::new()), EMPTY),
|
||||
] {
|
||||
let error = crate::parse::resolve_verify_user_password(password, env_name)
|
||||
.expect_err("empty or missing credential must be a usage error");
|
||||
let rendered = error.to_string();
|
||||
assert!(rendered.contains("--password"), "{rendered}");
|
||||
assert!(rendered.contains(env_name), "{rendered}");
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
crate::parse::resolve_verify_user_password(None, PRESENT).expect("env credential"),
|
||||
"env-sourced-credential"
|
||||
);
|
||||
assert_eq!(
|
||||
crate::parse::resolve_verify_user_password(Some("flag-credential".to_owned()), EMPTY)
|
||||
.expect("flag credential"),
|
||||
"flag-credential"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_write_secured_command() {
|
||||
let parsed = Cli::try_parse_from([
|
||||
"mxgw",
|
||||
"write-secured",
|
||||
"--session-id",
|
||||
"session-1",
|
||||
"--server-handle",
|
||||
"12",
|
||||
"--item-handle",
|
||||
"34",
|
||||
"--value-type",
|
||||
"int32",
|
||||
"--value",
|
||||
"5",
|
||||
"--current-user-id",
|
||||
"1",
|
||||
"--verifier-user-id",
|
||||
"2",
|
||||
]);
|
||||
assert!(parsed.is_ok(), "parse failed: {parsed:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_unregister_command() {
|
||||
let parsed = Cli::try_parse_from([
|
||||
"mxgw",
|
||||
"unregister",
|
||||
"--session-id",
|
||||
"session-1",
|
||||
"--server-handle",
|
||||
"12",
|
||||
]);
|
||||
assert!(parsed.is_ok(), "parse failed: {parsed:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_stream_alarms_command() {
|
||||
let parsed = Cli::try_parse_from([
|
||||
"mxgw",
|
||||
"stream-alarms",
|
||||
"--filter-prefix",
|
||||
"Tank01",
|
||||
"--max-events",
|
||||
"3",
|
||||
"--json",
|
||||
]);
|
||||
assert!(parsed.is_ok(), "parse failed: {parsed:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_stream_alarms_command_without_filter_prefix() {
|
||||
let parsed = Cli::try_parse_from(["mxgw", "stream-alarms"]);
|
||||
assert!(parsed.is_ok(), "parse failed: {parsed:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_acknowledge_alarm_command() {
|
||||
let parsed = Cli::try_parse_from([
|
||||
"mxgw",
|
||||
"acknowledge-alarm",
|
||||
"--reference",
|
||||
"Tank01.Level.HiHi",
|
||||
"--comment",
|
||||
"ack from cli",
|
||||
"--operator",
|
||||
"operator1",
|
||||
]);
|
||||
assert!(parsed.is_ok(), "parse failed: {parsed:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn acknowledge_alarm_requires_operator() {
|
||||
let parsed = Cli::try_parse_from([
|
||||
"mxgw",
|
||||
"acknowledge-alarm",
|
||||
"--reference",
|
||||
"Tank01.Level.HiHi",
|
||||
]);
|
||||
assert!(parsed.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn acknowledge_alarm_requires_reference() {
|
||||
let parsed = Cli::try_parse_from(["mxgw", "acknowledge-alarm"]);
|
||||
assert!(parsed.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_galaxy_watch_command_with_last_seen_and_max_events() {
|
||||
let parsed = Cli::try_parse_from([
|
||||
"mxgw",
|
||||
"galaxy",
|
||||
"watch",
|
||||
"--last-seen-deploy-time",
|
||||
"2026-04-28T15:30:00Z",
|
||||
"--max-events",
|
||||
"5",
|
||||
"--json",
|
||||
]);
|
||||
assert!(parsed.is_ok(), "parse failed: {parsed:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_galaxy_watch_deploy_events_alias() {
|
||||
let parsed = Cli::try_parse_from(["mxgw", "galaxy", "watch-deploy-events"]);
|
||||
assert!(parsed.is_ok(), "parse failed: {parsed:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_galaxy_browse_command_with_filters_and_depth() {
|
||||
let parsed = Cli::try_parse_from([
|
||||
"mxgw",
|
||||
"galaxy",
|
||||
"browse",
|
||||
"--parent-gobject-id",
|
||||
"42",
|
||||
"--category-id",
|
||||
"3",
|
||||
"--category-id",
|
||||
"5",
|
||||
"--template-contains",
|
||||
"$DelmiaReceiver",
|
||||
"--tag-name-glob",
|
||||
"Recv_*",
|
||||
"--include-attributes",
|
||||
"--alarm-bearing-only",
|
||||
"--depth",
|
||||
"2",
|
||||
"--json",
|
||||
]);
|
||||
assert!(parsed.is_ok(), "parse failed: {parsed:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_galaxy_browse_command_with_defaults() {
|
||||
let parsed = Cli::try_parse_from(["mxgw", "galaxy", "browse"]);
|
||||
assert!(parsed.is_ok(), "parse failed: {parsed:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_batch_command() {
|
||||
let parsed = Cli::try_parse_from(["mxgw", "batch"]);
|
||||
assert!(parsed.is_ok(), "parse failed: {parsed:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_eor_marker_is_stable() {
|
||||
assert_eq!(crate::batch::BATCH_EOR, "__MXGW_BATCH_EOR__");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bench_percentile_summary_matches_hand_built_sample() {
|
||||
// Hand-built sample with 5 values: 1, 2, 3, 4, 5.
|
||||
let sample: Vec<f64> = vec![1.0, 2.0, 3.0, 4.0, 5.0];
|
||||
let summary = crate::bench::percentile_summary(&sample);
|
||||
|
||||
assert_eq!(summary.max, 5.0);
|
||||
// Mean = 15/5 = 3.0
|
||||
assert!((summary.mean - 3.0).abs() < f64::EPSILON);
|
||||
// p50: rank = 0.5 * 4 = 2 -> sorted[2] = 3.0
|
||||
assert!((summary.p50 - 3.0).abs() < f64::EPSILON);
|
||||
// p95: rank = 0.95 * 4 = 3.8 -> 4.0 + 0.8 * (5.0 - 4.0) = 4.8
|
||||
assert!((summary.p95 - 4.8).abs() < f64::EPSILON);
|
||||
// p99: rank = 0.99 * 4 = 3.96 -> 4.0 + 0.96 * 1.0 = 4.96
|
||||
assert!((summary.p99 - 4.96).abs() < f64::EPSILON);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bench_percentile_summary_handles_empty_sample() {
|
||||
let summary = crate::bench::percentile_summary(&[]);
|
||||
assert_eq!(summary.p50, 0.0);
|
||||
assert_eq!(summary.p95, 0.0);
|
||||
assert_eq!(summary.p99, 0.0);
|
||||
assert_eq!(summary.max, 0.0);
|
||||
assert_eq!(summary.mean, 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bench_percentile_summary_handles_single_value_sample() {
|
||||
let summary = crate::bench::percentile_summary(&[42.0]);
|
||||
assert_eq!(summary.p50, 42.0);
|
||||
assert_eq!(summary.p95, 42.0);
|
||||
assert_eq!(summary.p99, 42.0);
|
||||
assert_eq!(summary.max, 42.0);
|
||||
assert_eq!(summary.mean, 42.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn register_page_token_accepts_distinct_tokens_and_rejects_repeats() {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
assert!(crate::galaxy::register_page_token(&mut seen, "tok-1").is_ok());
|
||||
assert!(crate::galaxy::register_page_token(&mut seen, "tok-2").is_ok());
|
||||
|
||||
let repeated = crate::galaxy::register_page_token(&mut seen, "tok-1");
|
||||
match repeated {
|
||||
Err(zb_mom_ww_mxgateway_client::Error::InvalidArgument { name, detail }) => {
|
||||
assert_eq!(name, "page_token");
|
||||
assert!(detail.contains("tok-1"), "detail: {detail}");
|
||||
}
|
||||
other => panic!("expected InvalidArgument on repeated token, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rfc3339_parser_rejects_trailing_characters() {
|
||||
let err = crate::parse::parse_rfc3339_timestamp("2026-04-28T15:30:00Zextra");
|
||||
assert!(err.is_err(), "trailing chars after Z must be rejected");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rfc3339_parser_rejects_day_zero() {
|
||||
let err = crate::parse::parse_rfc3339_timestamp("2026-04-00T15:30:00Z");
|
||||
assert!(err.is_err(), "day 0 must be rejected");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rfc3339_parser_rejects_month_thirteen() {
|
||||
let err = crate::parse::parse_rfc3339_timestamp("2026-13-01T15:30:00Z");
|
||||
assert!(err.is_err(), "month 13 must be rejected");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rfc3339_parser_rejects_day_out_of_range_for_month() {
|
||||
// April has 30 days.
|
||||
let err = crate::parse::parse_rfc3339_timestamp("2026-04-31T15:30:00Z");
|
||||
assert!(err.is_err(), "April 31 must be rejected");
|
||||
// February 29 in a non-leap year.
|
||||
let feb = crate::parse::parse_rfc3339_timestamp("2025-02-29T00:00:00Z");
|
||||
assert!(feb.is_err(), "Feb 29 in a non-leap year must be rejected");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rfc3339_parser_round_trips_z_and_offset_inputs() {
|
||||
// 2026-04-28T15:30:00Z = 1_777_995_000 (sanity-checked once below)
|
||||
let utc = crate::parse::parse_rfc3339_timestamp("2026-04-28T15:30:00Z").unwrap();
|
||||
let plus = crate::parse::parse_rfc3339_timestamp("2026-04-28T16:30:00+01:00").unwrap();
|
||||
let frac = crate::parse::parse_rfc3339_timestamp("2026-04-28T15:30:00.250Z").unwrap();
|
||||
|
||||
assert_eq!(utc.seconds, plus.seconds);
|
||||
assert_eq!(utc.nanos, 0);
|
||||
assert_eq!(frac.seconds, utc.seconds);
|
||||
assert_eq!(frac.nanos, 250_000_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alarm_feed_provider_status_renders_in_summary_and_json() {
|
||||
use zb_mom_ww_mxgateway_client::generated::mxaccess_gateway::v1::{
|
||||
alarm_feed_message, AlarmFeedMessage, AlarmProviderMode, AlarmProviderStatus,
|
||||
};
|
||||
|
||||
let message = AlarmFeedMessage {
|
||||
payload: Some(alarm_feed_message::Payload::ProviderStatus(
|
||||
AlarmProviderStatus {
|
||||
mode: AlarmProviderMode::Subtag as i32,
|
||||
degraded: true,
|
||||
reason: "alarmmgr unavailable".to_owned(),
|
||||
since: Some(prost_types::Timestamp {
|
||||
seconds: 1_777_995_000,
|
||||
nanos: 0,
|
||||
}),
|
||||
},
|
||||
)),
|
||||
};
|
||||
|
||||
let summary = crate::events::alarm_feed_message_summary(&message);
|
||||
assert!(summary.contains("provider-status"), "summary: {summary}");
|
||||
assert!(
|
||||
summary.contains("ALARM_PROVIDER_MODE_SUBTAG"),
|
||||
"summary: {summary}"
|
||||
);
|
||||
assert!(summary.contains("degraded=true"), "summary: {summary}");
|
||||
|
||||
let value = crate::events::alarm_feed_message_to_json(&message);
|
||||
let provider = &value["providerStatus"];
|
||||
assert_eq!(provider["mode"], "ALARM_PROVIDER_MODE_SUBTAG");
|
||||
assert_eq!(provider["degraded"], true);
|
||||
assert_eq!(provider["reason"], "alarmmgr unavailable");
|
||||
assert_eq!(provider["since"]["seconds"], 1_777_995_000_i64);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alarm_feed_snapshot_status_renders_in_summary_and_json() {
|
||||
use zb_mom_ww_mxgateway_client::generated::mxaccess_gateway::v1::{
|
||||
alarm_feed_message, AlarmFeedMessage, AlarmSnapshotStatus,
|
||||
};
|
||||
|
||||
let message = AlarmFeedMessage {
|
||||
payload: Some(alarm_feed_message::Payload::SnapshotStatus(
|
||||
AlarmSnapshotStatus { truncated: true },
|
||||
)),
|
||||
};
|
||||
|
||||
let summary = crate::events::alarm_feed_message_summary(&message);
|
||||
assert_eq!(summary, "snapshot-status truncated=true");
|
||||
|
||||
let value = crate::events::alarm_feed_message_to_json(&message);
|
||||
assert_eq!(value["snapshotStatus"]["truncated"], true);
|
||||
}
|
||||
@@ -84,6 +84,20 @@ message CloseSessionReply {
|
||||
message StreamEventsRequest {
|
||||
string session_id = 1;
|
||||
uint64 after_worker_sequence = 2;
|
||||
// Opt-in attach acknowledgement (mxaccessgw#227). When true, the gateway emits
|
||||
// one StreamAttached sentinel MxEvent (MxEvent.stream_attached) as the FIRST
|
||||
// message of this stream, sent only after this stream's subscriber is
|
||||
// registered on the session. Every event the session publishes after that
|
||||
// registration is delivered to this stream (subject only to the
|
||||
// after_worker_sequence filter and the backpressure policy), so a client that
|
||||
// waits for the sentinel before issuing AddItem/Advise/SubscribeBulk cannot
|
||||
// lose the initial value to the attach race.
|
||||
// Default false keeps the pre-#227 wire behaviour: no sentinel. It is opt-in
|
||||
// because existing consumers treat every streamed MxEvent's worker_sequence as
|
||||
// a resume cursor and would read the sentinel's 0 as one. A gateway that
|
||||
// predates this field ignores it and never sends the sentinel; such a gateway
|
||||
// does not list "stream-events-attached-ack" in OpenSessionReply.capabilities.
|
||||
bool emit_stream_attached = 3;
|
||||
}
|
||||
|
||||
message MxCommandRequest {
|
||||
@@ -405,6 +419,9 @@ message AcknowledgeAlarmCommand {
|
||||
string operator_user = 3;
|
||||
string operator_node = 4;
|
||||
string operator_domain = 5;
|
||||
// Accepted for wire compatibility but NOT propagated to MXAccess: the 8-arg
|
||||
// AlarmAckByName that carried it returns -55. operator_domain IS used (the
|
||||
// AuthenticateUser identity is "<operator_domain>\<operator_user>").
|
||||
string operator_full_name = 6;
|
||||
// Operator credential used for AuthenticateUser before the AckMsg write.
|
||||
// Implementations must keep this field out of logs, metrics labels, command
|
||||
@@ -435,6 +452,9 @@ message AcknowledgeAlarmByNameCommand {
|
||||
string operator_user = 5;
|
||||
string operator_node = 6;
|
||||
string operator_domain = 7;
|
||||
// Accepted for wire compatibility but NOT propagated to MXAccess: the 8-arg
|
||||
// AlarmAckByName that carried it returns -55. operator_domain IS used (the
|
||||
// AuthenticateUser identity is "<operator_domain>\<operator_user>").
|
||||
string operator_full_name = 8;
|
||||
// Operator credential used for AuthenticateUser before the AckMsg write.
|
||||
// Implementations must keep this field out of logs, metrics labels, command
|
||||
@@ -518,11 +538,15 @@ message WriteSecured2BulkEntry {
|
||||
// reply returns the cached value WITHOUT modifying the existing
|
||||
// subscription (was_cached = true).
|
||||
// - Otherwise the worker takes the snapshot lifecycle itself: AddItem +
|
||||
// Advise, wait up to `timeout_ms` for the first OnDataChange, then
|
||||
// UnAdvise + RemoveItem before returning. The session is left exactly
|
||||
// as it was before the call (was_cached = false).
|
||||
// Advise, wait for the first OnDataChange, then UnAdvise + RemoveItem
|
||||
// before returning. The session is left exactly as it was before the
|
||||
// call (was_cached = false).
|
||||
//
|
||||
// `timeout_ms == 0` uses the gateway-configured default (1000 ms).
|
||||
// `timeout_ms` is one deadline shared by the whole command, not a per-tag
|
||||
// budget: the worker adds and advises every uncached tag, waits once for all
|
||||
// of them, then tears them all down. A tag that has not delivered by the
|
||||
// deadline gets its own was_successful = false result.
|
||||
// `timeout_ms == 0` uses the worker's default (1000 ms).
|
||||
message ReadBulkCommand {
|
||||
int32 server_handle = 1;
|
||||
repeated string tag_addresses = 2;
|
||||
@@ -549,6 +573,7 @@ message ShutdownWorkerCommand {
|
||||
|
||||
message MxCommandReply {
|
||||
string session_id = 1;
|
||||
// Echoes the request's client_correlation_id.
|
||||
string correlation_id = 2;
|
||||
MxCommandKind kind = 3;
|
||||
ProtocolStatus protocol_status = 4;
|
||||
@@ -790,6 +815,18 @@ message MxEvent {
|
||||
// Additive (proto3): existing clients that ignore this field continue to
|
||||
// deserialize the stream unchanged.
|
||||
optional ReplayGap replay_gap = 14;
|
||||
// Gateway-synthesized attach acknowledgement (mxaccessgw#227). Set ONLY on the
|
||||
// single sentinel MxEvent the gateway emits as the FIRST message of a
|
||||
// StreamEvents stream whose request set emit_stream_attached = true. It is
|
||||
// sent after the stream's subscriber is registered, so every event the
|
||||
// session publishes after it reaches this stream. On a resumed stream it
|
||||
// precedes the ReplayGap sentinel (if any) and the replayed events.
|
||||
// On that sentinel, `family` is UNSPECIFIED, the `body` oneof is unset,
|
||||
// `worker_sequence` is 0, and no per-item fields are populated: it is a
|
||||
// control signal, not an MXAccess event, and its worker_sequence MUST NOT be
|
||||
// used as a resume cursor. Never set on a stream that did not opt in, and
|
||||
// ALWAYS unset on events in DrainEventsReply.
|
||||
optional StreamAttached stream_attached = 15;
|
||||
|
||||
oneof body {
|
||||
OnDataChangeEvent on_data_change = 20;
|
||||
@@ -827,6 +864,19 @@ message ReplayGap {
|
||||
uint64 oldest_available_sequence = 2;
|
||||
}
|
||||
|
||||
// Attach acknowledgement carried by a sentinel MxEvent (MxEvent.stream_attached)
|
||||
// at the head of a StreamEvents stream that requested it
|
||||
// (StreamEventsRequest.emit_stream_attached). Its arrival means the stream is
|
||||
// registered on the session: any event published from then on is delivered.
|
||||
message StreamAttached {
|
||||
// Live events on this stream are those with worker_sequence strictly greater
|
||||
// than this value. 0 on a fresh stream (after_worker_sequence = 0). On a
|
||||
// resumed stream it is the last sequence the replay batch that follows
|
||||
// covers (or the requested after_worker_sequence when nothing is replayed),
|
||||
// so it equals the watermark the gateway applies to live events.
|
||||
uint64 live_after_sequence = 1;
|
||||
}
|
||||
|
||||
enum MxEventFamily {
|
||||
MX_EVENT_FAMILY_UNSPECIFIED = 0;
|
||||
MX_EVENT_FAMILY_ON_DATA_CHANGE = 1;
|
||||
@@ -880,7 +930,7 @@ message OnAlarmTransitionEvent {
|
||||
|
||||
// When the alarm originally entered the active state. Preserved across
|
||||
// acknowledge transitions so the Part 9 condition keeps the original raise
|
||||
// time. Unset on retrigger from a previously-cleared condition.
|
||||
// time. Unset when the raise time is unknown (RETRIGGER is reserved and never produced).
|
||||
google.protobuf.Timestamp original_raise_timestamp = 6;
|
||||
|
||||
// When this specific transition occurred (raise time on Raise, ack time on
|
||||
@@ -930,6 +980,8 @@ enum AlarmTransitionKind {
|
||||
ALARM_TRANSITION_KIND_RAISE = 1;
|
||||
ALARM_TRANSITION_KIND_ACKNOWLEDGE = 2;
|
||||
ALARM_TRANSITION_KIND_CLEAR = 3;
|
||||
// Reserved: never produced by the gateway or worker. Retained so the numeric
|
||||
// value is not reused.
|
||||
ALARM_TRANSITION_KIND_RETRIGGER = 4;
|
||||
}
|
||||
|
||||
|
||||
@@ -65,6 +65,13 @@ message WorkerReady {
|
||||
string mxaccess_progid = 2;
|
||||
string mxaccess_clsid = 3;
|
||||
google.protobuf.Timestamp ready_timestamp = 4;
|
||||
// Outcome of the worker's process-wide MXSTATUS_PROXY record-info pin
|
||||
// (MxStatusProxyRecordInfoPin): "pinned {library-guid} vM.m record {record-guid}" on
|
||||
// success, or the failing call and HRESULT / exception type otherwise. Empty when the
|
||||
// worker made no attempt (an older worker, or a runtime that never created the
|
||||
// MXAccess COM object). Diagnostic only: the gateway logs it and shows it on the
|
||||
// dashboard, and never gates readiness on it, because the pin is a cache warm-up.
|
||||
string record_info_pin_status = 5;
|
||||
}
|
||||
|
||||
message WorkerCommand {
|
||||
@@ -127,6 +134,10 @@ enum WorkerState {
|
||||
|
||||
enum WorkerFaultCategory {
|
||||
WORKER_FAULT_CATEGORY_UNSPECIFIED = 0;
|
||||
// Values 1 and 2 are reserved: never emitted. Bootstrap failures (bad
|
||||
// arguments, gateway authentication) exit via WorkerExitCode before the pipe
|
||||
// exists, so there is no channel to carry a fault. Names kept so the numbers
|
||||
// are not reused.
|
||||
WORKER_FAULT_CATEGORY_INVALID_ARGUMENTS = 1;
|
||||
WORKER_FAULT_CATEGORY_GATEWAY_AUTHENTICATION_FAILED = 2;
|
||||
WORKER_FAULT_CATEGORY_PROTOCOL_MISMATCH = 3;
|
||||
|
||||
@@ -960,6 +960,8 @@ impl Session {
|
||||
.stream_events(StreamEventsRequest {
|
||||
session_id: self.id.clone(),
|
||||
after_worker_sequence,
|
||||
// #227 attach acknowledgement is opt-in; this stream keeps the default wire shape.
|
||||
emit_stream_attached: false,
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -128,6 +128,8 @@ async fn event_stream_preserves_order_and_drop_cancels_server_stream() {
|
||||
.stream_events(StreamEventsRequest {
|
||||
session_id: "session-fixture".to_owned(),
|
||||
after_worker_sequence: 0,
|
||||
// #227 attach acknowledgement is opt-in; this stream keeps the default wire shape.
|
||||
emit_stream_attached: false,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -192,6 +194,8 @@ async fn replay_gap_sentinel_surfaces_as_typed_event_item() {
|
||||
.stream_events(StreamEventsRequest {
|
||||
session_id: "session-fixture".to_owned(),
|
||||
after_worker_sequence: 5,
|
||||
// #227 attach acknowledgement is opt-in; this stream keeps the default wire shape.
|
||||
emit_stream_attached: false,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -707,10 +707,14 @@ The prior `DashboardAuthenticator` ctor took `IOptions<GatewayOptions>`, so the
|
||||
| Severity | Low |
|
||||
| Category | Testing coverage |
|
||||
| Location | `src/ZB.MOM.WW.MxGateway.IntegrationTests/WorkerLiveMxAccessSmokeTests.cs:577-709` |
|
||||
| Status | Deferred |
|
||||
| Status | Resolved |
|
||||
|
||||
**Description:** The new-COM-commands live test covers AuthenticateUser/ArchestrAUserToId/Suspend/Activate but not `AddItem2`/`Write2` — the B8 extended commands with a second context parameter introduced in the same bundle. Only live COM tests can verify the COM call succeeds with the correct argument split; a parity regression short-circuiting AddItem2/Write2 to InvalidRequest would not be caught.
|
||||
|
||||
**Recommendation:** Add AddItem2/Write2 to the parity test (or a dedicated test) asserting each produces a real reply (not InvalidRequest) against a valid handle and item-definition split.
|
||||
|
||||
**Resolution:** 2026-06-16: requires a live MXAccess rig + provider state not available on this dev box; add the AddItem2/Write2 parity assertions when running on the MXAccess host. → #212
|
||||
|
||||
2026-11-12: Resolved. `AddItem2` has worker-level live coverage (`Worker.Tests/MxAccess/MxAccessLiveComCreationTests.cs`); `Write2` is covered by `WorkerLiveMxAccessSmokeTests.GatewaySession_WithLiveWorker_Write2ValueWithTimestampToAdvisedItem` (`9c6ac0cd`), run live on windev at `04a40f2c` (x86 Release worker, item `TestChildObject.TestInt`) and PASSED, alone and with the rest of the class (10/10, `WriteSecured` excluded). `Write2` replied `ProtocolStatusCode.Ok`, hresult `0`, kind `Write2`, and MXAccess raised a matching `OnWriteComplete`. The MXAccess status on that completion was `success=0 category=SecurityError detail=1008`: the item's Galaxy security refuses an unauthenticated write, and `Write2` carries no user id. Plain `Write` got the identical refusal in the same run, and the value stayed at 7004 with an unchanged source timestamp. So the live run proves `Write2` reaches the COM call and comes back with a real provider status, not an `InvalidRequest` short-circuit. It does not prove that a value plus timestamp is *applied*, because the rig has no free-access integer test attribute. → #212 (closed)
|
||||
|
||||
2026-11-12 (later), correction: the "no free-access attribute on the rig" limit was wrong, or at least unproven. The windev test used a **plain** `Advise`, and MXAccess refuses a user-id-0 write on a plainly advised item with exactly that `SecurityError/1008`. On the DEV gateway (wonder-app-vd03, `2b13564e`), `MESReceiver_025.MoveInBatchID` (Int32, Z28062) behaved the same way: after `AdviseSupervisory`, `Write2` **applied** the value (`0` → `212212`, OnWriteComplete `Ok`/`RespondingAutomationObject`, then restored to `0`), and after a plain `Advise` the same `Write2` got `SecurityError/1008` and nothing changed. The value-applied proof is now the opt-in `clients/dotnet/ZB.MOM.WW.MxGateway.Client.Tests/LiveGatewayWrite2Tests.cs` (env vars in `docs/GatewayTesting.md`, "Live gateway write"). The windev test now uses `AdviseSupervisory` and restores the original value. It has **not** been re-run on windev since that change. The same run found that the timestamp is stored shifted by the host's UTC offset (sent `01:33:00Z`, stored `06:33:00Z` on the UTC-5 box) → #228.
|
||||
|
||||
@@ -345,7 +345,7 @@ Findings with status `Resolved`, `Won't Fix`, or `Deferred`.
|
||||
| IntegrationTests-030 | Low | Resolved | Documentation & comments | `docs/GatewayTesting.md:76`, `src/ZB.MOM.WW.MxGateway.IntegrationTests/WorkerLiveMxAccessSmokeTests.cs:576,728` |
|
||||
| IntegrationTests-031 | Low | Resolved | Documentation & comments | `src/ZB.MOM.WW.MxGateway.IntegrationTests/WorkerLiveMxAccessSmokeTests.cs:672` |
|
||||
| IntegrationTests-032 | Low | Resolved | Testing coverage | `src/ZB.MOM.WW.MxGateway.IntegrationTests/WorkerLiveMxAccessSmokeTests.cs:823-865` |
|
||||
| IntegrationTests-033 | Low | Deferred | Testing coverage | `src/ZB.MOM.WW.MxGateway.IntegrationTests/WorkerLiveMxAccessSmokeTests.cs:577-709` |
|
||||
| IntegrationTests-033 | Low | Resolved | Testing coverage | `src/ZB.MOM.WW.MxGateway.IntegrationTests/WorkerLiveMxAccessSmokeTests.cs:577-709` |
|
||||
| Server-007 | Low | Resolved | Performance & resource management | `src/MxGateway.Server/Galaxy/GalaxyHierarchyProjector.cs:55-70` |
|
||||
| Server-008 | Low | Resolved | Performance & resource management | `src/MxGateway.Server/Grpc/GalaxyRepositoryGrpcService.cs:111-134,160-189` |
|
||||
| Server-009 | Low | Resolved | Error handling & resilience | `src/MxGateway.Server/Security/Authentication/AuthSqliteConnectionFactory.cs:15-32` |
|
||||
|
||||
@@ -677,7 +677,12 @@ alarm-consumer surface unblocks A.2 fully. Outline:
|
||||
`ACK_RTN` → in_alarm=false, acked=true).
|
||||
- `DATE + TIME + GMTOFFSET + DSTADJUST` → reassemble UTC
|
||||
timestamp; matches the worker's existing `Timestamp`
|
||||
wire format.
|
||||
wire format. *Corrected 2026-11-12 (#226): `DATE` + `TIME`
|
||||
are already UTC — the 13:26:14.709 capture above was taken
|
||||
at 09:26 EDT — and `GMTOFFSET`/`DSTADJUST` only describe the
|
||||
producer's zone. Adding the offset made every alarm
|
||||
timestamp late by it (+5 h on DEV for a `GMTOFFSET=300`
|
||||
record).*
|
||||
- `PRIORITY` → severity (already 1-1000-ish range).
|
||||
- `TAGNAME` → reference; `PROVIDER_NAME` + `GROUP` for
|
||||
scope metadata.
|
||||
|
||||
@@ -120,6 +120,55 @@ Clients use these fixtures to verify that stream helpers preserve
|
||||
|
||||
Wrappers must not reorder, coalesce, or drop events while reading the fixture.
|
||||
|
||||
### Slow-Consumer And Backpressure Behavior
|
||||
|
||||
Each client treats a consumer that falls behind differently. The gateway side is
|
||||
the same for all of them: a subscriber whose bounded server-side event channel
|
||||
overflows is disconnected with an `EventQueueOverflow` fault (surfaced as gRPC
|
||||
`ResourceExhausted`) rather than having events silently dropped; see
|
||||
`MxGateway:Events:BackpressurePolicy` in `GatewayConfiguration.md`. The table
|
||||
covers only what each client does on its own side of the wire.
|
||||
|
||||
| Client | Client-side buffer | Default | When the consumer falls behind | Non-dropping alternative |
|
||||
|---|---|---|---|---|
|
||||
| .NET | none; `StreamEventsAsync` is a pull-based `IAsyncEnumerable<MxEvent>` | n/a | gRPC/HTTP-2 flow control applies back-pressure to the server, which can then overflow its per-subscriber channel | the same stream (it never drops client-side) |
|
||||
| Go | buffered channel from `Session.Events`/`EventsAfter`, sized by `Options.EventBufferSize` | 1024 | the call is cancelled; buffered results are still delivered in order, then a final result matching `errors.Is(err, mxgateway.ErrSlowConsumer)` | `SubscribeEvents`/`SubscribeEventsAfter` block instead of dropping |
|
||||
| Java | bounded queue behind the `streamEvents` iterator, sized by `MxGatewayClientOptions.eventQueueCapacity(n)` | 1024 | the call is cancelled; buffered events stay readable and `MxGatewayException` is thrown only after they are drained | `streamEventsAsync(request, StreamObserver<MxEvent>)` delivers on the gRPC thread with no client-side queue |
|
||||
| Python | none; `Session.stream_events` is an async iterator over the gRPC call | n/a | gRPC flow control applies back-pressure to the server | the same stream |
|
||||
| Rust | none; `EventStream` is a boxed `Stream` over the tonic response (the design requires any helper channel to be bounded) | n/a | gRPC flow control applies back-pressure to the server | the same stream |
|
||||
|
||||
### ResourceExhausted Reason Trailer
|
||||
|
||||
The gateway uses gRPC `ResourceExhausted` for several different conditions. The status
|
||||
code is unchanged, but every such failure now also carries a machine-readable reason in
|
||||
the `mxgw-reason` response trailer (ASCII value), so a client can tell "you fell behind and
|
||||
events were lost" (re-subscribe and resync) from "a limit was reached" (back off, do not
|
||||
retry immediately):
|
||||
|
||||
| `mxgw-reason` | Meaning | Client action |
|
||||
|---|---|---|
|
||||
| `event-queue-overflow` | The `StreamEvents` subscriber fell behind its bounded queue and was disconnected; events were lost. | Reopen with the last seen `afterWorkerSequence` and resync. |
|
||||
| `alarm-feed-overflow` | The `StreamAlarms` subscriber fell behind and was dropped. | Reconnect and re-snapshot. |
|
||||
| `subscriber-limit` | The per-session event-subscriber cap was reached. | Back off. |
|
||||
| `subscriber-already-active` | Only one subscriber is allowed and one is attached. | Back off. |
|
||||
| `session-limit` | The gateway session limit was reached. | Back off. |
|
||||
| `command-too-large` | A command exceeded the maximum frame size. | Do not retry unchanged. |
|
||||
|
||||
A missing trailer (an older gateway, or the API-key failure throttle's `ResourceExhausted`)
|
||||
means "reason unknown"; treat it as the generic status. Constants live in
|
||||
`ZB.MOM.WW.MxGateway.Contracts.ResourceExhaustedReasons`.
|
||||
|
||||
- **.NET** (additive): `ResourceExhausted` now surfaces as `MxGatewayResourceExhaustedException`
|
||||
(a subclass of `MxGatewayException`, so existing catches keep working) with `Reason`,
|
||||
`IsOverflow` and `IsSubscriberLimit`.
|
||||
- **Go, Java, Python, Rust**: no typed surface yet (doc note only). Read the `mxgw-reason`
|
||||
trailer from the failing call's trailing metadata (`status.Trailer()` / `Metadata` /
|
||||
`trailing_metadata()` / tonic `Status::metadata()`).
|
||||
|
||||
After a slow-consumer cancel or an `EventQueueOverflow` disconnect, reopen with
|
||||
the last seen `afterWorkerSequence`; if it predates the replay ring the stream
|
||||
opens with the replay-gap sentinel described in `Event Streams` above.
|
||||
|
||||
## Value And Status Conversion
|
||||
|
||||
Value fixtures live in `clients/proto/fixtures/behavior/values/`. Each case
|
||||
|
||||
@@ -137,6 +137,15 @@ alarm ack. The minor bump marks a new wire field. The Python, Rust, Java and
|
||||
Go clients were not republished in that release, and their manifests were
|
||||
left alone.
|
||||
|
||||
On 2026-11-12 (#227) the .NET pair alone moved to **0.4.0**: `nuget`
|
||||
`ZB.MOM.WW.MxGateway.Contracts` **0.4.0** and `ZB.MOM.WW.MxGateway.Client`
|
||||
**0.4.0**. The release carries the additive opt-in stream-attached
|
||||
acknowledgement from `afd504d5` (`StreamEventsRequest.emit_stream_attached`,
|
||||
`MxEvent.stream_attached`, capability `stream-events-attached-ack`) and the
|
||||
client's `OpenEventStreamAsync` awaitable, so OtOpcUa can close the
|
||||
subscribe-before-attach race (lmxopcua#877). The Python, Rust, Java and Go
|
||||
clients were not republished, and their manifests were left alone.
|
||||
|
||||
**The published pypi `0.2.0` artifact has a broken `connect()` (CLI-46).**
|
||||
Its `connect()` built the `grpc.aio` channel inside `asyncio.to_thread`, and
|
||||
a `grpc.aio` channel binds to the event loop current on the *constructing*
|
||||
|
||||
@@ -78,8 +78,8 @@ Setting it to `0` reverts to closing only on normal lease expiry.
|
||||
|
||||
A reconnecting client issues `StreamEvents` with `after_worker_sequence` set to
|
||||
the last sequence it observed; the gateway replays retained events newer than
|
||||
that watermark (capped by `MxGateway:Events:ReplayBufferCapacity` and
|
||||
`MxGateway:Events:ReplayRetentionSeconds`) then transitions seamlessly to live
|
||||
that watermark (capped by `MxGateway:Events:ReplayBufferCapacity`,
|
||||
`MxGateway:Events:ReplayRetentionSeconds` and `MxGateway:Events:ReplayBufferMaxBytes`) then transitions seamlessly to live
|
||||
delivery. If the requested position precedes the oldest retained event, a
|
||||
`ReplayGap` sentinel signals the client to re-snapshot. The replay→live handoff
|
||||
is atomic (no gap, no duplicate). See [Sessions](./Sessions.md) for the full
|
||||
@@ -576,9 +576,15 @@ Decision: model and forward `OperationComplete` only when native MXAccess fires
|
||||
it. Do not synthesize `OperationComplete` from writes, command replies, ASB
|
||||
completion queues, or other status frames.
|
||||
|
||||
Rationale: the event signature is known, but the MXAccess analysis has not yet
|
||||
captured the runtime condition that triggers the public event. Synthesizing it
|
||||
would risk breaking parity.
|
||||
Rationale: synthesizing it would risk breaking parity.
|
||||
|
||||
Trigger (captured live 2026-11-13, `docs/LiveCaptures-2026-11-13.md` §1, pinned by
|
||||
`OperationCompleteLiveProbeTests`): MXAccess raises `OperationComplete` after a
|
||||
`Suspend` or `Activate` whose synchronous `MxStatus` is Pending (raw category 1,
|
||||
detail 0). That happens only for an advised item whose reference resolved. The event
|
||||
carries the same server/item handles and one Ok row detected by RespondingLmx. A
|
||||
`Suspend`/`Activate` that returns Ok synchronously (already in that state, or an
|
||||
unresolved reference) raises nothing, and writes never raise it.
|
||||
|
||||
## Buffered Data Change
|
||||
|
||||
@@ -589,6 +595,12 @@ The event signature and native path are known. A live buffered sample batch has
|
||||
not yet been observed. Until then, preserve raw value, quality, timestamp, data
|
||||
type, and status metadata whenever conversion is incomplete.
|
||||
|
||||
The empty `NoData` event that the rig delivers after `Advise` is a resolution
|
||||
failure, not a bootstrap: its status row is ConfigurationError, detail 6 for the
|
||||
`(item, context)` form and detail 1002 `InvalidPropertyId` for a full reference to an
|
||||
attribute without a buffer (`docs/LiveCaptures-2026-11-13.md` §5). A multi-sample
|
||||
capture needs a deployed field attribute or I/O extension with *Buffer* enabled.
|
||||
|
||||
## Completion-Only Status Mapping
|
||||
|
||||
Decision: preserve completion-only operation-status bytes as raw diagnostic
|
||||
@@ -598,6 +610,12 @@ proves an exact `MXSTATUS_PROXY[]` mapping.
|
||||
Do not guess status category/source/detail values for frames that MXAccess does
|
||||
not expose through its public COM events.
|
||||
|
||||
Settled 2026-11-13 (`docs/LiveCaptures-2026-11-13.md` §2): every captured
|
||||
`OnWriteComplete` and `OperationComplete` carried a typed `MXSTATUS_PROXY[]`, and no
|
||||
public COM event delivers completion-only bytes. The mapping is not needed, and any
|
||||
such bytes stay raw permanently. `PreserveCompletionOnlyStatusBytes` has no production
|
||||
caller.
|
||||
|
||||
## API Key Administration
|
||||
|
||||
Decision: v1 API key management is a local administrative CLI/tool, not a
|
||||
|
||||
@@ -223,6 +223,8 @@ The shared `ZB.MOM.WW.Health` package maps three endpoints — `/healthz` (live)
|
||||
| Check | Endpoint tier | Fails when |
|
||||
|---|---|---|
|
||||
| `auth-store` | `ready` | The SQLite auth store cannot be opened. Every gRPC call authenticates against it, so its reachability genuinely gates whether the process should receive traffic. |
|
||||
| `worker-executable` | `ready` | The configured `MxGateway:Worker:ExecutablePath` does not resolve to an existing file, so every session start would fail with `ExecutableNotFound`. |
|
||||
| `galaxy-sql` | `ready` | The Galaxy Repository SQL ping fails or exceeds its 5 s bound. Never `live`: an outage takes the node out of rotation but a restart cannot fix it. |
|
||||
| `mxaccess-sessions` | `active` | Sessions exist and their workers have faulted. Reports `total` / `ready` / `faulted` / `starting` / `closing` as entry `data`. |
|
||||
|
||||
**Zero sessions is Healthy, and the tier choice follows from that.** The gateway opens an MXAccess
|
||||
|
||||
@@ -22,12 +22,14 @@ paths, timeouts, queue sizes, enum values, or protocol values are invalid.
|
||||
"WorkingDirectory": null,
|
||||
"RequiredArchitecture": "X86",
|
||||
"StartupTimeoutSeconds": 30,
|
||||
"StartupProbeRetryAttempts": 3,
|
||||
"StartupProbeRetryDelayMilliseconds": 250,
|
||||
"PipeConnectAttemptTimeoutMilliseconds": 2000,
|
||||
"ShutdownTimeoutSeconds": 10,
|
||||
"HeartbeatIntervalSeconds": 5,
|
||||
"HeartbeatCheckIntervalSeconds": 5,
|
||||
"HeartbeatGraceSeconds": 15,
|
||||
"HeartbeatStuckCeilingSeconds": 75,
|
||||
"WorkerHeartbeatSendIntervalSeconds": 5,
|
||||
"WorkerHeartbeatStuckCeilingSeconds": 75,
|
||||
"EventChannelFullModeTimeoutMilliseconds": 5000,
|
||||
"MaxMessageBytes": 16842752
|
||||
},
|
||||
"Sessions": {
|
||||
@@ -48,12 +50,16 @@ paths, timeouts, queue sizes, enum values, or protocol values are invalid.
|
||||
"BackpressurePolicy": "FailFast",
|
||||
"ReplayBufferCapacity": 1024,
|
||||
"ReplayRetentionSeconds": 300,
|
||||
"ReplayBufferMaxBytes": 67108864,
|
||||
"MaxSparseArrayLength": 1000000
|
||||
},
|
||||
"Dashboard": {
|
||||
"Enabled": true,
|
||||
"AllowAnonymousLocalhost": true,
|
||||
"DisableLogin": false,
|
||||
"AutoLoginUser": null,
|
||||
"RequireHttpsCookie": true,
|
||||
"CookieName": null,
|
||||
"SnapshotIntervalMilliseconds": 1000,
|
||||
"RecentFaultLimit": 100,
|
||||
"RecentSessionLimit": 200,
|
||||
@@ -81,7 +87,31 @@ paths, timeouts, queue sizes, enum values, or protocol values are invalid.
|
||||
"Enabled": false,
|
||||
"SubscriptionExpression": "",
|
||||
"DefaultArea": "",
|
||||
"ReconcileIntervalSeconds": 30
|
||||
"ReconcileIntervalSeconds": 30,
|
||||
"Fallback": {
|
||||
"Mode": "Auto",
|
||||
"ConsecutiveFailureThreshold": 3,
|
||||
"FailbackProbeIntervalSeconds": 30,
|
||||
"FailbackStableProbes": 3,
|
||||
"Discovery": {
|
||||
"UseGalaxyRepository": true,
|
||||
"Area": "",
|
||||
"IncludeAttributes": [],
|
||||
"ExcludeAttributes": []
|
||||
},
|
||||
"Subtags": {
|
||||
"Active": "InAlarm",
|
||||
"Acked": "Acked",
|
||||
"AckComment": "AckMsg",
|
||||
"Priority": "Priority"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Tls": {
|
||||
"SelfSignedCertPath": "C:\\ProgramData\\MxGateway\\certs\\gateway-selfsigned.pfx",
|
||||
"ValidityYears": 10,
|
||||
"AdditionalDnsNames": [],
|
||||
"RegenerateIfExpired": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -116,17 +146,20 @@ launch CWD (SEC-01, SEC-33).
|
||||
| `MxGateway:Worker:WorkingDirectory` | `null` | Optional working directory for the worker process. When set, it must be a valid filesystem path. |
|
||||
| `MxGateway:Worker:RequiredArchitecture` | `X86` | Required Portable Executable architecture for the worker. Supported values are `X86` and `X64`; MXAccess parity uses `X86`. |
|
||||
| `MxGateway:Worker:StartupTimeoutSeconds` | `30` | Total startup budget for process launch, startup probe, pipe connect, handshake, and worker readiness. |
|
||||
| `MxGateway:Worker:StartupProbeRetryAttempts` | `3` | Number of retry attempts for transient worker startup probe failures before pipe connection and handshake continue. |
|
||||
| `MxGateway:Worker:StartupProbeRetryDelayMilliseconds` | `250` | Delay between transient startup probe retry attempts. |
|
||||
| `MxGateway:Worker:PipeConnectAttemptTimeoutMilliseconds` | `2000` | Per-attempt timeout used by the worker named-pipe connect retry path. The overall pipe connection still stays under the startup budget. |
|
||||
| `MxGateway:Worker:WriteCompletionWaitMilliseconds` | `1500` | Bounded wait the worker holds a unary write reply (`Write`/`Write2`/`WriteSecured`/`WriteSecured2`; bulk writes excluded) for the matching MXAccess `OnWriteComplete` callback, so the reply's `statuses` carry the real commit outcome. `0` disables the wait (pure fire-and-forget replies). Must be `>= 0`. The gateway conveys the value to the worker via the `MXGATEWAY_WORKER_WRITE_COMPLETION_WAIT_MS` environment variable. Consumers that time their own writes must budget above this wait: OtOpcUa's GalaxyDriver wraps gateway writes in a 2 s Tier A resilience timeout, so a deployment raising this option past ~2000 must raise that driver `ResilienceConfig` write timeout in step or slow-but-successful commits surface as consumer-side failures. |
|
||||
| `MxGateway:Worker:EventQueueCapacity` | `10000` | Capacity, in events, of the worker's outbound MXAccess event queue. Must be between `1000` and `1000000`. This is burst headroom, not a throttle: the queue has no drop policy, so filling it records a `QueueOverflow` worker fault and faults the session. Raise it for sessions whose subscription set can outrun the drain loop (large advise sets, slow event consumers); the backing queue pre-allocates its slots, so the ceiling keeps a mistyped value from committing the 32-bit worker to an outsized allocation. The gateway conveys the value to the worker via the `MXGATEWAY_EVENT_QUEUE_CAPACITY` environment variable; a missing or unusable value leaves the worker on the 10000 default rather than failing the session. |
|
||||
| `MxGateway:Worker:ShutdownTimeoutSeconds` | `10` | Grace period for worker shutdown before the gateway treats shutdown as failed and may kill the worker process tree. |
|
||||
| `MxGateway:Worker:HeartbeatIntervalSeconds` | `5` | Worker heartbeat send interval and gateway heartbeat check cadence input. |
|
||||
| `MxGateway:Worker:HeartbeatGraceSeconds` | `15` | Maximum age of the last worker heartbeat before the gateway faults the worker. This must be greater than or equal to `HeartbeatIntervalSeconds`. |
|
||||
| `MxGateway:Worker:HeartbeatCheckIntervalSeconds` | `5` | How often the gateway checks the age of the worker's last heartbeat against `HeartbeatGraceSeconds`. This is the gateway-side check cadence only; the worker's send interval is `WorkerHeartbeatSendIntervalSeconds`. Must be greater than zero. |
|
||||
| `MxGateway:Worker:HeartbeatIntervalSeconds` | *(unset)* | **Deprecated** alias of `HeartbeatCheckIntervalSeconds` (mxaccessgw#192). The old name implied the worker's send interval, but the value only ever set the gateway's check cadence, which is what it still sets. Setting both keys fails validation. |
|
||||
| `MxGateway:Worker:HeartbeatGraceSeconds` | `15` | Maximum age of the last worker heartbeat before the gateway faults the worker. This must be greater than or equal to `HeartbeatCheckIntervalSeconds`, and strictly greater than `WorkerHeartbeatSendIntervalSeconds` — a grace at or below the worker's send interval declares a healthy worker dead between two heartbeats (mxaccessgw#218). |
|
||||
| `MxGateway:Worker:HeartbeatStuckCeilingSeconds` | `75` | Ceiling on the gateway's in-flight-command heartbeat skip. While a command is pending the gateway tolerates a stale heartbeat, because the worker STA is busy inside a COM call; once the oldest pending command is older than this, the watchdog faults the worker anyway so a truly stuck COM call cannot hide a dead worker. Must be greater than or equal to `HeartbeatGraceSeconds`. The worker's own watchdog has its separate ceiling, `WorkerHeartbeatStuckCeilingSeconds`. |
|
||||
| `MxGateway:Worker:WorkerHeartbeatSendIntervalSeconds` | `5` | Interval at which the worker sends heartbeats to the gateway. Must be between `1` and `86400`, and below `HeartbeatGraceSeconds`. Conveyed to the worker via `MXGATEWAY_WORKER_HEARTBEAT_SEND_INTERVAL_MS`; a missing or invalid value leaves the worker on 5 s. |
|
||||
| `MxGateway:Worker:WorkerHeartbeatGraceSeconds` | `15` | The worker's own STA-watchdog grace: how long STA activity may go stale before the worker faults `StaHung` (no command in flight). Must be between `1` and `86400` and below `WorkerHeartbeatStuckCeilingSeconds`; validation uses this configured value, not a copied constant (mxaccessgw#224). Conveyed via `MXGATEWAY_WORKER_HEARTBEAT_GRACE_MS`; a missing or invalid value, or a grace the ceiling does not exceed, leaves the worker on 15 s. |
|
||||
| `MxGateway:Worker:WorkerHeartbeatStuckCeilingSeconds` | `75` | Ceiling on the worker's own STA watchdog: once STA activity has been stale this long, the worker faults `StaHung` even while a command is in flight. Must be greater than `WorkerHeartbeatGraceSeconds` and at most `86400`. Raise it together with `HeartbeatStuckCeilingSeconds` for deployments that run very long bulk operations. Conveyed via `MXGATEWAY_WORKER_HEARTBEAT_STUCK_CEILING_MS`; a missing or invalid value leaves the worker on 75 s. |
|
||||
| `MxGateway:Worker:EventChannelFullModeTimeoutMilliseconds` | `5000` | How long the gateway waits for a session's bounded event channel (`MxGateway:Events:QueueCapacity`) to accept a worker event before faulting the session with `QueueOverflow`. A consumer stalled for longer than this is treated as stuck rather than slow. Must be greater than zero. |
|
||||
| `MxGateway:Worker:MaxMessageBytes` | `16842752` | Maximum worker IPC frame payload size in bytes. The validator allows values from `1024` through `268435456`, and additionally requires this to be at least `MxGateway:Protocol:MaxGrpcMessageBytes` plus a 65536-byte (64 KiB) envelope-overhead reserve **and at most that cap plus twice the reserve**. The default is the 16 MiB public gRPC cap plus one reserve. The gateway conveys the negotiated value to the worker in the handshake (`GatewayHello.max_frame_bytes`), so the worker frames to the same limit rather than a hard-coded default. The band is narrow by design, so changing either message-size knob alone no longer validates — move `MxGateway:Protocol:MaxGrpcMessageBytes` and this one together, keeping this one one to two reserves above it. |
|
||||
|
||||
`StartupProbeRetryAttempts`, `StartupProbeRetryDelayMilliseconds`,
|
||||
`PipeConnectAttemptTimeoutMilliseconds`, timeout values, heartbeat values, and
|
||||
`MaxMessageBytes` must be positive. `MaxMessageBytes` is intentionally bounded
|
||||
to avoid accidental large allocations from malformed or oversized frames. It
|
||||
@@ -169,6 +202,7 @@ All numeric session options must be greater than zero.
|
||||
| `MxGateway:Events:BackpressurePolicy` | `FailFast` | Per-subscriber event backpressure behavior when a subscriber's bounded event channel overflows. Overflow is isolated to the offending subscriber: it is always disconnected with an `EventQueueOverflow` fault while the session pump and other subscribers keep running. `FailFast` additionally faults the whole session only in the legacy single-subscriber case (the current default mode); with multiple subscribers it degrades to a per-subscriber disconnect so one slow consumer never faults a shared session. `DisconnectSubscriber` disconnects only the slow subscriber in all cases. |
|
||||
| `MxGateway:Events:ReplayBufferCapacity` | `1024` | Maximum number of events retained per session in the replay ring buffer, used to re-deliver events a returning subscriber missed (reconnect/reattach). The oldest retained event is evicted once this count is exceeded. `0` disables replay retention. |
|
||||
| `MxGateway:Events:ReplayRetentionSeconds` | `300` | Maximum age, in seconds, of an event retained in the replay ring buffer. Entries older than this are evicted regardless of capacity. `0` disables age-based eviction. |
|
||||
| `MxGateway:Events:ReplayBufferMaxBytes` | `67108864` (64 MiB) | Maximum summed serialized size, in bytes, of the events retained per session in the replay ring buffer. The count cap alone does not bound memory: one large-array event can approach the worker frame size, so 1024 of them could pin gigabytes per session. When the retained total exceeds this cap the oldest events are evicted first, and an event larger than the whole cap is not retained at all; a resuming subscriber then sees the ordinary `ReplayGap`. The default never binds for scalar traffic and only trims bursts of large events. `0` disables the byte cap. |
|
||||
| `MxGateway:Events:MaxSparseArrayLength` | `1000000` | Maximum `total_length` a sparse-array write (`MxSparseArray`) may declare. A write above this cap is rejected with `InvalidArgument` before the full array is materialized, guarding against a single write forcing a multi-GB allocation. Must be between `1` and `Array.MaxLength`. |
|
||||
|
||||
`QueueCapacity` must be greater than zero and no greater than `int.MaxValue / 2`
|
||||
@@ -186,8 +220,8 @@ subscribers `FailFast` degrades to a per-subscriber disconnect, matching
|
||||
healthy subscribers. With `DisconnectSubscriber`, overflow terminates only the
|
||||
affected stream while the MXAccess session remains active.
|
||||
|
||||
`ReplayBufferCapacity` and `ReplayRetentionSeconds` must each be greater than or
|
||||
equal to zero (either dimension can be disabled with `0`). A returning subscriber
|
||||
`ReplayBufferCapacity`, `ReplayRetentionSeconds` and `ReplayBufferMaxBytes` must
|
||||
each be greater than or equal to zero (any dimension can be disabled with `0`). A returning subscriber
|
||||
that asks for events older than the oldest still-retained event is told it missed
|
||||
events (a "gap") and must re-snapshot; whatever is still retained is replayed.
|
||||
|
||||
@@ -271,8 +305,9 @@ dev/test GLAuth posture (`glauth.md`), not a production posture.
|
||||
| `MxGateway:Ldap:Enabled` | `true` | Enables LDAP-backed dashboard login. |
|
||||
| `MxGateway:Ldap:Server` | `localhost` | LDAP server host. Dev points at the shared GLAuth instance (`10.100.0.35`). |
|
||||
| `MxGateway:Ldap:Port` | `3893` | LDAP server port. Must be between `1` and `65535`. |
|
||||
| `MxGateway:Ldap:Transport` | `None` | Connection transport: `None` (plaintext), `StartTls` (upgrade), or `Ldaps` (implicit TLS). The dev default is `None` because the shared GLAuth instance has LDAPS disabled and binds send cleartext. **Production hard-stop (SEC-06):** when the host runs in the `Production` environment, `Transport` must not be `None` — startup validation fails otherwise. Deployed hosts must set `Ldaps` or `StartTls`. |
|
||||
| `MxGateway:Ldap:Transport` | `None` | Connection transport: `None` (plaintext), `StartTls` (upgrade), or `Ldaps` (implicit TLS). The dev default is `None` (plaintext, the shared GLAuth's `:3893` listener). The shared GLAuth also serves LDAPS on `:3894` (self-signed, since 2026-11-10); use that with `Ldaps` plus `ServerCertificateThumbprintSha256` — windev does since 2026-11-13. **Production hard-stop (SEC-06):** when the host runs in the `Production` environment, `Transport` must not be `None` — startup validation fails otherwise. Deployed hosts must set `Ldaps` or `StartTls`. |
|
||||
| `MxGateway:Ldap:AllowInsecure` | `true` | Permits a plaintext bind. Must be `true` when `Transport` is `None`; set `false` (with `Ldaps`/`StartTls`) in production. |
|
||||
| `MxGateway:Ldap:ServerCertificateThumbprintSha256` | *(empty)* | Pins the LDAP server certificate by its SHA-256 thumbprint (mxaccessgw#180), so `Ldaps`/`StartTls` works against a directory with a self-signed certificate (e.g. GLAuth) without installing that certificate in the OS trust store. Empty (the default) keeps default OS trust-store validation, unchanged. When set, the server certificate is accepted **if and only if** its thumbprint matches one of the pins: chain and name errors are ignored for a matching certificate, and a non-matching certificate is rejected even if it chains to a trusted root. Format: the hex SHA-256 of the DER certificate, case-, colon-, dash- and space-insensitive — paste the output of `openssl x509 -in cert.pem -noout -fingerprint -sha256` (drop the `sha256 Fingerprint=` prefix) or, for a live server, `openssl s_client -connect host:636 </dev/null 2>/dev/null \| openssl x509 -noout -fingerprint -sha256`. To carry old + new across a certificate rotation, give several pins as a comma/semicolon-separated string (`"AB:CD:…,12:34:…"`, env var `MxGateway__Ldap__ServerCertificateThumbprintSha256`) or as a JSON array (`MxGateway__Ldap__ServerCertificateThumbprintSha256__0`, `__1`, …). Startup validation rejects an entry that is not 64 hex characters after normalization, and rejects any pin combined with `Transport=None` (plaintext has no certificate to pin). Applies to every endpoint, including `FallbackServers`. Shown on the dashboard Settings page. |
|
||||
| `MxGateway:Ldap:SearchBase` | `dc=zb,dc=local` | Search base DN. |
|
||||
| `MxGateway:Ldap:ServiceAccountDn` | `cn=serviceaccount,dc=zb,dc=local` | Bind DN for the search account. |
|
||||
| `MxGateway:Ldap:ServiceAccountPassword` | `${secret:ldap/mxgateway/bind}` | Search-account password. **Never a committed plaintext value (SEC-36):** the shared GLAuth bind credential is supplied out-of-band through one of three channels, all binding to this key. **(1) Encrypted secrets store (shipped default):** `appsettings.json` ships the reference `${secret:ldap/mxgateway/bind}`, which the pre-host `${secret:}` expander resolves at startup from the encrypted secrets store (the code-side design default is blank, so a missing/unresolved value fails closed rather than falling back to a leaked credential). Seed it once with `secret set ldap/mxgateway/bind <value>` (the store's master key must be present via `ZB_SECRETS_MASTER_KEY`); startup aborts with `SecretNotFoundException` if the secret is absent. **(2) Deployed hosts — env var:** override directly with `MxGateway__Ldap__ServiceAccountPassword` (double-underscore form) in the NSSM service environment — a plain literal there is used as-is and the store lookup is skipped. **(3) Dev boxes — user-secrets:** `dotnet user-secrets set "MxGateway:Ldap:ServiceAccountPassword" <value>` (the server carries `<UserSecretsId>mxaccessgw-server</UserSecretsId>`; user-secrets load automatically in the Development environment and live under the user profile, outside the tree). The value comes from the GLAuth source of truth `scadaproj/infra/glauth/`, never from a repo file. **Rotation:** because the credential was historically committed, it was rotated in `scadaproj/infra/glauth/` (and the shared GLAuth on `10.100.0.35` redeployed) on 2026-08-07 (SEC-36) — see `docs/runbooks/SEC-36-ldap-credential-rotation.md` for the cutover procedure used, and for future rotations. A blank/unresolved value fails startup validation with a message naming the two supported channels. |
|
||||
@@ -300,13 +335,21 @@ staging rig, e.g. one pointed at the plaintext shared GLAuth). A production-like
|
||||
deployment must therefore run with the literal `Production` environment name for
|
||||
the hard-stops to apply.
|
||||
|
||||
`windev` (`10.100.0.48`) is deliberately labelled `Staging` (its NSSM
|
||||
`DOTNET_ENVIRONMENT` entry, set 2026-08-07) rather than left at the `Production`
|
||||
default. It is the permissive rig the parenthesis above describes: it runs
|
||||
`Dashboard:DisableLogin=true` and binds the shared GLAuth, which offers no TLS,
|
||||
so a `Production` label would contradict its own configuration and both
|
||||
hard-stops would refuse the boot. Label a host `Production` only when its
|
||||
configuration can satisfy them.
|
||||
`windev` (`10.100.0.48`) runs as `Production` since 2026-11-13 (mxaccessgw#180).
|
||||
From 2026-08-07 until then it was deliberately labelled `Staging`, because it ran
|
||||
`Dashboard:DisableLogin=true` against the shared GLAuth's plaintext listener and both
|
||||
hard-stops would have refused a `Production` boot. Its NSSM `AppEnvironmentExtra` now sets
|
||||
`DOTNET_ENVIRONMENT=Production` and `ASPNETCORE_ENVIRONMENT=Production`, and it drops
|
||||
`MxGateway__Dashboard__DisableLogin`, so dashboard login is LDAP. It also sets
|
||||
`MxGateway__Ldap__Port=3894`, `MxGateway__Ldap__Transport=Ldaps`,
|
||||
`MxGateway__Ldap__AllowInsecure=false` and `MxGateway__Ldap__ServerCertificateThumbprintSha256`,
|
||||
the pin of the shared GLAuth's self-signed certificate, which lives in
|
||||
`scadaproj/infra/glauth/README.md`. Nothing goes into the OS trust store. The pre-change
|
||||
service key and appsettings are backed up in `C:\publish\mxaccessgw-backup-20261113-mxgw180\`;
|
||||
to roll back, run `reg import` on the `.reg` file and restart. The wonder boxes (vd03, vq03,
|
||||
vq04) still run `Staging`: each binds its own plain-only loopback GLAuth, and vd03 runs
|
||||
`DisableLogin=true`. Label a host `Production` only when its configuration can satisfy both
|
||||
hard-stops.
|
||||
|
||||
## Secrets Master Key
|
||||
|
||||
@@ -340,7 +383,8 @@ nssm set MxAccessGw AppEnvironmentExtra ZB_SECRETS_MASTER_KEY=<base64-32-bytes>
|
||||
|
||||
`AppEnvironmentExtra` is the same newline-separated `KEY=VALUE` block that
|
||||
already carries `ASPNETCORE_ENVIRONMENT`, `MxGateway__Worker__ExecutablePath`,
|
||||
and the API-key pepper (see the `wonder-app-vd03`/`windev` deploy notes) —
|
||||
and the API-key pepper (`MxGateway__ApiKeyPepper`; on `wonder-app-vd03` only since
|
||||
2026-11-12, see `docs/deploy/2026-11-12-vd03-pepper-to-service-env.md`) —
|
||||
`nssm set ... AppEnvironmentExtra` **replaces the entire block**, so always
|
||||
`get` first and re-include every existing entry alongside the new key, then
|
||||
restart the service for it to take effect.
|
||||
@@ -482,7 +526,7 @@ behavior.
|
||||
| `MxGateway:Alarms:DefaultArea` | _(empty)_ | Area name used to compose a default subscription when `SubscriptionExpression` is empty. If both are empty while `Enabled` is `true`, the monitor faults with a configuration diagnostic. |
|
||||
| `MxGateway:Alarms:ReconcileIntervalSeconds` | `30` | How often the monitor re-resolves and, on material change, hot-swaps the subtag fallback watch-list, then reconciles its in-process alarm cache against the worker's authoritative active-alarm snapshot. The acknowledged watch-list fingerprint advances only after an OK worker reply. Floored at 5 seconds. |
|
||||
| `MxGateway:Alarms:PollIntervalMilliseconds` | `500` | Cadence at which the worker's STA polls the AVEVA alarm consumer (`GetXmlCurrentAlarms2`) for the active-alarm snapshot the live feed diffs. Must be between `100` and `3600000` (one hour): every poll is a COM call plus an XML parse on the same STA that serves reads and writes, so a tighter cadence starves the command path, while a value above an hour stops being a cadence and silently disables alarm polling. The gateway conveys the value to the worker via the `MXGATEWAY_ALARM_POLL_INTERVAL_MS` environment variable; a missing or out-of-range value leaves the worker on the 500 ms default rather than failing the session. |
|
||||
| `MxGateway:Alarms:MaxAlarmsPerFetch` | `1024` | Cap the worker passes to `GetXmlCurrentAlarms2`'s `maxAlmCnt`. Must be between `64` and `65536` — the worker is a 32-bit process that materializes each reply as one BSTR plus a full `XmlDocument`, so an unbounded cap faults the STA with an out-of-memory rather than merely slowing it. It doubles as the **truncation threshold**: a fetch returning exactly this many records is treated as truncated, because the COM API caps its reply with no "more available" flag. On a truncated poll the worker retains the alarms the capped reply could not mention instead of letting their absence read as a clear, and logs a rate-limited `AlarmSnapshotTruncated` warning to its stderr (identifiers and counts only). **Remediation when you see that warning: raise this value** so the steady-state active-alarm count fits inside one fetch. A galaxy permanently above the cap holds stale entries in the snapshot until a sub-cap poll, and loses clear→re-raise cycles that happen entirely out of window (see `docs/DesignDecisions.md`). Conveyed to the worker via the `MXGATEWAY_ALARM_MAX_ALARMS_PER_FETCH` environment variable; a missing or out-of-range value leaves the worker on the 1024 default. |
|
||||
| `MxGateway:Alarms:MaxAlarmsPerFetch` | `1024` | Cap the worker passes to `GetXmlCurrentAlarms2`'s `maxAlmCnt`. Must be between `64` and `65536` — the worker is a 32-bit process that materializes each reply as one BSTR (streamed into one record per alarm, not a DOM), so an unbounded cap faults the STA with an out-of-memory rather than merely slowing it. It doubles as the **truncation threshold**: a fetch returning exactly this many records is treated as truncated, because the COM API caps its reply with no "more available" flag. On a truncated poll the worker retains the alarms the capped reply could not mention instead of letting their absence read as a clear, and logs a rate-limited `AlarmSnapshotTruncated` warning to its stderr (identifiers and counts only). **Remediation when you see that warning: raise this value** so the steady-state active-alarm count fits inside one fetch. A galaxy permanently above the cap holds stale entries in the snapshot until a sub-cap poll, and loses clear→re-raise cycles that happen entirely out of window (see `docs/DesignDecisions.md`). Conveyed to the worker via the `MXGATEWAY_ALARM_MAX_ALARMS_PER_FETCH` environment variable; a missing or out-of-range value leaves the worker on the 1024 default. |
|
||||
| `MxGateway:Alarms:AckClientName` | `MxGateway` | MXAccess client name the alarm worker's ack writer registers with; the Historian records it as each acknowledgement's OperatorNode. 1-64 printable characters. Conveyed via `MXGATEWAY_ALARM_ACK_CLIENT_NAME`. |
|
||||
|
||||
The alarm monitor is independent of client sessions: `AcknowledgeAlarm` and
|
||||
@@ -747,6 +791,37 @@ protected DACL whose only entry grants its own account (the account the worker
|
||||
is launched as); on the non-Windows test matrix it uses
|
||||
`PipeOptions.CurrentUserOnly`. See `WorkerPipeSecurity` and [Worker Frame Protocol](./WorkerFrameProtocol.md).
|
||||
|
||||
## Logging (Serilog file sink)
|
||||
|
||||
Logging is configured under the top-level `Serilog` section (not `MxGateway`) in `appsettings.json`. The file
|
||||
sink writes `logs/mxgateway-<date>.log` and is bounded so a long-running gateway cannot fill its disk:
|
||||
|
||||
| Key (`Serilog:WriteTo:1:Args:`) | Shipped value | Meaning |
|
||||
|---|---|---|
|
||||
| `rollingInterval` | `Day` | A new file per day. |
|
||||
| `retainedFileCountLimit` | `30` | Keep at most 30 files; older ones are deleted when a new file is created. |
|
||||
| `fileSizeLimitBytes` | `52428800` (50 MiB) | Per-file size cap. |
|
||||
| `rollOnFileSizeLimit` | `true` | Start a new file at the cap instead of silently dropping events for the rest of the day (the Serilog default when a size limit is set without this flag). |
|
||||
|
||||
Worst-case on-disk log footprint is therefore about `retainedFileCountLimit x fileSizeLimitBytes` (1.5 GiB).
|
||||
Raise or lower these in the deployed `appsettings.json` (or via `Serilog__WriteTo__1__Args__*` environment
|
||||
variables) to fit the host's disk budget.
|
||||
|
||||
## Runtime Settings (runtimeconfig)
|
||||
|
||||
Some settings belong to the .NET runtime rather than to `MxGateway:*` options. They ship in the
|
||||
build through `RuntimeHostConfigurationOption` items in the Server csproj, which write them into
|
||||
`ZB.MOM.WW.MxGateway.Server.runtimeconfig.json`. They therefore travel with every deploy and need
|
||||
no NSSM environment variables.
|
||||
|
||||
| Setting | Shipped value | Why |
|
||||
|---|---|---|
|
||||
| `System.Threading.ThreadPool.UnfairSemaphoreSpinLimit` | `10` (runtime default `70`) | A pool worker that finds no work spins before parking, and past step 10 it calls `Sleep(0)` on every other step. The event relay queues several pool work items per event, so on a busy host those spins became ~93% of the gateway's context switches (WPR trace on a 4-CPU production host, ~240 events/s). With `10`, idle workers spin briefly and then park. Measured on the dev box at ~240 events/s: gateway CPU −15%. |
|
||||
|
||||
To override a setting on one host without rebuilding, use the environment-variable form, which
|
||||
takes precedence over runtimeconfig: `DOTNET_ThreadPool_UnfairSemaphoreSpinLimit=<n>`. `0`
|
||||
disables the spin entirely.
|
||||
|
||||
## Related Documentation
|
||||
|
||||
- [Gateway Process Detailed Design](./GatewayProcessDesign.md)
|
||||
|
||||
@@ -482,7 +482,9 @@ Shows:
|
||||
- a session section: state badge, backend, client identity, client session name,
|
||||
client correlation id (all redacted), open time, last activity, lease expiry,
|
||||
events received, and last fault;
|
||||
- a worker section: process id, worker state, and last heartbeat time;
|
||||
- a worker section: process id, worker state, last heartbeat time, and the
|
||||
worker's `MXSTATUS_PROXY` record-info pin outcome from `WorkerReady` (`-` for an
|
||||
older worker that does not report it);
|
||||
- a "Recent events" table — the newest 50 events from the in-process mirror, with
|
||||
worker sequence, family, server handle, item handle, and status (no values), plus
|
||||
a live/offline pill; gated by the session ACL, so a caller who may not observe the
|
||||
|
||||
@@ -507,6 +507,15 @@ and nonce, waits for `WorkerReady`, and only then exposes `Ready` state. The
|
||||
read loop starts after readiness so the handshake has a single owner for its
|
||||
ordered frames.
|
||||
|
||||
`WorkerReady.record_info_pin_status` carries the worker's `MXSTATUS_PROXY`
|
||||
record-info pin outcome (see `MxAccessWorkerInstanceDesign.md`). The gateway does
|
||||
not capture worker stderr, so `WorkerClient` is where operators see it: a status
|
||||
starting `pinned ` is logged at Information, anything else at Warning, because an
|
||||
unpinned worker pays a type-library reload on every data change. It is kept as
|
||||
`IWorkerClient.RecordInfoPinStatus` and shown on the dashboard's session details
|
||||
page. It never gates readiness, and an empty status (an older worker) is neither
|
||||
logged nor shown.
|
||||
|
||||
### Read loop
|
||||
|
||||
The read loop:
|
||||
@@ -804,9 +813,12 @@ ZB.MOM.WW.MxGateway.Server apikey revoke-key --key-id operator01
|
||||
ZB.MOM.WW.MxGateway.Server apikey rotate-key --key-id operator01 --json
|
||||
```
|
||||
|
||||
The subcommands accept `--sqlite-path`, `--pepper`, and `--json`. `--pepper`
|
||||
sets the local `MxGateway:ApiKeyPepper` configuration value for the command
|
||||
process; deployments should normally provide the pepper through the configured
|
||||
The subcommands accept `--sqlite-path`, `--pepper`, `--pepper-stdin`, and `--json`.
|
||||
`--pepper-stdin` reads the first line of standard input and `--pepper <value>` takes it
|
||||
from the command line; either sets the local `MxGateway:ApiKeyPepper` configuration value
|
||||
for the command process (they are mutually exclusive). `--pepper` leaves the pepper in shell
|
||||
history and the process list, so the command prints a warning to stderr — prefer
|
||||
`--pepper-stdin`, the `MxGateway__ApiKeyPepper` environment variable, or the configured
|
||||
secret source. `create-key` and `rotate-key` print the full raw API key exactly
|
||||
once. `list-keys` never prints raw secrets or `secret_hash` values.
|
||||
|
||||
@@ -940,11 +952,9 @@ Suggested configuration shape:
|
||||
"WorkingDirectory": null,
|
||||
"RequiredArchitecture": "X86",
|
||||
"StartupTimeoutSeconds": 30,
|
||||
"StartupProbeRetryAttempts": 3,
|
||||
"StartupProbeRetryDelayMilliseconds": 250,
|
||||
"PipeConnectAttemptTimeoutMilliseconds": 2000,
|
||||
"ShutdownTimeoutSeconds": 10,
|
||||
"HeartbeatIntervalSeconds": 5,
|
||||
"HeartbeatCheckIntervalSeconds": 5,
|
||||
"HeartbeatGraceSeconds": 15,
|
||||
"MaxMessageBytes": 16777216
|
||||
},
|
||||
|
||||
@@ -51,7 +51,7 @@ shutdown request even when a command or event assertion fails. Cleanup failures
|
||||
in that `finally` block are logged rather than thrown, so a real assertion
|
||||
failure is never masked by a shutdown timeout.
|
||||
|
||||
`WorkerLiveMxAccessSmokeTests` additionally covers seven MXAccess parity paths the
|
||||
`WorkerLiveMxAccessSmokeTests` additionally covers eight MXAccess parity paths the
|
||||
fake-worker tests cannot validate:
|
||||
|
||||
- a `Write` round-trip against an advised item, asserting both that the reply is
|
||||
@@ -72,6 +72,13 @@ fake-worker tests cannot validate:
|
||||
gateway must transition the session to `SessionState.Faulted` with a
|
||||
non-empty fault description carrying a known worker-client classification
|
||||
(pipe disconnected / worker faulted / end-of-stream / heartbeat expired),
|
||||
- a `Write2` (value + `VT_DATE` timestamp) round-trip after `AdviseSupervisory`,
|
||||
asserting the reply is `Ok` / `MxCommandKind.Write2` and a matching
|
||||
`OnWriteComplete` arrives, then restoring the original value with a plain
|
||||
`Write`. It uses a supervisory advise because MXAccess refuses a user-id-0
|
||||
write on a plainly advised item with `SecurityError`/`1008` (#212). The
|
||||
completion status is logged, not asserted, because whether the windev item
|
||||
accepts the write has not been checked since the switch,
|
||||
- the B8 new COM commands — `AuthenticateUser`, `ArchestrAUserToId`, `Suspend`,
|
||||
and `Activate` — each asserting a real MXAccess reply (not `InvalidRequest`)
|
||||
is returned against an added-but-not-advised item, and
|
||||
@@ -81,11 +88,13 @@ fake-worker tests cannot validate:
|
||||
or dropping frames; live §3.2 multi-sample conversion is noted as a residual
|
||||
when the rig does not drive sample-bearing buffered batches on demand.
|
||||
|
||||
All eight tests are gated by the same `MXGATEWAY_RUN_LIVE_MXACCESS_TESTS=1`
|
||||
opt-in variable. Opt-in does not mean unscheduled: the `nightly-windev` job runs
|
||||
this suite on windev every night at 06:00 UTC and files a Gitea issue when it goes
|
||||
red (see [Continuous Integration](#continuous-integration)), so the smoke no longer
|
||||
depends on someone remembering to set the variable.
|
||||
All nine tests are gated by the same `MXGATEWAY_RUN_LIVE_MXACCESS_TESTS=1`
|
||||
opt-in variable. Nothing runs this suite on a schedule; run it on demand on windev with
|
||||
the `live` tier — dispatch the `ci` workflow with `windev_mode: live`, or run
|
||||
`CI_SHA=<sha> scripts/ci/run-windev-ci.sh live` (see
|
||||
[Continuous Integration](#continuous-integration)). The scheduled `nightly-windev` job
|
||||
that used to do this was removed on 2026-11-15 because it failed most nights for host
|
||||
reasons rather than code changes.
|
||||
|
||||
Known coverage gap: the suite reaches all six late-added MXAccess **COM** commands
|
||||
but none of the five **control** commands (`Ping`, `GetSessionState`,
|
||||
@@ -122,6 +131,42 @@ The test output includes session id, worker process id, command status,
|
||||
HRESULT/status diagnostics, event sequence and handles, close status, and worker
|
||||
stdout/stderr lines emitted during the run.
|
||||
|
||||
## Live gateway write (Client.Tests)
|
||||
|
||||
`LiveGatewayWrite2Tests` in `clients/dotnet/ZB.MOM.WW.MxGateway.Client.Tests/` drives a
|
||||
**running gateway** over gRPC with the .NET client (no worker launched by the test), so
|
||||
it can run from any OS against a deployed box. It writes to a real Galaxy attribute,
|
||||
so it is skipped unless all of these are set:
|
||||
|
||||
| Variable | Meaning |
|
||||
|---|---|
|
||||
| `MXGATEWAY_LIVE_GATEWAY_ENDPOINT` | Gateway gRPC endpoint, e.g. `http://<host>:5120`. |
|
||||
| `MXGATEWAY_LIVE_GATEWAY_API_KEY_FILE` | File (mode 0600) holding the `mxgw_...` key. `MXGATEWAY_LIVE_GATEWAY_API_KEY` works too, but the file keeps the key out of the environment. The key needs `session:open`, `session:close`, `invoke:read`, `invoke:write`, `events:read`; a `Write tag globs` constraint scoped to the test item is enough. |
|
||||
| `MXGATEWAY_LIVE_GATEWAY_WRITE_ITEM` | A test-only, writable **Int32** attribute. No default on purpose. On the DEV box use a Z28062 receiver attribute such as `MESReceiver_025.MoveInBatchID`, never anything on Z28061. |
|
||||
| `MXGATEWAY_LIVE_GATEWAY_ASSERT_WRITE2_TIMESTAMP` | `1` also runs `Write2_SupervisoryAdvise_KeepsSentTimestamp`. On a host whose clock is not UTC it fails against a worker older than the #228 fix (the stored time is off by the host's UTC offset). |
|
||||
|
||||
Each test does Register, AddItem, **AdviseSupervisory**, reads the original value from the first
|
||||
`OnDataChange`, `Write2`s a different value with a timestamp 30 s in the past, waits for the
|
||||
`OnDataChange` and `OnWriteComplete` (asserting an `Ok` completion), then restores the original
|
||||
value with a plain `Write` (also on any failure after the original was read).
|
||||
`Write2_SupervisoryAdvise_AppliesValue` asserts the value was applied and restored.
|
||||
|
||||
```bash
|
||||
MXGATEWAY_LIVE_GATEWAY_ENDPOINT=http://wonder-app-vd03.zmr.zimmer.com:5120 \
|
||||
MXGATEWAY_LIVE_GATEWAY_API_KEY_FILE=/path/to/key.txt \
|
||||
MXGATEWAY_LIVE_GATEWAY_WRITE_ITEM=MESReceiver_025.MoveInBatchID \
|
||||
dotnet test clients/dotnet/ZB.MOM.WW.MxGateway.Client.Tests --filter FullyQualifiedName~LiveGatewayWrite2Tests
|
||||
```
|
||||
|
||||
Run on the DEV box (vd03, gateway `2b13564e`) on 2026-11-12: the value test passed, and the
|
||||
timestamp test failed with exactly the #228 shift (sent `01:36:51Z`, stored `06:36:51Z`; vd03 is UTC-5).
|
||||
The worker fix for #228 converts the time argument to box-local time; rerun the timestamp test
|
||||
with `MXGATEWAY_LIVE_GATEWAY_ASSERT_WRITE2_TIMESTAMP=1` after that worker is deployed to the box.
|
||||
|
||||
The windev smoke `WorkerLiveMxAccessSmokeTests.GatewaySession_WithLiveWorker_Write2ValueWithTimestampToAdvisedItem`
|
||||
also sends a whole-second timestamp 30 s in the past and, when the completion is `Ok`, asserts the
|
||||
stored source timestamp equals it. It logs the box's zone, because on a UTC box the check cannot fail.
|
||||
|
||||
## Dev-rig Probes
|
||||
|
||||
`src/ZB.MOM.WW.MxGateway.Worker.Tests/Probes/` partitions runtime probes from the regular
|
||||
@@ -488,8 +533,8 @@ dotnet test src/ZB.MOM.WW.MxGateway.Tests/ZB.MOM.WW.MxGateway.Tests.csproj
|
||||
## Running the Gateway Suite on windev
|
||||
|
||||
The gateway suite (`ZB.MOM.WW.MxGateway.Tests`, net10.0/x64) is not part of the CI
|
||||
Windows tier — `windows-x86` and `nightly-windev` run only the x86 Worker build and
|
||||
`Worker.Tests`. It is still run on windev by hand when a change needs Windows
|
||||
Windows tier on a push — `windows-x86` runs only the x86 Worker build and
|
||||
`Worker.Tests` unless it is dispatched by hand with `windev_mode: live`. It is still run on windev by hand when a change needs Windows
|
||||
confirmation, and that run has three Windows-specific characteristics worth knowing
|
||||
before results are interpreted.
|
||||
|
||||
@@ -639,7 +684,7 @@ runtime because the x86 Worker cannot build on Linux:
|
||||
client (IPC-24 deleted the old unconditional churn-revert step, which masked exactly that
|
||||
class). The dev Mac has a Homebrew JDK 17, so `gradle generateProto` can be run there to refresh
|
||||
the Java aggregates when a `.proto` changes.
|
||||
- **`windows-x86`** (Linux runner, per push/PR) — builds the **x86 / net48 Worker and
|
||||
- **`windows-x86`** (Linux runner, per push/PR, and on demand via `workflow_dispatch`) — builds the **x86 / net48 Worker and
|
||||
Worker.Tests**, which are Windows-only and out of scope for the Linux jobs. It runs on a
|
||||
Linux runner that always schedules and SSHes to windev (`10.100.0.48`), where
|
||||
`scripts/ci/run-windev-ci.sh` fast-forwards the isolated CI clone `C:\build\mxaccessgw-ci`
|
||||
@@ -650,13 +695,35 @@ runtime because the x86 Worker cannot build on Linux:
|
||||
the tier is down, not the change**: an unreachable windev fails the job (never skips), so
|
||||
if it goes red without a related code change, check the tier — `ssh windev`, read
|
||||
`C:\build\mxaccessgw-ci\ci.log` — before assuming a real test failure.
|
||||
- **`nightly-windev`** (Linux runner, scheduled `0 6 * * *`) — runs, in order, the x86 Worker
|
||||
build, `Worker.Tests`, a full `slnx` build (which surfaces Windows-only analyzer diagnostics
|
||||
such as `xUnit1030`), the net10 gateway suite, and the live-MXAccess smoke
|
||||
(`MXGATEWAY_RUN_LIVE_MXACCESS_TESTS=1`). The checkout and all five tiers share the windev
|
||||
host lock, and the first nonzero native exit stops the sequence and propagates to the CI job.
|
||||
Gated `if: github.event_name == 'schedule'`, so it never gates a push. On failure it opens a
|
||||
Gitea issue via the Actions token, since nobody watches the Actions page.
|
||||
- **Deep windev tier, on demand** — there is no scheduled run. The `live` mode runs, in order,
|
||||
the x86 Worker build, `Worker.Tests`, a full `slnx` build (which surfaces Windows-only analyzer
|
||||
diagnostics such as `xUnit1030`), the net10 gateway suite, and the live-MXAccess smoke
|
||||
(`MXGATEWAY_RUN_LIVE_MXACCESS_TESTS=1`). Run it when a change needs it, the same way the clients
|
||||
are packed and published on demand: dispatch the `ci` workflow from the Gitea Actions page with
|
||||
`windev_mode: live`, or run `CI_SHA=<sha> scripts/ci/run-windev-ci.sh live` from a machine with
|
||||
SSH access to windev. The checkout and all five tiers share the windev host lock, and the first
|
||||
nonzero native exit stops the sequence and propagates back. This replaced the `nightly-windev`
|
||||
cron job (removed 2026-11-15), which failed most nights for host reasons and filed a Gitea issue
|
||||
each time.
|
||||
|
||||
The windev host lock is an exclusive file handle on `C:\build\mxaccessgw-ci.ci-lock`, held by
|
||||
the SSH bootstrap for the whole run. It replaced a `New-Item -ItemType Directory` lock that two
|
||||
runs starting in the same second could both take (PowerShell checks for the directory, then
|
||||
creates it), which is how the 2026-09-22 nightly (since removed) collided with the scheduled `windows-x86` run on
|
||||
`.git/index.lock` (mxaccessgw#150). The OS drops the handle when its holder dies, so a killed run
|
||||
leaves no stale lock, and a holder may delete a leftover `index.lock` because no other CI git can
|
||||
be running. Each run also writes a `host (start)` line — and a `host (failure)` line when a tier
|
||||
fails — to `C:\build\mxaccessgw-ci\ci.log` with free commit, physical memory, disk and the
|
||||
number of `testhost` processes, so a host-resource failure can be matched to the host's state.
|
||||
|
||||
When a `live` run goes red, sort the cause before touching code: a test that fails with an
|
||||
assertion or test exception is a test or product fault; `OutOfMemoryException` from
|
||||
MSBuild/csc/protoc, `csc.exe exited with code -1073741502` (0xC0000142, a process that could not
|
||||
initialize), a remote exit code with no `ci.log` lines at all, or an SSH `kex_exchange_identification`
|
||||
reset is the host, as is `No route to host`. The 2026-07-24 to 2026-08-03 red streak was the
|
||||
second kind: windev's System log carries a `Resource-Exhaustion-Detector` event 2004 (low virtual
|
||||
memory) every few minutes from 2026-07-23 until the box hard-reset on 2026-08-03, with no single
|
||||
process holding most of the commit.
|
||||
|
||||
### Runner capacity is shared and finite
|
||||
|
||||
@@ -680,7 +747,7 @@ second runner.
|
||||
When queue depth (or the missing-cancel reality) makes waiting impractical, verify a
|
||||
specific commit out of band instead of waiting behind the queue: run
|
||||
`CI_SHA=<sha> scripts/ci/run-windev-ci.sh <build|test|live>` from a machine with SSH access
|
||||
to windev (the same script the SSH-driven `windows-x86`/`nightly-windev` jobs use — see
|
||||
to windev (the same script the SSH-driven `windows-x86` job uses — see
|
||||
`scripts/ci/README.md`), or fall back to the manual windev worktree procedure below. This is
|
||||
the same escape hatch used when the windev tier itself is down — TST-30 generalizes it from
|
||||
"tier down" to "runner contended": either way, a stuck or slow shared runner should not
|
||||
|
||||
@@ -335,7 +335,7 @@ The pipeline has four stages:
|
||||
1. The session is resolved via `sessionManager.TryGetSession`. A miss raises `SessionManagerException(SessionNotFound)` so the handler reports `StatusCode.NotFound`.
|
||||
2. The attach is owner-scoped: the caller's API key id must match the key that opened the session, or the call fails with `PermissionDenied` before anything is attached or delivered.
|
||||
3. The call registers a subscriber on the distributor. A fresh stream (`after_worker_sequence == 0`) uses `session.AttachEventSubscriber(...)`. A resume uses `session.AttachEventSubscriberWithReplay(...)`, which snapshots the replay ring for events newer than the cursor and registers the live subscriber under one lock, so the replay-to-live handoff has no gap and no duplicate. In single-subscriber mode (the default) a second attach fails with `EventSubscriberAlreadyActive`; with `Sessions:AllowMultipleEventSubscribers` enabled, an attach beyond `MaxEventSubscribersPerSession` fails with `EventSubscriberLimitReached`. Both map to `ResourceExhausted`. The lease is released in the `finally` block, so the subscriber slot is freed even when the client cancels mid-stream.
|
||||
4. The call yields events from the lease's bounded channel (capacity `Events:QueueCapacity`). On a resume it first yields a `ReplayGap` sentinel when the cursor predates the oldest retained event, then the replayed batch, then live events filtered to sequences above the last replayed one. Per-session ordering is preserved end-to-end, because the pump is the single writer to each subscriber channel and writes in `WorkerSequence` order.
|
||||
4. The call yields events from the lease's bounded channel (capacity `Events:QueueCapacity`). When the request set `emit_stream_attached` it first yields the StreamAttached sentinel — after step 3, so the client's receipt of it proves the subscriber is registered (see [Sessions](./Sessions.md#attach-acknowledgement)). On a resume it then yields a `ReplayGap` sentinel when the cursor predates the oldest retained event, then the replayed batch, then live events filtered to sequences above the last replayed one. Per-session ordering is preserved end-to-end, because the pump is the single writer to each subscriber channel and writes in `WorkerSequence` order.
|
||||
|
||||
The replay ring is server-side state that outlives a single RPC: with the default `DetachGraceSeconds` and `ReplayRetentionSeconds`, a client that drops can reconnect with its last `worker_sequence` and receive what it missed, as long as the events are still retained.
|
||||
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
# Live MXAccess captures, 2026-11-13 (mxaccessgw#210, #211; lmxopcua#872)
|
||||
|
||||
Captured on windev (`DESKTOP-6JL3KKO`, TEST Galaxy `DEV`, Galaxy Repository DB `ZB`)
|
||||
between 04:10 and 04:35 UTC on 2026-11-13 (the box clock runs about 9 minutes behind
|
||||
UTC, so worker timestamps in raw logs read about 04:01 to 04:26).
|
||||
|
||||
Two capture paths were used:
|
||||
|
||||
- **Through the running gateway.** A throwaway .NET client (built on
|
||||
`ZB.MOM.WW.MxGateway.Client`) talked to the `MxAccessGw` service on
|
||||
`http://10.100.0.48:5120` (build `447070a5`) with a temporary API key, revoked
|
||||
afterwards. It opened sessions, added/advised items, ran commands and recorded every
|
||||
`StreamEvents` event and every command reply as JSON.
|
||||
- **Worker.Tests live facts on windev** (direct COM, no gateway): the two facts added
|
||||
with this document, `OperationCompleteLiveProbeTests` and
|
||||
`AlarmSubtagLiveSmokeTests.LiveSubtag_SelfDrivenRaiseThenClear_SynthesizesClear`.
|
||||
|
||||
The service was never restarted or reconfigured. Writes went to `TestMachine_037`,
|
||||
`_038` and `_039`; every value a probe changed was written back afterwards.
|
||||
|
||||
## 1. `OperationComplete` trigger (§3.1, #211): captured
|
||||
|
||||
`OperationComplete` follows a `Suspend` or `Activate` whose synchronous status is
|
||||
**Pending**. That happens only for an item that is advised (plain or supervisory)
|
||||
and whose reference resolved.
|
||||
|
||||
| Call | Synchronous `MxStatus` | `OperationComplete` |
|
||||
|---|---|---|
|
||||
| `Suspend`, advised resolved item | Pending (raw 1), success -1, detail 0, RequestingLmx | yes, 110-220 ms later: one row Ok, detail 0, **RespondingLmx (raw 1)**, same server/item handles |
|
||||
| `Activate` of that suspended item | Pending (raw 1), as above | yes, as above |
|
||||
| `Suspend` again on an already-suspended item | Ok | no |
|
||||
| `Activate` on an already-active item | Ok | no |
|
||||
| `Suspend`/`Activate`, advised but unresolved reference (`InvalidReference`) | Ok | no |
|
||||
| `Suspend`/`Activate`, added but not advised | `E_INVALIDARG` (0x80070057) | no |
|
||||
| `Suspend`/`Activate`, supervisory-advised resolved item | Pending | yes |
|
||||
| Any `Write`/`WriteSecured`/`Write2`, success or failure | n/a | never (only `OnWriteComplete`) |
|
||||
|
||||
The item stops delivering `OnDataChange` between the Suspend's completion and the
|
||||
Activate; the Activate's completion arrives together with a fresh `OnDataChange`.
|
||||
|
||||
The gateway already forwards the native event untouched (no synthesis), and the
|
||||
mapping is unchanged. `OperationCompleteLiveProbeTests` pins it, including the
|
||||
unresolved-reference negative control.
|
||||
|
||||
## 2. Completion-only status bytes (§3.3, #211): resolved, nothing to map
|
||||
|
||||
Of the 71 completion events captured (63 `OnWriteComplete`, 8 `OperationComplete`),
|
||||
every one carried a typed `MXSTATUS_PROXY[]` that the converter unpacked. None set
|
||||
`raw_status`. The public COM events have no completion-only byte payload.
|
||||
`MxStatusProxyConverter.PreserveCompletionOnlyStatusBytes` has no production caller.
|
||||
Any completion-only bytes exist only in the private ASB/NMX frames described by the
|
||||
MXAccess analysis, which the worker never sees. So no `MXSTATUS_PROXY[]` mapping is
|
||||
needed, and if such bytes ever reach the worker they stay raw.
|
||||
|
||||
## 3. Status rows observed (input for lmxopcua#872)
|
||||
|
||||
Every status-row shape these probes produced. **No `Warning` category (raw 2) was
|
||||
observed anywhere, and `Pending` (raw 1) appeared only as the synchronous return of
|
||||
`Suspend`/`Activate`.** It never appeared on an `OnDataChange`, `OnWriteComplete`,
|
||||
`OperationComplete` or write-reply row. Every `Pending` had detail 0 and success -1.
|
||||
|
||||
| Category (raw) | Detail | Detected by (raw) | Produced by |
|
||||
|---|---|---|---|
|
||||
| Ok (0) | 0 | RequestingLmx (0) | every good `OnDataChange` |
|
||||
| Ok (0) | 0 | RespondingAutomationObject (5) | every successful write completion |
|
||||
| Ok (0) | 0 | RespondingLmx (1) | `OperationComplete` |
|
||||
| **Pending (1)** | **0** | RequestingLmx (0) | `Suspend`/`Activate` synchronous return (success = -1) |
|
||||
| ConfigurationError (4) | 6 `InvalidReference` | RequestingLmx (0) | advise/write of a nonexistent object or attribute; `AddBufferedItem(item, context)` form |
|
||||
| ConfigurationError (4) | 8 `InvalidObjectId` | RespondingLmx (1) | advise of an attribute on an undeployed object (`BCD_T1`, `OtOpcUaParityTest_001`) |
|
||||
| ConfigurationError (4) | 1002 `InvalidPropertyId` | RespondingAutomationObject (5) | `AddBufferedItem` on a UDA without a buffer |
|
||||
| ConfigurationError (4) | 1003 `IndexOutOfRange` | RespondingAutomationObject (5) | advise/write `TestIntArray[99]` (dim 50) |
|
||||
| ConfigurationError (4) | 8001 (AO-specific) | RespondingAutomationObject (5) | write rejected for type conversion: string to double/duration/datetime/bool, int to datetime, 1e300 to float, string[] to bool[] |
|
||||
| OperationalError (5) | 1004 `DataOutOfRange` | RespondingAutomationObject (5) | alarm `Priority` 5000 or -3, `AlarmModeCmd` 99, scalar written to an array |
|
||||
| OperationalError (5) | 1007 `NotWriteable` | RespondingAutomationObject (5) | write to `.Acked`, `ScanState`, `Tagname` |
|
||||
| SecurityError (6) | 1008 `WriteAccessDenied` | RespondingAutomationObject (5) | plain `Write` to an Operate/Secured attribute through a plain advise; `WriteSecured` of a verified-write attribute with no verifier |
|
||||
| SecurityError (6) | 8018 (AO-specific) | RespondingAutomationObject (5) | `WriteSecured` of a verified-write attribute (`ProtectedValue1`) with verifier = the writing user |
|
||||
|
||||
Writes accepted silently (Ok): NaN, +Inf, a numeric string into a double, int64
|
||||
overflow / 3.7 / true into an int, float precision loss, a 3-element array into a
|
||||
50-element int array, and 60 strings into a 50-element string array. The last two
|
||||
**resize the array**. A plain `Write` through a *supervisory* advise succeeds where
|
||||
the same write through a plain advise is refused with 1008. Off-scan objects
|
||||
(`ScanStateCmd=false`) keep accepting writes, and their UDAs stay quality 192.
|
||||
Unconnected DI items (`OI_MBTCP.PLC.40001`) report quality 32 and then 4, with an
|
||||
Ok status row.
|
||||
|
||||
Conditions tried that produced no Warning: out-of-range, type mismatch, NaN/Inf,
|
||||
array resize, off-scan object, undeployed object, unconnected I/O, read-only,
|
||||
secured/verified writes, alarm-config writes, Suspend/Activate edge cases.
|
||||
|
||||
## 4. Subtag-mode Clear (§3.7, #210): captured
|
||||
|
||||
The rig's `TestAlarm00x` UDAs are `MxSecurityOperate`. A plain `Write` is refused
|
||||
with 1008, and that refusal is why the 2026-06 runs concluded the alarms were
|
||||
object-driven. `AuthenticateUser("Administrator", "")` followed by
|
||||
`WriteSecured` drives them both ways. With the subtag pipeline
|
||||
(`LmxSubtagAlarmSource` + `SubtagAlarmConsumer`, the production classes) watching
|
||||
`TestMachine_037.TestAlarm001`:
|
||||
|
||||
```
|
||||
Driving condition = true (RAISE) ...
|
||||
raw ValueChanged: TestMachine_037.TestAlarm001.InAlarm = True
|
||||
Transition emitted: Kind=Raise PreviousState=Unspecified State=UnackAlm ... Degraded=True Guid=9b60979f-826d-2842-e00b-2bf1234a7809
|
||||
Driving condition = false (CLEAR) ...
|
||||
raw ValueChanged: TestMachine_037.TestAlarm001.InAlarm = False
|
||||
Transition emitted: Kind=Clear PreviousState=UnackAlm State=UnackRtn ... Degraded=True Guid=9b60979f-826d-2842-e00b-2bf1234a7809
|
||||
CONFIRMED: subtag Clear synthesized (UnackAlm -> UnackRtn, Guid=9b60979f-826d-2842-e00b-2bf1234a7809).
|
||||
```
|
||||
|
||||
Mutation check: with the clear write removed, the fact fails on `Assert.NotNull`
|
||||
after its 30 s wait. The finally-block restore write then produces the Clear.
|
||||
|
||||
The same raise/clear through the running gateway's alarm feed (alarmmgr mode)
|
||||
emitted `RAISE` and then `CLEAR` for `Galaxy!TestArea3.TestMachine_037.TestAlarm001`
|
||||
(type `DSC`, severity 500, `sourceProvider` ALARMMGR).
|
||||
|
||||
## 5. Multi-sample `OnBufferedDataChange` (§3.2, #210): not capturable on this Galaxy
|
||||
|
||||
`AddBufferedItem` + `SetBufferedUpdateInterval` + `Advise` all return OK, but the
|
||||
first and only `OnBufferedDataChange` carries a **ConfigurationError** status row:
|
||||
|
||||
- the `(item, context)` form (`"TestDouble"`, `"TestMachine_039"`) gives detail 6
|
||||
`InvalidReference` (RequestingLmx);
|
||||
- the full-reference form (`"TestMachine_039.TestFloat"`, context `""`) gives detail
|
||||
1002 `InvalidPropertyId` from the automation object.
|
||||
|
||||
The empty `NoData` payload recorded as a "bootstrap" in B8 is therefore a
|
||||
resolution failure, not a parity bootstrap. Buffering is a property of a field
|
||||
attribute or I/O extension with *Buffer* enabled (the `_HasBuffer` property of the
|
||||
`AnalogUtilities`/`BooleanUtilities` primitives). No deployed object in this Galaxy
|
||||
has one. Rapid writes did not change this (36 secured writes at 150 ms to `TestDouble`
|
||||
and `TestFloat`, 3 s interval).
|
||||
|
||||
**What a capture needs (IDE work, not done):** an object with an analog or discrete
|
||||
field attribute (or I/O extension) that has *Buffer* enabled, bound to a source that
|
||||
changes faster than the buffered update interval (for example an OI server item with
|
||||
a reachable device or simulator), deployed. Then `AddBufferedItem("<Object>.<Attr>", "")`
|
||||
should deliver arrays of length > 1.
|
||||
|
||||
## 6. `provider_switches{from,to,reason}` (§1.3, #210): not driven
|
||||
|
||||
A real alarmmgr to subtag failover needs the monitor worker's
|
||||
`WnWrapAlarmConsumer.PollOnce` to throw `Threshold` times in a row. The only ways
|
||||
to make that happen on this box are to kill or stop `alarmmgr.exe` (the rig's
|
||||
Galaxy-wide alarm manager, which every engine's alarm provider registers with) or to
|
||||
change the gateway's `Alarms:Fallback:Mode` and restart it. The first can disrupt the
|
||||
rig's alarm registration for everyone using it, and its recovery is unproven. The
|
||||
second was ruled out because it restarts the service. Neither was done. The probe
|
||||
needs a maintenance window. Then either:
|
||||
|
||||
1. with the service running and `/metrics` scraped, stop `alarmmgr.exe` and wait for
|
||||
`mxgateway_alarms_provider_mode` to go to subtag and a `provider_switches` sample
|
||||
with `reason` set. Restart alarmmgr (or the platform) and watch the failback
|
||||
switch; or
|
||||
2. restart the gateway with `MxGateway__Alarms__Fallback__Mode=ForceSubtag`. This
|
||||
proves only the forced-start path (`AlarmProviderReasons.ForcedSubtag`), not a
|
||||
failover `reason`.
|
||||
@@ -46,7 +46,6 @@ All counters are `Counter<long>`. Tag values come from the call sites listed und
|
||||
| `mxgateway.workers.exited` | `reason` | Clean or fault-driven worker exits. |
|
||||
| `mxgateway.heartbeats.failed` | *(none)* | Aggregate worker heartbeat misses. The exported counter carries **no** `session_id` tag — per-session attribution is unbounded cardinality (every session mints a new time series), so it is kept out of the exporter; use the dashboard snapshot or the log scope for per-session detail. |
|
||||
| `mxgateway.grpc.streams.disconnected` | `reason` | Ends of a client `StreamEvents` stream. `reason` is one of a fixed set (`EventStreamDisconnectReasons`): `SessionClosed` (the session event stream completed), `Overflow` (subscriber fell behind its bounded queue), `WorkerFault` (the worker event stream faulted), `ClientCancelled` (the client cancelled or disconnected), `Error` (unclassified), `Detached` (the consumer stopped reading without cancelling). |
|
||||
| `mxgateway.retries.attempted` | `area` | Resilience retries executed by gateway components. |
|
||||
|
||||
### Histograms
|
||||
|
||||
@@ -97,19 +96,17 @@ public sealed record GatewayMetricsSnapshot(
|
||||
long WorkerExits,
|
||||
long HeartbeatFailures,
|
||||
long StreamDisconnects,
|
||||
long RetryAttempts,
|
||||
long AlarmProviderSwitchCount,
|
||||
IReadOnlyDictionary<string, long> CommandFailuresByMethod,
|
||||
IReadOnlyDictionary<string, long> EventsByFamily,
|
||||
IReadOnlyDictionary<string, long> EventsBySession,
|
||||
IReadOnlyDictionary<string, long> RetryAttemptsByArea);
|
||||
IReadOnlyDictionary<string, long> EventsBySession);
|
||||
```
|
||||
|
||||
The scalar fields mirror the counters and gauges. The four dictionaries provide the breakdowns that counter tags would otherwise require an exporter to aggregate:
|
||||
The scalar fields mirror the counters and gauges. The three dictionaries provide the breakdowns that counter tags would otherwise require an exporter to aggregate:
|
||||
|
||||
- `CommandFailuresByMethod` keys by gRPC method name.
|
||||
- `EventsByFamily` keys by event family (the `Family` enum on a worker event).
|
||||
- `EventsBySession` keys by `sessionId`; entries are removed via `RemoveSessionEvents` when a session closes so the map does not grow without bound.
|
||||
- `RetryAttemptsByArea` keys by the resilience `area` tag, e.g. `worker_startup`.
|
||||
|
||||
`EventsReceived` is read with `Interlocked.Read(ref _eventsReceived)` because `EventReceived` increments it via `Interlocked.Increment` outside the lock to keep the event-ingestion path non-blocking. `CommandsStarted`, `CommandsSucceeded`, `CommandsFailed`, and `CommandFailuresByMethod` are read the same way: the command counters run two-to-three times per gRPC call, so they are recorded with `Interlocked` and a `ConcurrentDictionary` rather than under `_syncRoot` (PERF-02). The two queue depths are pulled from their registered sources before the lock is taken, since those delegates reach into subscriber channels and worker clients.
|
||||
|
||||
@@ -152,15 +149,13 @@ _metrics.RemoveSessionEvents(session.SessionId);
|
||||
|
||||
### Worker process launcher
|
||||
|
||||
`Workers/WorkerProcessLauncher.cs` records process-level kills and startup retries:
|
||||
`Workers/WorkerProcessLauncher.cs` records process-level kills:
|
||||
|
||||
```csharp
|
||||
_metrics.WorkerKilled(reason);
|
||||
...
|
||||
_metrics.RetryAttempted("worker_startup");
|
||||
```
|
||||
|
||||
The `worker_startup` tag is hard-coded so the `RetryAttemptsByArea` snapshot reports launcher retries distinctly from other resilience areas.
|
||||
The launcher no longer retries the startup probe (mxaccessgw#188). The `mxgateway.retries.attempted` counter that the retry pipeline fed, together with the snapshot's `RetryAttempts` / `RetryAttemptsByArea` fields, was removed in mxaccessgw#215 because nothing recorded it any more; an exporter query on that name now finds no series rather than a flat zero.
|
||||
|
||||
### Session worker client factory
|
||||
|
||||
|
||||
@@ -100,6 +100,10 @@ MXGATEWAY_WORKER_WRITE_COMPLETION_WAIT_MS=<milliseconds>
|
||||
MXGATEWAY_EVENT_QUEUE_CAPACITY=<events>
|
||||
MXGATEWAY_ALARM_POLL_INTERVAL_MS=<milliseconds>
|
||||
MXGATEWAY_ALARM_MAX_ALARMS_PER_FETCH=<alarms>
|
||||
MXGATEWAY_ALARM_ACK_CLIENT_NAME=<client name>
|
||||
MXGATEWAY_WORKER_HEARTBEAT_SEND_INTERVAL_MS=<milliseconds>
|
||||
MXGATEWAY_WORKER_HEARTBEAT_GRACE_MS=<milliseconds>
|
||||
MXGATEWAY_WORKER_HEARTBEAT_STUCK_CEILING_MS=<milliseconds>
|
||||
```
|
||||
|
||||
The nonce is protected bootstrap material. The remaining values are derived
|
||||
@@ -133,9 +137,10 @@ starts the STA, or touches MXAccess:
|
||||
| `2` | `InvalidArguments` | Required arguments are missing or unknown arguments are present. |
|
||||
| `3` | `InvalidProtocolVersion` | `--protocol-version` is not numeric or does not match the supported worker protocol. |
|
||||
| `4` | `MissingNonce` | `MXGATEWAY_WORKER_NONCE` is absent or empty. |
|
||||
| `5` | `PipeConnectionFailed` | An `IOException` or `TimeoutException` escapes the pipe client. |
|
||||
| `6` | `ProtocolViolation` | A `WorkerFrameProtocolException` escapes the pipe client. |
|
||||
| `5` | `PipeConnectionFailed` | An `IOException` or `TimeoutException` escapes the pipe client, or a frame read hits end of stream because the gateway closed the pipe (gateway death). |
|
||||
| `6` | `ProtocolViolation` | Any other `WorkerFrameProtocolException` escapes the pipe client. |
|
||||
| `7` | `UnhandledException` | An exception reaches the `AppDomain.UnhandledException` hook (see `docs/WorkerBootstrap.md`). |
|
||||
| `8` | `EventQueueOverflow` | The outbound MXAccess event queue reached capacity (see the event overflow policy below). |
|
||||
|
||||
Bootstrap logs use `WorkerConsoleLogger` key/value output. `WorkerLogRedactor`
|
||||
redacts fields whose names indicate nonce, secret, password, token,
|
||||
@@ -223,7 +228,10 @@ Shutdown:
|
||||
|
||||
1. Mark the command queue as completing.
|
||||
2. Drain or reject pending commands according to shutdown mode.
|
||||
3. Optionally issue MXAccess cleanup calls for active handles.
|
||||
3. Issue MXAccess cleanup: `Unregister` every tracked server handle first (MXAccess removes
|
||||
its items and advise subscriptions with it). Only for a server whose `Unregister` failed,
|
||||
fall back to `UnAdvise` then `RemoveItem` over its remaining handles. Each step is
|
||||
guarded (a failure is recorded, never skips the rest) and logged at Debug (R21-K10, #175).
|
||||
4. Detach event handlers.
|
||||
5. Release COM references.
|
||||
6. Uninitialize COM.
|
||||
@@ -471,6 +479,34 @@ Creation rules:
|
||||
- Never marshal the raw COM object to pipe reader/writer threads.
|
||||
- Capture COM creation HRESULT or exception details.
|
||||
|
||||
**Record-info pin.** Before the first `LMXProxyServerClass` is created,
|
||||
`MxAccessComObjectFactory.Create()` calls `MxStatusProxyRecordInfoPin.EnsurePinned()`. Once per
|
||||
process, this loads the LMXProxy type library and the `MXSTATUS_PROXY` record info, and holds
|
||||
both references until exit. The GUIDs and version come from the interop assembly's metadata:
|
||||
library `{77e896ec-b3e3-4de4-b96f-f32570164211}` v3.2 (`MXAccess32.tlb`), record
|
||||
`{A162D9E4-9019-42F3-A087-79264007E542}`.
|
||||
|
||||
The pin exists because every `OnDataChange` carries a SAFEARRAY of `MXSTATUS_PROXY` records, and
|
||||
`lmxproxy.dll` resolves that record type with `GetRecordInfoFromGuids` each time it builds one.
|
||||
With no live reference, oleaut32 re-reads the registry and reloads the type library on every
|
||||
call:
|
||||
|
||||
- about 1 ms per event on the dev box;
|
||||
- worse under WOW64 registry redirection plus an EDR registry filter, where a production WPR trace
|
||||
put it at ~70% of the STA's CPU.
|
||||
|
||||
While one `IRecordInfo` is held, the same call returns oleaut32's cached instance in under a
|
||||
microsecond. Measured at ~240 events/s on the dev box, worker CPU fell from 67% to 10% of a core
|
||||
with the pin alone.
|
||||
|
||||
The pin only warms a cache. It changes no MXAccess behaviour, and a failure is never fatal. The
|
||||
outcome is in `MxStatusProxyRecordInfoPin.Status`. During the handshake `WorkerPipeSession` logs it
|
||||
as `WorkerRecordInfoPin` and copies it into `WorkerReady.record_info_pin_status`, unless the runtime
|
||||
already filled that field. The copy is the one operators see: the worker's own log goes to stderr,
|
||||
which the gateway's launcher does not redirect. The gateway logs the reported status (Warning when
|
||||
it is not a successful pin) and shows it on the dashboard's session details page; see
|
||||
`GatewayProcessDesign.md`.
|
||||
|
||||
If COM creation fails, the worker should send a structured fault with:
|
||||
|
||||
- fault category,
|
||||
@@ -556,9 +592,29 @@ everything that arrived — the loop must therefore re-check `DrainFault()` and
|
||||
re-drain after every wait, never treat a wake as "exactly one event". The 25 ms
|
||||
`EventDrainInterval` survives as the **fallback ceiling** on an unsignalled wait,
|
||||
not as a latency floor: an event arriving at an idle worker is framed at signal
|
||||
latency instead of waiting out a tick, an idle worker parks instead of waking 40
|
||||
times a second, and the interval only bounds how long the loop may sleep if some
|
||||
future path mutates the queue without signalling.
|
||||
latency instead of waiting out a tick, and the interval only bounds how long the
|
||||
loop may sleep if some future path mutates the queue without signalling. An idle
|
||||
worker still wakes at that ceiling, but a wake on an empty queue is cheap.
|
||||
|
||||
The loop runs on a **dedicated background thread** (`mxgw-event-drain`), not on the
|
||||
CLR thread pool:
|
||||
|
||||
- It parks in the blocking `IWorkerRuntimeSession.WaitForEvents`, which uses the
|
||||
same coalesced signal and single-waiter contract as `WaitForEventsAsync`.
|
||||
- It blocks on the frame writer's batch write.
|
||||
- `RunEventDrainLoopAsync` starts the thread and returns a task that completes,
|
||||
faults or cancels exactly as the loop does, so the message loop's `Task.WhenAny`
|
||||
supervision is unchanged. Cancelling the session ends the task Canceled, which
|
||||
teardown treats as a clean stop; an exception thrown on the thread faults the task
|
||||
with that same exception, which ends `RunAsync` with it as the async loop did.
|
||||
|
||||
The reason is .NET Framework's thread pool. As an async loop, every enqueue's
|
||||
semaphore release queued a continuation to the pool, and each pool worker that ran
|
||||
one then spun in `SleepEx` before parking. A production WPR trace measured ~150
|
||||
context switches per event and ~26% of the worker's CPU in that spin. With the
|
||||
dedicated thread and the frame writer's synchronous flush, the steady-state event
|
||||
path schedules no managed pool work. The overlapped pipe write still completes on
|
||||
an I/O completion thread.
|
||||
|
||||
A single event whose envelope exceeds the negotiated frame maximum is
|
||||
**undeliverable end to end** — the pipe maximum sits only the envelope-overhead
|
||||
@@ -868,9 +924,10 @@ category `QueueOverflow`. The event drain loop's next pass observes the fault
|
||||
through `DrainFault()`, writes the fault frame — a Control-priority frame, so
|
||||
it is not stuck behind a queued event backlog — and then throws to unwind
|
||||
`RunAsync`: the worker process exits rather than continuing in a state where
|
||||
events are being silently lost. The exit currently uses the generic
|
||||
`WorkerExitCode.UnexpectedFailure` rather than a dedicated overflow code; a
|
||||
distinct exit code remains open (tracked separately). Do not drop or coalesce
|
||||
events are being silently lost. The drain loop unwinds with a
|
||||
`WorkerEventQueueFaultException` carrying the fault category, and the process
|
||||
boundary maps `QueueOverflow` to the dedicated `WorkerExitCode.EventQueueOverflow`
|
||||
(8), so an overflow is identifiable from the worker's exit code alone. Do not drop or coalesce
|
||||
events to avoid this exit — that is explicitly out of scope for v1. Production
|
||||
coalescing may be added later, but it must be explicit and tested.
|
||||
|
||||
@@ -898,8 +955,10 @@ frame maximum cannot be delivered to the client at all.
|
||||
`WorkerPipeSession` starts the heartbeat loop after the gateway validates
|
||||
`WorkerHello` and receives `WorkerReady`. Heartbeats continue until
|
||||
`WorkerShutdown`, cancellation, or a pipe/protocol failure stops the session.
|
||||
The loop uses `WorkerPipeSessionOptions.HeartbeatInterval`; the default matches
|
||||
the gateway worker heartbeat interval.
|
||||
The loop uses `WorkerPipeSessionOptions.HeartbeatInterval` (default 5 s). The
|
||||
gateway does not configure it: `MxGateway:Worker:HeartbeatCheckIntervalSeconds`
|
||||
sets only how often the gateway checks heartbeat age, and
|
||||
`MxGateway:Worker:HeartbeatGraceSeconds` how stale a heartbeat may get.
|
||||
|
||||
The worker heartbeat proves that:
|
||||
|
||||
@@ -1025,6 +1084,16 @@ Graceful shutdown sequence:
|
||||
If shutdown wedges, the gateway kills the process. The worker should be written
|
||||
so process kill does not corrupt other sessions.
|
||||
|
||||
**Residual events are discarded (v1 behavior).** The worker has no final event
|
||||
flush. The event-drain loop runs concurrently with the shutdown steps above, so
|
||||
events that it frames before the message loop exits are delivered, but the loop
|
||||
is cancelled as soon as the shutdown ack has been written and the message loop
|
||||
returns. Events still queued in the worker's event queue at that point, and any
|
||||
event raised after the ack, are discarded with the session; they are not framed
|
||||
and not sent to the gateway. A caller that needs the last events of a session
|
||||
must drain them (`DrainEvents`, or consume the event stream) before requesting
|
||||
shutdown.
|
||||
|
||||
### Ending the pipe read (net48)
|
||||
|
||||
Step 8 above cannot be done by cancellation. On .NET Framework 4.8
|
||||
@@ -1148,7 +1217,9 @@ Worker logs should include:
|
||||
- protocol version,
|
||||
- gateway handshake result,
|
||||
- MXAccess COM creation result,
|
||||
- command start/end with correlation id,
|
||||
- command start/end with correlation id (`WorkerCommandStarted` /
|
||||
`WorkerCommandCompleted`, opt-in through `MXGATEWAY_WORKER_LOG_COMMANDS`; see
|
||||
`docs/WorkerBootstrap.md`),
|
||||
- HRESULT/status summary,
|
||||
- event family and sequence,
|
||||
- queue overflow,
|
||||
|
||||
@@ -62,7 +62,7 @@ Tags gate **visibility only**: which sessions' event metadata a dashboard user m
|
||||
`CloseSessionAsync` and `KillWorkerAsync` are both end-of-life paths but differ in what they offer the worker:
|
||||
|
||||
- `CloseSessionAsync` is the graceful path: it calls `GatewaySession.CloseAsync`, which asks the worker to shut down via `IWorkerClient.ShutdownAsync` and only kills the process as a fallback if shutdown fails.
|
||||
- `KillWorkerAsync` is the forceful path used by the dashboard's admin Kill button: it calls `GatewaySession.KillWorker` directly, which kills the worker process immediately with no graceful-shutdown attempt and transitions the session to `Closed`.
|
||||
- `KillWorkerAsync` is the forceful path used by the dashboard's admin Kill button: it calls `GatewaySession.KillWorkerWithCloseGateAsync`, which takes the per-session close gate (so it serializes with a concurrent `CloseAsync`), kills the worker process immediately with no graceful-shutdown attempt, and transitions the session to `Closed`. There is no ungated kill primitive on `GatewaySession`.
|
||||
|
||||
Both paths converge on the same registry/metrics cleanup, so the open-session slot is released and `mxgateway.sessions.closed` is incremented either way.
|
||||
|
||||
@@ -282,6 +282,7 @@ The handoff is sealed by a watermark. `RegisterWithReplay` returns `LiveResumeSe
|
||||
|
||||
Emit order on a resumed stream:
|
||||
|
||||
0. **StreamAttached sentinel (only when requested).** See [Attach acknowledgement](#attach-acknowledgement) below; when asked for, it precedes everything else on any stream, fresh or resumed.
|
||||
1. **ReplayGap sentinel (only when events were evicted).** If the requested `after_worker_sequence` predates the oldest event still retained — i.e. events in the open interval were dropped by capacity or age eviction and are unrecoverable — the gateway first yields a single sentinel `MxEvent` with `replay_gap` populated (`requested_after_sequence` = the requested watermark, `oldest_available_sequence` = the resume anchor described below). The sentinel carries the session id; its `family` is `UNSPECIFIED`, its `body` oneof is unset, and no per-item fields are populated. It is an explicit, documented control signal — *not* a synthesized MXAccess event — telling the client to discard local state and re-snapshot. A client that wants to resume without another gap should set `after_worker_sequence = oldest_available_sequence - 1` on its next request.
|
||||
2. **Retained replay batch.** The still-retained events newer than the requested watermark, in ascending `worker_sequence` order.
|
||||
3. **Live events**, resuming strictly after `LiveResumeSequence`.
|
||||
@@ -290,7 +291,17 @@ When `after_worker_sequence` is inside the retained window (nothing was evicted)
|
||||
|
||||
**`oldest_available_sequence` when the ring is empty.** Age eviction (`ReplayRetentionSeconds`, default 300) and a disabled ring (`ReplayBufferCapacity = 0`) both leave nothing retained, so there is no oldest-retained sequence to report. In that case the sentinel carries the **next sequence that can possibly be delivered** — the highest sequence the distributor has observed plus one — rather than `0`. That keeps `after_worker_sequence = oldest_available_sequence - 1` the single universal resume formula: the follow-up resume lands exactly on the highest observed sequence, replays nothing, reports no gap, and receives every subsequent live event. Reporting `0` here would make an unsigned client compute `2^64 - 1` and then silently receive nothing, because the live filter drops every event at or below that watermark. Nothing is lost relative to reporting `0` — the evicted interval is unrecoverable either way, and the sentinel's job is to tell the client to re-snapshot. `0` remains the value when there is no gap, where the field is meaningless and never emitted.
|
||||
|
||||
The ReplayGap sentinel is emitted **only** on the `StreamEvents` server stream and only to the resuming subscriber — it is never fanned to other subscribers and never appears in `DrainEventsReply` (the diagnostic drain path is untouched). Replay retention itself is bounded by `MxGateway:Events:ReplayBufferCapacity` (count) and `ReplayRetentionSeconds` (age); see [Configuration](GatewayConfiguration.md).
|
||||
The ReplayGap sentinel is emitted **only** on the `StreamEvents` server stream and only to the resuming subscriber — it is never fanned to other subscribers and never appears in `DrainEventsReply` (the diagnostic drain path is untouched). Replay retention itself is bounded by `MxGateway:Events:ReplayBufferCapacity` (count), `ReplayRetentionSeconds` (age) and `ReplayBufferMaxBytes` (summed serialized size, so a burst of large-array events cannot pin memory the count cap would allow); whichever binds first evicts oldest-first. Evicted slots are cleared at once, so an evicted event is released immediately rather than when its slot is next reused. See [Configuration](GatewayConfiguration.md).
|
||||
|
||||
#### Attach acknowledgement
|
||||
|
||||
A fresh stream is not replayed, so an event the session publishes before the gateway registers the stream's subscriber never reaches that stream. A client that advises an item right after issuing `StreamEvents` can lose the item's initial value that way, and for a slow-changing attribute (`ScanState`, a setpoint) the next value may be hours away (lmxopcua#865). The client cannot see when the HTTP/2 request has been processed, so it has nothing to wait on.
|
||||
|
||||
`StreamEventsRequest.emit_stream_attached` (#227, default `false`) gives it something. When set, `EventStreamService.StreamEventsAsync` yields one sentinel `MxEvent` with `stream_attached` populated as the **first** message of the stream, and yields it only after `AttachEventSubscriber` / `AttachEventSubscriberWithReplay` has returned — that is, after the subscriber channel is registered on the distributor. Every event the pump fans from that point lands in the channel, and the client cannot receive the sentinel before the server has executed that line, so "sentinel received" implies "registered": an advise issued after it cannot lose its initial value to the attach race. An attach that is refused (owner mismatch, `EventSubscriberAlreadyActive`, limit reached, session not ready) throws before the sentinel, so a refused stream never sees it.
|
||||
|
||||
The sentinel carries the session id and `StreamAttached.live_after_sequence` — the watermark live events are filtered at (`0` on a fresh stream, `LiveResumeSequence` on a resume). Like the ReplayGap sentinel its `family` is `UNSPECIFIED`, its `body` oneof is unset, its `worker_sequence` is `0` (so clients must not store it as a resume cursor), and it is a documented control signal rather than a synthesized MXAccess event. It is sent only to the requesting subscriber and never appears in `DrainEventsReply`.
|
||||
|
||||
It is opt-in because existing consumers treat every streamed `MxEvent` as data: ScadaBridge's MxGateway adapter stores every event's `worker_sequence` as its reconnect cursor, so an unrequested sentinel would reset that cursor to `0`. A gateway that predates the field ignores it (proto3 unknown field) and never sends the sentinel; gateways that honour it list `stream-events-attached-ack` (`GatewayCapabilities.StreamEventsAttachedAck`) in `OpenSessionReply.capabilities`, so a client can check before it waits.
|
||||
|
||||
### Close
|
||||
|
||||
|
||||
@@ -115,15 +115,16 @@ public static WorkerBootstrapResult Failure(WorkerExitCode exitCode, IEnumerable
|
||||
| `InvalidArguments` | 2 | One or more `--session-id`, `--pipe-name`, or `--protocol-version` errors (missing, empty, unknown flag, or no value). |
|
||||
| `InvalidProtocolVersion` | 3 | `--protocol-version` is not a `uint` or does not equal `GatewayContractInfo.WorkerProtocolVersion`. |
|
||||
| `MissingNonce` | 4 | The `MXGATEWAY_WORKER_NONCE` environment variable is null, empty, or whitespace. |
|
||||
| `PipeConnectionFailed` | 5 | An `IOException` or `TimeoutException` escapes the pipe client. |
|
||||
| `ProtocolViolation` | 6 | A `WorkerFrameProtocolException` escapes the pipe client. |
|
||||
| `PipeConnectionFailed` | 5 | An `IOException` or `TimeoutException` escapes the pipe client, or a `WorkerFrameProtocolException` with `EndOfStream` does — the gateway closed its end of the pipe, usually because it died. |
|
||||
| `ProtocolViolation` | 6 | Any other `WorkerFrameProtocolException` escapes the pipe client. |
|
||||
| `UnhandledException` | 7 | An exception reaches `AppDomain.CurrentDomain.UnhandledException` — thrown on a thread outside `WorkerApplication.Run`'s `try/catch` (a background task continuation, a timer, a COM callback thread). |
|
||||
| `EventQueueOverflow` | 8 | The outbound MXAccess event queue reached capacity: the event drain loop wrote the `QueueOverflow` fault and unwound with a `WorkerEventQueueFaultException`. Other event-queue fault categories still exit as `UnexpectedFailure`. |
|
||||
|
||||
`InvalidArguments`, `InvalidProtocolVersion`, and `MissingNonce` originate in the parser; `UnhandledException` originates in the process-wide hook described below; the others originate in `WorkerApplication.Run`'s `try/catch` around the pipe client.
|
||||
|
||||
### Unhandled-exception hook
|
||||
|
||||
The production entry point, `WorkerApplication.Run(string[])`, subscribes `AppDomain.CurrentDomain.UnhandledException` before it parses arguments. The handler (`WorkerApplication.HandleUnhandledException`) logs one `WorkerUnhandledException` error line and calls `Environment.Exit(7)`. Without it, an exception on a thread that `Run` does not own ended the process with the CLR's crash code and no worker log line, so the gateway saw an unexplained exit. The line carries `exit_code`, `exception_type`, and `is_terminating` only: the exception message and stack are left out because they can carry tag values or credentials passed through a command, the same rule every other worker failure line follows. A failure inside the logger is swallowed so the exit always happens. The injectable `Run` overloads that tests call do not install the hook, because it is process-global.
|
||||
The production entry point, `WorkerApplication.Run(string[])`, subscribes `AppDomain.CurrentDomain.UnhandledException` before it parses arguments. The handler (`WorkerApplication.HandleUnhandledException`) logs one `WorkerUnhandledException` error line and calls `Environment.Exit(7)`. Without it, an exception on a thread that `Run` does not own ended the process with the CLR's crash code and no worker log line, so the gateway saw an unexplained exit. The line carries `exit_code`, `exception_type`, and `is_terminating` only: the exception message and stack are left out because an exception from an arbitrary thread (a COM callback, a command path) can carry tag values or credentials passed through a command. A failure inside the logger is swallowed so the exit always happens. The injectable `Run` overloads that tests call do not install the hook, because it is process-global.
|
||||
|
||||
## Environment Abstraction
|
||||
|
||||
@@ -180,6 +181,12 @@ private void Write(
|
||||
}
|
||||
```
|
||||
|
||||
### Per-command start/end lines
|
||||
|
||||
`StaCommandDispatcher` can log one `WorkerCommandStarted` and one `WorkerCommandCompleted` line per STA command. Both carry `session_id`, `correlation_id`, and `command_method`; the start line adds `queued_ms` (time since the gateway enqueued the command) and the end line adds `protocol_status`, `hresult`, and `elapsed_ms` (time on the STA). Neither carries the command payload or the reply's diagnostic message, so tag values, secured-write credentials and provider detail stay out of the log.
|
||||
|
||||
The lines are off by default because a busy session dispatches many commands and `IWorkerLogger` has no Debug level to put them behind. Setting the environment variable `MXGATEWAY_WORKER_LOG_COMMANDS` to `1` or `true` turns them on (`WorkerCommandLogging`). The gateway launcher does not set it; a worker inherits it from the gateway process environment, so setting it on the gateway service enables it for every worker that service launches.
|
||||
|
||||
### What the redactor redacts and why
|
||||
|
||||
`gateway.md` "Security" requires that the worker never log raw credential values for `AuthenticateUser`, `WriteSecured`, or related secured operations. The bootstrap nonce is also a credential: anyone who reads it can impersonate the worker to the gateway pipe. `WorkerLogRedactor` enforces this by replacing values whose field name contains any of these substrings (case-insensitive) with the literal `[redacted]`:
|
||||
@@ -219,7 +226,7 @@ if (!result.Succeeded)
|
||||
}
|
||||
```
|
||||
|
||||
On success it logs `WorkerBootstrapSucceeded` with the session fields (the `nonce` field is redacted by `WorkerLogRedactor` because of its name), hands the `WorkerOptions` to `IWorkerPipeClient.RunAsync`, and waits synchronously. The `try/catch` around the pipe call maps `WorkerFrameProtocolException` to `ProtocolViolation`, `IOException`/`TimeoutException` to `PipeConnectionFailed`, and any other exception to `UnexpectedFailure`, so every code path through `Run` returns one of the values in `WorkerExitCode`.
|
||||
On success it logs `WorkerBootstrapSucceeded` with the session fields (the `nonce` field is redacted by `WorkerLogRedactor` because of its name), hands the `WorkerOptions` to `IWorkerPipeClient.RunAsync`, and waits synchronously. The `try/catch` around the pipe call maps a `WorkerFrameProtocolException` with `EndOfStream` to `PipeConnectionFailed` (a closed pipe is a lost connection, not a malformed frame), any other `WorkerFrameProtocolException` to `ProtocolViolation`, a `WorkerEventQueueFaultException` with category `QueueOverflow` to `EventQueueOverflow`, `IOException`/`TimeoutException` to `PipeConnectionFailed`, and any other exception to `UnexpectedFailure`, so every code path through `Run` returns one of the values in `WorkerExitCode`. Each of those failure lines carries `exit_code`, `exception_type`, and `exception_message`. The message is passed through `WorkerLogRedactor.RedactMessage` first, which scrubs the value of any `name=value` or `name: value` pair whose name looks sensitive (nonce, secret, password, token, credential, API key) and any `mxgw_` API key token, flattens line breaks, and caps the text at 512 characters. Field-name redaction alone cannot see inside free text.
|
||||
|
||||
## Related Documentation
|
||||
|
||||
|
||||
@@ -119,6 +119,17 @@ default:
|
||||
|
||||
`GetVariantTypeName` maps CLR types to canonical `VT_*` strings (`VT_BOOL`, `VT_I4`, `VT_BSTR`, `VT_DATE`, and so on). Unmapped CLR types fall back to `CLR:<FullName>` so the wire format never silently invents a `VT_*` tag it cannot justify. Array element tags are wrapped as `SAFEARRAY(<element>)` by `CreateArrayVariantType`.
|
||||
|
||||
### Timestamps: the two directions differ
|
||||
|
||||
MXAccess does not use one time convention for both directions, so the worker does not either.
|
||||
|
||||
- **Read (OnDataChange source timestamps, `VT_DATE` values).** MXAccess hands the worker UTC clock fields. `ToTimestamp` treats an unspecified-kind `DateTime` as UTC and converts a local-kind one with `ToUniversalTime`. A plain `Write` on vd03 (UTC-5) reports the current UTC time as its source timestamp, which confirms this.
|
||||
- **Write time argument (`Write2`, `WriteSecured2`, `Write2Bulk`, `WriteSecured2Bulk`).** MXAccess reads the `VT_DATE` time argument as **box-local** time and converts it to UTC itself. A `VT_DATE` has no offset field, and the COM marshaler ignores `DateTime.Kind`, so passing the UTC clock fields stored the source timestamp shifted by the box's UTC offset. On vd03 a `Write2` sent at `01:33:00Z` was stored at `06:33:00Z` (#228). `ConvertToComTimestamp` therefore converts the `timestamp_value` instant with `TimeZoneInfo.ConvertTimeFromUtc` into the worker box's zone (`TimeZoneInfo.Local`, DST rules included) before the COM call. The command executor uses it for the time argument only; `ConvertToComValue` still renders a timestamp *value* as UTC, because whether a `Time`-typed attribute value write follows the same rule has not been proven.
|
||||
|
||||
UTC to local is always defined: every UTC instant has exactly one local wall-clock time, and the conversion never produces a local time that does not exist (the skipped spring-forward hour). The one loss is on the MXAccess side. In the hour that repeats when DST ends, two UTC instants an hour apart share one local wall-clock time, and the offset-less `VT_DATE` cannot say which one is meant, so MXAccess may store an instant from that hour 1 h off. Run the worker box on UTC if exact timestamps across the fall-back hour matter. On a UTC box the conversion is the identity, which is why #228 could not be seen there.
|
||||
|
||||
A time argument of another kind (a string or a number) carries no zone and is passed through unchanged; its meaning is the caller's. Consumers must send `timestamp_value` as a UTC instant, as the proto `Timestamp` already is.
|
||||
|
||||
### Why lossless preservation matters
|
||||
|
||||
The MXAccess engine returns values whose semantic type only fully resolves after consulting the engine's own attribute metadata. Clients that round-trip these values through the gateway (replay, parity fixtures, diagnostics) need the original `VT_*` tag, the engine-declared `MxDataType`, and any conversion diagnostic; otherwise edge cases such as decimal-to-double rounding, ulong overflow, or an unknown SAFEARRAY element type become invisible bugs. Storing both the typed projection and the raw fields in the same `MxValue`/`MxArray` lets cross-language clients recover the original observation byte-for-byte where possible and detect lossy cases where it is not.
|
||||
|
||||
@@ -90,6 +90,12 @@ Protocol violations throw `WorkerFrameProtocolException` with a
|
||||
`WorkerFrameProtocolErrorCode` so callers can distinguish malformed frames,
|
||||
oversized frames, protocol version mismatches, and session mismatches.
|
||||
|
||||
Fields added to a body without a protocol version bump must be ones both ends can
|
||||
ignore. `WorkerReady.record_info_pin_status` (field 5) is the current example: it is
|
||||
diagnostic only, so a newer worker talking to an older gateway is simply not
|
||||
reported, and an older worker leaves it empty, which the gateway treats as "not
|
||||
reported". Neither end gates readiness on it.
|
||||
|
||||
## Write Scheduling And Sequencing
|
||||
|
||||
This section covers write scheduling (priority classes, enqueue-then-contend,
|
||||
@@ -135,7 +141,7 @@ Two failure shapes are distinguished during a drain pass:
|
||||
|
||||
Flushes are coalesced across a *run of same-class frames* inside a drain
|
||||
pass: each frame in the run is written to the stream without an individual
|
||||
flush, then one `FlushAsync` runs — at the end of the pass, and additionally
|
||||
flush, then one flush runs — at the end of the pass, and additionally
|
||||
at every control-to-event boundary — and only then does every
|
||||
successfully-written frame of that run resolve its completion. A caller's
|
||||
`WriteAsync` therefore still does not complete until its bytes are both
|
||||
@@ -166,11 +172,18 @@ end-of-pass flush, and additionally fails the event frame the drain had
|
||||
already claimed off its queue (nothing else would ever complete it) along
|
||||
with every frame still queued.
|
||||
|
||||
The flush is a synchronous `Stream.Flush()`, not `FlushAsync`. `PipeStream` does not
|
||||
override `FlushAsync`, so on .NET Framework the base implementation runs `Flush()`
|
||||
through `Task.Factory.StartNew`. That is one thread-pool work item per drain pass for
|
||||
a `PipeStream.Flush` that does no I/O, because it never calls `FlushFileBuffers`.
|
||||
Calling `Flush()` inline keeps the same written-and-flushed contract for any stream.
|
||||
|
||||
Note the ordering all of this implies at the peer: the frames reach the pipe
|
||||
before the flush that follows them, so the gateway can read a whole batch
|
||||
while the writer has not yet flushed it. Anything observing the flush itself
|
||||
(a test counting flushes, for instance) must wait for the flush, not infer it
|
||||
from frames arriving. The event drain loop (`WorkerPipeSession.RunEventDrainLoopAsync`)
|
||||
from frames arriving. The event drain loop (`WorkerPipeSession.RunEventDrainLoopAsync`, which
|
||||
runs on a dedicated thread; see `MxAccessWorkerInstanceDesign.md`)
|
||||
submits a whole drained event batch through `WriteBatchAsync`, which enqueues
|
||||
every frame under one `_gate` acquisition, takes the write lock once, and
|
||||
drains them together, so a burst of N events costs one flush rather than N —
|
||||
|
||||
@@ -28,7 +28,7 @@ diagnostics can report the launch command without exposing the secret.
|
||||
|
||||
All launch-variable names live in the shared Contracts
|
||||
`WorkerLaunchEnvironment` class and are consumed by both the launcher and the
|
||||
worker. The launcher always exports all six values:
|
||||
worker. The launcher always exports every value below:
|
||||
|
||||
| Environment variable | Gateway source | Worker default when missing/invalid |
|
||||
|---|---|---|
|
||||
@@ -38,6 +38,10 @@ worker. The launcher always exports all six values:
|
||||
| `MXGATEWAY_EVENT_QUEUE_CAPACITY` | `MxGateway:Worker:EventQueueCapacity` | `10000` events |
|
||||
| `MXGATEWAY_ALARM_POLL_INTERVAL_MS` | `MxGateway:Alarms:PollIntervalMilliseconds` | `500` ms |
|
||||
| `MXGATEWAY_ALARM_MAX_ALARMS_PER_FETCH` | `MxGateway:Alarms:MaxAlarmsPerFetch` | `1024` alarms |
|
||||
| `MXGATEWAY_ALARM_ACK_CLIENT_NAME` | `MxGateway:Alarms:AckClientName` | `MxGateway` |
|
||||
| `MXGATEWAY_WORKER_HEARTBEAT_SEND_INTERVAL_MS` | `MxGateway:Worker:WorkerHeartbeatSendIntervalSeconds` (× 1000) | `5000` ms |
|
||||
| `MXGATEWAY_WORKER_HEARTBEAT_GRACE_MS` | `MxGateway:Worker:WorkerHeartbeatGraceSeconds` (× 1000) | `15000` ms (also kept when the ceiling is not above it) |
|
||||
| `MXGATEWAY_WORKER_HEARTBEAT_STUCK_CEILING_MS` | `MxGateway:Worker:WorkerHeartbeatStuckCeilingSeconds` (× 1000) | `75000` ms (also kept when the value is not above the worker's watchdog grace) |
|
||||
|
||||
The write-completion wait applies to the four single-item write variants:
|
||||
`Write`, `Write2`, `WriteSecured`, and `WriteSecured2`. Bulk writes report COM
|
||||
@@ -54,12 +58,12 @@ The default probe only verifies that the worker did not exit immediately. The
|
||||
worker client replaces this probe when pipe connection, hello, and
|
||||
`WorkerReady` handling are implemented.
|
||||
|
||||
Startup probing uses a bounded Polly retry policy. The gateway starts the worker
|
||||
process once, then retries only transient startup-probe failures while the
|
||||
process remains alive. The policy is configured by
|
||||
`WorkerOptions.StartupProbeRetryAttempts` and
|
||||
`WorkerOptions.StartupProbeRetryDelayMilliseconds`; the retry counter is
|
||||
recorded as `mxgateway.retries.attempted` with `area=worker_startup`.
|
||||
The startup probe runs once, bounded by `WorkerOptions.StartupTimeoutSeconds`;
|
||||
it is not retried. The default probe only checks that the process is still
|
||||
alive, which cannot change on a retry, so the former
|
||||
`StartupProbeRetryAttempts` / `StartupProbeRetryDelayMilliseconds` options were
|
||||
removed (mxaccessgw#188). Stale keys in existing configuration are ignored by
|
||||
the binder. The worker pipe connect and handshake have their own retry loop.
|
||||
|
||||
The worker uses the exported pipe-attempt value inside its own bounded Polly
|
||||
retry loop.
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
# Pending: Worker time-conversion fixes #226 + #228 (DEV first, then QA)
|
||||
|
||||
**Status: DEV deployed 2026-11-12 (`76a71bc8`, both checks passed, record `2026-11-12-vd03-76a71bc8-worker-time-fixes.md`); QA vq03 + vq04 deployed the same night (`76a71bc8`, #228 passed on both, record `2026-11-12-qa-vq03-vq04-76a71bc8.md`).** This is the deploy note for the next gateway deploy. Ship both fixes in one
|
||||
deploy: they are both in the x86 Worker, both change timestamps consumers see, and both are on `main`.
|
||||
|
||||
| Fix | Commit | Behaviour change on the box |
|
||||
|---|---|---|
|
||||
| #226 wnwrap alarm DATE+TIME are already UTC; stop adding GMTOFFSET-DSTADJUST | `892bdc1a` | Every wnwrap alarm time (`QueryActiveAlarms`, alarm events) moves **4-5 h earlier**, to correct UTC. OtOpcUa/ScadaBridge dedup keyed on raise time sees each existing alarm once with the new time. |
|
||||
| #228 `Write2`/`WriteSecured2` (+ bulk) time argument sent as box-local time | `9ef6fc84` | The stored source timestamp of a timestamped write equals the instant sent, instead of being shifted by the box's UTC offset (+5 h on a UTC-5 box in winter, +4 h in summer). No consumer calls `Write2` today (ScadaBridge and OtOpcUa have no call site). |
|
||||
|
||||
Build **Server and Worker together from one `main` SHA at or after `9ef6fc84`** (the upgrade script refuses
|
||||
staged builds from different SHAs; they share `WorkerProtocolVersion`). Procedure, traps and rollback:
|
||||
`docs/runbooks/DeployUpgradeNssmService.md` and `scripts/deploy/Upgrade-MxGatewayService.ps1`.
|
||||
|
||||
## What else rides along
|
||||
|
||||
- **DEV vd03** runs `2b13564e`. `2b13564e..9ef6fc84` adds only #226, #227 (opt-in `emit_stream_attached`,
|
||||
additive proto, Contracts/Client 0.4.0) and #228, plus docs/tests. Nothing else changes for current
|
||||
consumers.
|
||||
- **QA vq03/vq04** run `4f931e4`. A `main` build also carries the 2026-10-21 review remediation and the
|
||||
operator-authenticated alarm ack (`488649c`). The QA deploy is therefore gated by **#170**: every QA
|
||||
OtOpcUa node with a Galaxy driver must first run lmxopcua `dc0a24f2`+ and have an `AlarmAck` fallback
|
||||
account (or per-key ack identities) configured, or every Galaxy ack is refused. Close that gate first or
|
||||
in the same window.
|
||||
|
||||
## DEV (wonder-app-vd03) first
|
||||
|
||||
1. Build on windev in a scratch folder from the chosen SHA: Worker
|
||||
`dotnet build src\ZB.MOM.WW.MxGateway.Worker\ZB.MOM.WW.MxGateway.Worker.csproj -c Release -p:Platform=x86`
|
||||
and run `Worker.Tests` x86 (expect 0 failures; 783 passed / 12 skipped at `9ef6fc84`); publish the Server
|
||||
self-contained as in runbook section 4. Do not touch windev's own `MxAccessGw` service.
|
||||
2. Stage both to vd03 over SMB, run the upgrade script on the box (deploy activity, WinRM in scope):
|
||||
`Upgrade-MxGatewayService.ps1 -ServerSource <stage>\Server -WorkerSource <stage>\Worker -ExpectedSha <sha> -Label issue226-228`.
|
||||
Single box: stop, swap, start once (trap 1, `OrphanWorkerTerminator`).
|
||||
3. Runbook section 7 checks (health 200, pre-upgrade `mxgw_` key authenticates, wrong key rejected, Worker
|
||||
path proven by a read).
|
||||
4. **#228 check, from the Mac, no remote exec:** with a scoped key for `MESReceiver_025.*` (Z28062, never
|
||||
Z28061), run
|
||||
`MXGATEWAY_LIVE_GATEWAY_ASSERT_WRITE2_TIMESTAMP=1 dotnet test clients/dotnet/ZB.MOM.WW.MxGateway.Client.Tests --filter FullyQualifiedName~LiveGatewayWrite2Tests`
|
||||
with `MXGATEWAY_LIVE_GATEWAY_ENDPOINT`, `MXGATEWAY_LIVE_GATEWAY_API_KEY_FILE` and
|
||||
`MXGATEWAY_LIVE_GATEWAY_WRITE_ITEM=MESReceiver_025.MoveInBatchID` (`docs/GatewayTesting.md`, "Live gateway
|
||||
write"). Both tests must pass: `Write2_SupervisoryAdvise_KeepsSentTimestamp` failed on `2b13564e` with
|
||||
sent `01:36:51Z` / stored `06:36:51Z`. Revoke and delete the key afterwards.
|
||||
5. **#226 check:** `QueryActiveAlarms` for `Galaxy!CVDAisle_1.TableAlarms_008.RuntimeAlert` reads
|
||||
`2026-07-28T20:02:46.830Z` (was `01:02:46.830Z` on 07-29), and a fresh alarm's time equals
|
||||
`Runtime.dbo.Events.EventTimeUtc` on wonder-sql-vd03 (read over SQL, not WinRM).
|
||||
6. Write the deploy record in `docs/deploy/` and update the scadaproj index row.
|
||||
|
||||
## QA (wonder-app-vq03 / vq04) after DEV passes
|
||||
|
||||
1. Confirm the #170 prerequisites above on both QA OtOpcUa nodes.
|
||||
2. Same SHA and staged builds as DEV. The gateways are singletons per box: deploy vq03, run the section 7
|
||||
checks, then vq04 (rolling). The vq04 gateway depends on vq03 for Galaxy SQL and alarms.
|
||||
3. #228 check as DEV step 4 against each QA gateway, with a Z28062 test attribute that exists on QA (pick
|
||||
and record it; `MESReceiver_025.MoveInBatchID` is the DEV item). #226 check as DEV step 5 against the
|
||||
QA Historian.
|
||||
4. Deploy record, index row.
|
||||
|
||||
## Rollback
|
||||
|
||||
Runbook section 8: stop, confirm no Server/Worker process, rename the `Server.bak-*`/`Worker.bak-*` pair back,
|
||||
start once. Both fixes are Worker-only behaviour; no store or schema changes, so rollback restores the old
|
||||
(wrong) times and nothing else.
|
||||
|
||||
## Evidence the fix works (windev, 2026-11-12, Eastern Standard Time, UTC-5)
|
||||
|
||||
The live smoke `WorkerLiveMxAccessSmokeTests.GatewaySession_WithLiveWorker_Write2ValueWithTimestampToAdvisedItem`
|
||||
(in-process gateway, its own worker; the `MxAccessGw` service was untouched) on `TestChildObject.TestInt`:
|
||||
|
||||
| Worker | Sent | Stored | Result |
|
||||
|---|---|---|---|
|
||||
| `9ef6fc84` (fix) | `2026-11-13T01:46:31Z` | `2026-11-13T01:46:31Z` | Passed |
|
||||
| `9ef6fc84` with the conversion removed (negative control) | `2026-11-13T01:47:32Z` | `2026-11-13T06:47:32Z` | Failed by exactly +5 h |
|
||||
|
||||
Both runs got `OnWriteComplete` `Ok` and restored the original value.
|
||||
@@ -0,0 +1,101 @@
|
||||
# 2026-11-12: QA wonder-app-vq03 + vq04: `4f931e4` -> `76a71bc8` (mxaccessgw#229 QA leg, #170)
|
||||
|
||||
Server and x86 Worker on both QA gateways moved from `4f931e4` (deployed 2026-09-10) to `origin/main` `76a71bc8`,
|
||||
the build DEV vd03 has run since earlier the same evening (`2026-11-12-vd03-76a71bc8-worker-time-fixes.md`). The jump is
|
||||
170 commits. Besides #226/#228/#227 it brings the 2026-10-21 review remediation and the operator-authenticated alarm ack
|
||||
(`488649c`, #170). There is no SQLite DDL change in the range (checked with `git diff 4f931e4 76a71bc8`), so a rollback
|
||||
needs no store restore. Owner-approved; rolling, vq03 first and then vq04. **First real run of the fixed
|
||||
`scripts/deploy/Upgrade-MxGatewayService.ps1` (`4890a3d1`, #230).**
|
||||
|
||||
## Prerequisites (checked before the first stop)
|
||||
|
||||
| Check | Result |
|
||||
|---|---|
|
||||
| #170: OtOpcUa nodes that ack Galaxy alarms through this gateway | **None on QA.** An anonymous OPC UA browse of both QA OtOpcUa endpoints (`opc.tcp://10.220.158.2:4840` and `.3:4840`, OtOpcUa CLI from the Mac) shows only the `script-runner-canary` Calculation driver, with no Galaxy driver. This matches the OtOpcUa QA record (`qa-upgrade-b8b4c18f-to-fea7de0a.md`: 1 driver, the canary). The Mac SQL login cannot open `OtOpcUaConfig`, so the read-only check went over OPC UA instead of SQL. |
|
||||
| ScadaBridge QA (`b3021e7c`) MxGateway adapter vs the new ack contract | It never acknowledges. `git grep AcknowledgeAlarm` at `b3021e7c` and at `main` finds no call site, and `NativeAlarmActor` is documented read-only. It pins Client/Contracts `0.2.1`, the same pin as DEV ScadaBridge `424db155`, which has run against `76a71bc8` on vd03 since the DEV deploy (810/810 resolved, unchanged). The data connection points only at `http://10.220.158.2:5120` (vq03), with no failover endpoint. |
|
||||
| Artifacts | The **DEV-deployed package**, pulled from vd03's stage `E:\psrem-stage\mxgw-229-76a71bc8\` over SMB: `mxgw-76a71bc8.zip` sha256 `B2771EEC2B6406A7AA84D7A125176F0C0F9A97138F82808AF519A693F211A302`, the same as DEV's `BUILD-INFO.txt`. All 473 files match `MANIFEST.sha256` on the Mac and again on each box after the SMB push. `MxGateway.Server.exe` and `ZB.MOM.WW.MxGateway.Server.exe` are byte-identical (sha256 `7d7974f0...6ebedc`). `MxGateway.Worker.exe` sha256 is `844ab6ad...38f1871`, PE32 x86. Every exe carries ProductVersion `0.1.2+76a71bc8`. The bundled runtime is 10.0.14 (`mscordaccore_amd64_amd64_10.0.1426.52326`) against 10.0.5 live, so this is an upgrade and not a downgrade. |
|
||||
|
||||
## Procedure
|
||||
|
||||
Staged on each box at `E:\psrem-stage\mxgw-229-qa-76a71bc8\`:
|
||||
- the zip and its `.sha256`, plus `BUILD-INFO.txt`;
|
||||
- `Upgrade-MxGatewayService.ps1` from `4890a3d1` (sha256 `9c721bca...06efb3`);
|
||||
- `stage229qa.ps1`, which checks the zip hash, expands it to `expanded\`, verifies the manifest and reads the stamps;
|
||||
- `dry229qa.ps1` and `real229qa.ps1`, thin wrappers that pass `-NssmPath C:\ProgramData\ZB\qa-build\tools\nssm.exe -ExpectedSha 76a71bc8 -Label issue229`;
|
||||
- `rollback229qa.ps1`.
|
||||
|
||||
**Dry run on both boxes first.** The plan matched #230's checklist:
|
||||
- `ZB.MOM.WW.MxGateway.Server#<pid>` is the child of the NSSM service host. QA's NSSM `Application` is `app\ZB.MOM.WW.MxGateway.Server.exe` and the Worker is `worker\MxGateway.Worker.exe`.
|
||||
- The carry plan covers `appsettings.json` and `appsettings.Development.json`. QA has no `dashboard.pfx`.
|
||||
- The env fingerprint has 33 names. vq03 and vq04 differ only in `MxGateway__Galaxy__ConnectionString`, because vq04 points at vq03's SQL. `MxGateway__ApiKeyPepper` sha256 prefix `88188ab11b50` is the same on both boxes.
|
||||
- The stores (`data\gateway-auth.db` triplet, `data\secrets.db`) and the KEK (`C:\ProgramData\ZB\kek\mxgateway.kek`) are outside the swap.
|
||||
- Expected warnings: `ASPNETCORE_ENVIRONMENT` is not `Production` (QA runs `Staging`, unchanged), and the live-only `app\logs\` directory stays in the `.bak`. New logs go to `MxAccessGateway\logs\` anyway.
|
||||
|
||||
| | vq03 | vq04 |
|
||||
|---|---|---|
|
||||
| Script stamp (box-local EST) | `20261112-233019` | `20261112-233532` |
|
||||
| Stop | clean within the 30 s wait, no STOP_PENDING, 0 gateway/Worker processes left | same |
|
||||
| Store backup | taken with the service fully stopped (`data\*.bak-<stamp>-issue229`, hash-verified) | same |
|
||||
| Env block | 33 entries, block sha256 `4d8a12b11735` at preflight, after the stop, after the swap, before and after the start, and after the 60 s window. Never written. | same, block `e731b618765c` |
|
||||
| Downtime | **about 8 s.** Old process `Application is shutting down` at 23:30:21; new process `Now listening` on :5130/:5120 at 23:30:29. | **about 9 s.** A Mac-side 1 s `/health/ready` poll failed 8 times, from 04:35:36Z to 04:35:44Z. |
|
||||
| Script verify | `/health/ready` and `/healthz` 200. Deployed SHA `76a71bc8`. Exactly one gateway, a child of the service host. Same PID for 60 s. | same |
|
||||
| Folder ACL | new `app\`/`worker\` inherit from `E:\ApiInstall\MxAccessGateway`, which carries the `NT SERVICE\OtOpcUaScriptWorker` deny (lmxopcua#891). The script reported no SDDL difference. | same |
|
||||
| Startup log | 0 WRN/ERR. `Alarm subscribe ... watchList=641`; `Gateway alarm monitor active on \\wonder-app-vq03\Galaxy!NAM` | same |
|
||||
|
||||
`install-service.bat` was not used. No second gateway instance was started, and no admin `apikey` verb was run.
|
||||
|
||||
## Verification (from the Mac unless noted)
|
||||
|
||||
| Check | vq03 | vq04 |
|
||||
|---|---|---|
|
||||
| `/healthz`, `/health/ready` (auth-store, worker-executable, galaxy-sql), `/health/active` | 200 / 200 / 200, 2 of 2 sessions | 200 / 200 / 200, 1 of 1 sessions |
|
||||
| Existing key (`otopcua-galaxy-qa`, token file `C:\ProgramData\ZB\qa-build\token-otopcua-galaxy-qa.txt`) | `galaxy-test-connection` `{ok:true}`; `open-session` OK, with a new Worker and gateway protocol 3; `close-session` CLOSED | same |
|
||||
| Negative control: bogus key | `Missing or invalid API key.` | same |
|
||||
| **#228** (`LiveGatewayWrite2Tests`, `ASSERT_WRITE2_TIMESTAMP=1`, item **`MESReceiver_025.MoveInBatchID`**) | **Before** the deploy, on `4f931e4`: `KeepsSentTimestamp` **FAILED**, sent `04:26:07Z`, stored `09:26:07Z` (+5 h; this is the negative control). **After: 2/2 passed**, sent = stored `04:32:02.000Z` | **2/2 passed**, sent = stored `04:38:27.000Z` |
|
||||
| ScadaBridge QA site `site-a` (active vq03) | MxGateway `Connected`, 2196/2196 resolved, good 2196 / bad 0 at 04:32:35Z, about 2 min after the restart. Same as the pre-deploy report. Z28061 and Z28062 snapshots 244/244 Good. | unaffected (SB does not use vq04); 2196 Good at 04:39:35Z |
|
||||
| OtOpcUa QA ServiceLevel | vq03 240 / vq04 250 before, during and after (vq04 is Primary since the OTel round) | same |
|
||||
| Overview `:5320` | 12/12 instances Up; both MxAccessGateway cards Active/Up | same |
|
||||
|
||||
**The QA #228 item.** QA's Galaxy (`\\wonder-app-vq03\Galaxy`) uses the same object names as DEV. `MESReceiver_025` is
|
||||
contained by `Left_002`, which is contained by **`Z28062`** (gobject 6201), so it is Z28062's left-side MES receiver
|
||||
(ScadaBridge `Z28062.LeftMESReceiver.MoveInBatchID`). Its value was `0` and had been unchanged since 2026-10-27. No
|
||||
ScadaBridge script triggers on it: every script on `CvdReactor` and `LeftMESReceiver` is call-triggered. Nothing was
|
||||
written on Z28061. Each run wrote `212212` and restored `0` through a plain `Write`. There were three runs (pre-vq03,
|
||||
post-vq03, post-vq04), with 2 writes and 2 restores each. If the attribute is historized, the pre-deploy run left one
|
||||
point stamped +5 h (`09:26:07Z`) for about 30 s, the same side effect DEV had.
|
||||
|
||||
**Temporary test keys.** `qa229-write2-test` was minted on each box's dashboard (LDAP login with the box GLAuth test user).
|
||||
- Scopes: `session:open`, `session:close`, `invoke:read`, `invoke:write`, `events:read`. Read and write globs: `MESReceiver_025.*`.
|
||||
- The vq03 key was minted **before** its deploy, and the vq04 key before its deploy too, so each key also proves the store survived the swap.
|
||||
- The secret was kept only in mode-0600 scratch files and never printed.
|
||||
- Afterwards each key was revoked and then deleted. A probe with each deleted key got `Missing or invalid API key`. The scratch files were removed, and each box's key list is back to the original `scadabridge-qa` and `otopcua-galaxy-qa`.
|
||||
|
||||
**#226 (wnwrap alarm times are UTC): could not be observed on QA.** The QA gateway's alarm feed (provider
|
||||
`ALARM_PROVIDER_MODE_ALARMMGR`) returned an **empty snapshot** before and after the deploy. `QueryActiveAlarms` returned 0,
|
||||
and the Historian (`Runtime.dbo.v_AlarmEventHistory2` on wonder-sql-vq03) recorded **no alarm transition** in the capture
|
||||
windows: a stream on vq03 from 04:25Z to the restart, and a 15-minute stream after it. The post-deploy stream on vq03 ran from 04:32Z to 04:47:30Z (provider ALARMMGR since 04:30:31Z): empty snapshot, 0 transitions. The Historian has 0 alarm rows for 03:48Z–04:48Z.
|
||||
The fix is the same Worker binary as DEV, where it was checked live (`RuntimeAlert` `2026-07-28T20:02:46.830Z` = AVEVA history).
|
||||
The empty QA snapshot is not new: it was already empty on `4f931e4`. Earlier the same day the Historian still showed recent
|
||||
`UNACK_ALM` rows, for example `Z28061.HeartbeatTimeoutAlarm` at 02:04:35Z. This was not diagnosed here, since it is out of
|
||||
scope for a deploy.
|
||||
|
||||
**#170 (operator-authenticated ack).** This is now deployed on DEV and QA. No consumer on either tier acks Galaxy alarms
|
||||
through the gateway: OtOpcUa has no Galaxy driver on vd03 or QA, and ScadaBridge never acks. So the Historian
|
||||
`ACK_ALM`-with-the-real-operator check has no live caller yet. It belongs to the first Galaxy driver authored against
|
||||
these gateways (lmxopcua `dc0a24f2`+ plus an `AlarmAck` fallback account or per-key identity; see #170's comments).
|
||||
|
||||
## Backup and rollback
|
||||
|
||||
Each box has the following under `E:\ApiInstall\MxAccessGateway\`:
|
||||
- previous build (`4f931e4`): `app.bak-<stamp>-issue229` and `worker.bak-<stamp>-issue229`;
|
||||
- `_deploy-backup-<stamp>-issue229\`, ACL SYSTEM + Administrators only, inheritance off. It holds `AppEnvironmentExtra.txt`, the service `.reg` export, `env-fingerprint.txt` and a copy of the KEK;
|
||||
- store copies: `data\gateway-auth.db{,-wal,-shm}.bak-<stamp>-issue229` and `data\secrets.db.bak-<stamp>-issue229`;
|
||||
- notes: `_DEPLOY-NOTES-<stamp>.txt`, which holds names and hash prefixes only.
|
||||
|
||||
Stamps: vq03 `20261112-233019`, vq04 `20261112-233532`.
|
||||
|
||||
To roll back, run this on the box, elevated:
|
||||
`powershell -NoProfile -ExecutionPolicy Bypass -File E:\psrem-stage\mxgw-229-qa-76a71bc8\rollback229qa.ps1 -Stamp <stamp>`
|
||||
- Add `-RestoreStores` only if the stores are damaged; there is no schema change.
|
||||
- The rollback was dry-run on both boxes after the deploy. It resolves `app.bak-`/`worker.bak-<stamp>-issue229`, and the env block matches the saved pre-upgrade fingerprint.
|
||||
- Rollback brings back the old (wrong) alarm and Write2 times, and the pre-#170 ack.
|
||||
@@ -0,0 +1,82 @@
|
||||
# 2026-11-12: wonder-app-vd03 (DEV): `2b13564e` -> `76a71bc8` (Worker time fixes #226 + #228, mxaccessgw#229)
|
||||
|
||||
Server and x86 Worker deployed together from `origin/main` `76a71bc8` (`76a71bc82d7ed41bad307d866257cb46951d9d2f`).
|
||||
It ships #226 (`892bdc1a`, wnwrap alarm times are UTC), #228 (`9ef6fc84`, the `Write2` time argument is sent as
|
||||
box-local time) and #227 (additive, opt-in `emit_stream_attached`). There are no config, package or schema changes since `2b13564e`.
|
||||
Procedure: `2026-11-12-pending-worker-time-fixes-226-228.md`. QA followed the same night: `2026-11-12-qa-vq03-vq04-76a71bc8.md`.
|
||||
|
||||
## Build and package
|
||||
|
||||
| Part | Where | How |
|
||||
|---|---|---|
|
||||
| Source | Mac | `git archive 76a71bc8` (tar sha256 `9f3bdf19...de04f24`), the same tar for both parts |
|
||||
| Worker | windev, scratch `C:\build\_tmp-mxgw-229-76a71bc8` | `dotnet build ...Worker.csproj -c Release -p:Platform=x86 -p:SourceRevisionId=76a71bc8`; **Worker.Tests x86: 783 passed, 0 failed, 12 skipped**. Apphost + `.config` renamed to `MxGateway.Worker.exe(.config)`; the 19-file set is name-identical to the live one, and the `.exe.config` is byte-identical. PE x86. |
|
||||
| Server | Mac (SDK 10.0.403) | `dotnet publish ...Server.csproj -c Release -r win-x64 --self-contained true -p:SourceRevisionId=76a71bc8` (453 files) + `MxGateway.Server.exe` as a byte copy of the apphost (the NSSM `Application`) |
|
||||
|
||||
The package is `mxgw-76a71bc8.zip` (sha256 `B2771EEC...F211A302`) with `MANIFEST.sha256` covering all 473 files.
|
||||
The hash was checked at every hop (windev -> Mac -> vd03 SMB push, plus an SMB pull round trip). ProductVersion is
|
||||
`0.1.2+76a71bc8` on both exes.
|
||||
|
||||
**A windev-built Server was rejected.** The windev SDK (10.0.204) publishes with runtime pack **10.0.8**, but live
|
||||
was on **10.0.14**, so it would have downgraded the self-contained runtime. The preflight showed this as a differing
|
||||
`mscordaccore_amd64_amd64_10.0.826.*.dll`. Build the self-contained Server where the SDK carries the newest runtime (the Mac
|
||||
here, as for `2b13564e`), or update the windev SDK.
|
||||
|
||||
## Why not `Upgrade-MxGatewayService.ps1`
|
||||
|
||||
The repo script has not been run on a real box. Reading it against vd03 found two blockers:
|
||||
- Its one-gateway and process-gone guards match only the `ZB.MOM.WW.MxGateway.Server` / `.Worker` process names.
|
||||
vd03 runs `MxGateway.Server.exe` / `MxGateway.Worker.exe`, so every OrphanWorkerTerminator guard and the
|
||||
STOP_PENDING kill would pass vacuously. The staged-Worker check also requires `ZB.MOM.WW.MxGateway.Worker.exe`.
|
||||
- It carries only `appsettings*.json` forward. vd03's `Server\` also holds `dashboard.pfx`.
|
||||
|
||||
The deploy used `preflight/swap/rollback` scripts adapted from the proven `2b13564e` set
|
||||
(`E:\psrem-stage\mxgw-229-76a71bc8\{common,pre,swap,rollback}229.ps1`). They match both exe names,
|
||||
carry `appsettings.json` (hash-checked), `appsettings.Development.json` and `dashboard.pfx` forward, never write NSSM
|
||||
`Application`/`AppDirectory`/`AppEnvironmentExtra`, and keep backups in the protected stage folder. The script gaps are filed
|
||||
as #230. **Fixed in #230:** the repo script now matches both exe naming schemes and fails closed, carries `dashboard.pfx`,
|
||||
accepts the file-based master key, fingerprints the env block, refuses a runtime downgrade, and can roll back these
|
||||
`.bak.20261112T211945` sets. Use it for QA.
|
||||
|
||||
## Timeline (box-local, EST)
|
||||
|
||||
- 21:19:20 preflight PASS (read-only). Zip and manifest OK; live `0.1.2+2b13564e` Server and Worker; exactly one gateway
|
||||
process; env 7 entries; `MxGateway__ApiKeyPepper` sha256 prefix `0d01abcc1fe5`; `Server\appsettings.json` sha256
|
||||
`464ACE1B...` with no pepper; E: 179.9 GB free.
|
||||
- 21:19:48 backup: `Server\appsettings*.json`, `dashboard.pfx` and the service `.reg` copied to the backup folder.
|
||||
- 21:19:50 stop (`Stop-Service -NoWait`). Stopped in 2 s with no STOP_PENDING and 0 gateway/worker processes. `data\` (6 files) copied, hash-verified.
|
||||
- 21:19:52 rename `Server`/`Worker` -> `*.bak.20261112T211945`. New files copied: Server 454, Worker 19. `appsettings.json`
|
||||
restored (hash match), `appsettings.Development.json` and `dashboard.pfx` carried forward (hash match).
|
||||
- 21:19:59 `/health/ready` 200, 4 s after start. **Downtime (stop -> ready) about 9 s.** After 30 s: same gateway PID
|
||||
(17972), one gateway process on the box, `/health/active` 2 of 2 sessions ready, `/healthz` 200.
|
||||
|
||||
## Verification
|
||||
|
||||
| Check | Result |
|
||||
|---|---|
|
||||
| Build stamp | Server and Worker `ProductVersion 0.1.2+76a71bc8` |
|
||||
| Health (from the Mac) | `/healthz` 200, `/health/ready` 200 (auth-store, worker-executable, galaxy-sql), `/health/active` 200 (2 of 2 sessions) |
|
||||
| NSSM env block | 7 entries, names identical, block hash `3f283e9a1d57` before, mid-swap and after; pepper prefix `0d01abcc1fe5` unchanged. Never written. |
|
||||
| `Server\appsettings.json` | `464ACE1B...` before and after (the #171 no-pepper version, not the install-root master) |
|
||||
| Existing key authenticates | a key minted **before** the stop opened a session, read `MESReceiver_025.MoveInBatchID` (`0`, Good) and closed. The Worker path is proven. |
|
||||
| Wrong key | `MxGatewayAuthenticationException` (Unauthenticated) |
|
||||
| **#228** | `LiveGatewayWrite2Tests` with `MXGATEWAY_LIVE_GATEWAY_ASSERT_WRITE2_TIMESTAMP=1` on `MESReceiver_025.MoveInBatchID`: **2/2 passed**. `KeepsSentTimestamp`: sent `2026-11-13T02:20:34.000Z`, stored `02:20:34.000Z` (on `2b13564e` it was stored +5 h). The value was restored to `0` both times. |
|
||||
| **#226** | `QueryActiveAlarms`: `Galaxy!CVDAisle_1.TableAlarms_008.RuntimeAlert` last transition **`2026-07-28T20:02:46.830Z`** (before: `2026-07-29T01:02:46.830Z`), which matches AVEVA history. `...TableAlarms_008.CommunicationAlarm` moved `2026-11-10T16:44:38.420Z` -> `11:44:38.420Z` (-5 h, EST). |
|
||||
| ScadaBridge vd03 | site `site-a` report 02:21:07Z: MxGateway `Connected`, 810/810 resolved, good 398 / bad 412, identical to the pre-deploy report. `Z28061`/`Z28062` debug snapshots identical. |
|
||||
| OtOpcUa vd03 | `:9000/health/ready` and `/health/active` 200 (no Galaxy driver on vd03) |
|
||||
| Folder ACLs | New `Server\`/`Worker\` inherit from `E:\ApiInstall\MxGateway` and carry the inherited `NT SERVICE\OtOpcUaScriptWorker` deny (lmxopcua#891). The old folders also had a redundant explicit `BUILTIN\Administrators` FullControl that the parent already grants, so the SDDL differs but nothing is loosened. |
|
||||
|
||||
**Test key:** `issue229-write2-test` was minted on the vd03 dashboard. Scopes: `session:open`, `session:close`, `invoke:read`,
|
||||
`invoke:write`, `events:read`; read and write globs `MESReceiver_025.*`. The secret only lived in a mode-0600 scratch file and
|
||||
was never printed. Afterwards the key was revoked and then deleted, a probe with it got Unauthenticated, the scratch file was
|
||||
deleted, and the key list is back to the original 6.
|
||||
|
||||
## Backup and rollback
|
||||
|
||||
- Previous install: `E:\ApiInstall\MxGateway\Server.bak.20261112T211945` + `Worker.bak.20261112T211945` (`2b13564e`).
|
||||
- `E:\psrem-stage\mxgw-229-76a71bc8\backup-20261112T211945\` (stage folder ACL: SYSTEM + Administrators only, inheritance off):
|
||||
`data\` (auth and secrets store triplets, `kek.key`, `dashboard.pfx`), `Server-appsettings*.json`, `Server-dashboard.pfx`,
|
||||
`MxAccessGw-servicekey-20261112T211945.reg`.
|
||||
- Notes: `E:\ApiInstall\MxGateway\_DEPLOY-NOTES-20261112T211945-issue229.txt` (names and hash prefixes only).
|
||||
- Rollback: `powershell -NoProfile -ExecutionPolicy Bypass -File E:\psrem-stage\mxgw-229-76a71bc8\rollback229.ps1 -Stamp 20261112T211945`
|
||||
(add `-RestoreData` only if the stores are damaged). There is no store or schema change, so rollback restores the old (wrong) times and nothing else.
|
||||
@@ -0,0 +1,65 @@
|
||||
# 2026-11-12: wonder-app-vd03 (DEV): API-key pepper moved into the service environment (mxaccessgw#171)
|
||||
|
||||
Config-only change on the DEV box, no binaries touched (Server/Worker stay at `2b13564e`).
|
||||
|
||||
## Why
|
||||
|
||||
The pepper (`MxGateway:ApiKeyPepper`) lived in `E:\ApiInstall\MxGateway\Server\appsettings.json`, inside the
|
||||
directory every upgrade renames or replaces. Losing or changing the pepper invalidates every issued `mxgw_...`
|
||||
token as completely as losing `gateway-auth.db`. The QA boxes (vq03/vq04) already keep it in the NSSM
|
||||
`AppEnvironmentExtra` block; vd03 now does the same.
|
||||
|
||||
## What changed
|
||||
|
||||
| Item | Before | After |
|
||||
|---|---|---|
|
||||
| NSSM `AppEnvironmentExtra` (`MxAccessGw`) | 6 entries, no pepper | 7 entries: the same 6 unchanged + `MxGateway__ApiKeyPepper` |
|
||||
| `Server\appsettings.json` | carried `MxGateway:ApiKeyPepper` (sha256 `035E641A…`) | that one line removed, nothing else changed (sha256 `464ACE1B…`); `Authentication:PepperSecretName` still `MxGateway:ApiKeyPepper` |
|
||||
| Effective pepper | sha256 prefix `0d01abcc1fe5` | sha256 prefix `0d01abcc1fe5` (same value, compared by hash prefix only, never printed) |
|
||||
|
||||
The env value was written straight to the registry (`REG_MULTI_SZ`), not via `nssm set`, so the pepper never
|
||||
appeared on a process command line. The JSON edit removed exactly one line; the edited file was parsed and
|
||||
compared object-for-object with the original minus that property before it was written (UTF-8 BOM and CRLF kept).
|
||||
The service was stopped before the edit so the running host's `reloadOnChange` could not drop the pepper
|
||||
before the environment took effect.
|
||||
|
||||
**Not changed:** the install-root master `E:\ApiInstall\MxGateway\appsettings.json` still carries the
|
||||
pepper. It sits outside the swapped `Server\` directory, and `install-service.bat` copies it into
|
||||
`Server\` and **replaces** the NSSM env block (dropping `MxGateway__ApiKeyPepper`), so the master copy is
|
||||
what keeps a reinstall working. Old `Server.bak.*` folders also still hold it; they are rollback targets.
|
||||
|
||||
## Timeline (box-local time)
|
||||
|
||||
- 19:47:51 backup taken, service stopped (clean, 2 s, no STOP_PENDING, 0 gateway/worker processes)
|
||||
- 19:47:53 env written and read back (pepper hash prefix match, original 6 entries identical), `appsettings.json` rewritten
|
||||
- 19:47:57 `/health/ready` 200 (downtime about 6 s); 30 s later still Running on the same PID, exactly one gateway process
|
||||
|
||||
## Verification
|
||||
|
||||
- `/health/ready` 200 (auth-store, worker-executable, galaxy-sql Healthy); `/health/active` 2 of 2 sessions ready.
|
||||
- Authenticated round-trip from the Mac with an existing pre-change key (`scadabridgeshared`, `MXGATEWAY_API_KEY`
|
||||
env, .NET client CLI): `galaxy-test-connection` `{ok:true}`, `open-session` (worker spawned) + `close-session` OK.
|
||||
The same probe ran before the change. Negative control: bogus key → `MxGatewayAuthenticationException`.
|
||||
Since `appsettings.json` no longer has the pepper, a pre-existing token verifying proves the environment
|
||||
supplies the same value.
|
||||
- ScadaBridge vd03 site health after the restart: MxGateway connection `Connected`, 810/810 tags resolved,
|
||||
quality good 398 / bad 412, identical to the pre-change report (the Bad tags are pre-existing idle receivers).
|
||||
`Z28061`/`Z28062` debug snapshots identical before/after.
|
||||
- OtOpcUa vd03 `/health/ready` and `/health/active` 200 (it has no Galaxy driver on vd03, so it does not call the gateway).
|
||||
|
||||
## Backup and rollback
|
||||
|
||||
Backup folder `E:\psrem-stage\mxgw-171-20261112T1950\` (ACL: SYSTEM + Administrators only, inheritance off):
|
||||
`backup\Server-appsettings.json` (+ `Server-appsettings.Development.json`, `root-appsettings.json`),
|
||||
`backup\MxAccessGw-servicekey-20261112T1950.reg`, `backup\AppEnvironmentExtra-pre.txt`, run log `_NOTES-20261112T1950.txt`.
|
||||
On-box note: `E:\ApiInstall\MxGateway\_DEPLOY-NOTES-20261112T1950-issue171-pepper-to-env.txt`.
|
||||
|
||||
Rollback: stop `MxAccessGw`, copy `backup\Server-appsettings.json` over `Server\appsettings.json`, restore
|
||||
`AppEnvironmentExtra` from `backup\AppEnvironmentExtra-pre.txt` (or import the `.reg`), start.
|
||||
|
||||
## For the next upgrade
|
||||
|
||||
`Upgrade-MxGatewayService.ps1` already treats the env block as authoritative and copies the live
|
||||
`appsettings*.json` back byte-identical, so nothing changes in the procedure. Expect an env count of **7**
|
||||
on vd03 now. Never rewrite the block with `nssm set AppEnvironmentExtra` without re-including
|
||||
`MxGateway__ApiKeyPepper`.
|
||||
@@ -0,0 +1,60 @@
|
||||
# 2026-11-19: DEV vd03 + QA vq03/vq04 on `e74918cc`, dashboard login on NAM AD
|
||||
|
||||
Server and x86 Worker moved from `76a71bc8` to `main` `e74918cc` (dashboard styling, accessible Galaxy browse/watch,
|
||||
overview fault context, Telemetry 0.3.1; **no proto change**), then dashboard login moved to NAM AD as part of the family
|
||||
cutover (scadaproj plan `docs/plans/2026-11-15-nam-ldap-cutover.md` §0 DEV, §0Q QA). Owner approvals 2026-11-19:
|
||||
"ok, do it. winrm usage approved (for the vd03 deploy)" and "do the qa ldap plan, winrm usage approved". Family records:
|
||||
scadaproj `docs/deploy/2026-11-19-vd03-nam-ldap/` and `docs/deploy/2026-11-19-qa-nam-ldap/`. **No rollback.**
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Package | `mxgw-e74918cc.zip` sha256 `f0999b75bee196375aeb8e3e277a0e948c54a747fd5251d336461c9665d847f2` (Server publish + Worker rebuilt on windev at `e74918cc`, `-p:Platform=x86`, apphost renamed `MxGateway.Worker.exe` for the wonder naming). ProductVersion `0.1.2+e74918cc` on both. Bundled runtime 10.0.14 = live |
|
||||
| Staged | vd03 `E:\psrem-stage\mxgw-ui-e74918cc\`; QA `E:\psrem-stage\mxgw-e74918cc\` (the same zip pulled from vd03 over SMB, re-hashed on each box) |
|
||||
| Script | `scripts/deploy/Upgrade-MxGatewayService.ps1` (`4890a3d1`) **with one local patch**: `nssm start` wrapped in `try/catch`, so a benign `SERVICE_START_PENDING` reply no longer aborts and auto-rolls back; the script's own 60 s RUNNING wait decides. The repo script is not fixed yet |
|
||||
|
||||
## DEV wonder-app-vd03
|
||||
|
||||
- **13:43 and 13:46: two failed attempts.** Both aborted at `nssm start` on `Unexpected status SERVICE_START_PENDING`
|
||||
and rolled back automatically; the old build came back healthy each time (the second printed a misleading "AUTOMATIC
|
||||
ROLLBACK FAILED"). Leftovers `E:\ApiInstall\MxGateway\{Server,Worker}.failed-20261119-1343*/1346*` can be removed.
|
||||
- **13:47:38 patched run:** carried `appsettings.json`, `appsettings.Development.json`, `dashboard.pfx`; env block (9
|
||||
entries, `b697148e6cbc`) unchanged at every step; `/health/ready` and `/healthz` 200; deployed SHA `e74918cc`; 60 s
|
||||
stability window clean; 2 of 2 MXAccess sessions ready, 0 faulted (existing consumer keys work through the new Worker).
|
||||
Downtime ~10 s on the final run. Backups `Server.bak-`/`Worker.bak-20261119-134738-ui-e74918cc`, `_deploy-backup-20261119-134738-ui-e74918cc\`.
|
||||
- **15:10 NAM login.** The service runs `ASPNETCORE_ENVIRONMENT=Staging` with no overlay, so `Server\appsettings.json` is
|
||||
the file read (the root `MxGateway\appsettings.json` is a stale unused copy). Edit: NAM `MxGateway:Ldap` block (LDAPS
|
||||
`uswap-vdc-nam1…:636`, fallback `nam2:636`, `svc_igntadmin@nam.zimmer.com`, `${secret:nam-ldap-svc-password}`,
|
||||
`sAMAccountName`/`name`/`memberOf`, `BindMode=ServiceAccount`; stale `RequiredGroup` dropped), `DisableLogin=false`,
|
||||
DEV `GroupToRole` (`UG_WW_APP_ADMIN_DEV`→Administrator, `UG_WW_APP_IDE_DEV`→Viewer, `UG_WW_APP_IDE_RO_DEV`→Viewer)
|
||||
replacing the `SCADA-*` rows; restart. Gates: anonymous → `/login`; bogus refused; `dohertj2` signs in as Administrator.
|
||||
|
||||
## QA wonder-app-vq03 + vq04 (one window: the upgrade and the LDAP change share one restart)
|
||||
|
||||
On QA the LDAP settings live in the **NSSM env** (`MxGateway__Ldap__*`, GLAuth `127.0.0.1:3893`), not in the file.
|
||||
|
||||
1. Secret `nam-ldap-svc-password` seeded into `data\secrets.db` (KEK `C:\ProgramData\ZB\kek\mxgateway.kek`), read back.
|
||||
2. `env-mxgw.ps1` (33 → 38 entries): the eight GLAuth `MxGateway__Ldap__*` entries and three `…GroupToRole__SCADA-*`
|
||||
entries replaced by the NAM block as `MxGateway__Ldap__*` plus `MxGateway__Dashboard__GroupToRole__UG_WW_APP_ADMIN_QA=Administrator`,
|
||||
`…UG_WW_APP_IDE_QA=Viewer`, `…UG_WW_APP_IDE_RO_QA=Viewer`. `MxGateway__Dashboard__RequireHttpsCookie=false` kept.
|
||||
3. Base `app\appsettings.json`: the `Dashboard:GroupToRole` `GwAdmin`/`GwReader` pair removed (it would merge with the env
|
||||
map). New sha `778534b9e771…`; the upgrade script carried it into the new `app\`, so future upgrades keep it.
|
||||
4. Patched upgrade script (dry run first on vq03): vq03 stamp `20261119-155641`, vq04 `20261119-155819`. Env fingerprint
|
||||
unchanged after stop, swap, start and the 60 s window on both (vq03 `239b02d0dcd8`, vq04 `48aae910c944`);
|
||||
`/health/ready` 200; deployed SHA `e74918cc`.
|
||||
|
||||
**Gates (both boxes):** anonymous → 302 `/login`; `zz_bogus_user_ldapcut` refused; `dohertj2` → 302 `/` (Administrator).
|
||||
Worker path with pre-existing keys: ScadaBridge's MxGateway connection reconnected after its own restart and reads
|
||||
**2196/2196 Good**. No LDAP or service-bind warning in the OTel log export.
|
||||
|
||||
## Rollback
|
||||
|
||||
- Binaries: `Upgrade-MxGatewayService.ps1 -Rollback -BackupStamp <stamp>` (stamps above).
|
||||
- LDAP: vd03 — restore `E:\ApiInstall\_ldapcut-20261119T145640\MxGateway_Server_appsettings.json`; QA —
|
||||
`reg import E:\ApiInstall\_ldapcut-20261119T152947\reg-MxAccessGw.reg` (vq03) / `…T152958\…` (vq04) and restore
|
||||
`MxAccessGateway_app_appsettings.json` from the same folder. Restart.
|
||||
|
||||
## Follow-ups
|
||||
|
||||
- Fix `Start-Gateway` in `Upgrade-MxGatewayService.ps1` (the `START_PENDING` abort) in the repo.
|
||||
- Every redeploy must keep the NAM settings: QA keeps them in env (untouched by the script); vd03 keeps them in
|
||||
`Server\appsettings.json`, which the script carries forward.
|
||||
@@ -0,0 +1,110 @@
|
||||
# 2026-11-20 — PROD first install of MxAccessGateway `e74918cc` on wonder-app-vp03 / wonder-app-vp04
|
||||
|
||||
Owner-approved PROD step: "use winrm to bring up mxaccessgw on prod vp03/vp04 … hold off on mxaccessgw on the
|
||||
site servers until the platform is deployed". Plan: `scadaproj/docs/plans/2026-11-19-prod-scadabridge-mxgw-install.md`
|
||||
(§0.4 step 4, §3A.5, §5 rollback). Stage pack: `scadaproj/docs/deploy/2026-11-19-prod-stage/mxgw/`.
|
||||
Driven from the Mac with the `winrm` CLI (profiles `vp03`/`vp04`, NAM\adm_dohertj2). No firewall changes, and no
|
||||
ScadaBridge services or files were touched (another agent was installing ScadaBridge on the same boxes at the same time).
|
||||
|
||||
## Build
|
||||
|
||||
| Item | Value |
|
||||
|---|---|
|
||||
| Artifact | `E:\psrem-stage\mxgw-e74918cc\mxgw-e74918cc.zip`, sha256 `F0999B75…D847F2` (script-verified on both boxes) |
|
||||
| `ZB.MOM.WW.MxGateway.Server.exe` ProductVersion | `0.1.2+e74918cc` |
|
||||
| `MxGateway.Worker.exe` (x86) ProductVersion | `0.1.2+e74918cc` |
|
||||
| LmxProxy.dll (MXAccess gate) | `6000.0045.2657.1` (sha256 `BD75A2FDE222`) on both boxes |
|
||||
| Service | `MxAccessGw`, NSSM, `LocalSystem`, Automatic, SCM recovery restart ×3 (5 s/5 s/30 s), failureflag 1 |
|
||||
| Layout | `E:\ApiInstall\MxAccessGateway\{app,worker,data,logs}`; KEK `C:\ProgramData\ZB\kek\mxgateway.kek` (32 bytes, per box) |
|
||||
| Env | 38 entries (ports 5120 h2c gRPC / 5130 dashboard; LDAPS 636 NAM, `svc_igntadmin`, `BindMode=ServiceAccount`; `UG_WW_APP_*_PROD` role map; `RequireHttpsCookie=false`; **`Alarms__Enabled=false`**; OTLP → 127.0.0.1:4317) |
|
||||
|
||||
## Staging-script fix applied before the install (PROD-STAGE PATCH 4)
|
||||
|
||||
The first dry run on vp03 (20:32:00Z) aborted:
|
||||
|
||||
```
|
||||
Install-MxGatewayService service=MxAccessGw dry=True
|
||||
ERROR: Can't open service!
|
||||
ABORT: Install-MxGatewayService exited 1
|
||||
```
|
||||
|
||||
Cause: `Invoke-Nssm` runs `& nssm status MxAccessGw 2>&1` under `$ErrorActionPreference='Stop'`. On Windows PowerShell
|
||||
5.1 that turns nssm's stderr ("Can't open service!", the *expected* answer on a fresh box) into a terminating
|
||||
NativeCommandError, so the `-AllowFail` existence probe can never succeed on a first install. Fix: run the native call
|
||||
under `Continue` (restored in `finally`). Only the staged copy was patched
|
||||
(`scadaproj/docs/deploy/2026-11-19-prod-stage/mxgw/Install-MxGatewayService.ps1`, sha256 `FB6F0F474A26…`); it was pushed
|
||||
over SMB to both boxes, and the previous copy was kept beside it as `Install-MxGatewayService.ps1.patch3`. **The repo's
|
||||
`scripts/deploy/Install-MxGatewayService.ps1` has the same defect (line 65, under EAP=Stop) and needs the same fix before the PAR boxes are installed.**
|
||||
|
||||
## wonder-app-vp03 (central, Galaxy Repository host)
|
||||
|
||||
| Step (UTC) | Result |
|
||||
|---|---|
|
||||
| 20:32:50 dry | DONE, no ABORT (one benign WARN: dry `WorkerDir` ≠ the env's canonical worker path); `dry\` deleted afterwards |
|
||||
| 20:33:08 real | DONE; service installed STOPPED; KEK generated sha256 `567A6AFF` |
|
||||
| 20:33:29 seed | `nam-ldap-svc-password` → `E:\ApiInstall\MxAccessGateway\data\secrets.db`, `set rc=0`, `readback-match=True`, `SEED DONE failures=0` |
|
||||
| 20:33:55 start | `nssm start` OK, Running after 3 s; stdout log shows listening on 5130 + 5120 and "Application started", stderr empty |
|
||||
| health | `/health/ready` **200 Healthy**: auth-store, worker-executable, galaxy-sql all Healthy. `/healthz` 200, `/health/active` 200. `/health/live` is **404** (this build doesn't map that route; not a fault) |
|
||||
| `GET /` | loopback 200 (`AllowAnonymousLocalhost=true`); from the Mac **302 → `/login?ReturnUrl=%2F`** |
|
||||
| 20:34:53 LDAP login | one POST `/auth/login` as `dohertj2` → **302 → `/` (success branch)**; dashboard pages 200 as `dohertj2`, Admin nav (API keys, Secrets) present, `/admin/secrets` 200. No LDAP bind warnings/errors in the log. Signed out afterwards |
|
||||
| Galaxy | Galaxy Repository page **Healthy**: 901 objects, 60 areas, 544,454 attributes, 5,373 historized, 5,326 alarm attributes; last deploy 2026-10-15 15:28:20 UTC; connection `Data Source=localhost;Initial Catalog=ZB;Integrated Security=True` |
|
||||
| Worker | none running (no session yet, as expected) |
|
||||
|
||||
Top-level Galaxy areas (Browse page, for the owner's alarm-area choice): **ControlSystem, EUR, KPI, KPI_CNC, NAM**.
|
||||
The other top-level entries are platforms/engines, not areas: ArcomHMI_Platform, Monitor_OMI_001, the OI_WAR_* OI servers,
|
||||
the VEHMI0x platforms and view engines, VitaminEPress_HMI_00x, WinPlatformBER01/02 and WinPlatform_PPPHMI_Row2.
|
||||
|
||||
## wonder-app-vp04 (central)
|
||||
|
||||
| Step (UTC) | Result |
|
||||
|---|---|
|
||||
| 20:36:19 dry | DONE, no ABORT; `dry\` deleted |
|
||||
| 20:36:31 real | DONE; service installed STOPPED; KEK generated sha256 `30C69B13`; account LocalSystem |
|
||||
| 20:36:45 seed | `set rc=0`, `readback-match=True`, `SEED DONE failures=0` |
|
||||
| 20:36:55 start | Running after 3 s; listening on 5130 + 5120; stderr empty |
|
||||
| health | `/health/ready` **503 Unhealthy**. auth-store and worker-executable are Healthy; `galaxy-sql` is Unhealthy ("Galaxy Repository SQL ping timed out after 5s.") |
|
||||
| `GET /` | from the Mac 302 → `/login` |
|
||||
| 20:37:40 LDAP login | one POST as `dohertj2` → **302 → `/` (success)**; `/`, `/admin/secrets`, `/galaxy` 200. No LDAP errors in the log. Signed out |
|
||||
| Galaxy | **NOT connected**. The Galaxy page shows "Awaiting…". Log, repeated every 30 s refresh: |
|
||||
|
||||
```
|
||||
[15:37:08 WRN] Galaxy hierarchy cache refresh failed.
|
||||
Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot open database "ZB" requested by the login. The login failed.
|
||||
Login failed for user 'ZMR\WONDER-APP-VP04$'.
|
||||
Error Number:4060,State:1,Class:11
|
||||
```
|
||||
|
||||
The computer account is in the **ZMR** domain (`ZMR\WONDER-APP-VP04$`, not NAM). It reaches vp03's SQL Server but has
|
||||
no access to the `ZB` database. SQL logins were **not** changed. **Fix (a DBA or owner action):** create a login for
|
||||
`ZMR\WONDER-APP-VP04$` on WONDER-APP-VP03's SQL Server and give it read access on `ZB`, as QA did for vq04 → vq03. The
|
||||
service was left running, because the gateway retries every 30 s and picks the database up without a restart once access
|
||||
exists. Until then its readiness answers 503.
|
||||
|
||||
## Clean-up
|
||||
|
||||
- `E:\psrem-stage\_values\mxgw-vp03` and `…\mxgw-vp04` deleted (verified absent). The seed file
|
||||
`E:\psrem-stage\_values\seed\nam-ldap-mxgw.txt` was deleted by `seed-secret-prod.ps1` on both boxes (verified). The
|
||||
spare copy taken before seeding was inside the deleted values dirs.
|
||||
- vp03 `E:\psrem-stage\_values\seed\` still holds `site-psk.txt`, which belongs to the ScadaBridge install and was left untouched.
|
||||
- Login cookies and the temporary password file on the Mac were deleted right after use.
|
||||
|
||||
## Probe note
|
||||
|
||||
curl caps the Cookie header at about 8 KB and silently drops cookies over that limit. The dashboard auth cookie for
|
||||
`dohertj2` is about 13 KB in four chunks (many `memberOf` groups), so a plain `curl -b jar` follow-up looks like a failed
|
||||
login. Replaying the jar as an explicit `Cookie:` header (`-H @file`) shows the session is valid. Kestrel's 32 KB header
|
||||
limit and browsers are fine.
|
||||
|
||||
## NOT done (open)
|
||||
|
||||
- **PAR site boxes (parvp03/parvp04): held** until WinPlatform/MXAccess is deployed there from the PROD Galaxy (plan Q3).
|
||||
- **Alarms disabled** (`MxGateway__Alarms__Enabled=false`) until the owner picks an area. Then set
|
||||
`MxGateway__Alarms__SubscriptionExpression=\\WONDER-APP-VP03\Galaxy!<area>`, set `Enabled=true` and restart.
|
||||
- **No API keys minted yet**, so no consumer can open a session and no x86 Worker has started on either box.
|
||||
- vp04 Galaxy Repository access (above).
|
||||
- Repo copy of `Install-MxGatewayService.ps1` still needs PATCH 4 (and PATCHES 2–3) upstreamed.
|
||||
|
||||
## Rollback (plan §5)
|
||||
|
||||
`nssm stop MxAccessGw; nssm remove MxAccessGw confirm`, then delete `E:\ApiInstall\MxAccessGateway` and
|
||||
`C:\ProgramData\ZB\kek\mxgateway.kek` on the box. Nothing else on either box depends on it yet.
|
||||
@@ -0,0 +1,88 @@
|
||||
# 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`.
|
||||
@@ -0,0 +1,402 @@
|
||||
# Deploy / Upgrade Runbook: NSSM-wrapped Gateway Service (Server + x86 Worker)
|
||||
|
||||
> Written for mxaccessgw#207 (archreview R21-O31 / cycle-1 TST-10). Since mxaccessgw#220 the procedure
|
||||
> is also scripted (see "Scripts" below); this runbook remains the spec the scripts implement. It is assembled only from what the repo contains
|
||||
> (`docs/GatewayConfiguration.md`, `docs/Authentication.md`, `docs/Diagnostics.md`,
|
||||
> `docs/runbooks/*`, `docs/plans/2026-08-07-*`, `docs/superpowers/plans/2026-10-19-ackmsg-as-operator.md`,
|
||||
> `src/.../appsettings.json`, `scripts/ci/`) cross-checked against `scadaproj/deployment.md` §5 and §7.1.
|
||||
>
|
||||
> **Verification legend.** Statements are either backed by a cited repo file, or tagged
|
||||
> **[UNVERIFIED]** (comes from deploy notes / other repos / memory and could not be confirmed from
|
||||
> this repo). Treat every **[UNVERIFIED]** item as "confirm on the box before relying on it".
|
||||
>
|
||||
> **Scope of remote execution.** On the wonder boxes (`wonder-app-vd03` DEV, `wonder-app-vq03`/`vq04`
|
||||
> QA) remote command execution is permitted for the on-box steps of a deploy the owner has asked for,
|
||||
> and nothing else (`CLAUDE.md` "Wonder box remote access" note; the umbrella `scadaproj` index
|
||||
> carries the current rule). No ad-hoc diagnostics over remote exec: use SMB file reads, HTTP probes
|
||||
> and direct SQL. Confirm the current rule before starting; this repo's note is dated 2026-09-11 and
|
||||
> the umbrella index has since relaxed it to deploy-only **[UNVERIFIED from this repo]**.
|
||||
|
||||
## Scripts (mxaccessgw#220)
|
||||
|
||||
> **Test status (mxaccessgw#230, 2026-11-12).** The upgrade script has run in `-DryRun` against the real
|
||||
> windev install (Windows PowerShell 5.1, live service, live processes): the guards found the running
|
||||
> gateway and its Workers, and a copy with the image names removed failed closed. It has **not yet run a real
|
||||
> upgrade on any box**: the first real use (QA, #229) should start with `-DryRun` on the box, read the plan, and
|
||||
> have section 8 ready by hand. Stop/start, STOP_PENDING, carry-over, the env-block checks and both rollbacks are
|
||||
> covered by the harness in `scripts/deploy/tests/` against a fake box (temp directories really renamed and copied,
|
||||
> fake `nssm`/process table/registry/clock), in both naming schemes:
|
||||
> `pwsh -NoProfile -File scripts/deploy/tests/Test-UpgradeMxGatewayService.ps1` (assertions) and
|
||||
> `pwsh -NoProfile -File scripts/deploy/tests/Invoke-UpgradeMutations.ps1` (re-introduces each guarded defect
|
||||
> and requires the harness to fail). The harness also passes under Windows PowerShell 5.1 on windev. The windev
|
||||
> run caught two defects the Mac harness could not: an empty `Win32_Service` result read as "check unavailable",
|
||||
> and Windows PowerShell 5.1's `Get-FileHash` returning nothing under `-WhatIf`, which aborted every `-WhatIf` plan.
|
||||
> Both are fixed. `Install-MxGatewayService.ps1` is still untested on a real box.
|
||||
>
|
||||
> **Before #230 the upgrade script was not safe on the wonder boxes**: its process guards matched only
|
||||
> `ZB.MOM.WW.MxGateway.*`, but vd03/vq03/vq04 run `MxGateway.Server.exe` / `MxGateway.Worker.exe`, so the
|
||||
> one-gateway guard, the pre-start OrphanWorkerTerminator guard and the STOP_PENDING kill passed vacuously;
|
||||
> `Server\dashboard.pfx` was dropped; and preflight refused a file-based master key. Do not use a copy of the
|
||||
> script older than the #230 commit.
|
||||
|
||||
| Script | Where it runs | Does |
|
||||
|---|---|---|
|
||||
| `scripts/deploy/Upgrade-MxGatewayService.ps1` | **On the Windows box**, Windows PowerShell 5.1 | Sections 3, 5, 6, 7, 8: preflight, stop, backup, swap Server + Worker, start, verify, rollback |
|
||||
| `scripts/deploy/Install-MxGatewayService.ps1` | On a **new** box | NSSM service install: recovery/restart, stop grace, log rotation, env block |
|
||||
|
||||
Both take `-DryRun` (or `-WhatIf`): read-only probes (`nssm get/status`, process list, disk, file
|
||||
existence) still run, every mutating action is printed instead of executed.
|
||||
|
||||
**Upgrade script** (`-ServerSource`, `-WorkerSource` are the staged outputs from section 4, built from one SHA):
|
||||
|
||||
- Parameters: `-ServerSource -WorkerSource -ServiceName MxAccessGw -NssmPath -ServerDir -WorkerDir
|
||||
-ExpectedSha -Label -HealthBaseUrl http://localhost:5130 -Rollback -BackupStamp -RestoreStores
|
||||
-NoAutoRollback -TakeNewAppSettings -AllowRuntimeDowngrade -SkipFreeSpaceCheck -MinFreeGB -StopTimeoutSeconds
|
||||
-StableSeconds -ReadyTimeoutSeconds -DryRun`. `ServerDir` defaults to NSSM `AppDirectory`, `WorkerDir`
|
||||
to the parent of `MxGateway__Worker__ExecutablePath` read from the env block.
|
||||
- **Process matching (trap 1).** Gateway processes are recognised by image name **and** by path. The names
|
||||
are those of the installed exes (the leaf of NSSM `Application` and of `MxGateway__Worker__ExecutablePath`)
|
||||
plus both naming schemes in the field: `ZB.MOM.WW.MxGateway.Server`/`.Worker` (windev) and
|
||||
`MxGateway.Server`/`.Worker` (wonder boxes), so a stray gateway of the other scheme is caught too. The
|
||||
process table comes from `Win32_Process` (path + parent PID).
|
||||
- **The one-gateway guard fails closed.** With the service RUNNING it requires exactly one gateway Server, at
|
||||
the `Application` path, whose parent is the NSSM service host PID. A RUNNING service whose gateway it cannot
|
||||
find is an **abort**, not a pass (that is how the pre-#230 guard went blind). It also refuses: more than one
|
||||
gateway Server; any gateway/Worker process while the service is STOPPED; a gateway while the service is in
|
||||
another state; another service launching the same exe. It asserts no Server/Worker process exists right
|
||||
before every `nssm start`.
|
||||
- Preflight also refuses on: missing service, empty env block, a store path (or `Secrets__MasterKey__FilePath`)
|
||||
that is relative or inside the Server/Worker dir, a `*.db`/`-wal`/`-shm` inside the Server/Worker dir, a
|
||||
staged dir that does not contain the **installed** exe names (`Split-Path -Leaf` of `Application` and of the
|
||||
Worker path), a staged Worker that is not x86, staged Server/Worker from different SHAs (or not matching
|
||||
`-ExpectedSha`), too little disk, and a staged **self-contained runtime older than the live one** (compares
|
||||
`mscordaccore_amd64_amd64_<ver>.dll`; `-AllowRuntimeDowngrade` overrides; see section 4). A master key that
|
||||
is not in the env block (neither `ZB_SECRETS_MASTER_KEY` nor `Secrets__MasterKey__FilePath`, as on windev)
|
||||
is a warning, since the upgrade does not change where it comes from.
|
||||
- **Env block (trap 4): read, fingerprinted, never written.** The block is read from the service's registry
|
||||
`Parameters\AppEnvironmentExtra` (what NSSM uses; `nssm get` is the fallback). The fingerprint is the entry
|
||||
names plus a 12-hex SHA-256 prefix of each value, and the whole-block hash; values are never printed and
|
||||
sensitive values are redacted from all output and notes. It is compared after the stop, after the swap,
|
||||
before and after the start, and after the stability window; any added, removed or changed entry (or a
|
||||
reorder) aborts and triggers the automatic rollback. On vd03 the pepper lives **only** in this block (#171),
|
||||
so this check is what proves it survived.
|
||||
- Stop waits `-StopTimeoutSeconds`; on STOP_PENDING (trap 8) it kills **this install's** Server, then its
|
||||
Workers (path under the Server/Worker dir, or the installed image name when the path is unreadable; never by
|
||||
a generic name), then the service host as a last resort. It then waits for every gateway/Worker process on
|
||||
the box to be gone.
|
||||
- Backup goes to `<install root>\_deploy-backup-<stamp>[-label]\`, restricted to SYSTEM + Administrators
|
||||
(inheritance off) **before** anything is written; if `icacls` fails nothing is written. It holds
|
||||
`AppEnvironmentExtra.txt` (the raw block: secrets), the service registry key export, `env-fingerprint.txt`
|
||||
(names + hash prefixes only) and a copy of a file-based master key. The stores are only **copied** (`.db`,
|
||||
`-wal`, `-shm` -> `*.bak-<stamp>`, hash-checked), never moved or deleted.
|
||||
- Swap is **rename-in-place** (`Server` -> `Server.bak-<stamp>[-label]`, same for `Worker`), so NSSM
|
||||
`Application`/`AppDirectory`/`ExecutablePath` never change. **Carried forward** from the live dir
|
||||
(hash-verified, explicit ACLs copied): `appsettings*.json` (unless `-TakeNewAppSettings`) and certificates/keys
|
||||
(`*.pfx`, `*.p12`, `*.pem`, `*.key`, `*.crt`, `*.cer`, e.g. vd03's `Server\dashboard.pfx`) always as the live
|
||||
copy, plus every other live-only top-level file that is not a binary. Live-only binaries
|
||||
(`.dll`/`.exe`/`.pdb`) are leftovers of the old build and stay in the `.bak`; live-only sub-directories are
|
||||
listed as a warning. `data\` (the wonder store dir) sits beside `Server\`, outside the swap, and is not touched.
|
||||
Preflight prints the carry plan.
|
||||
- Verify: `/health/ready` = 200, `/healthz` = 200, `ProductVersion` SHA of the deployed Server exe against
|
||||
`-ExpectedSha` (still subject to the version-stamp caveat in trap 7), exactly one gateway at the
|
||||
`Application` path that is the service host's child, the same PID and SERVICE_RUNNING through
|
||||
`-StableSeconds`, env fingerprint unchanged. Health with zero sessions does not prove the Worker path: do the
|
||||
section 7.3 API-key session read yourself.
|
||||
- A failed start or verify triggers an automatic rollback to the just-made backups (disable with
|
||||
`-NoAutoRollback`); a failed backup restarts the unchanged build. Manual rollback:
|
||||
`-Rollback [-BackupStamp <stamp>] [-RestoreStores]`. It accepts both backup spellings, `Server.bak-<stamp>`
|
||||
(this script) and `Server.bak.<yyyyMMddTHHmmss>` (the adapted scripts used for #229 on vd03), and refuses
|
||||
a Server backup without a Worker backup of the same stamp. It compares the env block to the saved
|
||||
`env-fingerprint.txt` (section 8 step 4). The failed directories are kept as `*.failed-<stamp>`.
|
||||
`-RestoreStores` restores the db triplet from the matching `*.bak-<stamp>` (stale wal/shm are moved aside,
|
||||
nothing is deleted); use it only after a schema bump.
|
||||
|
||||
**Install script**: `-ServerDir -WorkerDir [-ServiceName -NssmPath -DataDir C:\ProgramData\MxGateway
|
||||
-LogDir -EnvFile -Env -ObjectName -ServiceAccountPassword -EnvironmentName -RestartDelayMs -ThrottleMs
|
||||
-StopGraceMs -RotateBytes -Start -DryRun]`. It refuses if the service exists or any gateway process is
|
||||
running, requires the KEK and a `*Pepper*` env entry, requires store paths absolute and outside the content
|
||||
root, and sets the env block in **one** `nssm set AppEnvironmentExtra` on a service that has none. Defaults
|
||||
it applies: auto start, `AppExit Default Restart`, restart delay 5 s, throttle 10 s, console stop grace 20 s
|
||||
(covers `Worker:ShutdownTimeoutSeconds` = 10), stdout/stderr to `<DataDir>\logs` with rotation,
|
||||
`sc failure ... restart/5000/restart/5000/restart/30000`, reset 1 day. Secret values are masked in output.
|
||||
The service is left stopped unless `-Start` is given.
|
||||
|
||||
**Driving from the Mac (winrm skill, deployment-only).** Remote execution on the wonder boxes is allowed
|
||||
only for the on-box steps of a deploy the owner asked for. The intended flow, none of which was run for #220:
|
||||
|
||||
1. Build both artifacts on windev from one SHA (section 4); `smb push` them to a staging dir on the box
|
||||
(UNC/SMB copies are always allowed), together with the two scripts.
|
||||
2. `winrm exec` the script with `-DryRun` first, read the printed plan, then run it for real:
|
||||
`powershell -NoProfile -ExecutionPolicy Bypass -File <stage>\Upgrade-MxGatewayService.ps1 -ServerSource <stage>\Server -WorkerSource <stage>\Worker -ExpectedSha <sha> -Label <label>`.
|
||||
One box at a time; the exit code is 0 on success, 1 on any abort or failed run.
|
||||
3. Do the section 7.3 Worker-path check from the Mac over gRPC (no remote exec needed), then write the deploy note.
|
||||
|
||||
## 0. What is being deployed
|
||||
|
||||
Two artifacts, deployed together because they share a wire protocol (`WorkerProtocolVersion`,
|
||||
`appsettings.json` `MxGateway:Protocol`):
|
||||
|
||||
| Artifact | Build | Runs as |
|
||||
|---|---|---|
|
||||
| **Server** (x64 .NET 10, gRPC `:5120` h2c + Blazor dashboard `:5130`) | `dotnet publish src/ZB.MOM.WW.MxGateway.Server -c Release` (framework-dependent in the windev flow; self-contained is the alternative if the box lacks a .NET 10 runtime **[UNVERIFIED]**) | The NSSM service `MxAccessGw` |
|
||||
| **Worker** (x86 .NET Framework 4.8, one process per gateway session, owns the MXAccess COM STA) | `dotnet build src/ZB.MOM.WW.MxGateway.Worker/ZB.MOM.WW.MxGateway.Worker.csproj -p:Platform=x86` (`CLAUDE.md`) - **Windows only; builds on windev**, not on macOS/Linux (`scripts/ci/README.md`) | Child of the Server, launched from `MxGateway:Worker:ExecutablePath`. **Not a service of its own.** |
|
||||
|
||||
The Server finds the Worker through `MxGateway:Worker:ExecutablePath`
|
||||
(`docs/GatewayConfiguration.md`, default is a repo-relative `bin\x86\Release` path, so deployed hosts
|
||||
override it via the NSSM env var `MxGateway__Worker__ExecutablePath`).
|
||||
|
||||
Service name `MxAccessGw` and the windev layout (`C:\publish\mxaccessgw\Server-YYYYMMDD`,
|
||||
`C:\publish\mxaccessgw\Worker`, build clone `C:\build\mxaccessgw-ci`) are from
|
||||
`docs/superpowers/plans/2026-10-19-ackmsg-as-operator.md` Task "Deploy" and
|
||||
`docs/runbooks/IdentifyingADeployedBuild.md`. The wonder boxes use `E:\ApiInstall\...` per
|
||||
`scadaproj/deployment.md` §7.1; the exact `MxAccessGw` subfolder names there are **[UNVERIFIED]**.
|
||||
|
||||
Configuration is delivered as NSSM `AppEnvironmentExtra` environment variables
|
||||
(`Kestrel__Endpoints__*`, `MxGateway__Authentication__SqlitePath`, `MxGateway__Worker__ExecutablePath`,
|
||||
`ASPNETCORE_ENVIRONMENT`/`DOTNET_ENVIRONMENT`, `ZB_SECRETS_MASTER_KEY`, the API-key pepper,
|
||||
`MxGateway__Ldap__ServiceAccountPassword`), not by editing `appsettings.json`
|
||||
(`docs/GatewayConfiguration.md`, "Kestrel", "Secrets Master Key").
|
||||
|
||||
## 1. State that MUST survive the swap
|
||||
|
||||
The upgrade renames/replaces the application directory. Anything stored inside it is lost. The
|
||||
validator therefore rejects stores inside the content root (see the 2026-08-09 incident below).
|
||||
|
||||
| State | Setting | Default location (Windows) | Notes |
|
||||
|---|---|---|---|
|
||||
| API-key store (SQLite) | `MxGateway:Authentication:SqlitePath` (NSSM: `MxGateway__Authentication__SqlitePath`) | `C:\ProgramData\MxGateway\gateway-auth.db` | Must be rooted; validator also rejects a path inside the content root. Back up the `-wal`/`-shm` siblings with it. |
|
||||
| API-key **pepper** | secret `MxGateway:ApiKeyPepper` (`PepperSecretName`); lives outside the DB, in NSSM env / Secrets store | n/a | Without the same pepper every issued `mxgw_...` token fails verification. Never in the DB (`docs/Authentication.md`). Back it up in the org vault. On the wonder boxes it is the `MxGateway__ApiKeyPepper` env entry: QA vq03/vq04 since 2026-08-14, DEV vd03 since 2026-11-12 (moved out of `Server\appsettings.json`, mxaccessgw#171, `docs/deploy/2026-11-12-vd03-pepper-to-service-env.md`). |
|
||||
| Secrets store (SQLite) | `Secrets:SqlitePath` (NSSM: `Secrets__SqlitePath`) | `C:\ProgramData\MxGateway\mxgateway-secrets.db` | **Must be absolute AND outside the content root**; fail-closed with no opt-out (`docs/GatewayConfiguration.md` L349; `scadaproj` Secrets notes). |
|
||||
| Secrets master key (KEK) | `ZB_SECRETS_MASTER_KEY` in NSSM `AppEnvironmentExtra` | n/a | Losing it makes the store unrecoverable; no `RewrapAll` yet (`docs/GatewayConfiguration.md`, "Rotation / DR"). Back it up in the vault, not just on the box. |
|
||||
| Galaxy snapshot cache | `MxGateway:Galaxy:SnapshotCachePath` | `C:\ProgramData\MxGateway\galaxy-snapshot.json` | Cache only; rejected inside content root so it survives deploys. Losing it is harmless. |
|
||||
| TLS self-signed cert | `Tls:SelfSignedCertPath` | `C:\ProgramData\MxGateway\certs\gateway-selfsigned.pfx` | If lost, clients pinned to the old cert see a changed cert. |
|
||||
| NSSM env block | `nssm get MxAccessGw AppEnvironmentExtra` | NSSM registry config | File copies do not touch it, but `nssm set AppEnvironmentExtra` **replaces the whole block**. |
|
||||
| Local `appsettings*.json` overrides in the deploy dir | n/a | deploy dir | Copy the live ones aside and restore them after the swap (the windev plan copies `appsettings.json` / `appsettings.Development.json` from the current dir). |
|
||||
|
||||
**Incident that motivates the rule (2026-08-09, per `docs/GatewayConfiguration.md` L127):** the
|
||||
API-key store lived inside the application directory; the upgrade renamed that directory to
|
||||
`Server.bak.*`, silently starting an empty store, and no gRPC client could authenticate for two
|
||||
days. The SQLite DB must also never be opened with a host-side `sqlite3` while the service runs
|
||||
(copy the file triplet and query the copy; cross-repo lesson, **[UNVERIFIED from this repo]**).
|
||||
|
||||
## 2. Traps (read before touching anything)
|
||||
|
||||
1. **`OrphanWorkerTerminator` kills live workers if a second gateway starts.**
|
||||
On startup the Server enumerates processes named after the configured Worker exe
|
||||
(`ZB.MOM.WW.MxGateway.Worker` on windev, `MxGateway.Worker` on the wonder boxes) and kills every one whose path equals the configured
|
||||
`ExecutablePath` - or whose path it cannot read, which is the normal case for an x86 process seen
|
||||
from an x64 gateway, so it falls back to **image-name match only**
|
||||
(`src/ZB.MOM.WW.MxGateway.Server/Workers/OrphanWorkerTerminator.cs`). It skips only its own PID's
|
||||
children logic (`currentProcessId`), not another gateway's workers. Consequence: starting a
|
||||
second gateway process on the same box (a manual `dotnet ...Server.dll` or `Server.exe` while the
|
||||
service is up, a second NSSM service, a "test" start of the new build before stopping the old one,
|
||||
or a rollback started while the new one still runs) **terminates every live session's Worker** and
|
||||
all MXAccess subscriptions with it. Rule: **exactly one gateway process per box at any time**;
|
||||
stop the service and confirm the process has exited before starting anything else. Never smoke-test
|
||||
the new build by launching it beside the running service. (On QA, vq03 and vq04 are independent
|
||||
boxes with independent gateways; this trap is per-box, not per-pair.)
|
||||
2. **A gateway restart does not reattach workers** (`OrphanWorkerTerminator` summary). Plan for every
|
||||
client session to drop and for clients to reopen sessions. Session-resilience reattach is opt-in
|
||||
design only (`docs/plans/2026-06-15-session-resilience-design.md`); do not assume it is on.
|
||||
3. **Secrets store path.** `Secrets:SqlitePath` must be absolute and outside the content root or the
|
||||
host fails closed at startup. A store left at an in-tree path is exactly what the swap removes.
|
||||
Also: the `secret` CLI and the gateway must use the same `Secrets__SqlitePath`, or the CLI seeds a
|
||||
different store and the gateway then fails closed as if the secret were never set
|
||||
(`docs/GatewayConfiguration.md` L381-395).
|
||||
4. **`nssm set ... AppEnvironmentExtra` replaces the whole block.** `nssm get` first, save the output
|
||||
(redact `Password=`/key values in anything you paste), then re-include every entry
|
||||
(`docs/GatewayConfiguration.md` L370-374; `docs/runbooks/SEC-36-ldap-credential-rotation.md`).
|
||||
The `nssm set MxAccessGw Application`/`AppDirectory` commands used for repointing do **not** touch
|
||||
the env block.
|
||||
5. **Worker bitness.** The Worker must be built x86 (`-p:Platform=x86`) and `RequiredArchitecture`
|
||||
stays `X86`. The Server (x64) cannot load MXAccess COM. Build on windev (`ssh windev` flow,
|
||||
`scripts/ci/windev-worker-ci.ps1`), not on a Mac. Deploying a Worker from a different commit than
|
||||
the Server risks a protocol mismatch; build both from the same SHA.
|
||||
6. **Environment name gates security hard-stops** (`docs/GatewayConfiguration.md` L317-335):
|
||||
`Dashboard:DisableLogin` and plaintext LDAP are refused only when the environment name is exactly
|
||||
`Production`. Do not change `ASPNETCORE_ENVIRONMENT`/`DOTNET_ENVIRONMENT` during an upgrade; a
|
||||
host that boots under a different label silently loses those guards, and a host that was
|
||||
permissive may refuse to boot if you "fix" the label.
|
||||
7. **Version stamp.** Do not trust `InformationalVersion` for builds from 2026-07-09 to 2026-08-10
|
||||
(`docs/runbooks/IdentifyingADeployedBuild.md`). Record the SHA yourself in the deploy notes.
|
||||
8. **Stuck `STOP_PENDING`.** Stopping the service can hang in `STOP_PENDING` (workers must exit within
|
||||
`Worker:ShutdownTimeoutSeconds`, default 10). Observed on the QA boxes per deploy notes
|
||||
**[UNVERIFIED from this repo]**; if it hangs, wait, then kill the Server process by PID. Do not start the new
|
||||
build until no gateway Server and no Worker process is left. Check **both** naming schemes:
|
||||
`ZB.MOM.WW.MxGateway.Server`/`.Worker` (windev) and `MxGateway.Server`/`.Worker` (wonder boxes).
|
||||
|
||||
## 3. Preflight (no changes yet)
|
||||
|
||||
1. Decide the target SHA on `origin/main`; confirm CI is green for it (`windows-x86` job runs the
|
||||
Worker build + `Worker.Tests` on windev; run the live tier on demand with
|
||||
`CI_SHA=<sha> scripts/ci/run-windev-ci.sh live` or a `windev_mode: live` dispatch,
|
||||
`scripts/ci/README.md`).
|
||||
2. Read the current state of the service (read-only):
|
||||
```text
|
||||
nssm get MxAccessGw Application
|
||||
nssm get MxAccessGw AppDirectory
|
||||
nssm get MxAccessGw AppParameters
|
||||
nssm get MxAccessGw AppEnvironmentExtra # save to the deploy notes; redact secrets
|
||||
```
|
||||
Note the entry count and names of the env block; verify the same count after the start.
|
||||
3. Confirm the effective store paths from the env block: `MxGateway__Authentication__SqlitePath`,
|
||||
`Secrets__SqlitePath`, `MxGateway__Worker__ExecutablePath`. If either store path is missing from
|
||||
the env block it is on the code default (`C:\ProgramData\MxGateway\...`), which is fine; if it is
|
||||
under the application directory, **stop and move it first** (see section 1).
|
||||
4. Confirm the pepper and `ZB_SECRETS_MASTER_KEY` are present in the env block (names only).
|
||||
5. Read the dashboard **Settings** page (`/settings` on the dashboard port, `:5130`) and save the
|
||||
effective config; it now includes the heartbeat check interval, stuck ceiling, event-channel
|
||||
full-mode timeout and replay byte cap. Compare after the upgrade to catch config drift.
|
||||
6. Check the box is quiet: dashboard sessions list, or `GET /health/active` (the `mxaccess-sessions`
|
||||
check reports `total/ready/faulted/starting/closing`). Agree a window with clients (OtOpcUa
|
||||
`GalaxyDriver`, ScadaBridge MxGateway adapter) - their sessions will drop.
|
||||
7. Check the new build's required config: diff the repo `src/ZB.MOM.WW.MxGateway.Server/appsettings.json`
|
||||
and the changelog for new mandatory options, and `docs/GatewayConfiguration.md` for validator
|
||||
changes (the validator can refuse to boot on a bad value, which is a rollback trigger).
|
||||
8. Free disk for a full copy of the deploy dir and the stores (see backup).
|
||||
9. Check auth-store schema compatibility: the Server migrates the API-key DB on start
|
||||
(`Authentication:RunMigrationsOnStartup: true`) via the `ZB.MOM.WW.Auth` package. If the new build
|
||||
bumps the Auth package, the schema can migrate forward and **the old binary may not read it back**
|
||||
(see the 2026-08-07 follow-up plan's `AuthStoreMigrationException` check). Treat the DB backup as
|
||||
the rollback for a schema bump.
|
||||
|
||||
## 4. Build (on windev; no deploy yet)
|
||||
|
||||
windev flow from `docs/superpowers/plans/2026-10-19-ackmsg-as-operator.md`:
|
||||
|
||||
```powershell
|
||||
git -C C:\build\mxaccessgw-ci fetch origin
|
||||
git -C C:\build\mxaccessgw-ci worktree add C:\build\mxgw-deploy <sha> # detached worktree, host checkout untouched
|
||||
cd C:\build\mxgw-deploy
|
||||
dotnet publish src\ZB.MOM.WW.MxGateway.Server -c Release -o C:\publish\mxaccessgw\Server-YYYYMMDD
|
||||
dotnet build src\ZB.MOM.WW.MxGateway.Worker\ZB.MOM.WW.MxGateway.Worker.csproj -c Release -p:Platform=x86
|
||||
# stage the Worker output (bin\x86\Release) into a temp dir, e.g. C:\publish\mxaccessgw\Worker-new
|
||||
```
|
||||
|
||||
Remove the worktree afterwards (`git worktree remove`); an absent `C:\build\mxgw-deploy` is the
|
||||
normal end state (`IdentifyingADeployedBuild.md`). Whether the Worker is built with `dotnet build`
|
||||
or `dotnet publish`, and its exact output folder, should be matched to the existing `Worker` folder on
|
||||
the host **[UNVERIFIED]**. Note: the Worker is net48 and must be built where the net48 targeting
|
||||
pack and MSBuild are present (windev; `scadaproj` notes say Build Tools 2022 + net48 reference
|
||||
assemblies verified 2026-09-10 **[UNVERIFIED from this repo]**).
|
||||
|
||||
**Self-contained runtime.** A self-contained Server carries its own .NET runtime, so the SDK that builds it
|
||||
decides the runtime on the box. On 2026-11-12 the windev SDK (10.0.204) produced runtime 10.0.8 while vd03 ran
|
||||
10.0.14, which would have been a downgrade; the Mac SDK (10.0.403) produced 10.0.14. Build where the SDK carries
|
||||
the newest runtime. The upgrade script refuses a downgrade (it compares `mscordaccore_amd64_amd64_<ver>.dll`
|
||||
between the live and staged dirs). The wonder boxes use the `MxGateway.Server.exe` / `MxGateway.Worker.exe`
|
||||
names: stage a byte copy of the apphost under that name and rename the Worker apphost and its `.config`
|
||||
(`docs/deploy/2026-11-12-vd03-76a71bc8-worker-time-fixes.md`).
|
||||
|
||||
For the wonder boxes the staged output is copied over SMB (UNC copy is always allowed) into a
|
||||
staging directory such as `E:\psrem-stage\<app>-<sha>\` per `scadaproj/deployment.md` §7.1
|
||||
(**[UNVERIFIED]** path convention); the on-box steps below are then the only remote-exec part.
|
||||
|
||||
## 5. Backup
|
||||
|
||||
With the service **still running** copy nothing live; do these after stopping (section 6 step 1), or
|
||||
copy the stores with the service stopped. Back up:
|
||||
|
||||
1. The current deploy directory (`Server-YYYYMMDD` or `Server`) to a sibling `Server.bak.<timestamp>`
|
||||
(the convention `IdentifyingADeployedBuild.md` reads as a deploy history chain), and the current
|
||||
`Worker` directory to `Worker.bak-<timestamp>[-label]`.
|
||||
2. `gateway-auth.db` plus `gateway-auth.db-wal` / `-shm` if present, and `mxgateway-secrets.db` (plus
|
||||
its `-wal`/`-shm`), to `*.bak-<label>` next to the originals. **Never delete or move the live DB.**
|
||||
3. The saved `AppEnvironmentExtra` text and the `nssm get Application/AppDirectory` values (for rollback
|
||||
repointing).
|
||||
4. Off-box: the KEK and pepper in the org vault (not on the box only).
|
||||
5. Record the old and new SHA, timestamps and backup paths in a `_DEPLOY-NOTES-<timestamp>.txt`
|
||||
next to the install (the convention seen on wonder per `deployment.md` §7.1, **[UNVERIFIED]**).
|
||||
|
||||
## 6. Stop / swap / start
|
||||
|
||||
Do this on **one box at a time**; QA vq03 and vq04 are independent gateways, so roll them one after
|
||||
the other (`deployment.md` §7.1 records the 2026-09-10 round as "rolling, one stop per box").
|
||||
|
||||
1. **Stop and confirm gone.**
|
||||
```powershell
|
||||
nssm stop MxAccessGw # or Stop-Service MxAccessGw -Force
|
||||
Get-Process ZB.MOM.WW.MxGateway.Server, ZB.MOM.WW.MxGateway.Worker, MxGateway.Server, MxGateway.Worker -ErrorAction SilentlyContinue
|
||||
```
|
||||
Both lists must be empty before continuing (traps 1 and 8). If a Worker is left over, the next
|
||||
start will kill it as an orphan (by design) - but it signals an unclean stop worth noting.
|
||||
2. **Backup** (section 5) now that nothing holds the stores open.
|
||||
3. **Swap the Server.** Preferred: deploy to a *new dated directory* and repoint NSSM, which leaves the
|
||||
old directory intact as the rollback target:
|
||||
```powershell
|
||||
Copy-Item <old>\appsettings.json, <old>\appsettings.Development.json <new>\ # preserve live file config
|
||||
nssm set MxAccessGw Application <new>\ZB.MOM.WW.MxGateway.Server.exe
|
||||
nssm set MxAccessGw AppDirectory <new>
|
||||
```
|
||||
(`2026-10-19-ackmsg-as-operator.md`; `IdentifyingADeployedBuild.md` "Deployment-side naming".)
|
||||
Alternative used on the wonder boxes: rename `app` to `app.bak.<timestamp>` and copy the new files
|
||||
into `app` (`deployment.md` §7.1; **[UNVERIFIED]**). Either way, restore any host-specific
|
||||
`appsettings*.json` byte-identical; do not edit the NSSM env block unless the release notes require it.
|
||||
4. **Swap the Worker.** Rename `Worker` to `Worker.bak-<timestamp>`, copy the new x86 Worker build in
|
||||
its place, and make sure `MxGateway__Worker__ExecutablePath` points at it
|
||||
(the path is matched case-insensitively by the orphan terminator, so keep one canonical spelling).
|
||||
5. **Verify the env block is untouched**: `nssm get MxAccessGw AppEnvironmentExtra` entry count equals the
|
||||
preflight count.
|
||||
6. **Start** (`nssm start MxAccessGw`). Exactly once; do not retry-start concurrently with anything else.
|
||||
|
||||
## 7. Post-deploy verification
|
||||
|
||||
All of this can be done over HTTP/gRPC from another machine or from the box without further remote
|
||||
exec beyond the deploy window.
|
||||
|
||||
1. Service `RUNNING` and stable for at least 60 s (no restart loop); the Application event log has a
|
||||
clean host start and **no** new `AuthStoreMigrationException` / `Hosting failed to start` after the
|
||||
start time (`2026-08-07-followups-windev-ldapfixtures-runners.md` Task 2).
|
||||
2. Health: `GET http://<host>:5130/healthz` (live), `/health/ready` (`auth-store` check),
|
||||
`/health/active` (`mxaccess-sessions`). These endpoints are anonymous by design
|
||||
(`GatewayApplication.cs`, `docs/Diagnostics.md`). Zero sessions is Healthy, so green does not prove
|
||||
the Worker/COM path works.
|
||||
3. Prove the **Worker** path, since an idle health probe does not: open a gRPC session with an existing
|
||||
API key (any of the clients, or the `mxa` CLI) and do a read of a known tag. This also proves the
|
||||
API-key store and pepper survived: a `mxgw_...` token issued before the upgrade must authenticate.
|
||||
Negative control: a wrong token must be rejected (`UNAUTHENTICATED`).
|
||||
4. Dashboard: login works (or the localhost anonymous policy applies), `/settings` matches the
|
||||
preflight capture, the version/Worker protocol line is right.
|
||||
5. Identify the deployed build by behaviour, not the version stamp where it is unreliable
|
||||
(`IdentifyingADeployedBuild.md`): a plain `Write` returning `statuses[0]` proves a Worker at or
|
||||
past `53f69cd`.
|
||||
6. Check the Server log for `Terminated orphan worker process` - expected only if the previous stop was
|
||||
unclean.
|
||||
7. Check downstream clients reconnected (OtOpcUa `GalaxyDriver`; ScadaBridge MxGateway adapter) and, on
|
||||
a pair of QA boxes, repeat sections 5-7 for the second box.
|
||||
8. Write the deploy note: SHA, backup paths, env-entry count, evidence for each check above.
|
||||
|
||||
## 8. Rollback
|
||||
|
||||
Triggers: service will not stay `RUNNING`, host fails validator at start, health red beyond the grace
|
||||
window, API keys no longer authenticate, or a Worker session cannot be opened.
|
||||
|
||||
1. `nssm stop MxAccessGw`; confirm no Server/Worker process (trap 1: **never start the old build while
|
||||
the new one is still up**).
|
||||
2. Repoint: `nssm set MxAccessGw Application <old>\...Server.exe` and `AppDirectory <old>`, or rename
|
||||
`app.bak.<ts>` back to `app`, and restore `Worker.bak-<ts>` over `Worker`.
|
||||
3. If the API-key DB was migrated (schema bump, trap in section 3 step 9) or damaged, restore
|
||||
`gateway-auth.db` from the backup (restore the `-wal`/`-shm` together or none). Otherwise leave the
|
||||
live store alone: the env-block stores are outside the swap and need no restore.
|
||||
4. `nssm get AppEnvironmentExtra` entry count equals the preflight count; if you changed it, restore the
|
||||
saved block (all entries).
|
||||
5. `nssm start MxAccessGw`; repeat section 7 steps 1-3.
|
||||
6. Report: what failed, the log excerpt, backup paths used.
|
||||
|
||||
## 9. Open gaps (not verifiable from this repo)
|
||||
|
||||
- Install layout on the wonder boxes, confirmed on vd03 (2026-11-12, #229/#230): `E:\ApiInstall\MxGateway\Server\MxGateway.Server.exe`
|
||||
(NSSM `Application`), `Worker\MxGateway.Worker.exe` (`MxGateway__Worker__ExecutablePath`), stores and `kek.key` in
|
||||
`E:\ApiInstall\MxGateway\data\`, `Server\dashboard.pfx`, master key `Secrets__MasterKey__Source=File`. windev:
|
||||
`C:\publish\mxaccessgw\Server-<date>-<sha>\ZB.MOM.WW.MxGateway.Server.exe` and `C:\publish\mxaccessgw\Worker\`, stores in
|
||||
`C:\ProgramData\MxGateway\`. vq03/vq04 are assumed to match vd03; the dry run shows it.
|
||||
- Whether the Server on each box is framework-dependent or self-contained (a box without .NET 10
|
||||
needs self-contained; the 2026-10-19 windev plan says framework-dependent).
|
||||
- The `STOP_PENDING` behaviour and the NSSM service account (`LocalSystem` per `deployment.md`).
|
||||
- New-box install and the upgrade are now scripted (see "Scripts"), but **untested on a real box**; the
|
||||
recovery/stop-grace/log-rotation defaults in `Install-MxGatewayService.ps1` are chosen from the repo's
|
||||
own settings (`Worker:ShutdownTimeoutSeconds`), not copied from an existing box. Compare against the
|
||||
`nssm dump` of a known-good box (vd03/vq03) before relying on them.
|
||||
- The Worker output folder and build-vs-publish question (section 4) is still **[UNVERIFIED]**: the upgrade
|
||||
script copies whatever the staged `-WorkerSource` directory contains over `Worker`, so stage exactly what
|
||||
the existing `Worker` folder holds. Confirm with a file listing of the live `Worker` dir on the next deploy.
|
||||
@@ -0,0 +1,53 @@
|
||||
"""Actual BrowsePage/real projection/index; only cached synthetic metadata and fake redacted reads."""
|
||||
import json,sys
|
||||
from pathlib import Path
|
||||
from playwright.sync_api import sync_playwright
|
||||
ROOT=Path(__file__).resolve().parent
|
||||
sys.path.insert(0,'/Users/dohertj2/.codex/worktrees/scada-ui-consistency/scadaproj/components/ui-theme/validation/theme-1.0.0/canary')
|
||||
from browser_zoom import zoom_browser,set_browser_zoom
|
||||
BASE=json.load(open('/tmp/mx-ui-browse-state.json'))['origin'];OUT=ROOT/'evidence/browse-confirmation';OUT.mkdir(exist_ok=True)
|
||||
long='Pump01.'+'x'*200
|
||||
results=[];errors=[]
|
||||
def flow(page,touch=False,capture=None):
|
||||
page.goto(BASE+'/browse-fixture');page.wait_for_selector('html[data-mx-ready="true"]');page.evaluate('document.fonts.ready')
|
||||
page.get_by_role('button',name='Expand SyntheticPlant',exact=True).tap() if touch else page.get_by_role('button',name='Expand SyntheticPlant',exact=True).press('Enter')
|
||||
page.get_by_role('button',name='Expand Pump01',exact=True).tap() if touch else page.get_by_role('button',name='Expand Pump01',exact=True).press('Space')
|
||||
watch=page.get_by_role('button',name='Watch Pump01.PV',exact=True);watch.tap() if touch else watch.press('Space')
|
||||
page.wait_for_function("document.querySelectorAll('.sub-table tbody tr').length===1")
|
||||
watch.tap() if touch else watch.press('Space');assert page.locator('.sub-table tbody tr').count()==1
|
||||
page.get_by_role('button',name='Watch '+long,exact=True).tap() if touch else page.get_by_role('button',name='Watch '+long,exact=True).press('Enter')
|
||||
page.wait_for_function("document.querySelectorAll('.sub-table tbody tr').length===2")
|
||||
assert long in page.locator('.sub-table').inner_text()
|
||||
targets=page.locator('.tree-node-toggle,.tree-watch,.sub-actions-col button').evaluate_all('(es)=>es.map(e=>({name:e.getAttribute("aria-label")||e.textContent.trim(),width:e.getBoundingClientRect().width,height:e.getBoundingClientRect().height}))')
|
||||
if capture:page.screenshot(path=str(OUT/f'expanded-{capture}.png'),full_page=False)
|
||||
region=page.get_by_role('region',name='Watched attribute values',exact=True)
|
||||
region.evaluate('(e)=>e.scrollLeft=0');region.focus();page.keyboard.press('Tab')
|
||||
page.wait_for_function("document.querySelector('.sub-table').closest('[role=region]').scrollLeft>0")
|
||||
assert page.get_by_role('button',name='Remove Pump01.PV',exact=True).evaluate('(e)=>e===document.activeElement')
|
||||
search=page.get_by_role('searchbox',name='Filter Galaxy attributes');search.fill('PV')
|
||||
page.get_by_test_id('browse-search-status').filter(has_text='2 matching attributes.').wait_for()
|
||||
page.get_by_role('button',name='Watch Pump01.PV',exact=True).tap() if touch else page.get_by_role('button',name='Watch Pump01.PV',exact=True).press('Space');assert page.locator('.sub-table tbody tr').count()==2
|
||||
search.fill('no-such-fixture');page.get_by_text('No attributes match',exact=False).wait_for()
|
||||
page.get_by_role('button',name='Clear search',exact=True).tap() if touch else page.get_by_role('button',name='Clear search',exact=True).click()
|
||||
page.wait_for_function("document.activeElement.id==='browse-search'")
|
||||
assert page.locator('.sub-table tbody tr').count()==2
|
||||
return {'viewport':page.evaluate('innerWidth'),'scroll':page.evaluate('document.documentElement.scrollWidth'),'coarse':page.evaluate("matchMedia('(pointer:coarse)').matches"),'targets':targets,'namedScrollRegions':page.get_by_role('region').count(),'workflow':['keyboardExpand','spaceWatch','repeatedWatchNoDuplicate','fullLongPathPreserved','searchWatchSameSubscription','noMatchClearFocus','subscriptionsRetained','namedScrollerTabReachesActions']}
|
||||
with sync_playwright() as p:
|
||||
with zoom_browser(p) as (ctx,worker):
|
||||
page=ctx.new_page();page.on('pageerror',lambda e:errors.append(str(e)))
|
||||
for width,zoom in [(1440,1),(1024,1),(390,1),(1440,2)]:
|
||||
page.set_viewport_size({'width':width,'height':900});page.goto(BASE+'/browse-fixture');set_browser_zoom(worker,page,zoom)
|
||||
result=flow(page,capture=f'{width}-zoom{zoom}');result['zoom']=zoom;result['dpr']=page.evaluate('devicePixelRatio');results.append(result)
|
||||
page.screenshot(path=str(OUT/f'browse-{width}-zoom{zoom}.png'),full_page=False)
|
||||
set_browser_zoom(worker,page,1)
|
||||
browser=p.chromium.launch(channel='chromium',headless=True)
|
||||
page=browser.new_page(viewport={'width':390,'height':844},is_mobile=True,has_touch=True)
|
||||
page.on('pageerror',lambda e:errors.append(str(e)))
|
||||
page.goto(BASE+'/browse-fixture');cdp=page.context.new_cdp_session(page);cdp.send('Emulation.setTouchEmulationEnabled',{'enabled':True,'maxTouchPoints':1})
|
||||
assert page.evaluate("matchMedia('(pointer:coarse)').matches && navigator.maxTouchPoints===1")
|
||||
result=flow(page,touch=True,capture='coarse390');results.append(result)
|
||||
page.screenshot(path=str(OUT/'browse-coarse390.png'),full_page=False);browser.close()
|
||||
assert all(r['scroll']<=r['viewport'] for r in results)
|
||||
assert all(min(t['width'],t['height'])>=44 for r in results if r['coarse'] for t in r['targets'])
|
||||
(OUT/'results.json').write_text(json.dumps({'cases':results,'errors':errors},indent=2))
|
||||
print(json.dumps({'cases':len(results),'overflow':[(r['viewport'],r['scroll']) for r in results if r['scroll']>r['viewport']],'coarseBelow44':[t for r in results if r['coarse'] for t in r['targets'] if min(t['width'],t['height'])<44],'errors':errors},indent=2))
|
||||
@@ -0,0 +1,11 @@
|
||||
Determining projects to restore...
|
||||
Restored /Users/dohertj2/Desktop/MxAccessGateway/src/ZB.MOM.WW.MxGateway.Tests/ZB.MOM.WW.MxGateway.Tests.csproj (in 182 ms).
|
||||
2 of 3 projects are up-to-date for restore.
|
||||
ZB.MOM.WW.MxGateway.Contracts -> /Users/dohertj2/Desktop/MxAccessGateway/src/ZB.MOM.WW.MxGateway.Contracts/bin/Release/net10.0/ZB.MOM.WW.MxGateway.Contracts.dll
|
||||
ZB.MOM.WW.MxGateway.Server -> /Users/dohertj2/Desktop/MxAccessGateway/src/ZB.MOM.WW.MxGateway.Server/bin/Release/net10.0/ZB.MOM.WW.MxGateway.Server.dll
|
||||
ZB.MOM.WW.MxGateway.Tests -> /Users/dohertj2/Desktop/MxAccessGateway/src/ZB.MOM.WW.MxGateway.Tests/bin/Release/net10.0/ZB.MOM.WW.MxGateway.Tests.dll
|
||||
Test run for /Users/dohertj2/Desktop/MxAccessGateway/src/ZB.MOM.WW.MxGateway.Tests/bin/Release/net10.0/ZB.MOM.WW.MxGateway.Tests.dll (.NETCoreApp,Version=v10.0)
|
||||
A total of 1 test files matched the specified pattern.
|
||||
Results File: /Users/dohertj2/Desktop/MxAccessGateway/docs/ui-validation/evidence/baseline/dashboard-baseline.trx
|
||||
|
||||
Passed! - Failed: 0, Passed: 341, Skipped: 0, Total: 341, Duration: 1 s - ZB.MOM.WW.MxGateway.Tests.dll (net10.0)
|
||||
@@ -0,0 +1,84 @@
|
||||
Determining projects to restore...
|
||||
All projects are up-to-date for restore.
|
||||
Project 'ZB.MOM.WW.MxGateway.Server' has the following package references
|
||||
[net10.0]:
|
||||
Top-level Package Requested Resolved
|
||||
> Grpc.AspNetCore 2.76.0 2.76.0
|
||||
> Microsoft.AspNetCore.App.Internal.Assets (A) [10.0.14, ) 10.0.14
|
||||
> Microsoft.Data.SqlClient 6.0.2 6.0.2
|
||||
> Microsoft.Data.Sqlite 10.0.13 10.0.13
|
||||
> Polly.Core 8.6.6 8.6.6
|
||||
> Serilog.AspNetCore 10.0.0 10.0.0
|
||||
> Serilog.Sinks.Console 6.1.1 6.1.1
|
||||
> Serilog.Sinks.File 7.0.0 7.0.0
|
||||
> SQLitePCLRaw.lib.e_sqlite3 2.1.13 2.1.13
|
||||
> System.Security.Cryptography.Pkcs 10.0.13 10.0.13
|
||||
> ZB.MOM.WW.Audit 0.1.0 0.1.0
|
||||
> ZB.MOM.WW.Auth.Abstractions 0.4.1 0.4.1
|
||||
> ZB.MOM.WW.Auth.ApiKeys 0.4.1 0.4.1
|
||||
> ZB.MOM.WW.Auth.AspNetCore 0.4.1 0.4.1
|
||||
> ZB.MOM.WW.Auth.Ldap 0.4.1 0.4.1
|
||||
> ZB.MOM.WW.Configuration 0.1.0 0.1.0
|
||||
> ZB.MOM.WW.GalaxyRepository 0.2.0 0.2.0
|
||||
> ZB.MOM.WW.Health 0.3.0 0.3.0
|
||||
> ZB.MOM.WW.Secrets 0.6.2 0.6.2
|
||||
> ZB.MOM.WW.Secrets.Abstractions 0.6.2 0.6.2
|
||||
> ZB.MOM.WW.Secrets.Ui 0.6.2 0.6.2
|
||||
> ZB.MOM.WW.Telemetry 0.3.1 0.3.1
|
||||
> ZB.MOM.WW.Telemetry.Serilog 0.3.1 0.3.1
|
||||
> ZB.MOM.WW.Theme 0.5.0 0.5.0
|
||||
|
||||
Transitive Package Resolved
|
||||
> Azure.Core 1.38.0
|
||||
> Azure.Identity 1.11.4
|
||||
> Google.Protobuf 3.34.1
|
||||
> Grpc.AspNetCore.Server 2.76.0
|
||||
> Grpc.AspNetCore.Server.ClientFactory 2.76.0
|
||||
> Grpc.Core.Api 2.76.0
|
||||
> Grpc.Net.Client 2.76.0
|
||||
> Grpc.Net.ClientFactory 2.76.0
|
||||
> Grpc.Net.Common 2.76.0
|
||||
> Grpc.Tools 2.76.0
|
||||
> Microsoft.Bcl.AsyncInterfaces 1.1.1
|
||||
> Microsoft.Bcl.Cryptography 9.0.4
|
||||
> Microsoft.Data.SqlClient.SNI.runtime 6.0.2
|
||||
> Microsoft.Data.Sqlite.Core 10.0.13
|
||||
> Microsoft.Extensions.DependencyModel 10.0.0
|
||||
> Microsoft.Identity.Client 4.61.3
|
||||
> Microsoft.Identity.Client.Extensions.Msal 4.61.3
|
||||
> Microsoft.IdentityModel.Abstractions 7.5.0
|
||||
> Microsoft.IdentityModel.JsonWebTokens 7.5.0
|
||||
> Microsoft.IdentityModel.Logging 7.5.0
|
||||
> Microsoft.IdentityModel.Protocols 7.5.0
|
||||
> Microsoft.IdentityModel.Protocols.OpenIdConnect 7.5.0
|
||||
> Microsoft.IdentityModel.Tokens 7.5.0
|
||||
> Microsoft.SqlServer.Server 1.0.0
|
||||
> Novell.Directory.Ldap.NETStandard 3.6.0
|
||||
> OpenTelemetry 1.15.3
|
||||
> OpenTelemetry.Api 1.15.3
|
||||
> OpenTelemetry.Api.ProviderBuilderExtensions 1.15.3
|
||||
> OpenTelemetry.Exporter.OpenTelemetryProtocol 1.15.3
|
||||
> OpenTelemetry.Exporter.Prometheus.AspNetCore 1.15.3-beta.1
|
||||
> OpenTelemetry.Extensions.Hosting 1.15.3
|
||||
> OpenTelemetry.Instrumentation.AspNetCore 1.15.2
|
||||
> OpenTelemetry.Instrumentation.GrpcNetClient 1.15.1-beta.1
|
||||
> OpenTelemetry.Instrumentation.Http 1.15.1
|
||||
> OpenTelemetry.Instrumentation.Process 1.15.1-beta.1
|
||||
> OpenTelemetry.Instrumentation.Runtime 1.15.1
|
||||
> Serilog 4.3.1
|
||||
> Serilog.Extensions.Hosting 10.0.0
|
||||
> Serilog.Extensions.Logging 10.0.0
|
||||
> Serilog.Formatting.Compact 3.0.0
|
||||
> Serilog.Settings.Configuration 10.0.0
|
||||
> Serilog.Sinks.Debug 3.0.0
|
||||
> Serilog.Sinks.OpenTelemetry 4.2.0
|
||||
> SQLitePCLRaw.bundle_e_sqlite3 2.1.13
|
||||
> SQLitePCLRaw.core 2.1.13
|
||||
> SQLitePCLRaw.provider.e_sqlite3 2.1.13
|
||||
> System.ClientModel 1.0.0
|
||||
> System.Configuration.ConfigurationManager 9.0.4
|
||||
> System.IdentityModel.Tokens.Jwt 7.5.0
|
||||
> System.Memory.Data 1.0.2
|
||||
> System.Security.Cryptography.ProtectedData 9.0.4
|
||||
|
||||
(A) : Auto-referenced package.
|
||||
@@ -0,0 +1,3 @@
|
||||
Determining projects to restore...
|
||||
Restored /Users/dohertj2/Desktop/MxAccessGateway/src/ZB.MOM.WW.MxGateway.Server/ZB.MOM.WW.MxGateway.Server.csproj (in 139 ms).
|
||||
1 of 2 projects are up-to-date for restore.
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"cases": 5,
|
||||
"overflow": [],
|
||||
"coarseBelow44": [],
|
||||
"errors": []
|
||||
}
|
||||
|
After Width: | Height: | Size: 77 KiB |
|
After Width: | Height: | Size: 83 KiB |
|
After Width: | Height: | Size: 72 KiB |
|
After Width: | Height: | Size: 59 KiB |
|
After Width: | Height: | Size: 57 KiB |
|
After Width: | Height: | Size: 59 KiB |
|
After Width: | Height: | Size: 85 KiB |
|
After Width: | Height: | Size: 131 KiB |
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 53 KiB |
@@ -0,0 +1,278 @@
|
||||
{
|
||||
"cases": [
|
||||
{
|
||||
"viewport": 1440,
|
||||
"scroll": 1440,
|
||||
"coarse": false,
|
||||
"targets": [
|
||||
{
|
||||
"name": "Collapse SyntheticPlant",
|
||||
"width": 128.78125,
|
||||
"height": 19.6875
|
||||
},
|
||||
{
|
||||
"name": "Collapse Pump01",
|
||||
"width": 86.09375,
|
||||
"height": 19.6875
|
||||
},
|
||||
{
|
||||
"name": "Watch Pump01.PV",
|
||||
"width": 56.546875,
|
||||
"height": 27.46875
|
||||
},
|
||||
{
|
||||
"name": "Watch Pump01.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
|
||||
"width": 56.546875,
|
||||
"height": 27.46875
|
||||
},
|
||||
{
|
||||
"name": "Expand Sibling01",
|
||||
"width": 91.375,
|
||||
"height": 19.6875
|
||||
},
|
||||
{
|
||||
"name": "Remove Pump01.PV",
|
||||
"width": 66.515625,
|
||||
"height": 27.46875
|
||||
},
|
||||
{
|
||||
"name": "Remove Pump01.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
|
||||
"width": 66.515625,
|
||||
"height": 27.46875
|
||||
}
|
||||
],
|
||||
"namedScrollRegions": 2,
|
||||
"workflow": [
|
||||
"keyboardExpand",
|
||||
"spaceWatch",
|
||||
"repeatedWatchNoDuplicate",
|
||||
"fullLongPathPreserved",
|
||||
"searchWatchSameSubscription",
|
||||
"noMatchClearFocus",
|
||||
"subscriptionsRetained",
|
||||
"namedScrollerTabReachesActions"
|
||||
],
|
||||
"zoom": 1,
|
||||
"dpr": 1
|
||||
},
|
||||
{
|
||||
"viewport": 1024,
|
||||
"scroll": 1024,
|
||||
"coarse": false,
|
||||
"targets": [
|
||||
{
|
||||
"name": "Collapse SyntheticPlant",
|
||||
"width": 128.78125,
|
||||
"height": 19.6875
|
||||
},
|
||||
{
|
||||
"name": "Collapse Pump01",
|
||||
"width": 86.09375,
|
||||
"height": 19.6875
|
||||
},
|
||||
{
|
||||
"name": "Watch Pump01.PV",
|
||||
"width": 56.546875,
|
||||
"height": 27.46875
|
||||
},
|
||||
{
|
||||
"name": "Watch Pump01.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
|
||||
"width": 56.546875,
|
||||
"height": 27.46875
|
||||
},
|
||||
{
|
||||
"name": "Expand Sibling01",
|
||||
"width": 91.375,
|
||||
"height": 19.6875
|
||||
},
|
||||
{
|
||||
"name": "Remove Pump01.PV",
|
||||
"width": 66.515625,
|
||||
"height": 27.46875
|
||||
},
|
||||
{
|
||||
"name": "Remove Pump01.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
|
||||
"width": 66.515625,
|
||||
"height": 27.46875
|
||||
}
|
||||
],
|
||||
"namedScrollRegions": 2,
|
||||
"workflow": [
|
||||
"keyboardExpand",
|
||||
"spaceWatch",
|
||||
"repeatedWatchNoDuplicate",
|
||||
"fullLongPathPreserved",
|
||||
"searchWatchSameSubscription",
|
||||
"noMatchClearFocus",
|
||||
"subscriptionsRetained",
|
||||
"namedScrollerTabReachesActions"
|
||||
],
|
||||
"zoom": 1,
|
||||
"dpr": 1
|
||||
},
|
||||
{
|
||||
"viewport": 390,
|
||||
"scroll": 390,
|
||||
"coarse": false,
|
||||
"targets": [
|
||||
{
|
||||
"name": "Collapse SyntheticPlant",
|
||||
"width": 128.78125,
|
||||
"height": 19.6875
|
||||
},
|
||||
{
|
||||
"name": "Collapse Pump01",
|
||||
"width": 86.09375,
|
||||
"height": 19.6875
|
||||
},
|
||||
{
|
||||
"name": "Watch Pump01.PV",
|
||||
"width": 56.546875,
|
||||
"height": 27.46875
|
||||
},
|
||||
{
|
||||
"name": "Watch Pump01.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
|
||||
"width": 56.546875,
|
||||
"height": 27.46875
|
||||
},
|
||||
{
|
||||
"name": "Expand Sibling01",
|
||||
"width": 91.375,
|
||||
"height": 19.6875
|
||||
},
|
||||
{
|
||||
"name": "Remove Pump01.PV",
|
||||
"width": 66.515625,
|
||||
"height": 27.46875
|
||||
},
|
||||
{
|
||||
"name": "Remove Pump01.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
|
||||
"width": 66.515625,
|
||||
"height": 27.46875
|
||||
}
|
||||
],
|
||||
"namedScrollRegions": 2,
|
||||
"workflow": [
|
||||
"keyboardExpand",
|
||||
"spaceWatch",
|
||||
"repeatedWatchNoDuplicate",
|
||||
"fullLongPathPreserved",
|
||||
"searchWatchSameSubscription",
|
||||
"noMatchClearFocus",
|
||||
"subscriptionsRetained",
|
||||
"namedScrollerTabReachesActions"
|
||||
],
|
||||
"zoom": 1,
|
||||
"dpr": 1
|
||||
},
|
||||
{
|
||||
"viewport": 720,
|
||||
"scroll": 720,
|
||||
"coarse": false,
|
||||
"targets": [
|
||||
{
|
||||
"name": "Collapse SyntheticPlant",
|
||||
"width": 128.78125,
|
||||
"height": 19.671875
|
||||
},
|
||||
{
|
||||
"name": "Collapse Pump01",
|
||||
"width": 86.078125,
|
||||
"height": 19.671875
|
||||
},
|
||||
{
|
||||
"name": "Watch Pump01.PV",
|
||||
"width": 56.546875,
|
||||
"height": 27.4609375
|
||||
},
|
||||
{
|
||||
"name": "Watch Pump01.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
|
||||
"width": 56.546875,
|
||||
"height": 27.4609375
|
||||
},
|
||||
{
|
||||
"name": "Expand Sibling01",
|
||||
"width": 91.359375,
|
||||
"height": 19.671875
|
||||
},
|
||||
{
|
||||
"name": "Remove Pump01.PV",
|
||||
"width": 66.515625,
|
||||
"height": 27.4609375
|
||||
},
|
||||
{
|
||||
"name": "Remove Pump01.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
|
||||
"width": 66.515625,
|
||||
"height": 27.4609375
|
||||
}
|
||||
],
|
||||
"namedScrollRegions": 2,
|
||||
"workflow": [
|
||||
"keyboardExpand",
|
||||
"spaceWatch",
|
||||
"repeatedWatchNoDuplicate",
|
||||
"fullLongPathPreserved",
|
||||
"searchWatchSameSubscription",
|
||||
"noMatchClearFocus",
|
||||
"subscriptionsRetained",
|
||||
"namedScrollerTabReachesActions"
|
||||
],
|
||||
"zoom": 2,
|
||||
"dpr": 2
|
||||
},
|
||||
{
|
||||
"viewport": 390,
|
||||
"scroll": 390,
|
||||
"coarse": true,
|
||||
"targets": [
|
||||
{
|
||||
"name": "Collapse SyntheticPlant",
|
||||
"width": 128.78125,
|
||||
"height": 44
|
||||
},
|
||||
{
|
||||
"name": "Collapse Pump01",
|
||||
"width": 86.09375,
|
||||
"height": 44
|
||||
},
|
||||
{
|
||||
"name": "Watch Pump01.PV",
|
||||
"width": 56.546875,
|
||||
"height": 44
|
||||
},
|
||||
{
|
||||
"name": "Watch Pump01.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
|
||||
"width": 56.546875,
|
||||
"height": 44
|
||||
},
|
||||
{
|
||||
"name": "Expand Sibling01",
|
||||
"width": 91.375,
|
||||
"height": 44
|
||||
},
|
||||
{
|
||||
"name": "Remove Pump01.PV",
|
||||
"width": 66.515625,
|
||||
"height": 44
|
||||
},
|
||||
{
|
||||
"name": "Remove Pump01.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
|
||||
"width": 66.515625,
|
||||
"height": 44
|
||||
}
|
||||
],
|
||||
"namedScrollRegions": 2,
|
||||
"workflow": [
|
||||
"keyboardExpand",
|
||||
"spaceWatch",
|
||||
"repeatedWatchNoDuplicate",
|
||||
"fullLongPathPreserved",
|
||||
"searchWatchSameSubscription",
|
||||
"noMatchClearFocus",
|
||||
"subscriptionsRetained",
|
||||
"namedScrollerTabReachesActions"
|
||||
]
|
||||
}
|
||||
],
|
||||
"errors": []
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"cases": 5,
|
||||
"overflow": [],
|
||||
"coarseBelow44": [],
|
||||
"errors": []
|
||||
}
|
||||
|
After Width: | Height: | Size: 69 KiB |