test(live): prove Write2 applies a value via supervisory advise on DEV (#212)
ci / nightly-windev (push) Has been skipped
ci / portable (push) Failing after 7m54s
ci / windows-x86 (push) Failing after 10m16s
ci / java (push) Failing after 10m17s

On the DEV gateway (wonder-app-vd03, 2b13564e), Write2 after
AdviseSupervisory applied the value to MESReceiver_025.MoveInBatchID
(0 -> 212212, OnWriteComplete Ok), and the value was restored to 0. After a
plain Advise, the same Write2 got SecurityError/1008, which is exactly what
the windev run saw. So that refusal came from the plain advise. It does not
show that windev has no writable attribute.

- Client.Tests: add the opt-in LiveGatewayWrite2Tests (gated by
  LiveGatewayWriteFact: endpoint, key file and write item env vars). It runs
  supervisory advise -> Write2 -> readback -> restore. The value test passed
  live on vd03. The timestamp-parity test needs a second opt-in; it fails on
  a non-UTC host until #228 is fixed.
- IntegrationTests: the windev Write2 smoke now uses AdviseSupervisory and
  restores the original value. It has not been re-run on windev.
- GatewayTesting.md: document the env vars. code-reviews IntegrationTests-033:
  correct the "no writable attribute" limit.

The run also found that the Write2 timestamp is read as host-local time
(stored +5 h on the UTC-5 box); filed as #228.

Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
This commit is contained in:
Joseph Doherty
2026-11-12 20:40:46 -05:00
parent ebbfaa4c03
commit 7481b95905
5 changed files with 406 additions and 9 deletions
@@ -0,0 +1,203 @@
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. On a host whose clock is not
/// UTC this fails until mxaccessgw#228 is fixed (MXAccess reads the VT_DATE as local time).
/// </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_&lt;id&gt;_&lt;secret&gt;</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();
}
}
}