test(live): prove Write2 applies a value via supervisory advise on DEV (#212)
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:
@@ -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);
|
||||
}
|
||||
Reference in New Issue
Block a user