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;
///
/// Live proof that Write2 applies a value and timestamp through a real gateway (#212).
/// The item is advised supervisory 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 Write before the test returns.
///
public sealed class LiveGatewayWrite2Tests(ITestOutputHelper output)
{
private static readonly TimeSpan EventTimeout = TimeSpan.FromSeconds(20);
/// Write2 on a supervisory-advised item applies the value; the original is restored.
/// A task that represents the asynchronous operation.
[LiveGatewayWriteFact]
public async Task Write2_SupervisoryAdvise_AppliesValue()
{
Write2Outcome outcome = await RunWrite2RoundTripAsync();
Assert.Equal(outcome.WrittenValue, outcome.ObservedValue);
Assert.Equal(outcome.OriginalValue, outcome.RestoredValue);
}
///
/// 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.
///
/// A task that represents the asynchronous operation.
[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 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 events = Channel.CreateUnbounded();
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 WaitForAsync(Channel 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;
}
}
}
/// Waits for the OnDataChange and OnWriteComplete a write raises, in either order.
private static async Task<(MxEvent DataChange, MxEvent Completion)> WaitForWriteAsync(Channel 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);
}