diff --git a/src/ZB.MOM.WW.MxGateway.IntegrationTests/WorkerLiveMxAccessSmokeTests.cs b/src/ZB.MOM.WW.MxGateway.IntegrationTests/WorkerLiveMxAccessSmokeTests.cs
index c95d284f..a0debd8a 100644
--- a/src/ZB.MOM.WW.MxGateway.IntegrationTests/WorkerLiveMxAccessSmokeTests.cs
+++ b/src/ZB.MOM.WW.MxGateway.IntegrationTests/WorkerLiveMxAccessSmokeTests.cs
@@ -475,6 +475,269 @@ public sealed class WorkerLiveMxAccessSmokeTests(ITestOutputHelper output)
}
}
+ /// Exercises bulk operations and both snapshot read paths over gRPC.
+ /// A task that represents the live test.
+ [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 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 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);
+ }
+ }
+
+ /// Verifies managed alarm provider callbacks forwarded by the Rust worker.
+ /// A task that represents the live test.
+ [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 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 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());
+ Manager = sessionManager;
MxAccessGrpcMapper mapper = new();
EventStreamService eventStreamService = new(
sessionManager,
@@ -2520,6 +2784,9 @@ public sealed class WorkerLiveMxAccessSmokeTests(ITestOutputHelper output)
///
public MxAccessGatewayService Service { get; }
+ /// The manager used by the gateway's internal alarm monitor.
+ public SessionManager Manager { get; }
+
///
/// 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
diff --git a/src/mxgateway-worker-rust/Cargo.lock b/src/mxgateway-worker-rust/Cargo.lock
index 9ba84348..96e18adb 100644
--- a/src/mxgateway-worker-rust/Cargo.lock
+++ b/src/mxgateway-worker-rust/Cargo.lock
@@ -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",
diff --git a/src/mxgateway-worker-rust/Cargo.toml b/src/mxgateway-worker-rust/Cargo.toml
index 94376a95..e1e2e1e0 100644
--- a/src/mxgateway-worker-rust/Cargo.toml
+++ b/src/mxgateway-worker-rust/Cargo.toml
@@ -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",
diff --git a/src/mxgateway-worker-rust/README.md b/src/mxgateway-worker-rust/README.md
index bbfa11f9..d500b363 100644
--- a/src/mxgateway-worker-rust/README.md
+++ b/src/mxgateway-worker-rust/README.md
@@ -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`
diff --git a/src/mxgateway-worker-rust/src/alarm.rs b/src/mxgateway-worker-rust/src/alarm.rs
new file mode 100644
index 00000000..e9b3fc98
--- /dev/null
+++ b/src/mxgateway-worker-rust/src/alarm.rs
@@ -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>,
+ replies: mpsc::Receiver,
+ reader: JoinHandle<()>,
+ shutting_down: Arc,
+}
+
+impl AlarmWorker {
+ pub async fn start(session: &str, max: usize, publisher: Publisher) -> io::Result {
+ 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 {
+ 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 {
+ 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 {
+ 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 {
+ 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 {
+ // 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::() 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",
+ )
+}
diff --git a/src/mxgateway-worker-rust/src/automation.rs b/src/mxgateway-worker-rust/src/automation.rs
index b986842e..1872abc4 100644
--- a/src/mxgateway-worker-rust/src/automation.rs
+++ b/src/mxgateway-worker-rust/src/automation.rs
@@ -660,13 +660,163 @@ fn file_time_timestamp(ticks: i64) -> Option {
// 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::