Complete Rust worker command coverage and bridge the alarm provider
This commit is contained in:
@@ -475,6 +475,269 @@ public sealed class WorkerLiveMxAccessSmokeTests(ITestOutputHelper output)
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Exercises bulk operations and both snapshot read paths over gRPC.</summary>
|
||||
/// <returns>A task that represents the live test.</returns>
|
||||
[RustWorkerLiveFact]
|
||||
public async Task GatewayGrpc_WithRustWorker_BulkItemsAndReads()
|
||||
{
|
||||
const string first = "TestMachine_001.TestChangingInt";
|
||||
const string second = "TestMachine_002.TestChangingInt";
|
||||
string workerPath = IntegrationTestEnvironment.ResolveLiveMxAccessWorkerExecutablePath();
|
||||
await using GatewayServiceFixture fixture = new(workerPath, new TestWorkerProcessFactory(output), output);
|
||||
await using WebApplication app = BuildLoopbackGateway(fixture.Service);
|
||||
using CancellationTokenSource deadline = new(TimeSpan.FromSeconds(60));
|
||||
CancellationToken token = deadline.Token;
|
||||
await app.StartAsync(token).ConfigureAwait(false);
|
||||
using GrpcChannel channel = GrpcChannel.ForAddress(app.Urls.Single());
|
||||
MxAccessGateway.MxAccessGatewayClient client = new(channel);
|
||||
OpenSessionReply opened = await client.OpenSessionAsync(new OpenSessionRequest
|
||||
{
|
||||
ClientSessionName = "rust-worker-bulk-items",
|
||||
}, cancellationToken: token).ResponseAsync.ConfigureAwait(false);
|
||||
Assert.Equal(ProtocolStatusCode.Ok, opened.ProtocolStatus.Code);
|
||||
string id = opened.SessionId;
|
||||
|
||||
try
|
||||
{
|
||||
async Task<MxCommandReply> InvokeAsync(MxCommand command)
|
||||
{
|
||||
MxCommandReply reply = await client.InvokeAsync(new MxCommandRequest
|
||||
{
|
||||
SessionId = id, ClientCorrelationId = Guid.NewGuid().ToString("N"), Command = command,
|
||||
}, cancellationToken: token).ResponseAsync.ConfigureAwait(false);
|
||||
Assert.Equal(ProtocolStatusCode.Ok, reply.ProtocolStatus.Code);
|
||||
return reply;
|
||||
}
|
||||
|
||||
int server = (await InvokeAsync(CreateRegisterRequest(id).Command).ConfigureAwait(false)).Register.ServerHandle;
|
||||
MxCommandReply extended = await InvokeAsync(new MxCommand
|
||||
{
|
||||
Kind = MxCommandKind.AddItem2,
|
||||
AddItem2 = new AddItem2Command { ServerHandle = server, ItemDefinition = "TestChangingInt", ItemContext = "TestMachine_003" },
|
||||
}).ConfigureAwait(false);
|
||||
Assert.True(extended.AddItem2.ItemHandle > 0);
|
||||
|
||||
MxCommandReply subscribed = await InvokeAsync(new MxCommand
|
||||
{
|
||||
Kind = MxCommandKind.SubscribeBulk,
|
||||
SubscribeBulk = new SubscribeBulkCommand { ServerHandle = server, TagAddresses = { first } },
|
||||
}).ConfigureAwait(false);
|
||||
SubscribeResult subscription = Assert.Single(subscribed.SubscribeBulk.Results);
|
||||
Assert.True(subscription.WasSuccessful, subscription.ErrorMessage);
|
||||
|
||||
// Observe the permanent advice before checking the worker's value cache.
|
||||
using (AsyncServerStreamingCall<MxEvent> events = client.StreamEvents(
|
||||
new StreamEventsRequest { SessionId = id, EmitStreamAttached = true },
|
||||
cancellationToken: token))
|
||||
{
|
||||
while (await events.ResponseStream.MoveNext(token).ConfigureAwait(false))
|
||||
{
|
||||
MxEvent change = events.ResponseStream.Current;
|
||||
if (change.Family == MxEventFamily.OnDataChange && change.ItemHandle == subscription.ItemHandle)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
MxCommandReply read = await InvokeAsync(new MxCommand
|
||||
{
|
||||
Kind = MxCommandKind.ReadBulk,
|
||||
ReadBulk = new ReadBulkCommand { ServerHandle = server, TimeoutMs = 3000, TagAddresses = { first, second, second } },
|
||||
}).ConfigureAwait(false);
|
||||
Assert.Collection(read.ReadBulk.Results,
|
||||
cached => { Assert.True(cached.WasSuccessful, cached.ErrorMessage); Assert.True(cached.WasCached); },
|
||||
snapshot => { Assert.True(snapshot.WasSuccessful, snapshot.ErrorMessage); Assert.False(snapshot.WasCached); },
|
||||
duplicate =>
|
||||
{
|
||||
Assert.True(duplicate.WasSuccessful, duplicate.ErrorMessage);
|
||||
Assert.False(duplicate.WasCached);
|
||||
Assert.Equal(read.ReadBulk.Results[1].ItemHandle, duplicate.ItemHandle);
|
||||
});
|
||||
|
||||
MxCommandReply added = await InvokeAsync(new MxCommand
|
||||
{
|
||||
Kind = MxCommandKind.AddItemBulk,
|
||||
AddItemBulk = new AddItemBulkCommand { ServerHandle = server, TagAddresses = { second } },
|
||||
}).ConfigureAwait(false);
|
||||
SubscribeResult item = Assert.Single(added.AddItemBulk.Results);
|
||||
Assert.True(item.WasSuccessful, item.ErrorMessage);
|
||||
MxCommandReply advised = await InvokeAsync(new MxCommand
|
||||
{
|
||||
Kind = MxCommandKind.AdviseItemBulk,
|
||||
AdviseItemBulk = new AdviseItemBulkCommand { ServerHandle = server, ItemHandles = { item.ItemHandle } },
|
||||
}).ConfigureAwait(false);
|
||||
Assert.True(Assert.Single(advised.AdviseItemBulk.Results).WasSuccessful);
|
||||
MxCommandReply unadvised = await InvokeAsync(new MxCommand
|
||||
{
|
||||
Kind = MxCommandKind.UnAdviseItemBulk,
|
||||
UnAdviseItemBulk = new UnAdviseItemBulkCommand { ServerHandle = server, ItemHandles = { item.ItemHandle } },
|
||||
}).ConfigureAwait(false);
|
||||
Assert.True(Assert.Single(unadvised.UnAdviseItemBulk.Results).WasSuccessful);
|
||||
MxCommandReply removed = await InvokeAsync(new MxCommand
|
||||
{
|
||||
Kind = MxCommandKind.RemoveItemBulk,
|
||||
RemoveItemBulk = new RemoveItemBulkCommand { ServerHandle = server, ItemHandles = { item.ItemHandle, extended.AddItem2.ItemHandle } },
|
||||
}).ConfigureAwait(false);
|
||||
Assert.All(removed.RemoveItemBulk.Results, result => Assert.True(result.WasSuccessful, result.ErrorMessage));
|
||||
MxCommandReply unsubscribed = await InvokeAsync(new MxCommand
|
||||
{
|
||||
Kind = MxCommandKind.UnsubscribeBulk,
|
||||
UnsubscribeBulk = new UnsubscribeBulkCommand { ServerHandle = server, ItemHandles = { subscription.ItemHandle } },
|
||||
}).ConfigureAwait(false);
|
||||
Assert.True(Assert.Single(unsubscribed.UnsubscribeBulk.Results).WasSuccessful);
|
||||
output.WriteLine("Bulk add, advise, cached and snapshot reads, unadvise, remove, subscribe, and unsubscribe passed.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
Assert.Equal(ProtocolStatusCode.Ok, (await client.CloseSessionAsync(new CloseSessionRequest
|
||||
{
|
||||
SessionId = id,
|
||||
}, deadline: DateTime.UtcNow.AddSeconds(25)).ResponseAsync.ConfigureAwait(false)).ProtocolStatus.Code);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Verifies managed alarm provider callbacks forwarded by the Rust worker.</summary>
|
||||
/// <returns>A task that represents the live test.</returns>
|
||||
[RustWorkerLiveFact]
|
||||
public async Task GatewayGrpc_WithRustWorker_ForwardsAlarmProviderCommandsAndEvents()
|
||||
{
|
||||
const string reference = "Galaxy!DEV.TestMachine_001.RustWorkerSmoke";
|
||||
string workerPath = IntegrationTestEnvironment.ResolveLiveMxAccessWorkerExecutablePath();
|
||||
await using GatewayServiceFixture fixture = new(workerPath, new TestWorkerProcessFactory(output), output);
|
||||
await using WebApplication app = BuildLoopbackGateway(fixture.Service);
|
||||
using CancellationTokenSource deadline = new(TimeSpan.FromSeconds(75));
|
||||
CancellationToken token = deadline.Token;
|
||||
await app.StartAsync(token).ConfigureAwait(false);
|
||||
using GrpcChannel channel = GrpcChannel.ForAddress(app.Urls.Single());
|
||||
MxAccessGateway.MxAccessGatewayClient client = new(channel);
|
||||
OpenSessionReply opened = await client.OpenSessionAsync(new OpenSessionRequest
|
||||
{
|
||||
ClientSessionName = "rust-worker-alarms",
|
||||
}, cancellationToken: token).ResponseAsync.ConfigureAwait(false);
|
||||
Assert.Equal(ProtocolStatusCode.Ok, opened.ProtocolStatus.Code);
|
||||
string id = opened.SessionId;
|
||||
|
||||
try
|
||||
{
|
||||
async Task<MxCommandReply> AlarmAsync(MxCommand command)
|
||||
{
|
||||
WorkerCommandReply envelope = await fixture.Manager.InvokeAsync(id,
|
||||
new WorkerCommand { Command = command }, token).ConfigureAwait(false);
|
||||
Assert.Equal(command.Kind, envelope.Reply.Kind);
|
||||
return envelope.Reply;
|
||||
}
|
||||
|
||||
using AsyncServerStreamingCall<MxEvent> events = client.StreamEvents(
|
||||
new StreamEventsRequest { SessionId = id, EmitStreamAttached = true }, cancellationToken: token);
|
||||
Assert.True(await events.ResponseStream.MoveNext(token).ConfigureAwait(false));
|
||||
Assert.NotNull(events.ResponseStream.Current.StreamAttached);
|
||||
MxCommandReply subscribed = await AlarmAsync(new MxCommand
|
||||
{
|
||||
Kind = MxCommandKind.SubscribeAlarms,
|
||||
SubscribeAlarms = new SubscribeAlarmsCommand
|
||||
{
|
||||
SubscriptionExpression = $@"\\{Environment.MachineName}\Galaxy!DEV",
|
||||
ForcedMode = AlarmProviderMode.Subtag,
|
||||
WatchList = { new AlarmSubtagTarget
|
||||
{
|
||||
AlarmFullReference = reference, SourceObjectReference = "TestMachine_001",
|
||||
ActiveSubtag = "TestMachine_001.TestChangingInt",
|
||||
} },
|
||||
},
|
||||
}).ConfigureAwait(false);
|
||||
Assert.True(subscribed.ProtocolStatus.Code == ProtocolStatusCode.Ok, subscribed.DiagnosticMessage);
|
||||
|
||||
MxEvent? transition = null;
|
||||
while (await events.ResponseStream.MoveNext(token).ConfigureAwait(false))
|
||||
{
|
||||
if (events.ResponseStream.Current.OnAlarmTransition?.AlarmFullReference == reference)
|
||||
{
|
||||
transition = events.ResponseStream.Current;
|
||||
break;
|
||||
}
|
||||
}
|
||||
Assert.NotNull(transition);
|
||||
Assert.Equal(id, transition.SessionId);
|
||||
Assert.True(transition.WorkerSequence > 0);
|
||||
Assert.True(transition.OnAlarmTransition.Degraded);
|
||||
output.WriteLine($"Forwarded {transition.OnAlarmTransition.TransitionKind} at worker sequence {transition.WorkerSequence}.");
|
||||
|
||||
MxCommandReply snapshot = await AlarmAsync(new MxCommand
|
||||
{
|
||||
Kind = MxCommandKind.QueryActiveAlarms,
|
||||
QueryActiveAlarmsCommand = new QueryActiveAlarmsCommand { AlarmFilterPrefix = reference },
|
||||
}).ConfigureAwait(false);
|
||||
Assert.Equal(ProtocolStatusCode.Ok, snapshot.ProtocolStatus.Code);
|
||||
Assert.Contains(snapshot.QueryActiveAlarms.Snapshots, alarm => alarm.AlarmFullReference == reference);
|
||||
MxCommandReply unknownAck = await AlarmAsync(new MxCommand
|
||||
{
|
||||
Kind = MxCommandKind.AcknowledgeAlarm,
|
||||
AcknowledgeAlarmCommand = new AcknowledgeAlarmCommand { AlarmGuid = Guid.NewGuid().ToString() },
|
||||
}).ConfigureAwait(false);
|
||||
Assert.NotNull(unknownAck.AcknowledgeAlarm);
|
||||
Assert.NotEqual(0, unknownAck.AcknowledgeAlarm.NativeStatus);
|
||||
MxCommandReply unknownName = await AlarmAsync(new MxCommand
|
||||
{
|
||||
Kind = MxCommandKind.AcknowledgeAlarmByName,
|
||||
AcknowledgeAlarmByNameCommand = new AcknowledgeAlarmByNameCommand
|
||||
{
|
||||
AlarmName = "RustWorkerMissingAlarm", ProviderName = "Galaxy", GroupName = "DEV",
|
||||
},
|
||||
}).ConfigureAwait(false);
|
||||
Assert.NotNull(unknownName.AcknowledgeAlarm);
|
||||
Assert.NotEqual(0, unknownName.AcknowledgeAlarm.NativeStatus);
|
||||
MxCommandReply update = await AlarmAsync(new MxCommand
|
||||
{
|
||||
Kind = MxCommandKind.UpdateAlarmWatchList,
|
||||
UpdateAlarmWatchList = new UpdateAlarmWatchListCommand(),
|
||||
}).ConfigureAwait(false);
|
||||
Assert.Equal(ProtocolStatusCode.MxaccessFailure, update.ProtocolStatus.Code);
|
||||
MxCommandReply unsubscribed = await AlarmAsync(new MxCommand
|
||||
{
|
||||
Kind = MxCommandKind.UnsubscribeAlarms,
|
||||
UnsubscribeAlarms = new UnsubscribeAlarmsCommand(),
|
||||
}).ConfigureAwait(false);
|
||||
Assert.Equal(ProtocolStatusCode.Ok, unsubscribed.ProtocolStatus.Code);
|
||||
|
||||
MxCommandReply fallback = await AlarmAsync(new MxCommand
|
||||
{
|
||||
Kind = MxCommandKind.SubscribeAlarms,
|
||||
SubscribeAlarms = new SubscribeAlarmsCommand
|
||||
{
|
||||
SubscriptionExpression = $@"\\{Environment.MachineName}\Galaxy!DEV",
|
||||
FallbackEnabled = true,
|
||||
Failover = new AlarmFailoverConfig
|
||||
{
|
||||
ConsecutiveFailureThreshold = 1, FailbackProbeIntervalSeconds = 30, FailbackStableProbes = 3,
|
||||
},
|
||||
},
|
||||
}).ConfigureAwait(false);
|
||||
Assert.True(fallback.ProtocolStatus.Code == ProtocolStatusCode.Ok, fallback.DiagnosticMessage);
|
||||
MxCommandReply replacement = await AlarmAsync(new MxCommand
|
||||
{
|
||||
Kind = MxCommandKind.UpdateAlarmWatchList,
|
||||
UpdateAlarmWatchList = new UpdateAlarmWatchListCommand
|
||||
{
|
||||
WatchList = { new AlarmSubtagTarget
|
||||
{
|
||||
AlarmFullReference = reference, SourceObjectReference = "TestMachine_001",
|
||||
ActiveSubtag = "TestMachine_001.TestChangingInt",
|
||||
} },
|
||||
},
|
||||
}).ConfigureAwait(false);
|
||||
Assert.True(replacement.ProtocolStatus.Code == ProtocolStatusCode.Ok, replacement.DiagnosticMessage);
|
||||
output.WriteLine("Updated the live alarm provider's fallback watch list.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
Assert.Equal(ProtocolStatusCode.Ok, (await client.CloseSessionAsync(new CloseSessionRequest
|
||||
{
|
||||
SessionId = id,
|
||||
}, deadline: DateTime.UtcNow.AddSeconds(25)).ResponseAsync.ConfigureAwait(false)).ProtocolStatus.Code);
|
||||
}
|
||||
}
|
||||
|
||||
private static WebApplication BuildLoopbackGateway(MxAccessGatewayService service)
|
||||
{
|
||||
WebApplicationBuilder builder = WebApplication.CreateSlimBuilder();
|
||||
@@ -2492,6 +2755,7 @@ public sealed class WorkerLiveMxAccessSmokeTests(ITestOutputHelper output)
|
||||
options,
|
||||
_metrics,
|
||||
logger: _loggerFactory.CreateLogger<SessionManager>());
|
||||
Manager = sessionManager;
|
||||
MxAccessGrpcMapper mapper = new();
|
||||
EventStreamService eventStreamService = new(
|
||||
sessionManager,
|
||||
@@ -2520,6 +2784,9 @@ public sealed class WorkerLiveMxAccessSmokeTests(ITestOutputHelper output)
|
||||
/// </summary>
|
||||
public MxAccessGatewayService Service { get; }
|
||||
|
||||
/// <summary>The manager used by the gateway's internal alarm monitor.</summary>
|
||||
public SessionManager Manager { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a session by id directly against the in-process registry. The abnormal
|
||||
/// worker-exit test needs to observe the session's State / FinalFault as the gateway
|
||||
|
||||
Generated
+11
@@ -313,6 +313,16 @@ dependencies = [
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "signal-hook-registry"
|
||||
version = "1.4.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
|
||||
dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "socket2"
|
||||
version = "0.6.5"
|
||||
@@ -368,6 +378,7 @@ dependencies = [
|
||||
"libc",
|
||||
"mio",
|
||||
"pin-project-lite",
|
||||
"signal-hook-registry",
|
||||
"socket2",
|
||||
"tokio-macros",
|
||||
"windows-sys",
|
||||
|
||||
@@ -10,13 +10,16 @@ prost-types = "0.13.5"
|
||||
tokio = { version = "1.48", features = ["io-util"] }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
tokio = { version = "1.48", features = ["macros", "net", "rt", "sync", "time"] }
|
||||
tokio = { version = "1.48", features = ["macros", "net", "process", "rt", "sync", "time"] }
|
||||
windows-sys = { version = "0.61", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_Globalization",
|
||||
"Win32_Security",
|
||||
"Win32_Security_Cryptography",
|
||||
"Win32_System_Com",
|
||||
"Win32_System_JobObjects",
|
||||
"Win32_System_Ole",
|
||||
"Win32_System_Pipes",
|
||||
"Win32_System_Threading",
|
||||
"Win32_System_Time",
|
||||
"Win32_System_Variant",
|
||||
|
||||
@@ -6,9 +6,10 @@ schemas at build time.
|
||||
|
||||
The worker authenticates the launch nonce, negotiates a frame limit, activates
|
||||
LMXProxy on a dedicated message-pumping STA, and reports readiness and heartbeats.
|
||||
It supports Register, Unregister, AddItem, RemoveItem, Advise,
|
||||
AdviseSupervisory, UnAdvise, and the worker diagnostic commands. The worker uses the base MXAccess COM connection
|
||||
point for OnDataChange, OperationComplete, and OnWriteComplete notifications.
|
||||
It supports registration, item lifecycle and advice, value snapshots, identity
|
||||
lookup, writes, and the worker diagnostic commands. The worker attaches to
|
||||
both MXAccess COM connection points to deliver OnDataChange, OperationComplete,
|
||||
OnWriteComplete, and OnBufferedDataChange notifications.
|
||||
OnDataChange carries the value, quality, MXAccess status records, source
|
||||
timestamp when available, and worker sequence and timestamp. The bounded queue
|
||||
faults the session on overflow. Shutdown detaches the sink, unadvises remaining
|
||||
@@ -17,10 +18,15 @@ gateway default.
|
||||
|
||||
Event conversion supports standard Automation scalar values and homogeneous
|
||||
arrays of those types. Other variant types are reported as unknown with the
|
||||
Automation type in the diagnostic. The worker serializes commands and faults
|
||||
the session if a COM call exceeds the STA timeout. Buffered advice, bulk
|
||||
subscriptions, snapshot reads, and alarm commands are outside the current
|
||||
implementation.
|
||||
Automation type in the diagnostic. The worker serializes COM commands, accepts
|
||||
cancellation for commands still waiting, and continues sending events and
|
||||
heartbeats while a command runs. A COM call that exceeds the STA ceiling faults
|
||||
the session.
|
||||
|
||||
Bulk item operations return one ordered result per requested item. ReadBulk
|
||||
uses a cached value for an existing advice when available and otherwise uses
|
||||
temporary advice with a shared timeout. Duplicate snapshot reads share one
|
||||
subscription.
|
||||
|
||||
The worker supports Write, Write2, WriteSecured, and WriteSecured2, including
|
||||
their bulk forms. It converts scalar and typed array inputs to Automation
|
||||
@@ -32,6 +38,27 @@ by MXAccess. The event also flows through StreamEvents. Bulk results report
|
||||
per-item COM acceptance and clients can observe commit outcomes on the event
|
||||
stream.
|
||||
|
||||
## Managed alarm provider
|
||||
|
||||
The Rust process owns the gateway session, native data operations, and event
|
||||
sequencing. Alarm commands run in the existing x86 .NET Framework worker, which
|
||||
owns the WnWrap alarm manager, subtag fallback, watch-list replacement, alarm
|
||||
snapshots, and acknowledgement. The managed process starts on the first alarm
|
||||
command. It connects to a private local pipe whose client PID and launch nonce
|
||||
are checked. A Windows job ties the managed process to the Rust worker's
|
||||
lifetime.
|
||||
|
||||
Build the C# worker with the matching repository revision and deliver its
|
||||
entire output directory under `alarm-worker` beside the Rust executable. Keep
|
||||
the managed executable named `ZB.MOM.WW.MxGateway.Worker.exe`, or set
|
||||
`MXGATEWAY_RUST_ALARM_WORKER_EXE` to its absolute path in the gateway process
|
||||
environment.
|
||||
|
||||
```powershell
|
||||
dotnet build src/ZB.MOM.WW.MxGateway.Worker -c Release -p:Platform=x86
|
||||
```
|
||||
|
||||
|
||||
## Build and test
|
||||
|
||||
From this directory on Windows, with Rust, the x86 MSVC target and linker, and
|
||||
@@ -82,6 +109,14 @@ $env:MXGATEWAY_LIVE_MXACCESS_ITEM = 'TestChildObject.TestInt'
|
||||
dotnet test src/ZB.MOM.WW.MxGateway.IntegrationTests --filter FullyQualifiedName~GatewayGrpc_WithRustWorker_WritesAndReceivesOnWriteComplete
|
||||
```
|
||||
|
||||
The remaining parity smoke tests use the deployed `TestChangingInt` items
|
||||
for bulk snapshots and a read-only, synthetic subtag alarm. Set the absolute
|
||||
managed worker path before running the alarm test.
|
||||
|
||||
```powershell
|
||||
dotnet test src/ZB.MOM.WW.MxGateway.IntegrationTests --filter 'FullyQualifiedName~GatewayGrpc_WithRustWorker_BulkItemsAndReads|FullyQualifiedName~GatewayGrpc_WithRustWorker_ForwardsAlarmProviderCommandsAndEvents'
|
||||
```
|
||||
|
||||
## COM interface evidence
|
||||
|
||||
The native adapter uses the dual `ILMXProxyServer` interface from the installed
|
||||
@@ -100,3 +135,5 @@ the corresponding native calls and event callbacks.
|
||||
`ev_97162abcd831b2d84b5b43fb72cd9876252bbe3bb0af5c4673a6954911500e54`
|
||||
- REA write member evidence for `ILMXProxyServer` and `ILMXProxyServer4`
|
||||
`ev_1b4fe7ab436437391b76f9fa3a300f45b58a4e1cff6aa84e30854f653c0a20df`
|
||||
- REA extended COM and buffered event member evidence
|
||||
`ev_39de39d626e3a933b259fa2650b42311ba60d6844d7b012284467284e8b82977`
|
||||
|
||||
@@ -0,0 +1,340 @@
|
||||
//! The existing managed alarm provider owns WnWrap, fallback subscriptions, and
|
||||
//! acknowledgement. This bridge carries its alarm RPCs and callbacks over the
|
||||
//! worker protocol while the Rust process owns the gateway session and sequencing.
|
||||
|
||||
use std::io;
|
||||
use std::mem::size_of;
|
||||
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
|
||||
use std::path::PathBuf;
|
||||
use std::ptr::{null, null_mut};
|
||||
use std::sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc,
|
||||
};
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::io::{split, WriteHalf};
|
||||
use tokio::net::windows::named_pipe::{NamedPipeServer, ServerOptions};
|
||||
use tokio::process::{Child, Command};
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio::time::timeout;
|
||||
use windows_sys::Win32::Security::Cryptography::{
|
||||
BCryptGenRandom, BCRYPT_USE_SYSTEM_PREFERRED_RNG,
|
||||
};
|
||||
use windows_sys::Win32::System::JobObjects::{
|
||||
AssignProcessToJobObject, CreateJobObjectW, JobObjectExtendedLimitInformation,
|
||||
SetInformationJobObject, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
|
||||
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
|
||||
};
|
||||
use windows_sys::Win32::System::Pipes::GetNamedPipeClientProcessId;
|
||||
|
||||
use crate::mxevent::{EventFault, Publisher};
|
||||
use crate::wire::{
|
||||
self,
|
||||
mxaccess_gateway::v1::{
|
||||
MxCommand, MxCommandKind, MxCommandReply, MxEventFamily, ProtocolStatusCode,
|
||||
},
|
||||
mxaccess_worker::v1::{GatewayHello, WorkerCommand, WorkerShutdown},
|
||||
Body, WorkerEnvelope, Writer, DEFAULT_MAX, VERSION,
|
||||
};
|
||||
|
||||
const ALARM_WORKER_ENV: &str = "MXGATEWAY_RUST_ALARM_WORKER_EXE";
|
||||
|
||||
pub fn handles(kind: MxCommandKind) -> bool {
|
||||
matches!(
|
||||
kind,
|
||||
MxCommandKind::SubscribeAlarms
|
||||
| MxCommandKind::UnsubscribeAlarms
|
||||
| MxCommandKind::UpdateAlarmWatchList
|
||||
| MxCommandKind::QueryActiveAlarms
|
||||
| MxCommandKind::AcknowledgeAlarm
|
||||
| MxCommandKind::AcknowledgeAlarmByName
|
||||
)
|
||||
}
|
||||
|
||||
pub struct AlarmWorker {
|
||||
child: Child,
|
||||
_job: OwnedHandle,
|
||||
writer: Writer<WriteHalf<NamedPipeServer>>,
|
||||
replies: mpsc::Receiver<WorkerEnvelope>,
|
||||
reader: JoinHandle<()>,
|
||||
shutting_down: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl AlarmWorker {
|
||||
pub async fn start(session: &str, max: usize, publisher: Publisher) -> io::Result<Self> {
|
||||
let executable = alarm_executable()?;
|
||||
let pipe_name = format!("mxgw-rust-alarm-{}", random_token()?);
|
||||
let nonce = random_token()?;
|
||||
let pipe = ServerOptions::new()
|
||||
.first_pipe_instance(true)
|
||||
.reject_remote_clients(true)
|
||||
.create(format!(r"\\.\pipe\{pipe_name}"))?;
|
||||
let job = kill_on_close_job()?;
|
||||
let mut command = Command::new(&executable);
|
||||
if let Some(directory) = executable.parent() {
|
||||
command.current_dir(directory);
|
||||
}
|
||||
let child = command
|
||||
.args([
|
||||
"--session-id",
|
||||
session,
|
||||
"--pipe-name",
|
||||
&pipe_name,
|
||||
"--protocol-version",
|
||||
"1",
|
||||
])
|
||||
.env("MXGATEWAY_WORKER_NONCE", &nonce)
|
||||
.kill_on_drop(true)
|
||||
.spawn()?;
|
||||
let pid = child.id().ok_or_else(disconnected)?;
|
||||
let child_handle = child.raw_handle().ok_or_else(disconnected)?;
|
||||
// SAFETY: both handles remain live and the new job is owned by this worker.
|
||||
if unsafe { AssignProcessToJobObject(job.as_raw_handle(), child_handle) } == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
|
||||
let (mut reader, writer) = timeout(Duration::from_secs(15), async {
|
||||
pipe.connect().await?;
|
||||
let mut connected_pid = 0;
|
||||
if unsafe { GetNamedPipeClientProcessId(pipe.as_raw_handle(), &mut connected_pid) } == 0
|
||||
{
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
if connected_pid != pid {
|
||||
return Err(invalid(
|
||||
"Unexpected process connected to the alarm worker pipe",
|
||||
));
|
||||
}
|
||||
let (mut reader, writer) = split(pipe);
|
||||
let mut writer = Writer::new(writer);
|
||||
writer
|
||||
.send(
|
||||
session,
|
||||
"",
|
||||
Body::GatewayHello(GatewayHello {
|
||||
supported_protocol_version: VERSION,
|
||||
nonce: nonce.clone(),
|
||||
max_frame_bytes: max as u32,
|
||||
gateway_version: env!("CARGO_PKG_VERSION").into(),
|
||||
}),
|
||||
DEFAULT_MAX,
|
||||
)
|
||||
.await?;
|
||||
let hello = wire::read(&mut reader, session, DEFAULT_MAX).await?;
|
||||
match hello.body {
|
||||
Some(Body::WorkerHello(hello))
|
||||
if hello.protocol_version == VERSION
|
||||
&& hello.worker_process_id == pid as i32
|
||||
&& hello.nonce == nonce => {}
|
||||
_ => return Err(invalid("Alarm worker handshake failed")),
|
||||
}
|
||||
let ready = wire::read(&mut reader, session, max).await?;
|
||||
match ready.body {
|
||||
Some(Body::WorkerReady(ready)) if ready.worker_process_id == pid as i32 => {
|
||||
Ok((reader, writer))
|
||||
}
|
||||
_ => Err(invalid("Managed alarm worker failed to initialize")),
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "Alarm worker startup timed out"))??;
|
||||
|
||||
let (incoming, replies) = mpsc::channel(1);
|
||||
let reader_session = session.to_owned();
|
||||
let shutting_down = Arc::new(AtomicBool::new(false));
|
||||
let closing = Arc::clone(&shutting_down);
|
||||
let reader = tokio::spawn(async move {
|
||||
while let Ok(frame) = wire::read(&mut reader, &reader_session, max).await {
|
||||
match frame.body.as_ref() {
|
||||
Some(Body::WorkerEvent(event)) => {
|
||||
if let Some(event) = event.event.as_ref() {
|
||||
if matches!(
|
||||
event.family(),
|
||||
MxEventFamily::OnAlarmTransition
|
||||
| MxEventFamily::OnAlarmProviderModeChanged
|
||||
) {
|
||||
publisher.publish(event.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(Body::WorkerHeartbeat(_)) => {}
|
||||
Some(Body::WorkerCommandReply(_) | Body::WorkerShutdownAck(_)) => {
|
||||
if incoming.send(frame).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
if !closing.load(Ordering::Acquire) {
|
||||
publisher.report_fault(EventFault::AlarmDisconnected);
|
||||
}
|
||||
});
|
||||
Ok(Self {
|
||||
child,
|
||||
_job: job,
|
||||
writer,
|
||||
replies,
|
||||
reader,
|
||||
shutting_down,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn invoke(
|
||||
&mut self,
|
||||
session: &str,
|
||||
max: usize,
|
||||
correlation: &str,
|
||||
command: MxCommand,
|
||||
) -> io::Result<MxCommandReply> {
|
||||
let kind = command.kind;
|
||||
self.writer
|
||||
.send(
|
||||
session,
|
||||
correlation,
|
||||
Body::WorkerCommand(WorkerCommand {
|
||||
command: Some(command),
|
||||
enqueue_timestamp: Some(std::time::SystemTime::now().into()),
|
||||
}),
|
||||
max,
|
||||
)
|
||||
.await?;
|
||||
let frame = self.replies.recv().await.ok_or_else(disconnected)?;
|
||||
match frame.body {
|
||||
Some(Body::WorkerCommandReply(response)) if frame.correlation_id == correlation => {
|
||||
response
|
||||
.reply
|
||||
.filter(|reply| {
|
||||
reply.session_id == session
|
||||
&& reply.correlation_id == correlation
|
||||
&& reply.kind == kind
|
||||
})
|
||||
.ok_or_else(|| invalid("Alarm worker reply did not match the request"))
|
||||
}
|
||||
_ => Err(invalid("Alarm worker sent an unexpected response")),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn shutdown(
|
||||
mut self,
|
||||
session: &str,
|
||||
max: usize,
|
||||
grace: Duration,
|
||||
) -> io::Result<usize> {
|
||||
self.shutting_down.store(true, Ordering::Release);
|
||||
self.writer
|
||||
.send(
|
||||
session,
|
||||
"",
|
||||
Body::WorkerShutdown(WorkerShutdown {
|
||||
grace_period: prost_types::Duration::try_from(grace).ok(),
|
||||
reason: String::new(),
|
||||
}),
|
||||
max,
|
||||
)
|
||||
.await?;
|
||||
let mut failures = match self.replies.recv().await.and_then(|frame| frame.body) {
|
||||
Some(Body::WorkerShutdownAck(ack))
|
||||
if ack
|
||||
.status
|
||||
.as_ref()
|
||||
.is_some_and(|status| status.code() == ProtocolStatusCode::Ok) =>
|
||||
{
|
||||
0
|
||||
}
|
||||
_ => 1,
|
||||
};
|
||||
if !self.child.wait().await?.success() {
|
||||
failures += 1;
|
||||
}
|
||||
Ok(failures)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for AlarmWorker {
|
||||
fn drop(&mut self) {
|
||||
self.shutting_down.store(true, Ordering::Release);
|
||||
self.reader.abort();
|
||||
}
|
||||
}
|
||||
|
||||
fn alarm_executable() -> io::Result<PathBuf> {
|
||||
let current = std::env::current_exe()?.canonicalize()?;
|
||||
let path = match std::env::var_os(ALARM_WORKER_ENV) {
|
||||
Some(value) => {
|
||||
let path = PathBuf::from(value);
|
||||
if !path.is_absolute() {
|
||||
return Err(invalid("Configured alarm worker path must be absolute"));
|
||||
}
|
||||
path
|
||||
}
|
||||
None => current
|
||||
.with_file_name("alarm-worker")
|
||||
.join("ZB.MOM.WW.MxGateway.Worker.exe"),
|
||||
};
|
||||
let path = path.canonicalize().map_err(|_| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::NotFound,
|
||||
"Managed alarm worker executable was not found",
|
||||
)
|
||||
})?;
|
||||
if path == current || !path.is_file() {
|
||||
return Err(invalid("Managed alarm worker path is invalid"));
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
fn random_token() -> io::Result<String> {
|
||||
let mut bytes = [0_u8; 24];
|
||||
// SAFETY: BCrypt writes exactly the declared length to the local buffer.
|
||||
if unsafe {
|
||||
BCryptGenRandom(
|
||||
null_mut(),
|
||||
bytes.as_mut_ptr(),
|
||||
bytes.len() as u32,
|
||||
BCRYPT_USE_SYSTEM_PREFERRED_RNG,
|
||||
)
|
||||
} < 0
|
||||
{
|
||||
return Err(io::Error::other(
|
||||
"Could not generate an alarm worker handshake token",
|
||||
));
|
||||
}
|
||||
Ok(bytes.iter().map(|byte| format!("{byte:02x}")).collect())
|
||||
}
|
||||
|
||||
fn kill_on_close_job() -> io::Result<OwnedHandle> {
|
||||
// SAFETY: ownership of the unnamed job transfers to OwnedHandle.
|
||||
let handle = unsafe { CreateJobObjectW(null(), null()) };
|
||||
if handle.is_null() {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let handle = unsafe { OwnedHandle::from_raw_handle(handle) };
|
||||
let mut limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
|
||||
limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
|
||||
if unsafe {
|
||||
SetInformationJobObject(
|
||||
handle.as_raw_handle(),
|
||||
JobObjectExtendedLimitInformation,
|
||||
(&limits as *const JOBOBJECT_EXTENDED_LIMIT_INFORMATION).cast(),
|
||||
size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(handle)
|
||||
}
|
||||
|
||||
fn invalid(message: &'static str) -> io::Error {
|
||||
io::Error::new(io::ErrorKind::InvalidData, message)
|
||||
}
|
||||
|
||||
fn disconnected() -> io::Error {
|
||||
io::Error::new(
|
||||
io::ErrorKind::BrokenPipe,
|
||||
"Managed alarm worker disconnected",
|
||||
)
|
||||
}
|
||||
@@ -660,13 +660,163 @@ fn file_time_timestamp(ticks: i64) -> Option<Timestamp> {
|
||||
|
||||
// Installed MXSTATUS_PROXY 3.2: 16 bytes with members at offsets 0, 4, 8, 12.
|
||||
#[repr(C)]
|
||||
struct StatusRecord {
|
||||
#[derive(Default)]
|
||||
pub struct StatusRecord {
|
||||
success: i16,
|
||||
category: i32,
|
||||
source: i32,
|
||||
detail: i16,
|
||||
}
|
||||
|
||||
impl StatusRecord {
|
||||
pub fn to_proto(&self) -> MxStatusProxy {
|
||||
MxStatusProxy {
|
||||
success: self.success.into(),
|
||||
category: match self.category {
|
||||
0..=8 => self.category + 2,
|
||||
_ => MxStatusCategory::Unknown as i32,
|
||||
},
|
||||
detected_by: match self.source {
|
||||
0..=5 => self.source + 2,
|
||||
_ => MxStatusSource::Unknown as i32,
|
||||
},
|
||||
detail: self.detail.into(),
|
||||
raw_category: self.category,
|
||||
raw_detected_by: self.source,
|
||||
diagnostic_text: status_detail(self.detail).into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MXAccess completion detail codes, shared with the managed converter.
|
||||
fn status_detail(detail: i16) -> &'static str {
|
||||
match detail {
|
||||
16 => "Request timed out",
|
||||
17 => "Platform communication error",
|
||||
18 => "Invalid platform ID",
|
||||
19 => "Invalid engine ID",
|
||||
20 => "Engine communication error",
|
||||
21 => "Invalid reference",
|
||||
22 => "No Galaxy Repository",
|
||||
23 => "Invalid object ID",
|
||||
24 => "Object signature mismatch",
|
||||
25 => "Invalid primitive ID",
|
||||
26 => "Invalid attribute ID",
|
||||
27 => "Invalid property ID",
|
||||
28 => "Index out of range",
|
||||
29 => "Data out of range",
|
||||
30 => "Incorrect data type",
|
||||
31 => "Attribute not readable",
|
||||
32 => "Attribute not writeable",
|
||||
33 => "Write access denied",
|
||||
34 => "Unknown error",
|
||||
36 => "Wrong data type",
|
||||
37 => "Wrong number of dimensions",
|
||||
38 => "Invalid index",
|
||||
39 => "Index out of order",
|
||||
40 => "Dimension does not exist",
|
||||
41 => "Conversion not supported",
|
||||
42 => "Unable to convert string",
|
||||
43 => "Overflow",
|
||||
44 => "Attribute signature mismatch",
|
||||
47 => "Nmx version mismatch",
|
||||
48 => "Nmx command not valid",
|
||||
49 => "Lmx version mismatch",
|
||||
50 => "Lmx command not valid",
|
||||
56 => "Secured Write",
|
||||
57 => "Verified Write",
|
||||
60 => "User did not have the necessary permissions to write",
|
||||
61 => "Verifier did not have the necessary permissions to verify",
|
||||
541 => "Conversion to intended data type is not supported",
|
||||
542 => "Unable to convert the input string to intended data type",
|
||||
8017 => "Object must be offscan to modify attributes that have an MxSecurityConfigure security classification",
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn native_data_type(raw: i32) -> i32 {
|
||||
match raw {
|
||||
0..=17 => raw + 2,
|
||||
_ => MxDataType::Unknown as i32,
|
||||
}
|
||||
}
|
||||
|
||||
pub unsafe fn buffered_array(value: &VARIANT, expected: MxDataType) -> MxArray {
|
||||
// Buffered timestamp arrays can carry signed 64-bit Windows FILETIME values.
|
||||
let converted = unsafe { dispatch_value(value) };
|
||||
let kind = converted.kind;
|
||||
if let Some(Kind::ArrayValue(mut array)) = kind {
|
||||
if expected == MxDataType::Time {
|
||||
if let Some(Values::Int64Values(ticks)) = &array.values {
|
||||
if let Some(timestamps) = ticks
|
||||
.values
|
||||
.iter()
|
||||
.copied()
|
||||
.map(file_time_timestamp)
|
||||
.collect::<Option<Vec<_>>>()
|
||||
{
|
||||
array.element_data_type = expected as i32;
|
||||
array.values = Some(Values::TimestampValues(TimestampArray {
|
||||
values: timestamps,
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
return array;
|
||||
}
|
||||
let values = match kind {
|
||||
Some(Kind::BoolValue(value)) => Some(Values::BoolValues(BoolArray {
|
||||
values: vec![value],
|
||||
})),
|
||||
Some(Kind::Int32Value(value)) => Some(Values::Int32Values(Int32Array {
|
||||
values: vec![value],
|
||||
})),
|
||||
Some(Kind::Int64Value(value)) if expected == MxDataType::Time => file_time_timestamp(value)
|
||||
.map(|value| {
|
||||
Values::TimestampValues(TimestampArray {
|
||||
values: vec![value],
|
||||
})
|
||||
}),
|
||||
Some(Kind::Int64Value(value)) => Some(Values::Int64Values(Int64Array {
|
||||
values: vec![value],
|
||||
})),
|
||||
Some(Kind::FloatValue(value)) => Some(Values::FloatValues(FloatArray {
|
||||
values: vec![value],
|
||||
})),
|
||||
Some(Kind::DoubleValue(value)) => Some(Values::DoubleValues(DoubleArray {
|
||||
values: vec![value],
|
||||
})),
|
||||
Some(Kind::StringValue(value)) => Some(Values::StringValues(StringArray {
|
||||
values: vec![value],
|
||||
})),
|
||||
Some(Kind::TimestampValue(value)) => Some(Values::TimestampValues(TimestampArray {
|
||||
values: vec![value],
|
||||
})),
|
||||
_ => None,
|
||||
};
|
||||
let element_data_type = if matches!(values, Some(Values::TimestampValues(_))) {
|
||||
MxDataType::Time as i32
|
||||
} else {
|
||||
converted.data_type
|
||||
};
|
||||
MxArray {
|
||||
element_data_type,
|
||||
variant_type: converted.variant_type,
|
||||
dimensions: if values.is_some() {
|
||||
vec![1]
|
||||
} else {
|
||||
Vec::new()
|
||||
},
|
||||
raw_diagnostic: if converted.raw_diagnostic.is_empty() {
|
||||
"Buffered MXAccess event argument was not a SAFEARRAY.".into()
|
||||
} else {
|
||||
converted.raw_diagnostic
|
||||
},
|
||||
values,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub unsafe fn dispatch_statuses(value: &VARIANT) -> Result<Vec<MxStatusProxy>, &'static str> {
|
||||
let value = unsafe { unwrap_variant(*value) }.ok_or("null status VARIANT")?;
|
||||
let inner = unsafe { &value.Anonymous.Anonymous };
|
||||
@@ -706,24 +856,7 @@ unsafe fn read_status_records(array: *const SAFEARRAY) -> Result<Vec<MxStatusPro
|
||||
} else {
|
||||
// SAFETY: the checked one-dimensional record array remains locked while copied.
|
||||
let records = unsafe { slice::from_raw_parts(data.cast::<StatusRecord>(), count) };
|
||||
Ok(records
|
||||
.iter()
|
||||
.map(|record| MxStatusProxy {
|
||||
success: record.success.into(),
|
||||
category: match record.category {
|
||||
0..=8 => record.category + 2,
|
||||
_ => MxStatusCategory::Unknown as i32,
|
||||
},
|
||||
detected_by: match record.source {
|
||||
0..=5 => record.source + 2,
|
||||
_ => MxStatusSource::Unknown as i32,
|
||||
},
|
||||
detail: record.detail.into(),
|
||||
raw_category: record.category,
|
||||
raw_detected_by: record.source,
|
||||
..Default::default()
|
||||
})
|
||||
.collect())
|
||||
Ok(records.iter().map(StatusRecord::to_proto).collect())
|
||||
};
|
||||
unsafe { SafeArrayUnaccessData(array) };
|
||||
result
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
#[cfg(all(windows, not(target_arch = "x86")))]
|
||||
compile_error!("The MXAccess COM server requires a 32-bit x86 Windows worker.");
|
||||
|
||||
#[cfg(all(windows, target_arch = "x86"))]
|
||||
mod alarm;
|
||||
#[cfg(all(windows, target_arch = "x86"))]
|
||||
mod automation;
|
||||
#[cfg(all(windows, target_arch = "x86"))]
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
use crate::automation::{AutomationString, WriteValue, WriteValueError};
|
||||
use crate::automation::{AutomationString, StatusRecord, WriteValue, WriteValueError};
|
||||
use crate::mxevent::{ComReference, Connection, Publisher, RecordInfoPin, WriteCompletion};
|
||||
use crate::wire::mxaccess_gateway::v1::{BulkWriteResult, MxValue};
|
||||
use std::collections::BTreeSet;
|
||||
use crate::wire::mxaccess_gateway::v1::{
|
||||
BulkReadResult, BulkWriteResult, MxStatusProxy, MxValue, SubscribeResult,
|
||||
};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::time::Duration;
|
||||
mod items;
|
||||
use std::ffi::c_void;
|
||||
use std::io;
|
||||
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
|
||||
@@ -10,7 +14,7 @@ use std::sync::{mpsc, Arc};
|
||||
use std::thread;
|
||||
use tokio::sync::oneshot;
|
||||
use windows_sys::core::{BSTR, GUID, HRESULT};
|
||||
use windows_sys::Win32::Foundation::WAIT_OBJECT_0;
|
||||
use windows_sys::Win32::Foundation::{E_INVALIDARG, WAIT_OBJECT_0};
|
||||
use windows_sys::Win32::System::Com::{
|
||||
CoCreateInstance, CoInitializeEx, CoUninitialize, CLSCTX_INPROC_SERVER,
|
||||
COINIT_APARTMENTTHREADED,
|
||||
@@ -26,6 +30,9 @@ pub const PROG_ID: &str = "LMXProxy.LMXProxyServer.1";
|
||||
pub const CLASS_ID: &str = "{C30B52F5-2CB5-4760-AF0A-3A344A7EB5DC}";
|
||||
const CLSID: GUID = GUID::from_u128(0xc30b52f5_2cb5_4760_af0a_3a344a7eb5dc);
|
||||
const IID: GUID = GUID::from_u128(0xcce67fb7_eafd_4367_9212_617043bf126d);
|
||||
const IID_V2: GUID = GUID::from_u128(0x020a8a87_69c5_497f_a893_b629e669fbff);
|
||||
const IID_V3: GUID = GUID::from_u128(0x57d006b6_f25e_4654_a81e_bcbafd60fe59);
|
||||
const IID_V5: GUID = GUID::from_u128(0xeceff506_a752_46e3_9e31_0a8e257c9926);
|
||||
const IID_V4: GUID = GUID::from_u128(0x9dc0d5c1_9371_4e84_86f8_7091d316a66c);
|
||||
|
||||
pub enum Command {
|
||||
@@ -33,6 +40,23 @@ pub enum Command {
|
||||
Register(String),
|
||||
Unregister(i32),
|
||||
AddItem(i32, String),
|
||||
AddWithContext {
|
||||
server: i32,
|
||||
definition: String,
|
||||
context: String,
|
||||
buffered: bool,
|
||||
},
|
||||
SetBufferedInterval(i32, i32),
|
||||
Activation {
|
||||
server: i32,
|
||||
item: i32,
|
||||
active: bool,
|
||||
},
|
||||
Authenticate(i32, String, String),
|
||||
UserToId(i32, String),
|
||||
SubscribeBulk(i32, Vec<String>, bool),
|
||||
ItemBulk(i32, Vec<i32>, ItemOperation),
|
||||
ReadBulk(i32, Vec<String>, Duration),
|
||||
RemoveItem(i32, i32),
|
||||
Advise {
|
||||
server: i32,
|
||||
@@ -44,6 +68,14 @@ pub enum Command {
|
||||
UnAdvise(i32, i32),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum ItemOperation {
|
||||
Advise,
|
||||
UnAdvise,
|
||||
Remove,
|
||||
Unsubscribe,
|
||||
}
|
||||
|
||||
pub enum WriteAccess {
|
||||
Plain(i32),
|
||||
Secured { current_user: i32, verifier: i32 },
|
||||
@@ -75,6 +107,9 @@ impl From<WriteValueError> for CommandError {
|
||||
pub enum CommandResult {
|
||||
Done,
|
||||
Handle(i32),
|
||||
Status(MxStatusProxy),
|
||||
SubscribeBulk(Vec<SubscribeResult>),
|
||||
ReadBulk(Vec<BulkReadResult>),
|
||||
Write(WriteCompletion),
|
||||
WriteBulk(Vec<BulkWriteResult>),
|
||||
}
|
||||
@@ -278,27 +313,45 @@ struct ProxyVtable {
|
||||
unadvise: unsafe extern "system" fn(*mut c_void, i32, i32) -> HRESULT,
|
||||
write: unsafe extern "system" fn(*mut c_void, i32, i32, VARIANT, i32) -> HRESULT,
|
||||
write_secured: unsafe extern "system" fn(*mut c_void, i32, i32, i32, i32, VARIANT) -> HRESULT,
|
||||
authenticate_user: usize,
|
||||
authenticate_user: unsafe extern "system" fn(*mut c_void, i32, BSTR, BSTR, *mut i32) -> HRESULT,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct ProxyV2Vtable {
|
||||
base: ProxyVtable,
|
||||
archestra_user_to_id: unsafe extern "system" fn(*mut c_void, i32, BSTR, *mut i32) -> HRESULT,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct ProxyV3Vtable {
|
||||
base: ProxyV2Vtable,
|
||||
add_item2: unsafe extern "system" fn(*mut c_void, i32, BSTR, BSTR, *mut i32) -> HRESULT,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct ProxyV4Vtable {
|
||||
base: ProxyVtable,
|
||||
archestra_user_to_id: usize,
|
||||
add_item2: usize,
|
||||
base: ProxyV3Vtable,
|
||||
write2: unsafe extern "system" fn(*mut c_void, i32, i32, VARIANT, VARIANT, i32) -> HRESULT,
|
||||
write_secured2:
|
||||
unsafe extern "system" fn(*mut c_void, i32, i32, i32, i32, VARIANT, VARIANT) -> HRESULT,
|
||||
suspend: usize,
|
||||
activate: usize,
|
||||
suspend: unsafe extern "system" fn(*mut c_void, i32, i32, *mut StatusRecord) -> HRESULT,
|
||||
activate: unsafe extern "system" fn(*mut c_void, i32, i32, *mut StatusRecord) -> HRESULT,
|
||||
advise_supervisory: unsafe extern "system" fn(*mut c_void, i32, i32) -> HRESULT,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct ProxyV5Vtable {
|
||||
base: ProxyV4Vtable,
|
||||
add_buffered_item: unsafe extern "system" fn(*mut c_void, i32, BSTR, BSTR, *mut i32) -> HRESULT,
|
||||
set_buffered_update_interval: unsafe extern "system" fn(*mut c_void, i32, i32) -> HRESULT,
|
||||
}
|
||||
|
||||
struct Proxy {
|
||||
interface: NonNull<c_void>,
|
||||
registrations: BTreeSet<i32>,
|
||||
publisher: Publisher,
|
||||
connection: Option<Connection>,
|
||||
connections: Vec<Connection>,
|
||||
items: BTreeMap<(i32, i32), String>,
|
||||
}
|
||||
|
||||
impl Proxy {
|
||||
@@ -318,10 +371,15 @@ impl Proxy {
|
||||
interface: NonNull::new(interface).ok_or(0x8000_4003_u32 as i32)?,
|
||||
registrations: BTreeSet::new(),
|
||||
publisher,
|
||||
connection: None,
|
||||
connections: Vec::new(),
|
||||
items: BTreeMap::new(),
|
||||
};
|
||||
// SAFETY: this STA owns the live proxy and its connection point.
|
||||
proxy.connection = Some(unsafe { Connection::attach(interface, proxy.publisher.clone()) }?);
|
||||
for buffered in [false, true] {
|
||||
proxy
|
||||
.connections
|
||||
.push(unsafe { Connection::attach(interface, proxy.publisher.clone(), buffered) }?);
|
||||
}
|
||||
Ok(proxy)
|
||||
}
|
||||
|
||||
@@ -354,23 +412,137 @@ impl Proxy {
|
||||
.map_err(CommandError::HResult)?;
|
||||
self.registrations.remove(&server);
|
||||
self.publisher.unregister(server);
|
||||
self.items.retain(|(handle, _), _| *handle != server);
|
||||
Ok(CommandResult::Done)
|
||||
}
|
||||
Command::AddItem(server, definition) => {
|
||||
Command::AddItem(server, definition_text) => {
|
||||
self.require_registration(server)?;
|
||||
let definition =
|
||||
AutomationString::new(&definition).map_err(CommandError::HResult)?;
|
||||
AutomationString::new(&definition_text).map_err(CommandError::HResult)?;
|
||||
check(unsafe {
|
||||
(table.add_item)(object, server, definition.as_raw(), &mut handle)
|
||||
})
|
||||
.map_err(CommandError::HResult)?;
|
||||
self.items.insert((server, handle), definition_text);
|
||||
Ok(CommandResult::Handle(handle))
|
||||
}
|
||||
Command::AddWithContext {
|
||||
server,
|
||||
definition,
|
||||
context,
|
||||
buffered,
|
||||
} => {
|
||||
self.require_registration(server)?;
|
||||
let item = AutomationString::new(&definition).map_err(CommandError::HResult)?;
|
||||
let context_value =
|
||||
AutomationString::new(&context).map_err(CommandError::HResult)?;
|
||||
let status = if buffered {
|
||||
let extended = self.query(&IID_V5).map_err(CommandError::HResult)?;
|
||||
unsafe {
|
||||
(interface_table::<ProxyV5Vtable>(&extended).add_buffered_item)(
|
||||
extended.as_ptr(),
|
||||
server,
|
||||
item.as_raw(),
|
||||
context_value.as_raw(),
|
||||
&mut handle,
|
||||
)
|
||||
}
|
||||
} else {
|
||||
let extended = self.query(&IID_V3).map_err(CommandError::HResult)?;
|
||||
// The V3 vtable ends at AddItem2. Only the prefix containing that slot is read.
|
||||
let table = unsafe { interface_table::<ProxyV3Vtable>(&extended) };
|
||||
unsafe {
|
||||
(table.add_item2)(
|
||||
extended.as_ptr(),
|
||||
server,
|
||||
item.as_raw(),
|
||||
context_value.as_raw(),
|
||||
&mut handle,
|
||||
)
|
||||
}
|
||||
};
|
||||
check(status).map_err(CommandError::HResult)?;
|
||||
// Context is an input to the native resolver; the C# index keys the item definition.
|
||||
self.items.insert((server, handle), definition);
|
||||
Ok(CommandResult::Handle(handle))
|
||||
}
|
||||
Command::SetBufferedInterval(server, interval) => {
|
||||
self.require_registration(server)?;
|
||||
let extended = self.query(&IID_V5).map_err(CommandError::HResult)?;
|
||||
check(unsafe {
|
||||
(interface_table::<ProxyV5Vtable>(&extended).set_buffered_update_interval)(
|
||||
extended.as_ptr(),
|
||||
server,
|
||||
interval,
|
||||
)
|
||||
})
|
||||
.map_err(CommandError::HResult)?;
|
||||
Ok(CommandResult::Done)
|
||||
}
|
||||
Command::Activation {
|
||||
server,
|
||||
item,
|
||||
active,
|
||||
} => {
|
||||
self.require_registration(server)?;
|
||||
let extended = self.extended().map_err(CommandError::HResult)?;
|
||||
let table = extended_table(&extended);
|
||||
let method = if active {
|
||||
table.activate
|
||||
} else {
|
||||
table.suspend
|
||||
};
|
||||
let mut status = StatusRecord::default();
|
||||
check(unsafe { method(extended.as_ptr(), server, item, &mut status) })
|
||||
.map_err(CommandError::HResult)?;
|
||||
Ok(CommandResult::Status(status.to_proto()))
|
||||
}
|
||||
Command::Authenticate(server, user, password) => {
|
||||
self.require_registration(server)?;
|
||||
let user = AutomationString::new(&user).map_err(CommandError::HResult)?;
|
||||
let password = AutomationString::new(&password).map_err(CommandError::HResult)?;
|
||||
check(unsafe {
|
||||
(table.authenticate_user)(
|
||||
object,
|
||||
server,
|
||||
user.as_raw(),
|
||||
password.as_raw(),
|
||||
&mut handle,
|
||||
)
|
||||
})
|
||||
.map_err(CommandError::HResult)?;
|
||||
Ok(CommandResult::Handle(handle))
|
||||
}
|
||||
Command::UserToId(server, guid) => {
|
||||
self.require_registration(server)?;
|
||||
let guid = AutomationString::new(&guid).map_err(CommandError::HResult)?;
|
||||
let extended = self.query(&IID_V2).map_err(CommandError::HResult)?;
|
||||
check(unsafe {
|
||||
(interface_table::<ProxyV2Vtable>(&extended).archestra_user_to_id)(
|
||||
extended.as_ptr(),
|
||||
server,
|
||||
guid.as_raw(),
|
||||
&mut handle,
|
||||
)
|
||||
})
|
||||
.map_err(CommandError::HResult)?;
|
||||
Ok(CommandResult::Handle(handle))
|
||||
}
|
||||
Command::SubscribeBulk(server, tags, advise) => Ok(CommandResult::SubscribeBulk(
|
||||
self.subscribe_bulk(server, tags, advise),
|
||||
)),
|
||||
Command::ItemBulk(server, handles, operation) => Ok(CommandResult::SubscribeBulk(
|
||||
self.item_bulk(server, handles, operation),
|
||||
)),
|
||||
Command::ReadBulk(server, tags, timeout) => Ok(CommandResult::ReadBulk(
|
||||
self.read_bulk(server, tags, timeout),
|
||||
)),
|
||||
Command::RemoveItem(server, item) => {
|
||||
self.require_registration(server)?;
|
||||
check(unsafe { (table.remove_item)(object, server, item) })
|
||||
.map_err(CommandError::HResult)?;
|
||||
self.publisher.unadvise(server, item);
|
||||
self.items.remove(&(server, item));
|
||||
Ok(CommandResult::Done)
|
||||
}
|
||||
Command::Advise {
|
||||
@@ -509,6 +681,7 @@ impl Proxy {
|
||||
match self.write(request, false) {
|
||||
Ok(_) => result.was_successful = true,
|
||||
Err(CommandError::NotRegistered) => {
|
||||
result.hresult = Some(E_INVALIDARG);
|
||||
result.error_message = "Server handle is not registered in this session".into()
|
||||
}
|
||||
Err(CommandError::Invalid(message)) => result.error_message = message.into(),
|
||||
@@ -522,10 +695,14 @@ impl Proxy {
|
||||
}
|
||||
|
||||
fn extended(&self) -> Result<ComReference, HRESULT> {
|
||||
self.query(&IID_V4)
|
||||
}
|
||||
|
||||
fn query(&self, iid: &GUID) -> Result<ComReference, HRESULT> {
|
||||
let mut pointer = null_mut();
|
||||
// SAFETY: this is a live proxy on its STA. The IID matches ProxyV4Vtable.
|
||||
check(unsafe {
|
||||
(self.vtable().query_interface)(self.interface.as_ptr(), &IID_V4, &mut pointer)
|
||||
(self.vtable().query_interface)(self.interface.as_ptr(), iid, &mut pointer)
|
||||
})?;
|
||||
ComReference::new(pointer)
|
||||
}
|
||||
@@ -542,7 +719,7 @@ impl Proxy {
|
||||
self.publisher.discard_pending_write();
|
||||
let advice = self.publisher.take_advice();
|
||||
let mut failures = 0;
|
||||
if let Some(mut connection) = self.connection.take() {
|
||||
for mut connection in self.connections.drain(..) {
|
||||
if let Err(hr) = connection.detach() {
|
||||
failures += 1;
|
||||
eprintln!(
|
||||
@@ -584,7 +761,7 @@ impl Proxy {
|
||||
|
||||
impl Drop for Proxy {
|
||||
fn drop(&mut self) {
|
||||
drop(self.connection.take());
|
||||
self.connections.clear();
|
||||
// SAFETY: release the reference returned by CoCreateInstance on this STA.
|
||||
unsafe { (self.vtable().release)(self.interface.as_ptr()) };
|
||||
}
|
||||
@@ -592,7 +769,12 @@ impl Drop for Proxy {
|
||||
|
||||
fn extended_table(reference: &ComReference) -> &ProxyV4Vtable {
|
||||
// SAFETY: the reference was obtained for IID_V4 by Proxy::extended.
|
||||
unsafe { &**reference.as_ptr().cast::<*const ProxyV4Vtable>() }
|
||||
unsafe { interface_table::<ProxyV4Vtable>(reference) }
|
||||
}
|
||||
|
||||
unsafe fn interface_table<V>(reference: &ComReference) -> &V {
|
||||
// SAFETY: caller selects the vtable matching QueryInterface's IID.
|
||||
unsafe { &**reference.as_ptr().cast::<*const V>() }
|
||||
}
|
||||
|
||||
fn check(status: HRESULT) -> Result<(), HRESULT> {
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
use super::*;
|
||||
use crate::wire::mxaccess_gateway::v1::MxEvent;
|
||||
use std::time::Instant;
|
||||
|
||||
impl Proxy {
|
||||
pub(super) fn subscribe_bulk(
|
||||
&mut self,
|
||||
server: i32,
|
||||
tags: Vec<String>,
|
||||
advise: bool,
|
||||
) -> Vec<SubscribeResult> {
|
||||
tags.into_iter()
|
||||
.map(|tag| {
|
||||
let mut result = SubscribeResult {
|
||||
server_handle: server,
|
||||
tag_address: tag,
|
||||
..Default::default()
|
||||
};
|
||||
if result.tag_address.trim().is_empty() {
|
||||
result.error_message = "Tag address is required.".into();
|
||||
return result;
|
||||
}
|
||||
match self.add_item_handle(server, &result.tag_address) {
|
||||
Ok(item) => {
|
||||
result.item_handle = item;
|
||||
if advise {
|
||||
if let Err(error) = self.advise_item(server, item) {
|
||||
result.error_message = error.message();
|
||||
if let Err(cleanup) =
|
||||
self.execute(Command::RemoveItem(server, item))
|
||||
{
|
||||
result.error_message.push_str(&format!(
|
||||
"; cleanup RemoveItem failed: {}",
|
||||
cleanup.message()
|
||||
));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
result.was_successful = true;
|
||||
}
|
||||
Err(error) => result.error_message = error.message(),
|
||||
}
|
||||
result
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) fn item_bulk(
|
||||
&mut self,
|
||||
server: i32,
|
||||
items: Vec<i32>,
|
||||
operation: ItemOperation,
|
||||
) -> Vec<SubscribeResult> {
|
||||
items
|
||||
.into_iter()
|
||||
.map(|item| {
|
||||
let mut result = SubscribeResult {
|
||||
server_handle: server,
|
||||
item_handle: item,
|
||||
..Default::default()
|
||||
};
|
||||
result.error_message = match operation {
|
||||
ItemOperation::Advise => self
|
||||
.advise_item(server, item)
|
||||
.err()
|
||||
.map_or_else(String::new, |err| err.message()),
|
||||
ItemOperation::UnAdvise => self
|
||||
.execute(Command::UnAdvise(server, item))
|
||||
.err()
|
||||
.map_or_else(String::new, |err| err.message()),
|
||||
ItemOperation::Remove => self
|
||||
.execute(Command::RemoveItem(server, item))
|
||||
.err()
|
||||
.map_or_else(String::new, |err| err.message()),
|
||||
ItemOperation::Unsubscribe => {
|
||||
let unadvise = self.execute(Command::UnAdvise(server, item));
|
||||
let remove = self.execute(Command::RemoveItem(server, item));
|
||||
[("UnAdvise", unadvise), ("RemoveItem", remove)]
|
||||
.into_iter()
|
||||
.filter_map(|(operation, result)| {
|
||||
result
|
||||
.err()
|
||||
.map(|error| format!("{operation} failed: {}", error.message()))
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("; ")
|
||||
}
|
||||
};
|
||||
result.was_successful = result.error_message.is_empty();
|
||||
result
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) fn read_bulk(
|
||||
&mut self,
|
||||
server: i32,
|
||||
tags: Vec<String>,
|
||||
timeout: Duration,
|
||||
) -> Vec<BulkReadResult> {
|
||||
let original_items: BTreeSet<_> = self
|
||||
.items
|
||||
.keys()
|
||||
.filter_map(|&(handle, item)| (handle == server).then_some(item))
|
||||
.collect();
|
||||
let mut results = Vec::with_capacity(tags.len());
|
||||
let mut waiting = Vec::new();
|
||||
let mut cleanup = BTreeMap::new();
|
||||
let mut seen_tags = BTreeMap::new();
|
||||
|
||||
for tag in tags {
|
||||
let index = results.len();
|
||||
let mut result = BulkReadResult {
|
||||
server_handle: server,
|
||||
tag_address: tag,
|
||||
..Default::default()
|
||||
};
|
||||
if result.tag_address.trim().is_empty() {
|
||||
result.error_message = "Tag address is required.".into();
|
||||
} else if let Some((item, event)) = self
|
||||
.items
|
||||
.range((server, i32::MIN)..=(server, i32::MAX))
|
||||
.filter(|(_, definition)| definition.as_str() == result.tag_address.as_str())
|
||||
.find_map(|(&(_, item), _)| {
|
||||
// Only original items count as a cached read for this command.
|
||||
original_items
|
||||
.contains(&item)
|
||||
.then(|| self.publisher.latest_value(server, item))
|
||||
.flatten()
|
||||
.map(|event| (item, event))
|
||||
})
|
||||
{
|
||||
result.item_handle = item;
|
||||
result.was_cached = true;
|
||||
fill_value(&mut result, event);
|
||||
} else if let Some(&owner) = seen_tags.get(&result.tag_address) {
|
||||
// A repeated address shares the same snapshot and outcome.
|
||||
waiting.push((index, Some(owner)));
|
||||
} else {
|
||||
seen_tags.insert(result.tag_address.clone(), index);
|
||||
match self.add_item_handle(server, &result.tag_address) {
|
||||
Err(error) => result.error_message = error.message(),
|
||||
Ok(item) => {
|
||||
result.item_handle = item;
|
||||
let already_advised = self.publisher.is_advised(server, item);
|
||||
if let std::collections::btree_map::Entry::Vacant(entry) =
|
||||
cleanup.entry(item)
|
||||
{
|
||||
let advice = if already_advised {
|
||||
Ok(())
|
||||
} else {
|
||||
self.advise_item(server, item)
|
||||
};
|
||||
entry.insert((
|
||||
!original_items.contains(&item),
|
||||
!already_advised && advice.is_ok(),
|
||||
));
|
||||
if let Err(error) = advice {
|
||||
result.error_message = error.message();
|
||||
}
|
||||
}
|
||||
if result.error_message.is_empty() {
|
||||
waiting.push((index, None));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
results.push(result);
|
||||
if index % 16 == 15 {
|
||||
pump_messages();
|
||||
}
|
||||
}
|
||||
|
||||
let deadline = Instant::now() + timeout;
|
||||
while pump_messages()
|
||||
&& waiting.iter().any(|&(index, owner)| {
|
||||
owner.is_none()
|
||||
&& self
|
||||
.publisher
|
||||
.latest_value(server, results[index].item_handle)
|
||||
.is_none()
|
||||
})
|
||||
{
|
||||
let remaining = deadline.saturating_duration_since(Instant::now());
|
||||
if remaining.is_zero() {
|
||||
break;
|
||||
}
|
||||
// The STA remains available to deliver the OnDataChange callbacks.
|
||||
unsafe {
|
||||
MsgWaitForMultipleObjectsEx(
|
||||
0,
|
||||
null(),
|
||||
remaining.as_millis().min(u32::MAX as u128 - 1) as u32,
|
||||
QS_ALLINPUT,
|
||||
MWMO_INPUTAVAILABLE,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
for (index, owner) in waiting {
|
||||
if let Some(owner) = owner {
|
||||
let tag = std::mem::take(&mut results[index].tag_address);
|
||||
results[index] = results[owner].clone();
|
||||
results[index].tag_address = tag;
|
||||
} else if let Some(event) = self
|
||||
.publisher
|
||||
.latest_value(server, results[index].item_handle)
|
||||
{
|
||||
fill_value(&mut results[index], event);
|
||||
} else {
|
||||
results[index].error_message = format!(
|
||||
"ReadBulk timed out after {} ms waiting for first OnDataChange.",
|
||||
timeout.as_millis()
|
||||
);
|
||||
}
|
||||
}
|
||||
for (item, (remove, unadvise)) in cleanup {
|
||||
if unadvise {
|
||||
let _ = self.execute(Command::UnAdvise(server, item));
|
||||
}
|
||||
if remove {
|
||||
let _ = self.execute(Command::RemoveItem(server, item));
|
||||
}
|
||||
}
|
||||
results
|
||||
}
|
||||
|
||||
fn add_item_handle(&mut self, server: i32, address: &str) -> Result<i32, CommandError> {
|
||||
match self.execute(Command::AddItem(server, address.into()))? {
|
||||
CommandResult::Handle(handle) => Ok(handle),
|
||||
_ => unreachable!("AddItem returns a handle"),
|
||||
}
|
||||
}
|
||||
|
||||
fn advise_item(&mut self, server: i32, item: i32) -> Result<(), CommandError> {
|
||||
self.execute(Command::Advise {
|
||||
server,
|
||||
item,
|
||||
supervisory: false,
|
||||
})
|
||||
.map(|_| ())
|
||||
}
|
||||
}
|
||||
|
||||
fn fill_value(result: &mut BulkReadResult, event: MxEvent) {
|
||||
result.was_successful = true;
|
||||
result.value = event.value;
|
||||
result.quality = event.quality;
|
||||
result.source_timestamp = event.source_timestamp;
|
||||
result.statuses = event.statuses;
|
||||
}
|
||||
|
||||
impl CommandError {
|
||||
fn message(&self) -> String {
|
||||
match self {
|
||||
Self::NotRegistered => "Server handle is not registered in this session".into(),
|
||||
Self::Invalid(message) => (*message).into(),
|
||||
Self::HResult(hr) => format!("MXAccess command failed (HRESULT 0x{:08X})", *hr as u32),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
use std::collections::BTreeSet;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::ffi::c_void;
|
||||
use std::ptr::{null_mut, NonNull};
|
||||
use std::sync::{
|
||||
@@ -17,13 +17,17 @@ use windows_sys::Win32::System::Com::{DISPPARAMS, EXCEPINFO};
|
||||
use windows_sys::Win32::System::Ole::{GetRecordInfoFromGuids, LoadRegTypeLib};
|
||||
use windows_sys::Win32::System::Variant::VARIANT;
|
||||
|
||||
use crate::automation::{dispatch_i32, dispatch_statuses, dispatch_timestamp, dispatch_value};
|
||||
use crate::automation::{
|
||||
buffered_array, dispatch_i32, dispatch_statuses, dispatch_timestamp, dispatch_value,
|
||||
native_data_type,
|
||||
};
|
||||
use crate::wire::mxaccess_gateway::v1::{
|
||||
mx_event, MxEvent, MxEventFamily, MxStatusProxy, OnDataChangeEvent, OnWriteCompleteEvent,
|
||||
OperationCompleteEvent,
|
||||
mx_event, mx_value, MxDataType, MxEvent, MxEventFamily, MxStatusProxy,
|
||||
OnBufferedDataChangeEvent, OnDataChangeEvent, OnWriteCompleteEvent, OperationCompleteEvent,
|
||||
};
|
||||
|
||||
const EVENTS_IID: GUID = GUID::from_u128(0x848299b6_dd61_4a0d_a304_3947a564b89c);
|
||||
const BUFFERED_EVENTS_IID: GUID = GUID::from_u128(0xc70a6fc4_09ef_4f31_8874_a049fee87a95);
|
||||
const DISPATCH_IID: GUID = GUID::from_u128(0x00020400_0000_0000_c000_000000000046);
|
||||
const CONNECTION_POINT_CONTAINER_IID: GUID =
|
||||
GUID::from_u128(0xb196b284_bab4_101a_b69c_00aa00341d07);
|
||||
@@ -33,6 +37,7 @@ const RECORD_ID: GUID = GUID::from_u128(0xa162d9e4_9019_42f3_a087_79264007e542);
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum EventFault {
|
||||
Overflow,
|
||||
AlarmDisconnected,
|
||||
Conversion(&'static str),
|
||||
}
|
||||
|
||||
@@ -56,6 +61,7 @@ struct PendingWrite {
|
||||
struct PublisherState {
|
||||
advised: BTreeSet<(i32, i32)>,
|
||||
last_sequence: u64,
|
||||
latest_values: BTreeMap<(i32, i32), MxEvent>,
|
||||
pending_write: Option<PendingWrite>,
|
||||
}
|
||||
|
||||
@@ -87,15 +93,26 @@ impl Publisher {
|
||||
}
|
||||
|
||||
pub fn unadvise(&self, server: i32, item: i32) {
|
||||
self.state.lock().unwrap().advised.remove(&(server, item));
|
||||
let mut state = self.state.lock().unwrap();
|
||||
state.advised.remove(&(server, item));
|
||||
state.latest_values.remove(&(server, item));
|
||||
}
|
||||
|
||||
pub fn unregister(&self, server: i32) {
|
||||
let mut state = self.state.lock().unwrap();
|
||||
state.advised.retain(|(handle, _)| *handle != server);
|
||||
state
|
||||
.latest_values
|
||||
.retain(|(handle, _), _| *handle != server);
|
||||
}
|
||||
|
||||
pub fn latest_value(&self, server: i32, item: i32) -> Option<MxEvent> {
|
||||
self.state
|
||||
.lock()
|
||||
.unwrap()
|
||||
.advised
|
||||
.retain(|(handle, _)| *handle != server);
|
||||
.latest_values
|
||||
.get(&(server, item))
|
||||
.cloned()
|
||||
}
|
||||
|
||||
pub fn take_advice(&self) -> BTreeSet<(i32, i32)> {
|
||||
@@ -106,11 +123,11 @@ impl Publisher {
|
||||
self.state.lock().unwrap().last_sequence
|
||||
}
|
||||
|
||||
fn is_advised(&self, server: i32, item: i32) -> bool {
|
||||
pub(crate) fn is_advised(&self, server: i32, item: i32) -> bool {
|
||||
self.state.lock().unwrap().advised.contains(&(server, item))
|
||||
}
|
||||
|
||||
fn report_fault(&self, fault: EventFault) {
|
||||
pub(crate) fn report_fault(&self, fault: EventFault) {
|
||||
self.faults.send_if_modified(|current| {
|
||||
if current.is_some() {
|
||||
return false;
|
||||
@@ -134,11 +151,18 @@ impl Publisher {
|
||||
self.state.lock().unwrap().pending_write.take();
|
||||
}
|
||||
|
||||
fn publish(&self, mut event: MxEvent) {
|
||||
pub(crate) fn publish(&self, mut event: MxEvent) {
|
||||
let mut state = self.state.lock().unwrap();
|
||||
event.session_id = self.session.to_string();
|
||||
event.worker_timestamp = Some(SystemTime::now().into());
|
||||
event.worker_sequence = state.last_sequence + 1;
|
||||
if event.family() == MxEventFamily::OnDataChange {
|
||||
let key = (event.server_handle, event.item_handle);
|
||||
if !state.advised.contains(&key) {
|
||||
return;
|
||||
}
|
||||
state.latest_values.insert(key, event.clone());
|
||||
}
|
||||
if event.family() == MxEventFamily::OnWriteComplete
|
||||
&& state.pending_write.as_ref().is_some_and(|pending| {
|
||||
pending.server == event.server_handle && pending.item == event.item_handle
|
||||
@@ -181,7 +205,16 @@ pub struct Connection {
|
||||
|
||||
impl Connection {
|
||||
// The caller supplies the live LMXProxy interface on the owning STA.
|
||||
pub unsafe fn attach(proxy: *mut c_void, publisher: Publisher) -> Result<Self, HRESULT> {
|
||||
pub unsafe fn attach(
|
||||
proxy: *mut c_void,
|
||||
publisher: Publisher,
|
||||
buffered: bool,
|
||||
) -> Result<Self, HRESULT> {
|
||||
let events_iid = if buffered {
|
||||
BUFFERED_EVENTS_IID
|
||||
} else {
|
||||
EVENTS_IID
|
||||
};
|
||||
let mut container = null_mut();
|
||||
let unknown = unsafe { vtable::<IUnknown_Vtbl>(proxy) };
|
||||
check(unsafe {
|
||||
@@ -191,12 +224,13 @@ impl Connection {
|
||||
let mut point = null_mut();
|
||||
let table = unsafe { vtable::<ConnectionPointContainerVtable>(container.as_ptr()) };
|
||||
check(unsafe {
|
||||
(table.find_connection_point)(container.as_ptr(), &EVENTS_IID, &mut point)
|
||||
(table.find_connection_point)(container.as_ptr(), &events_iid, &mut point)
|
||||
})?;
|
||||
let point = ComReference::new(point)?;
|
||||
|
||||
let sink = Box::new(Sink {
|
||||
table: &SINK_VTABLE,
|
||||
buffered,
|
||||
reference_count: AtomicU32::new(1),
|
||||
publisher,
|
||||
});
|
||||
@@ -289,6 +323,7 @@ fn check(hr: HRESULT) -> Result<(), HRESULT> {
|
||||
#[repr(C)]
|
||||
struct Sink {
|
||||
table: &'static DispatchVtable,
|
||||
buffered: bool,
|
||||
reference_count: AtomicU32,
|
||||
publisher: Publisher,
|
||||
}
|
||||
@@ -343,7 +378,13 @@ unsafe extern "system" fn query_interface(
|
||||
let Some(iid) = (unsafe { iid.as_ref() }) else {
|
||||
return E_POINTER;
|
||||
};
|
||||
if [EVENTS_IID, DISPATCH_IID, IID_IUnknown]
|
||||
let sink = unsafe { &*this.cast::<Sink>() };
|
||||
let events_iid = if sink.buffered {
|
||||
BUFFERED_EVENTS_IID
|
||||
} else {
|
||||
EVENTS_IID
|
||||
};
|
||||
if [events_iid, DISPATCH_IID, IID_IUnknown]
|
||||
.iter()
|
||||
.any(|supported| {
|
||||
supported.data1 == iid.data1
|
||||
@@ -430,18 +471,23 @@ unsafe extern "system" fn invoke(
|
||||
|
||||
impl Sink {
|
||||
unsafe fn on_dispatch(&self, member: i32, parameters: *const DISPPARAMS) -> HRESULT {
|
||||
let (count, family, body) = match member {
|
||||
1 => (
|
||||
let (count, family, body) = match (self.buffered, member) {
|
||||
(true, 1) => (
|
||||
7,
|
||||
MxEventFamily::OnBufferedDataChange,
|
||||
mx_event::Body::OnBufferedDataChange(OnBufferedDataChangeEvent::default()),
|
||||
),
|
||||
(false, 1) => (
|
||||
6,
|
||||
MxEventFamily::OnDataChange,
|
||||
mx_event::Body::OnDataChange(OnDataChangeEvent {}),
|
||||
),
|
||||
2 => (
|
||||
(false, 2) => (
|
||||
3,
|
||||
MxEventFamily::OnWriteComplete,
|
||||
mx_event::Body::OnWriteComplete(OnWriteCompleteEvent {}),
|
||||
),
|
||||
3 => (
|
||||
(false, 3) => (
|
||||
3,
|
||||
MxEventFamily::OperationComplete,
|
||||
mx_event::Body::OperationComplete(OperationCompleteEvent {}),
|
||||
@@ -460,7 +506,7 @@ impl Sink {
|
||||
// IDispatch packs its positional arguments in reverse order. LMXProxy
|
||||
// puts them at four-byte aligned addresses on x86, so copy them before
|
||||
// forming Rust references to the eight-byte-aligned VARIANT type.
|
||||
let mut args = [VARIANT::default(); 6];
|
||||
let mut args = [VARIANT::default(); 7];
|
||||
for (index, argument) in args[..count].iter_mut().enumerate() {
|
||||
*argument = unsafe { parameters.rgvarg.add(index).read_unaligned() };
|
||||
}
|
||||
@@ -490,7 +536,32 @@ impl Sink {
|
||||
body: Some(body),
|
||||
..Default::default()
|
||||
};
|
||||
if member == 1 {
|
||||
if self.buffered {
|
||||
let Some(raw_data_type) = (unsafe { dispatch_i32(&args[4]) }) else {
|
||||
self.publisher.report_fault(EventFault::Conversion(
|
||||
"unexpected buffered MXAccess data type",
|
||||
));
|
||||
return DISP_E_TYPEMISMATCH;
|
||||
};
|
||||
let data_type = native_data_type(raw_data_type);
|
||||
let mut value = unsafe { dispatch_value(&args[3]) };
|
||||
if let Some(mx_value::Kind::ArrayValue(array)) = &mut value.kind {
|
||||
if data_type != MxDataType::NoData as i32 && data_type != MxDataType::Unknown as i32
|
||||
{
|
||||
// Inferred Automation scalar/array types remain available on the value.
|
||||
array.raw_element_data_type = raw_data_type;
|
||||
}
|
||||
}
|
||||
event.value = Some(value);
|
||||
event.body = Some(mx_event::Body::OnBufferedDataChange(
|
||||
OnBufferedDataChangeEvent {
|
||||
data_type,
|
||||
raw_data_type,
|
||||
quality_values: Some(unsafe { buffered_array(&args[2], MxDataType::Integer) }),
|
||||
timestamp_values: Some(unsafe { buffered_array(&args[1], MxDataType::Time) }),
|
||||
},
|
||||
));
|
||||
} else if member == 1 {
|
||||
let Some(quality) = (unsafe { dispatch_i32(&args[2]) }) else {
|
||||
self.publisher
|
||||
.report_fault(EventFault::Conversion("unexpected MXAccess quality type"));
|
||||
@@ -520,6 +591,7 @@ mod tests {
|
||||
let (publisher, mut events, faults) = event_channel("session", 1);
|
||||
let sink = Sink {
|
||||
table: &SINK_VTABLE,
|
||||
buffered: false,
|
||||
reference_count: AtomicU32::new(1),
|
||||
publisher,
|
||||
};
|
||||
@@ -602,6 +674,93 @@ mod tests {
|
||||
assert_eq!(events.try_recv().unwrap().statuses, statuses);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_buffered_samples_quality_and_filetime_timestamps() {
|
||||
use crate::automation::WriteValue;
|
||||
use crate::wire::mxaccess_gateway::v1::{
|
||||
mx_array::Values, Int32Array, Int64Array, MxArray, MxValue,
|
||||
};
|
||||
let (publisher, mut events, _) = event_channel("session", 4);
|
||||
let sink = Sink {
|
||||
table: &SINK_VTABLE,
|
||||
buffered: true,
|
||||
reference_count: AtomicU32::new(1),
|
||||
publisher,
|
||||
};
|
||||
sink.publisher.advise(5, 7);
|
||||
let array = |values| {
|
||||
WriteValue::new(
|
||||
MxValue {
|
||||
kind: Some(mx_value::Kind::ArrayValue(MxArray {
|
||||
dimensions: vec![2],
|
||||
values: Some(values),
|
||||
..Default::default()
|
||||
})),
|
||||
..Default::default()
|
||||
},
|
||||
false,
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
let samples = array(Values::Int32Values(Int32Array {
|
||||
values: vec![40, 41],
|
||||
}));
|
||||
let qualities = array(Values::Int32Values(Int32Array {
|
||||
values: vec![192, 0],
|
||||
}));
|
||||
let times = array(Values::Int64Values(Int64Array {
|
||||
values: vec![116_444_736_000_000_000, 116_444_736_010_000_000],
|
||||
}));
|
||||
let mut arguments = [
|
||||
VARIANT::default(),
|
||||
times.by_value(),
|
||||
qualities.by_value(),
|
||||
samples.by_value(),
|
||||
integer(2),
|
||||
integer(7),
|
||||
integer(5),
|
||||
];
|
||||
let parameters = DISPPARAMS {
|
||||
rgvarg: arguments.as_mut_ptr(),
|
||||
cArgs: 7,
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(unsafe { sink.on_dispatch(1, ¶meters) }, S_OK);
|
||||
|
||||
let event = events.try_recv().unwrap();
|
||||
assert_eq!(event.family(), MxEventFamily::OnBufferedDataChange);
|
||||
let Some(mx_value::Kind::ArrayValue(value)) = event.value.unwrap().kind else {
|
||||
panic!("missing buffered values");
|
||||
};
|
||||
assert_eq!(
|
||||
value.values,
|
||||
Some(Values::Int32Values(Int32Array {
|
||||
values: vec![40, 41]
|
||||
}))
|
||||
);
|
||||
let Some(mx_event::Body::OnBufferedDataChange(body)) = event.body else {
|
||||
panic!("missing buffered body");
|
||||
};
|
||||
assert_eq!(body.data_type, MxDataType::Integer as i32);
|
||||
assert_eq!(
|
||||
body.quality_values.unwrap().values,
|
||||
Some(Values::Int32Values(Int32Array {
|
||||
values: vec![192, 0]
|
||||
}))
|
||||
);
|
||||
let Some(Values::TimestampValues(times)) = body.timestamp_values.unwrap().values else {
|
||||
panic!("missing timestamps");
|
||||
};
|
||||
assert_eq!(
|
||||
times
|
||||
.values
|
||||
.into_iter()
|
||||
.map(|value| value.seconds)
|
||||
.collect::<Vec<_>>(),
|
||||
[0, 1]
|
||||
);
|
||||
}
|
||||
|
||||
fn integer(value: i32) -> VARIANT {
|
||||
let mut result = VARIANT::default();
|
||||
result.Anonymous.Anonymous.vt = VT_I4;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use std::collections::HashMap;
|
||||
use std::io;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
use prost::Message;
|
||||
@@ -7,20 +8,24 @@ use prost_types::Timestamp;
|
||||
use tokio::io::{split, AsyncWrite};
|
||||
use tokio::net::windows::named_pipe::{ClientOptions, NamedPipeClient};
|
||||
use tokio::sync::{mpsc, watch};
|
||||
use tokio::time::{interval, sleep, timeout, Instant, MissedTickBehavior};
|
||||
use tokio::time::{interval, sleep, timeout, Instant, Interval, MissedTickBehavior};
|
||||
use windows_sys::Win32::Foundation::E_INVALIDARG;
|
||||
|
||||
use crate::alarm::{self, AlarmWorker};
|
||||
use crate::automation::int32;
|
||||
use crate::mxaccess::{
|
||||
Command, CommandError, CommandResult, Sta, StartError, WriteAccess, WriteRequest, CLASS_ID,
|
||||
PROG_ID,
|
||||
Command, CommandError, CommandResult, ItemOperation, Sta, StartError, WriteAccess,
|
||||
WriteRequest, CLASS_ID, PROG_ID,
|
||||
};
|
||||
use crate::mxevent::{event_channel, EventFault, Publisher};
|
||||
use crate::wire::{
|
||||
self,
|
||||
mxaccess_gateway::v1::{
|
||||
mx_command, mx_command_reply, AddItemReply, BulkWriteReply, DrainEventsReply, MxCommand,
|
||||
MxCommandKind, MxCommandReply, MxEvent, ProtocolStatus, ProtocolStatusCode, RegisterReply,
|
||||
SessionState, SessionStateReply, WorkerInfoReply,
|
||||
mx_command, mx_command_reply, ActivateReply, AddBufferedItemReply, AddItem2Reply,
|
||||
AddItemReply, ArchestrAUserToIdReply, AuthenticateUserReply, BulkReadReply,
|
||||
BulkSubscribeReply, BulkWriteReply, DrainEventsReply, MxCommand, MxCommandKind,
|
||||
MxCommandReply, MxEvent, ProtocolStatus, ProtocolStatusCode, RegisterReply, SessionState,
|
||||
SessionStateReply, SuspendReply, WorkerInfoReply,
|
||||
},
|
||||
mxaccess_worker::v1::{
|
||||
GatewayHello, WorkerCommand, WorkerCommandReply, WorkerEvent, WorkerFault,
|
||||
@@ -165,20 +170,6 @@ pub async fn run() -> Result<(), Error> {
|
||||
let options = Options::load()?;
|
||||
let (mut reader, sender) = split(connect(&options).await?);
|
||||
let mut writer = Writer::new(sender);
|
||||
writer
|
||||
.send(
|
||||
&options.session,
|
||||
"",
|
||||
Body::WorkerHello(WorkerHello {
|
||||
protocol_version: VERSION,
|
||||
nonce: options.nonce.clone(),
|
||||
worker_process_id: pid(),
|
||||
worker_version: WORKER_VERSION.into(),
|
||||
}),
|
||||
DEFAULT_MAX,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let hello = wire::read(&mut reader, &options.session, DEFAULT_MAX).await?;
|
||||
let max = match check_hello(hello.body, &options.nonce) {
|
||||
Ok(max) => max,
|
||||
@@ -196,6 +187,20 @@ pub async fn run() -> Result<(), Error> {
|
||||
}
|
||||
};
|
||||
|
||||
writer
|
||||
.send(
|
||||
&options.session,
|
||||
"",
|
||||
Body::WorkerHello(WorkerHello {
|
||||
protocol_version: VERSION,
|
||||
nonce: options.nonce.clone(),
|
||||
worker_process_id: pid(),
|
||||
worker_version: WORKER_VERSION.into(),
|
||||
}),
|
||||
DEFAULT_MAX,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let mut events = EventStream::new(&options);
|
||||
let (sta, pin_status) = match Sta::start(events.publisher.clone()).await {
|
||||
Ok(started) => started,
|
||||
@@ -234,25 +239,64 @@ pub async fn run() -> Result<(), Error> {
|
||||
)
|
||||
.await?;
|
||||
|
||||
// Run the frame reader independently so a heartbeat cannot cancel a partial read.
|
||||
let (incoming, mut frames) = mpsc::channel(1);
|
||||
// Keep reading cancellation frames while the STA is running a command.
|
||||
let (incoming, frames) = mpsc::channel(128);
|
||||
let pending = PendingCommands::default();
|
||||
let reader_pending = pending.clone();
|
||||
let session = options.session.clone();
|
||||
let reader_task = tokio::spawn(async move {
|
||||
loop {
|
||||
let frame = wire::read(&mut reader, &session, max).await;
|
||||
let end = frame.is_err();
|
||||
if incoming.send(frame).await.is_err() || end {
|
||||
return;
|
||||
let reader_task =
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
let frame = wire::read(&mut reader, &session, max).await;
|
||||
let end = frame.is_err();
|
||||
if let Ok(frame) = &frame {
|
||||
match frame.body.as_ref() {
|
||||
Some(Body::WorkerCancel(_)) => {
|
||||
reader_pending.cancel(&frame.correlation_id);
|
||||
continue;
|
||||
}
|
||||
Some(Body::WorkerCommand(command)) => {
|
||||
if command.command.as_ref().is_some_and(|command| {
|
||||
command.kind() == MxCommandKind::ShutdownWorker
|
||||
}) {
|
||||
reader_pending.cancel_all();
|
||||
}
|
||||
reader_pending.queue(&frame.correlation_id);
|
||||
}
|
||||
Some(Body::WorkerShutdown(_)) => reader_pending.cancel_all(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if incoming.send(frame).await.is_err() || end {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
let result = command_loop(&options, max, &sta, &mut writer, &mut frames, &mut events).await;
|
||||
let result = command_loop(
|
||||
&options,
|
||||
max,
|
||||
&sta,
|
||||
&mut writer,
|
||||
CommandFrames { frames, pending },
|
||||
&mut events,
|
||||
)
|
||||
.await;
|
||||
// Keep the read half alive during graceful shutdown so the gateway can
|
||||
// finish a control write before reading the ack.
|
||||
let acknowledgement = match result {
|
||||
Ok(grace) => {
|
||||
let shutdown = timeout(grace, sta.shutdown()).await;
|
||||
let shutdown = timeout(grace, async {
|
||||
let alarms = async {
|
||||
match events.alarm_worker.take() {
|
||||
Some(worker) => worker.shutdown(&options.session, max, grace).await,
|
||||
None => Ok(0),
|
||||
}
|
||||
};
|
||||
let (sta_result, alarm_result) = tokio::join!(sta.shutdown(), alarms);
|
||||
Ok::<_, io::Error>(sta_result? + alarm_result?)
|
||||
})
|
||||
.await;
|
||||
let (code, message) = match shutdown {
|
||||
Ok(Ok(0)) => (ProtocolStatusCode::Ok, "Graceful shutdown completed".into()),
|
||||
Ok(Ok(failures)) => (
|
||||
@@ -278,6 +322,7 @@ pub async fn run() -> Result<(), Error> {
|
||||
.map_err(Error::from)
|
||||
}
|
||||
Err(error) => {
|
||||
drop(events.alarm_worker.take());
|
||||
let _ = timeout(Duration::from_secs(2), sta.shutdown()).await;
|
||||
Err(error)
|
||||
}
|
||||
@@ -315,12 +360,51 @@ fn check_hello(
|
||||
wire::negotiated_max(max_frame_bytes).map_err(|error| (ProtocolViolation, error.into()))
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct PendingCommands(Arc<Mutex<HashMap<String, bool>>>);
|
||||
|
||||
impl PendingCommands {
|
||||
fn queue(&self, correlation: &str) {
|
||||
self.0.lock().unwrap().insert(correlation.into(), false);
|
||||
}
|
||||
|
||||
fn cancel(&self, correlation: &str) {
|
||||
if let Some(canceled) = self.0.lock().unwrap().get_mut(correlation) {
|
||||
*canceled = true;
|
||||
}
|
||||
}
|
||||
|
||||
fn cancel_all(&self) {
|
||||
for canceled in self.0.lock().unwrap().values_mut() {
|
||||
*canceled = true;
|
||||
}
|
||||
}
|
||||
|
||||
fn begin(&self, correlation: &str) -> bool {
|
||||
!self
|
||||
.0
|
||||
.lock()
|
||||
.unwrap()
|
||||
.remove(correlation)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn count(&self) -> u32 {
|
||||
self.0.lock().unwrap().len() as u32
|
||||
}
|
||||
}
|
||||
|
||||
struct CommandFrames {
|
||||
frames: mpsc::Receiver<io::Result<wire::WorkerEnvelope>>,
|
||||
pending: PendingCommands,
|
||||
}
|
||||
|
||||
async fn command_loop<W: AsyncWrite + Unpin>(
|
||||
options: &Options,
|
||||
max: usize,
|
||||
sta: &Sta,
|
||||
writer: &mut Writer<W>,
|
||||
frames: &mut mpsc::Receiver<io::Result<wire::WorkerEnvelope>>,
|
||||
mut commands: CommandFrames,
|
||||
events: &mut EventStream,
|
||||
) -> Result<Duration, Error> {
|
||||
let mut heartbeat = interval(options.heartbeat_interval);
|
||||
@@ -328,57 +412,29 @@ async fn command_loop<W: AsyncWrite + Unpin>(
|
||||
loop {
|
||||
let callback_fault = *events.faults.borrow_and_update();
|
||||
if let Some(failure) = callback_fault {
|
||||
let (category, message, exit_code) = match failure {
|
||||
EventFault::Overflow => (
|
||||
WorkerFaultCategory::QueueOverflow,
|
||||
"MXAccess event backlog exceeded the outbound queue capacity",
|
||||
8,
|
||||
),
|
||||
EventFault::Conversion(message) => (
|
||||
WorkerFaultCategory::MxaccessEventConversionFailed,
|
||||
message,
|
||||
1,
|
||||
),
|
||||
};
|
||||
fault(writer, &options.session, max, category, None, message).await;
|
||||
return Err(Error(exit_code, message.into()));
|
||||
return Err(report_event_fault(writer, &options.session, max, failure).await);
|
||||
}
|
||||
tokio::select! {
|
||||
_ = events.faults.changed() => continue,
|
||||
next = recv_event(&mut events.pending, &mut events.receiver) => {
|
||||
let event = next.ok_or_else(|| Error(1, "MXAccess event channel closed".into()))?;
|
||||
let result = writer.send(
|
||||
&options.session, "", Body::WorkerEvent(WorkerEvent { event: Some(event) }), max,
|
||||
).await;
|
||||
if let Err(error) = result {
|
||||
if error.kind() == io::ErrorKind::InvalidData {
|
||||
fault(writer, &options.session, max, WorkerFaultCategory::ProtocolViolation, None,
|
||||
"MXAccess event exceeds the negotiated frame maximum").await;
|
||||
}
|
||||
return Err(error.into());
|
||||
}
|
||||
send_event(writer, &options.session, max, next).await?;
|
||||
}
|
||||
frame = frames.recv() => {
|
||||
frame = commands.frames.recv() => {
|
||||
let frame = frame.ok_or_else(|| Error(5, "Worker pipe reader exited".into()))??;
|
||||
let correlation = frame.correlation_id;
|
||||
match frame.body.expect("reader validates body presence") {
|
||||
Body::WorkerCommand(WorkerCommand { command, .. }) if !correlation.is_empty() => {
|
||||
let kind = command.as_ref().map_or(0, |command| command.kind);
|
||||
let execution = timeout(
|
||||
options.command_ceiling,
|
||||
execute(sta, command, options, &correlation, events, max),
|
||||
).await;
|
||||
let mut reply = match execution {
|
||||
Ok(Ok(reply)) => reply,
|
||||
Ok(Err(error)) => {
|
||||
fault(writer, &options.session, max, WorkerFaultCategory::StaHung, None, &error.1).await;
|
||||
return Err(error);
|
||||
}
|
||||
Err(_) => {
|
||||
let message = "MXAccess command exceeded the STA stuck ceiling";
|
||||
fault(writer, &options.session, max, WorkerFaultCategory::StaHung, None, message).await;
|
||||
return Err(Error(1, message.into()));
|
||||
}
|
||||
let mut reply = if commands.pending.begin(&correlation) {
|
||||
run_command(
|
||||
sta, command, &correlation,
|
||||
CommandIo { options, max, writer, events, heartbeat: &mut heartbeat, pending: &commands.pending },
|
||||
).await?
|
||||
} else {
|
||||
let mut reply = command_reply(&options.session, &correlation, kind);
|
||||
reply.hresult = None;
|
||||
set_status(&mut reply, ProtocolStatusCode::Canceled, "Command was canceled before execution.");
|
||||
reply
|
||||
};
|
||||
let shutdown = kind == MxCommandKind::ShutdownWorker as i32
|
||||
&& reply.protocol_status.as_ref().is_some_and(|status| status.code() == ProtocolStatusCode::Ok);
|
||||
@@ -399,8 +455,6 @@ async fn command_loop<W: AsyncWrite + Unpin>(
|
||||
.filter(|grace| !grace.is_zero()).unwrap_or(Duration::from_secs(10));
|
||||
return Ok(grace.min(Duration::from_secs(300)));
|
||||
}
|
||||
// This slice has no pending COM work once control returns to the loop.
|
||||
Body::WorkerCancel(_) => {}
|
||||
_ => {
|
||||
let message = "Unexpected gateway envelope or missing command correlation";
|
||||
fault(writer, &options.session, max, WorkerFaultCategory::ProtocolViolation, None, message).await;
|
||||
@@ -418,6 +472,7 @@ async fn command_loop<W: AsyncWrite + Unpin>(
|
||||
worker_process_id: pid(),
|
||||
state: WorkerState::Ready as i32,
|
||||
last_sta_activity_timestamp: Some(now()),
|
||||
pending_command_count: commands.pending.count(),
|
||||
outbound_event_queue_depth: events.depth() as u32,
|
||||
last_event_sequence: events.publisher.last_sequence(),
|
||||
..Default::default()
|
||||
@@ -427,14 +482,172 @@ async fn command_loop<W: AsyncWrite + Unpin>(
|
||||
}
|
||||
}
|
||||
|
||||
struct CommandIo<'a, W> {
|
||||
options: &'a Options,
|
||||
max: usize,
|
||||
writer: &'a mut Writer<W>,
|
||||
events: &'a mut EventStream,
|
||||
heartbeat: &'a mut Interval,
|
||||
pending: &'a PendingCommands,
|
||||
}
|
||||
|
||||
async fn run_command<W: AsyncWrite + Unpin>(
|
||||
sta: &Sta,
|
||||
command: Option<MxCommand>,
|
||||
correlation: &str,
|
||||
io: CommandIo<'_, W>,
|
||||
) -> Result<MxCommandReply, Error> {
|
||||
let CommandIo {
|
||||
options,
|
||||
max,
|
||||
writer,
|
||||
events,
|
||||
heartbeat,
|
||||
pending,
|
||||
} = io;
|
||||
let drain = command.as_ref().and_then(|command| {
|
||||
if command.kind() != MxCommandKind::DrainEvents {
|
||||
return None;
|
||||
}
|
||||
let requested = match &command.payload {
|
||||
Some(mx_command::Payload::DrainEvents(request)) => request.max_events,
|
||||
None => 0,
|
||||
_ => return None,
|
||||
};
|
||||
Some(events.drain(requested, max))
|
||||
});
|
||||
let context = ExecutorContext {
|
||||
options,
|
||||
max,
|
||||
publisher: &events.publisher,
|
||||
alarm_worker: &mut events.alarm_worker,
|
||||
};
|
||||
let execution = timeout(
|
||||
options.command_ceiling,
|
||||
execute(sta, command, correlation, context, drain),
|
||||
);
|
||||
tokio::pin!(execution);
|
||||
let started = now();
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
result = &mut execution => {
|
||||
return match result {
|
||||
Ok(Ok(reply)) => Ok(reply),
|
||||
failure => {
|
||||
let error = match failure {
|
||||
Ok(Err(error)) => error,
|
||||
Err(_) => Error(1, "MXAccess command exceeded the STA stuck ceiling".into()),
|
||||
Ok(Ok(_)) => unreachable!(),
|
||||
};
|
||||
fault(writer, &options.session, max, WorkerFaultCategory::StaHung, None, &error.1).await;
|
||||
Err(error)
|
||||
}
|
||||
};
|
||||
}
|
||||
_ = events.faults.changed() => {
|
||||
let failure = *events.faults.borrow_and_update();
|
||||
if let Some(failure) = failure {
|
||||
return Err(report_event_fault(writer, &options.session, max, failure).await);
|
||||
}
|
||||
}
|
||||
_ = heartbeat.tick() => {
|
||||
writer.send(&options.session, "", Body::WorkerHeartbeat(WorkerHeartbeat {
|
||||
worker_process_id: pid(),
|
||||
state: WorkerState::ExecutingCommand as i32,
|
||||
last_sta_activity_timestamp: Some(started),
|
||||
current_command_correlation_id: correlation.into(),
|
||||
pending_command_count: pending.count(),
|
||||
outbound_event_queue_depth: (events.receiver.len() + usize::from(events.pending.is_some())) as u32,
|
||||
last_event_sequence: events.publisher.last_sequence(),
|
||||
}), max).await?;
|
||||
}
|
||||
event = recv_event(&mut events.pending, &mut events.receiver) => {
|
||||
send_event(writer, &options.session, max, event).await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn send_event(
|
||||
writer: &mut Writer<impl AsyncWrite + Unpin>,
|
||||
session: &str,
|
||||
max: usize,
|
||||
event: Option<MxEvent>,
|
||||
) -> Result<(), Error> {
|
||||
let event = event.ok_or_else(|| Error(1, "MXAccess event channel closed".into()))?;
|
||||
let result = writer
|
||||
.send(
|
||||
session,
|
||||
"",
|
||||
Body::WorkerEvent(WorkerEvent { event: Some(event) }),
|
||||
max,
|
||||
)
|
||||
.await;
|
||||
if result
|
||||
.as_ref()
|
||||
.is_err_and(|error| error.kind() == io::ErrorKind::InvalidData)
|
||||
{
|
||||
fault(
|
||||
writer,
|
||||
session,
|
||||
max,
|
||||
WorkerFaultCategory::ProtocolViolation,
|
||||
None,
|
||||
"MXAccess event exceeds the negotiated frame maximum",
|
||||
)
|
||||
.await;
|
||||
}
|
||||
result.map_err(Error::from)
|
||||
}
|
||||
|
||||
async fn report_event_fault(
|
||||
writer: &mut Writer<impl AsyncWrite + Unpin>,
|
||||
session: &str,
|
||||
max: usize,
|
||||
failure: EventFault,
|
||||
) -> Error {
|
||||
let (category, message, exit_code) = match failure {
|
||||
EventFault::Overflow => (
|
||||
WorkerFaultCategory::QueueOverflow,
|
||||
"MXAccess event backlog exceeded the outbound queue capacity",
|
||||
8,
|
||||
),
|
||||
EventFault::AlarmDisconnected => (
|
||||
WorkerFaultCategory::PipeDisconnected,
|
||||
"Managed alarm worker disconnected",
|
||||
5,
|
||||
),
|
||||
EventFault::Conversion(message) => (
|
||||
WorkerFaultCategory::MxaccessEventConversionFailed,
|
||||
message,
|
||||
1,
|
||||
),
|
||||
};
|
||||
fault(writer, session, max, category, None, message).await;
|
||||
Error(exit_code, message.into())
|
||||
}
|
||||
|
||||
struct ExecutorContext<'a> {
|
||||
options: &'a Options,
|
||||
max: usize,
|
||||
publisher: &'a Publisher,
|
||||
alarm_worker: &'a mut Option<AlarmWorker>,
|
||||
}
|
||||
|
||||
async fn execute(
|
||||
sta: &Sta,
|
||||
command: Option<MxCommand>,
|
||||
options: &Options,
|
||||
correlation: &str,
|
||||
events: &mut EventStream,
|
||||
max: usize,
|
||||
context: ExecutorContext<'_>,
|
||||
drain: Option<DrainEventsReply>,
|
||||
) -> Result<MxCommandReply, Error> {
|
||||
let ExecutorContext {
|
||||
options,
|
||||
max,
|
||||
publisher,
|
||||
alarm_worker,
|
||||
} = context;
|
||||
use mx_command::Payload;
|
||||
use mx_command_reply::Payload as Reply;
|
||||
use MxCommandKind as Kind;
|
||||
@@ -453,6 +666,44 @@ async fn execute(
|
||||
return Ok(reply);
|
||||
};
|
||||
let kind = command.kind();
|
||||
if alarm::handles(kind) {
|
||||
if alarm_worker.is_none() {
|
||||
if kind == Kind::UnsubscribeAlarms
|
||||
&& matches!(command.payload, Some(Payload::UnsubscribeAlarms(_)))
|
||||
{
|
||||
return Ok(reply);
|
||||
}
|
||||
match AlarmWorker::start(&options.session, max, publisher.clone()).await {
|
||||
Ok(worker) => *alarm_worker = Some(worker),
|
||||
Err(error) => {
|
||||
set_status(
|
||||
&mut reply,
|
||||
ProtocolStatusCode::WorkerUnavailable,
|
||||
&error.to_string(),
|
||||
);
|
||||
reply.hresult = None;
|
||||
return Ok(reply);
|
||||
}
|
||||
}
|
||||
}
|
||||
let worker = alarm_worker.as_mut().expect("alarm worker was started");
|
||||
return match worker
|
||||
.invoke(&options.session, max, correlation, command)
|
||||
.await
|
||||
{
|
||||
Ok(reply) => Ok(reply),
|
||||
Err(error) => {
|
||||
publisher.report_fault(EventFault::AlarmDisconnected);
|
||||
set_status(
|
||||
&mut reply,
|
||||
ProtocolStatusCode::WorkerUnavailable,
|
||||
&error.to_string(),
|
||||
);
|
||||
reply.hresult = None;
|
||||
Ok(reply)
|
||||
}
|
||||
};
|
||||
}
|
||||
let native = match (kind, command.payload) {
|
||||
(Kind::Register, Some(Payload::Register(request))) => {
|
||||
Command::Register(request.client_name)
|
||||
@@ -463,6 +714,84 @@ async fn execute(
|
||||
(Kind::AddItem, Some(Payload::AddItem(request))) => {
|
||||
Command::AddItem(request.server_handle, request.item_definition)
|
||||
}
|
||||
(Kind::AddItem2, Some(Payload::AddItem2(request))) => Command::AddWithContext {
|
||||
server: request.server_handle,
|
||||
definition: request.item_definition,
|
||||
context: request.item_context,
|
||||
buffered: false,
|
||||
},
|
||||
(Kind::AddBufferedItem, Some(Payload::AddBufferedItem(request))) => {
|
||||
Command::AddWithContext {
|
||||
server: request.server_handle,
|
||||
definition: request.item_definition,
|
||||
context: request.item_context,
|
||||
buffered: true,
|
||||
}
|
||||
}
|
||||
(Kind::SetBufferedUpdateInterval, Some(Payload::SetBufferedUpdateInterval(request))) => {
|
||||
Command::SetBufferedInterval(
|
||||
request.server_handle,
|
||||
request.update_interval_milliseconds,
|
||||
)
|
||||
}
|
||||
(Kind::Suspend, Some(Payload::Suspend(request))) => Command::Activation {
|
||||
server: request.server_handle,
|
||||
item: request.item_handle,
|
||||
active: false,
|
||||
},
|
||||
(Kind::Activate, Some(Payload::Activate(request))) => Command::Activation {
|
||||
server: request.server_handle,
|
||||
item: request.item_handle,
|
||||
active: true,
|
||||
},
|
||||
(Kind::AuthenticateUser, Some(Payload::AuthenticateUser(request))) => {
|
||||
Command::Authenticate(
|
||||
request.server_handle,
|
||||
request.verify_user,
|
||||
request.verify_user_password,
|
||||
)
|
||||
}
|
||||
(Kind::ArchestraUserToId, Some(Payload::ArchestraUserToId(request))) => {
|
||||
Command::UserToId(request.server_handle, request.user_id_guid)
|
||||
}
|
||||
(Kind::AddItemBulk, Some(Payload::AddItemBulk(request))) => {
|
||||
Command::SubscribeBulk(request.server_handle, request.tag_addresses, false)
|
||||
}
|
||||
(Kind::SubscribeBulk, Some(Payload::SubscribeBulk(request))) => {
|
||||
Command::SubscribeBulk(request.server_handle, request.tag_addresses, true)
|
||||
}
|
||||
(Kind::AdviseItemBulk, Some(Payload::AdviseItemBulk(request))) => Command::ItemBulk(
|
||||
request.server_handle,
|
||||
request.item_handles,
|
||||
ItemOperation::Advise,
|
||||
),
|
||||
(Kind::RemoveItemBulk, Some(Payload::RemoveItemBulk(request))) => Command::ItemBulk(
|
||||
request.server_handle,
|
||||
request.item_handles,
|
||||
ItemOperation::Remove,
|
||||
),
|
||||
(Kind::UnAdviseItemBulk, Some(Payload::UnAdviseItemBulk(request))) => Command::ItemBulk(
|
||||
request.server_handle,
|
||||
request.item_handles,
|
||||
ItemOperation::UnAdvise,
|
||||
),
|
||||
(Kind::UnsubscribeBulk, Some(Payload::UnsubscribeBulk(request))) => Command::ItemBulk(
|
||||
request.server_handle,
|
||||
request.item_handles,
|
||||
ItemOperation::Unsubscribe,
|
||||
),
|
||||
(Kind::ReadBulk, Some(Payload::ReadBulk(request))) => {
|
||||
let timeout = if request.timeout_ms == 0 {
|
||||
1_000
|
||||
} else {
|
||||
request.timeout_ms
|
||||
};
|
||||
Command::ReadBulk(
|
||||
request.server_handle,
|
||||
request.tag_addresses,
|
||||
Duration::from_millis(timeout.into()),
|
||||
)
|
||||
}
|
||||
(Kind::RemoveItem, Some(Payload::RemoveItem(request))) => {
|
||||
Command::RemoveItem(request.server_handle, request.item_handle)
|
||||
}
|
||||
@@ -609,12 +938,8 @@ async fn execute(
|
||||
}));
|
||||
return Ok(reply);
|
||||
}
|
||||
(Kind::DrainEvents, payload @ (None | Some(Payload::DrainEvents(_)))) => {
|
||||
let requested = match payload {
|
||||
Some(Payload::DrainEvents(request)) => request.max_events,
|
||||
_ => 0,
|
||||
};
|
||||
reply.payload = Some(Reply::DrainEvents(events.drain(requested, max)));
|
||||
(Kind::DrainEvents, _) if drain.is_some() => {
|
||||
reply.payload = drain.map(Reply::DrainEvents);
|
||||
return Ok(reply);
|
||||
}
|
||||
_ => {
|
||||
@@ -638,7 +963,9 @@ async fn execute(
|
||||
}
|
||||
match sta.execute(native).await.map_err(Error::sta)? {
|
||||
Ok(CommandResult::Handle(handle)) => {
|
||||
reply.return_value = Some(int32(handle));
|
||||
if !matches!(kind, Kind::AuthenticateUser | Kind::ArchestraUserToId) {
|
||||
reply.return_value = Some(int32(handle));
|
||||
}
|
||||
reply.payload = Some(match kind {
|
||||
Kind::Register => Reply::Register(RegisterReply {
|
||||
server_handle: handle,
|
||||
@@ -646,7 +973,45 @@ async fn execute(
|
||||
Kind::AddItem => Reply::AddItem(AddItemReply {
|
||||
item_handle: handle,
|
||||
}),
|
||||
_ => unreachable!("only Register and AddItem return a handle"),
|
||||
Kind::AddItem2 => Reply::AddItem2(AddItem2Reply {
|
||||
item_handle: handle,
|
||||
}),
|
||||
Kind::AddBufferedItem => Reply::AddBufferedItem(AddBufferedItemReply {
|
||||
item_handle: handle,
|
||||
}),
|
||||
Kind::AuthenticateUser => {
|
||||
Reply::AuthenticateUser(AuthenticateUserReply { user_id: handle })
|
||||
}
|
||||
Kind::ArchestraUserToId => {
|
||||
Reply::ArchestraUserToId(ArchestrAUserToIdReply { user_id: handle })
|
||||
}
|
||||
_ => unreachable!("command has no integer result"),
|
||||
});
|
||||
}
|
||||
Ok(CommandResult::Status(status)) => {
|
||||
reply.payload = Some(match kind {
|
||||
Kind::Suspend => Reply::Suspend(SuspendReply {
|
||||
status: Some(status),
|
||||
}),
|
||||
Kind::Activate => Reply::Activate(ActivateReply {
|
||||
status: Some(status),
|
||||
}),
|
||||
_ => unreachable!("command has no status result"),
|
||||
});
|
||||
}
|
||||
Ok(CommandResult::ReadBulk(results)) => {
|
||||
reply.payload = Some(Reply::ReadBulk(BulkReadReply { results }))
|
||||
}
|
||||
Ok(CommandResult::SubscribeBulk(results)) => {
|
||||
let bulk = BulkSubscribeReply { results };
|
||||
reply.payload = Some(match kind {
|
||||
Kind::AddItemBulk => Reply::AddItemBulk(bulk),
|
||||
Kind::AdviseItemBulk => Reply::AdviseItemBulk(bulk),
|
||||
Kind::RemoveItemBulk => Reply::RemoveItemBulk(bulk),
|
||||
Kind::UnAdviseItemBulk => Reply::UnAdviseItemBulk(bulk),
|
||||
Kind::SubscribeBulk => Reply::SubscribeBulk(bulk),
|
||||
Kind::UnsubscribeBulk => Reply::UnsubscribeBulk(bulk),
|
||||
_ => unreachable!("command has no bulk subscription result"),
|
||||
});
|
||||
}
|
||||
Ok(CommandResult::Done) => {}
|
||||
@@ -657,7 +1022,7 @@ async fn execute(
|
||||
reply.statuses = statuses;
|
||||
}
|
||||
}
|
||||
events.publisher.discard_pending_write();
|
||||
publisher.discard_pending_write();
|
||||
}
|
||||
Ok(CommandResult::WriteBulk(results)) => {
|
||||
let bulk = BulkWriteReply { results };
|
||||
@@ -673,9 +1038,10 @@ async fn execute(
|
||||
set_status(&mut reply, ProtocolStatusCode::InvalidRequest, message);
|
||||
}
|
||||
Err(CommandError::NotRegistered) => {
|
||||
reply.hresult = Some(E_INVALIDARG);
|
||||
set_status(
|
||||
&mut reply,
|
||||
ProtocolStatusCode::InvalidRequest,
|
||||
ProtocolStatusCode::MxaccessFailure,
|
||||
"Server handle is not registered in this session",
|
||||
);
|
||||
}
|
||||
@@ -693,6 +1059,7 @@ struct EventStream {
|
||||
receiver: mpsc::Receiver<MxEvent>,
|
||||
faults: watch::Receiver<Option<EventFault>>,
|
||||
pending: Option<MxEvent>,
|
||||
alarm_worker: Option<AlarmWorker>,
|
||||
}
|
||||
|
||||
impl EventStream {
|
||||
@@ -703,6 +1070,7 @@ impl EventStream {
|
||||
receiver,
|
||||
faults,
|
||||
pending: None,
|
||||
alarm_worker: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -833,3 +1201,24 @@ fn now() -> Timestamp {
|
||||
fn pid() -> i32 {
|
||||
std::process::id() as i32
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::PendingCommands;
|
||||
|
||||
#[test]
|
||||
fn cancellation_only_marks_commands_that_have_not_started() {
|
||||
let pending = PendingCommands::default();
|
||||
pending.queue("running");
|
||||
pending.queue("queued");
|
||||
assert!(pending.begin("running"));
|
||||
pending.cancel("running");
|
||||
pending.cancel("queued");
|
||||
assert_eq!(pending.count(), 1);
|
||||
assert!(!pending.begin("queued"));
|
||||
pending.queue("another");
|
||||
pending.cancel_all();
|
||||
assert!(!pending.begin("another"));
|
||||
assert_eq!(pending.count(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,11 +55,6 @@ async fn activates_registers_and_shuts_down_over_a_windows_pipe() {
|
||||
pipe.connect().await.unwrap();
|
||||
let (mut reader, sender) = split(pipe);
|
||||
let mut writer = Writer::new(sender);
|
||||
let Body::WorkerHello(hello) = read_body(&mut reader, session).await else {
|
||||
panic!("expected WorkerHello");
|
||||
};
|
||||
assert_eq!(hello.nonce, token);
|
||||
assert_eq!(hello.worker_process_id, child.0.id() as i32);
|
||||
writer
|
||||
.send(
|
||||
session,
|
||||
@@ -74,6 +69,11 @@ async fn activates_registers_and_shuts_down_over_a_windows_pipe() {
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let Body::WorkerHello(hello) = read_body(&mut reader, session).await else {
|
||||
panic!("expected WorkerHello");
|
||||
};
|
||||
assert_eq!(hello.nonce, token);
|
||||
assert_eq!(hello.worker_process_id, child.0.id() as i32);
|
||||
let ready = read_body(&mut reader, session).await;
|
||||
let Body::WorkerReady(ready) = ready else {
|
||||
panic!("expected WorkerReady, got {ready:?}");
|
||||
@@ -247,7 +247,7 @@ async fn invoke(
|
||||
loop {
|
||||
let frame = wire::read(reader, session, 4096).await.unwrap();
|
||||
match frame.body.unwrap() {
|
||||
Body::WorkerHeartbeat(_) => {}
|
||||
Body::WorkerHeartbeat(_) | Body::WorkerEvent(_) => {}
|
||||
Body::WorkerCommandReply(result) => {
|
||||
let reply = result.reply.unwrap();
|
||||
assert_eq!(frame.correlation_id, correlation);
|
||||
|
||||
Reference in New Issue
Block a user