Files
lmxopcua/docs/plans/evidence/2026-11-13-717-t13/harness/Program.cs
T
Joseph Doherty f826af8e8a
v2-ci / unit-tests (push) Waiting to run
docs(717): T13 live gate evidence on an isolated Warm pair
Every applicable T13 leg passes on 0c19f26c + c569f806. The leg list covers:
- metadata and ServiceLevel bands;
- standby projection;
- alarm suppression with Standby ConditionRefresh and the promotion refresh;
- the three D4 demotion timings, run live;
- standby write and Part 9 refusal (BadInvalidState);
- graceful and crash failover, with no failback;
- subscription transfer;
- the Mode=Unset regression.

The two crash-path defects the gate found are fixed in c569f806. Evidence, rig files and the
raw-client harness are in docs/plans/evidence/2026-11-13-717-t13/.

Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
2026-11-13 04:39:17 -05:00

446 lines
27 KiB
C#

// #717 T13 live-gate harness: a raw OPC UA client (SDK 2.0.1) against the isolated otopcua-t13 pair.
using System.Diagnostics;
using System.Text;
using System.Text.Json;
using Opc.Ua;
using Opc.Ua.Client;
const string RawNs = "https://zb.com/otopcua/raw";
const string UnsNs = "https://zb.com/otopcua/uns";
const string Equip = "EQ-3326c7a4728e";
var apiKey = File.ReadAllText(Environment.GetEnvironmentVariable("T13_APIKEY_FILE") ?? "../apikey.txt").Trim();
var cmd = args[0];
var url = args.Length > 1 ? args[1] : "opc.tcp://localhost:14840/OtOpcUa";
using var cts = new CancellationTokenSource();
Console.CancelKeyPress += (_, e) => { e.Cancel = true; cts.Cancel(); };
var ct = cts.Token;
switch (cmd)
{
case "meta": await Meta(url); break;
case "browse": await Browse(url, args[2]); break;
case "watch": await Watch(url, args[2], args.Length > 3 && args[3] == "anon"); break;
case "probe": await Probe(url, args.Length > 2 && args[2] == "ack"); break;
case "timing1": await Timing1(url, args[2]); break;
case "timing2": await Timing2(url, args[2]); break;
case "timing3": await Timing3(url, args[2]); break;
case "transfer": await Transfer(url, args[2]); break;
default: throw new ArgumentException(cmd);
}
return;
// ------------------------------------------------------------------ helpers
static string Now() => DateTime.UtcNow.ToString("HH:mm:ss.fff");
static RequestHeader H() => new() { Timestamp = DateTimeUtc.Now, TimeoutHint = 10_000 };
static string Val(DataValue v) => $"{(v.WrappedValue.IsNull ? "null" : v.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy)?.ToString())} [{StatusCode.LookupSymbolicId(v.StatusCode.Code) ?? v.StatusCode.ToString()}] src={((DateTime)v.SourceTimestamp):HH:mm:ss.fff}";
static string Sc(StatusCode s) => StatusCode.LookupSymbolicId(s.Code) ?? s.ToString();
async Task<ISession> Connect(string endpointUrl, bool anonymous = false)
{
var telemetry = DefaultTelemetry.Create(_ => { });
var pki = Path.Combine(Path.GetTempPath(), "t13-client-pki");
var config = new ApplicationConfiguration(telemetry)
{
ApplicationName = "T13Harness",
ApplicationUri = $"urn:T13Harness:{Guid.NewGuid():N}",
ApplicationType = ApplicationType.Client,
SecurityConfiguration = new SecurityConfiguration
{
ApplicationCertificate = new CertificateIdentifier { StoreType = CertificateStoreType.Directory, StorePath = Path.Combine(pki, "own") },
TrustedIssuerCertificates = new CertificateTrustList { StoreType = CertificateStoreType.Directory, StorePath = Path.Combine(pki, "issuer") },
TrustedPeerCertificates = new CertificateTrustList { StoreType = CertificateStoreType.Directory, StorePath = Path.Combine(pki, "trusted") },
RejectedCertificateStore = new CertificateTrustList { StoreType = CertificateStoreType.Directory, StorePath = Path.Combine(pki, "rejected") },
AutoAcceptUntrustedCertificates = true,
},
ClientConfiguration = new ClientConfiguration { DefaultSessionTimeout = 60_000 },
};
await config.ValidateAsync(ApplicationType.Client, ct);
var endpoint = await CoreClientUtils.SelectEndpointAsync(config, endpointUrl, false, telemetry, ct);
var identity = anonymous ? new UserIdentity(new AnonymousIdentityToken()) : new UserIdentity("apikey", Encoding.UTF8.GetBytes(apiKey));
return await new DefaultSessionFactory(telemetry).CreateAsync(config,
new ConfiguredEndpoint(null, endpoint!, EndpointConfiguration.Create(config)),
false, false, "T13Harness", 60_000, identity, default, ct);
}
NodeId RawN(ISession s, string id) => new(id, (ushort)s.NamespaceUris.GetIndex(RawNs));
NodeId UnsN(ISession s, string id) => new(id, (ushort)s.NamespaceUris.GetIndex(UnsNs));
async Task<DataValue> Read(ISession s, NodeId n, uint attr = Attributes.Value)
{
var r = await ((SessionClient)s).ReadAsync(H(), 0, TimestampsToReturn.Both, new[] { new ReadValueId { NodeId = n, AttributeId = attr } }, ct);
return r.Results[0];
}
async Task<byte> ReadSl(ISession s) => Convert.ToByte((await Read(s, VariableIds.Server_ServiceLevel)).WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy));
static EventFilter EventFilter()
{
var f = new EventFilter();
f.AddSelectClause(new NodeId(ObjectTypes.BaseEventType), QualifiedName.From(BrowseNames.EventId)); // 0
f.AddSelectClause(new NodeId(ObjectTypes.BaseEventType), QualifiedName.From(BrowseNames.EventType)); // 1
f.AddSelectClause(new NodeId(ObjectTypes.BaseEventType), QualifiedName.From(BrowseNames.Message)); // 2
f.AddSelectClause(new NodeId(ObjectTypes.BaseEventType), QualifiedName.From(BrowseNames.Time)); // 3
f.SelectClauses += new SimpleAttributeOperand { TypeDefinitionId = ObjectTypeIds.ConditionType, AttributeId = Attributes.NodeId }; // 4 ConditionId
f.AddSelectClause(ObjectTypeIds.ConditionType, QualifiedName.From(BrowseNames.Retain)); // 5
f.SelectClauses += new SimpleAttributeOperand(ObjectTypeIds.AlarmConditionType, [QualifiedName.From(BrowseNames.ActiveState), QualifiedName.From(BrowseNames.Id)]); // 6
f.SelectClauses += new SimpleAttributeOperand(ObjectTypeIds.AcknowledgeableConditionType, [QualifiedName.From(BrowseNames.AckedState), QualifiedName.From(BrowseNames.Id)]); // 7
f.AddSelectClause(new NodeId(ObjectTypes.BaseEventType), QualifiedName.From(BrowseNames.SourceName)); // 8
return f;
}
static string TypeName(NodeId t) =>
t == ObjectTypeIds.RefreshStartEventType ? "RefreshStart" :
t == ObjectTypeIds.RefreshEndEventType ? "RefreshEnd" :
t == ObjectTypeIds.GeneralModelChangeEventType ? "ModelChange" :
t.IsNull ? "?" : t.ToString();
static string EventStr(ArrayOf<Variant> f)
{
var type = TypeName(f[1].GetNodeId());
var msg = f[2].GetLocalizedText().Text;
var cond = f[4].IsNull ? "" : f[4].AsBoxedObject(Variant.BoxingBehavior.Legacy)?.ToString();
return $"type={type} msg=\"{msg}\" cond={cond} retain={f[5].AsBoxedObject(Variant.BoxingBehavior.Legacy)} active={f[6].AsBoxedObject(Variant.BoxingBehavior.Legacy)} acked={f[7].AsBoxedObject(Variant.BoxingBehavior.Legacy)} time={(f[3].IsNull ? "" : ((DateTime)f[3].GetDateTime()).ToString("HH:mm:ss.fff"))}";
}
async Task<uint> AddItem(SessionClient c, uint sub, NodeId node, uint handle, uint queue = 10, MonitoringMode mode = MonitoringMode.Reporting, MonitoringFilter? filter = null, uint attr = Attributes.Value)
{
var r = await c.CreateMonitoredItemsAsync(H(), sub, TimestampsToReturn.Both, new[]
{
new MonitoredItemCreateRequest
{
ItemToMonitor = new ReadValueId { NodeId = node, AttributeId = attr },
MonitoringMode = mode,
RequestedParameters = new MonitoringParameters
{
ClientHandle = handle, SamplingInterval = attr == Attributes.EventNotifier ? 0 : 100, QueueSize = queue, DiscardOldest = true,
Filter = filter is null ? ExtensionObject.Null : new ExtensionObject(filter),
},
},
}, ct);
Console.WriteLine($"{Now()} create item h={handle} {node}: {Sc(r.Results[0].StatusCode)} id={r.Results[0].MonitoredItemId}");
return r.Results[0].MonitoredItemId;
}
static List<string> Lines(NotificationMessage m, IReadOnlyDictionary<uint, string> names)
{
var list = new List<string>();
for (var i = 0; i < m.NotificationData.Count; i++)
{
if (m.NotificationData[i].TryGetValue<DataChangeNotification>(out var d))
for (var j = 0; j < d.MonitoredItems.Count; j++)
list.Add($"data h={d.MonitoredItems[j].ClientHandle}({names.GetValueOrDefault(d.MonitoredItems[j].ClientHandle, "?")}) {Val(d.MonitoredItems[j].Value)}");
else if (m.NotificationData[i].TryGetValue<EventNotificationList>(out var e))
foreach (var ev in e.Events) list.Add($"event h={ev.ClientHandle}({names.GetValueOrDefault(ev.ClientHandle, "?")}) {EventStr(ev.EventFields)}");
else if (m.NotificationData[i].TryGetValue<StatusChangeNotification>(out var s))
list.Add($"status {Sc(s.Status)}");
}
return list;
}
static List<(uint Handle, DataValue Value)> DataChanges(NotificationMessage m)
{
var list = new List<(uint, DataValue)>();
for (var i = 0; i < m.NotificationData.Count; i++)
if (m.NotificationData[i].TryGetValue<DataChangeNotification>(out var d))
for (var j = 0; j < d.MonitoredItems.Count; j++) list.Add((d.MonitoredItems[j].ClientHandle, d.MonitoredItems[j].Value));
return list;
}
async Task<PublishResponse> PublishData(SessionClient c, ArrayOf<SubscriptionAcknowledgement> acks = default)
{
for (var i = 0; i < 40; i++)
{
var r = await c.PublishAsync(H(), acks, ct);
acks = default;
if (r.NotificationMessage.NotificationData.Count > 0) return r;
}
throw new InvalidOperationException("no data message");
}
// Stops the container in the background and returns once this session reads a non-Active ServiceLevel.
async Task<(Process Stop, DateTime Issued, DateTime Demoted, byte Sl)> StopAndWaitForDemotion(ISession s, string container)
{
var issued = DateTime.UtcNow;
var p = Process.Start(new ProcessStartInfo("docker", $"stop -t 60 {container}") { RedirectStandardOutput = true, RedirectStandardError = true })!;
Console.WriteLine($"{Now()} docker stop {container} issued");
while (true)
{
var sl = await ReadSl(s);
if (sl < 200) { var t = DateTime.UtcNow; Console.WriteLine($"{Now()} demoted: ServiceLevel={sl} after {(t - issued).TotalMilliseconds:F0} ms"); return (p, issued, t, sl); }
await Task.Delay(10, ct);
}
}
// ------------------------------------------------------------------ commands
async Task Meta(string u)
{
using var s = await Connect(u, anonymous: true);
Console.WriteLine($"endpoint {s.Endpoint.EndpointUrl} server={s.Endpoint.Server.ApplicationUri}");
foreach (var (name, n) in new[] { ("RedundancySupport i=3709", VariableIds.Server_ServerRedundancy_RedundancySupport),
("ServerUriArray i=11314", VariableIds.Server_ServerRedundancy_ServerUriArray),
("ServiceLevel i=2267", VariableIds.Server_ServiceLevel),
("ServerArray i=2254", VariableIds.Server_ServerArray) })
{
var v = await Read(s, n);
var o = v.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy);
Console.WriteLine($"{name}: {(o is Array a ? "[" + string.Join(", ", a.Cast<object>()) + "]" : o)} [{Sc(v.StatusCode)}]");
}
var b = await ((SessionClient)s).BrowseAsync(H(), null, 0, new[]
{
new BrowseDescription { NodeId = ObjectIds.Server_ServerRedundancy, BrowseDirection = BrowseDirection.Forward,
ReferenceTypeId = ReferenceTypeIds.HasTypeDefinition, IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All },
}, ct);
Console.WriteLine($"ServerRedundancy i=2296 TypeDefinition: {string.Join(",", b.Results[0].References.ToArray()!.Select(r => r.BrowseName.Name + " " + r.NodeId))}");
var w = await ((SessionClient)s).WriteAsync(H(), new[]
{
new WriteValue { NodeId = VariableIds.Server_ServerRedundancy_ServerUriArray, AttributeId = Attributes.Value,
Value = new DataValue(Variant.From(new[] { "urn:x" })) },
}, ct);
Console.WriteLine($"Write ServerUriArray: {Sc(w.Results[0])}");
}
async Task Browse(string u, string node)
{
using var s = await Connect(u, anonymous: true);
var start = node.StartsWith("raw:") ? RawN(s, node[4..]) : node.StartsWith("uns:") ? UnsN(s, node[4..]) : NodeId.Parse(node);
var b = await ((SessionClient)s).BrowseAsync(H(), null, 0, new[]
{
new BrowseDescription { NodeId = start, BrowseDirection = BrowseDirection.Forward, ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences,
IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All },
}, ct);
Console.WriteLine($"browse {start}: {Sc(b.Results[0].StatusCode)}");
foreach (var r in b.Results[0].References.ToArray()!) Console.WriteLine($" {r.BrowseName.Name} {r.NodeId} {r.NodeClass}");
}
async Task Watch(string u, string outFile, bool anonymous)
{
var tag = Path.GetFileNameWithoutExtension(outFile);
await using var w = new StreamWriter(outFile, append: true) { AutoFlush = true };
void Log(string line) { var l = $"{Now()} [{tag}] {line}"; w.WriteLine(l); Console.WriteLine(l); }
var names = new Dictionary<uint, string> { [1] = "SL", [2] = "raw calc-seconds", [3] = "uns calc-seconds", [4] = "uns vt-second", [10] = "ev Server", [11] = "ev equipment" };
while (!ct.IsCancellationRequested)
{
ISession s;
try { s = await Connect(u, anonymous); }
catch (Exception ex) { Log($"connect failed: {ex.GetType().Name} {ex.Message.Split('\n')[0]}"); await Task.Delay(500, ct); continue; }
try
{
Log($"connected session={s.SessionId}; boot read ServiceLevel={await ReadSl(s)}");
var c = (SessionClient)s;
var sub = (await c.CreateSubscriptionAsync(H(), 100, 600, 10, 0, true, 0, ct)).SubscriptionId;
await AddItem(c, sub, VariableIds.Server_ServiceLevel, 1);
await AddItem(c, sub, RawN(s, "t13-calc/Device1/calc-seconds"), 2);
await AddItem(c, sub, UnsN(s, "t13/warm/t13-equipment/calc-seconds"), 3);
await AddItem(c, sub, UnsN(s, $"{Equip}/vt-second"), 4);
await AddItem(c, sub, ObjectIds.Server, 10, 1000, filter: EventFilter(), attr: Attributes.EventNotifier);
await AddItem(c, sub, UnsN(s, Equip), 11, 1000, filter: EventFilter(), attr: Attributes.EventNotifier);
ArrayOf<SubscriptionAcknowledgement> acks = default;
while (!ct.IsCancellationRequested)
{
var r = await c.PublishAsync(H(), acks, ct);
var m = r.NotificationMessage;
acks = m.NotificationData.Count > 0 ? new[] { new SubscriptionAcknowledgement { SubscriptionId = r.SubscriptionId, SequenceNumber = m.SequenceNumber } } : default;
foreach (var line in Lines(m, names)) Log($"seq={m.SequenceNumber} {line}");
}
}
catch (Exception ex) when (!ct.IsCancellationRequested)
{
Log($"session lost: {ex.GetType().Name} {ex.Message.Split('\n')[0]}");
}
finally { try { s.Dispose(); } catch { } }
await Task.Delay(250, CancellationToken.None);
}
}
async Task Probe(string u, bool ack)
{
using var s = await Connect(u);
var c = (SessionClient)s;
Console.WriteLine($"{Now()} probe {u} ServiceLevel={await ReadSl(s)}");
foreach (var (name, n) in new[] { ("raw calc-seconds", RawN(s, "t13-calc/Device1/calc-seconds")), ("uns calc-seconds", UnsN(s, "t13/warm/t13-equipment/calc-seconds")),
("uns vt-second", UnsN(s, $"{Equip}/vt-second")), ("raw calc-writable", RawN(s, "t13-calc/Device1/calc-writable")) })
Console.WriteLine($" read {name}: {Val(await Read(s, n))}");
foreach (var (name, n) in new[] { ("raw calc-writable", RawN(s, "t13-calc/Device1/calc-writable")), ("uns calc-writable", UnsN(s, "t13/warm/t13-equipment/calc-writable")) })
{
var w = await c.WriteAsync(H(), new[] { new WriteValue { NodeId = n, AttributeId = Attributes.Value, Value = new DataValue(Variant.From(7)) } }, ct);
Console.WriteLine($" write {name}=7: {Sc(w.Results[0])}");
}
var hr = await c.HistoryReadAsync(H(), new ExtensionObject(new ReadRawModifiedDetails
{
StartTime = DateTime.UtcNow.AddMinutes(-5), EndTime = DateTime.UtcNow, NumValuesPerNode = 10, ReturnBounds = false,
}), TimestampsToReturn.Both, false, new[] { new HistoryReadValueId { NodeId = RawN(s, "t13-calc/Device1/calc-seconds") } }, ct);
Console.WriteLine($" HistoryRead raw calc-seconds: service={Sc(hr.ResponseHeader.ServiceResult)} result={Sc(hr.Results[0].StatusCode)}");
// ConditionRefresh on a fresh subscription with a Server-object event item.
var sub = (await c.CreateSubscriptionAsync(H(), 100, 600, 10, 0, true, 0, ct)).SubscriptionId;
await AddItem(c, sub, ObjectIds.Server, 10, 1000, filter: EventFilter(), attr: Attributes.EventNotifier);
var names = new Dictionary<uint, string> { [10] = "ev Server" };
await c.PublishAsync(H(), default, ct); // drain anything initial
var refresh = await c.CallAsync(H(), new[] { new CallMethodRequest { ObjectId = ObjectTypeIds.ConditionType, MethodId = MethodIds.ConditionType_ConditionRefresh,
InputArguments = new[] { Variant.From(sub) } } }, ct);
Console.WriteLine($" ConditionRefresh call: {Sc(refresh.Results[0].StatusCode)}");
byte[]? eventId = null; NodeId? condId = null;
var until = DateTime.UtcNow.AddSeconds(3);
ArrayOf<SubscriptionAcknowledgement> acks = default;
while (DateTime.UtcNow < until)
{
var r = await c.PublishAsync(H(), acks, ct);
acks = r.NotificationMessage.NotificationData.Count > 0 ? new[] { new SubscriptionAcknowledgement { SubscriptionId = sub, SequenceNumber = r.NotificationMessage.SequenceNumber } } : default;
foreach (var line in Lines(r.NotificationMessage, names)) Console.WriteLine($" {Now()} {line}");
for (var i = 0; i < r.NotificationMessage.NotificationData.Count; i++)
if (r.NotificationMessage.NotificationData[i].TryGetValue<EventNotificationList>(out var e))
foreach (var ev in e.Events)
if (!ev.EventFields[4].IsNull) { eventId = ev.EventFields[0].GetByteString().ToArray(); condId = ev.EventFields[4].GetNodeId(); }
}
if (condId is not null)
{
foreach (var (mname, method, inArgs) in new (string, NodeId, Variant[])[]
{
("Acknowledge", MethodIds.AcknowledgeableConditionType_Acknowledge, [Variant.From(ByteString.From(eventId!)), Variant.From(new LocalizedText("t13"))]),
("AddComment", MethodIds.ConditionType_AddComment, [Variant.From(ByteString.From(eventId!)), Variant.From(new LocalizedText("t13 note"))]),
})
{
if (mname == "Acknowledge" && !ack) continue;
var call = await c.CallAsync(H(), new[] { new CallMethodRequest { ObjectId = condId.Value, MethodId = method, InputArguments = inArgs } }, ct);
Console.WriteLine($" {mname} on {condId}: {Sc(call.Results[0].StatusCode)}");
}
}
else Console.WriteLine(" no condition seen in refresh");
}
async Task Timing1(string u, string container)
{
using var s = await Connect(u);
var c = (SessionClient)s;
Console.WriteLine($"{Now()} T1 on {u}: ServiceLevel={await ReadSl(s)}");
var sub = (await c.CreateSubscriptionAsync(H(), 50, 600, 10, 0, true, 0, ct)).SubscriptionId;
var tagItem = await AddItem(c, sub, RawN(s, "t13-calc/Device1/calc-seconds"), 1, 10);
await AddItem(c, sub, VariableIds.Server_ServiceLevel, 2, 5);
var first = DataChanges((await PublishData(c)).NotificationMessage);
Console.WriteLine($"{Now()} initial: {string.Join("; ", first.Select(x => $"h{x.Handle} {Val(x.Value)}"))}");
await c.SetPublishingModeAsync(H(), false, new[] { sub }, ct);
await Task.Delay(3500, ct); // ~3 Good samples queue in the item while Active
await c.ModifyMonitoredItemsAsync(H(), sub, TimestampsToReturn.Both, new[]
{
new MonitoredItemModifyRequest { MonitoredItemId = tagItem, RequestedParameters = new MonitoringParameters { ClientHandle = 99, SamplingInterval = 100, QueueSize = 10, DiscardOldest = true } },
}, ct);
Console.WriteLine($"{Now()} publishing disabled 3.5 s, client handle 1 -> 99");
var (stop, _, _, _) = await StopAndWaitForDemotion(s, container);
await c.SetPublishingModeAsync(H(), true, new[] { sub }, ct);
var msg = await PublishData(c);
var changes = DataChanges(msg.NotificationMessage);
foreach (var x in changes) Console.WriteLine($"{Now()} first delivery seq={msg.NotificationMessage.SequenceNumber}: h{x.Handle} {Val(x.Value)}");
var tagChanges = changes.Where(x => x.Handle is 1 or 99).ToList();
var pass1 = tagChanges.Count > 0 && tagChanges.All(x => x.Value.StatusCode == StatusCodes.BadOutOfService && x.Value.WrappedValue.IsNull);
var re = await c.RepublishAsync(H(), sub, msg.NotificationMessage.SequenceNumber, ct);
var reTag = DataChanges(re.NotificationMessage).Where(x => x.Handle is 1 or 99).ToList();
foreach (var x in DataChanges(re.NotificationMessage)) Console.WriteLine($"{Now()} republish seq={msg.NotificationMessage.SequenceNumber}: h{x.Handle} {Val(x.Value)}");
var pass2 = reTag.Count == tagChanges.Count && reTag.All(x => x.Value.StatusCode == StatusCodes.BadOutOfService);
Console.WriteLine($"T1 RESULT first-delivery-projected={pass1} republish-matches={pass2} (queued Good samples={tagChanges.Count})");
await stop.WaitForExitAsync(ct);
Console.WriteLine($"{Now()} docker stop returned");
}
async Task Timing2(string u, string container)
{
using var s = await Connect(u);
var c = (SessionClient)s;
Console.WriteLine($"{Now()} T2 on {u}: ServiceLevel={await ReadSl(s)}");
var sub = (await c.CreateSubscriptionAsync(H(), 50, 600, 10, 1, true, 0, ct)).SubscriptionId; // maxNotificationsPerPublish=1
await AddItem(c, sub, RawN(s, "t13-calc/Device1/calc-seconds"), 1, 10);
Console.WriteLine($"{Now()} initial: {string.Join("; ", DataChanges((await PublishData(c)).NotificationMessage).Select(x => Val(x.Value)))}");
await c.SetPublishingModeAsync(H(), false, new[] { sub }, ct);
await Task.Delay(4500, ct);
await c.SetPublishingModeAsync(H(), true, new[] { sub }, ct);
var a = await PublishData(c);
var aVal = DataChanges(a.NotificationMessage).Single();
Console.WriteLine($"{Now()} a seq={a.NotificationMessage.SequenceNumber} {Val(aVal.Value)} available=[{string.Join(",", a.AvailableSequenceNumbers.ToArray()!)}] more={a.MoreNotifications}");
var (stop, _, _, _) = await StopAndWaitForDemotion(s, container);
var next = a.NotificationMessage.SequenceNumber + 1;
string unsent;
try { await c.RepublishAsync(H(), sub, next, ct); unsent = "Good (unexpected)"; }
catch (ServiceResultException ex) { unsent = Sc(ex.StatusCode); }
Console.WriteLine($"{Now()} Republish(prebuilt never-sent seq={next}): {unsent}");
var b = await PublishData(c);
foreach (var x in DataChanges(b.NotificationMessage)) Console.WriteLine($"{Now()} b seq={b.NotificationMessage.SequenceNumber}: {Val(x.Value)}");
var bProjected = DataChanges(b.NotificationMessage).All(x => x.Value.StatusCode == StatusCodes.BadOutOfService);
var bRe = await c.RepublishAsync(H(), sub, b.NotificationMessage.SequenceNumber, ct);
var bReProjected = DataChanges(bRe.NotificationMessage).All(x => x.Value.StatusCode == StatusCodes.BadOutOfService);
Console.WriteLine($"T2 RESULT a-good={aVal.Value.StatusCode == StatusCodes.Good} unsent-republish={unsent} b-seq-is-next={b.NotificationMessage.SequenceNumber == next} b-projected={bProjected} b-republish-projected={bReProjected}");
await stop.WaitForExitAsync(ct);
Console.WriteLine($"{Now()} docker stop returned");
}
async Task Timing3(string u, string container)
{
using var s = await Connect(u);
var c = (SessionClient)s;
Console.WriteLine($"{Now()} T3 on {u}: ServiceLevel={await ReadSl(s)}");
var sub = (await c.CreateSubscriptionAsync(H(), 50, 600, 10, 0, true, 0, ct)).SubscriptionId;
await AddItem(c, sub, RawN(s, "t13-calc/Device1/calc-seconds"), 1, 10);
var first = await PublishData(c);
foreach (var x in DataChanges(first.NotificationMessage)) Console.WriteLine($"{Now()} first seq={first.NotificationMessage.SequenceNumber}: {Val(x.Value)}");
var firstGood = DataChanges(first.NotificationMessage).All(x => x.Value.StatusCode == StatusCodes.Good);
await c.SetPublishingModeAsync(H(), false, new[] { sub }, ct); // keep later sequence numbers out of the way
var (stop, _, _, _) = await StopAndWaitForDemotion(s, container);
var again = await c.RepublishAsync(H(), sub, first.NotificationMessage.SequenceNumber, ct);
foreach (var x in DataChanges(again.NotificationMessage)) Console.WriteLine($"{Now()} republish after demotion seq={first.NotificationMessage.SequenceNumber}: {Val(x.Value)}");
var againGood = DataChanges(again.NotificationMessage).All(x => x.Value.StatusCode == StatusCodes.Good);
await c.SetPublishingModeAsync(H(), true, new[] { sub }, ct);
var acked = await c.PublishAsync(H(), new[] { new SubscriptionAcknowledgement { SubscriptionId = sub, SequenceNumber = first.NotificationMessage.SequenceNumber } }, ct);
Console.WriteLine($"{Now()} ack seq={first.NotificationMessage.SequenceNumber}: {Sc(acked.Results[0])}");
string after;
try { await c.RepublishAsync(H(), sub, first.NotificationMessage.SequenceNumber, ct); after = "Good (unexpected)"; }
catch (ServiceResultException ex) { after = Sc(ex.StatusCode); }
Console.WriteLine($"T3 RESULT first-good={firstGood} republish-after-demotion-good={againGood} republish-after-ack={after}");
await stop.WaitForExitAsync(ct);
Console.WriteLine($"{Now()} docker stop returned");
}
async Task Transfer(string u, string outFile)
{
var tag = Path.GetFileNameWithoutExtension(outFile);
await using var w = new StreamWriter(outFile, append: true) { AutoFlush = true };
void Log(string line) { var l = $"{Now()} [{tag}] {line}"; w.WriteLine(l); Console.WriteLine(l); }
var names = new Dictionary<uint, string> { [1] = "SL", [2] = "raw calc-seconds", [3] = "uns calc-seconds" };
using var a = await Connect(u);
var ca = (SessionClient)a;
Log($"session A={a.SessionId} ServiceLevel={await ReadSl(a)}");
var sub = (await ca.CreateSubscriptionAsync(H(), 100, 600, 10, 0, true, 0, ct)).SubscriptionId;
await AddItem(ca, sub, VariableIds.Server_ServiceLevel, 1);
await AddItem(ca, sub, RawN(a, "t13-calc/Device1/calc-seconds"), 2);
await AddItem(ca, sub, UnsN(a, "t13/warm/t13-equipment/calc-seconds"), 3);
var pre = await ca.PublishAsync(H(), default, ct);
foreach (var line in Lines(pre.NotificationMessage, names)) Log($"A seq={pre.NotificationMessage.SequenceNumber} {line}");
using var b = await Connect(u);
var cb = (SessionClient)b;
var t = await cb.TransferSubscriptionsAsync(H(), new[] { sub }, true, ct);
Log($"session B={b.SessionId} TransferSubscriptions({sub}, sendInitialValues=true): {Sc(t.Results[0].StatusCode)}");
var aAfter = await ca.PublishAsync(H(), default, ct);
foreach (var line in Lines(aAfter.NotificationMessage, names)) Log($"A after transfer: {line}");
ArrayOf<SubscriptionAcknowledgement> acks = default;
try
{
while (!ct.IsCancellationRequested)
{
var r = await cb.PublishAsync(H(), acks, ct);
var m = r.NotificationMessage;
acks = m.NotificationData.Count > 0 ? new[] { new SubscriptionAcknowledgement { SubscriptionId = r.SubscriptionId, SequenceNumber = m.SequenceNumber } } : default;
foreach (var line in Lines(m, names)) Log($"B seq={m.SequenceNumber} {line}");
}
}
catch (Exception ex) when (!ct.IsCancellationRequested) { Log($"B session lost: {ex.GetType().Name} {ex.Message.Split('\n')[0]}"); }
}