Prototype native Rust MXAccess worker
This commit is contained in:
Generated
+412
@@ -0,0 +1,412 @@
|
|||||||
|
# This file is automatically @generated by Cargo.
|
||||||
|
# It is not intended for manual editing.
|
||||||
|
version = 4
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "aho-corasick"
|
||||||
|
version = "1.1.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
|
||||||
|
dependencies = [
|
||||||
|
"memchr",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "anyhow"
|
||||||
|
version = "1.0.104"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "bitflags"
|
||||||
|
version = "2.13.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "bytes"
|
||||||
|
version = "1.12.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "cfg-if"
|
||||||
|
version = "1.0.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "either"
|
||||||
|
version = "1.19.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "equivalent"
|
||||||
|
version = "1.0.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "errno"
|
||||||
|
version = "0.3.15"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
"windows-sys",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "fastrand"
|
||||||
|
version = "2.5.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "fixedbitset"
|
||||||
|
version = "0.5.9"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "5905ec755cc8386d7928353e4d356d2be3e89e81e5ca01fe630a1ca4d08dc175"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "getrandom"
|
||||||
|
version = "0.4.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
|
||||||
|
dependencies = [
|
||||||
|
"cfg-if",
|
||||||
|
"libc",
|
||||||
|
"r-efi",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "hashbrown"
|
||||||
|
version = "0.17.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "heck"
|
||||||
|
version = "0.5.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "indexmap"
|
||||||
|
version = "2.14.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
|
||||||
|
dependencies = [
|
||||||
|
"equivalent",
|
||||||
|
"hashbrown",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "itertools"
|
||||||
|
version = "0.14.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"
|
||||||
|
dependencies = [
|
||||||
|
"either",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "libc"
|
||||||
|
version = "0.2.191"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "linux-raw-sys"
|
||||||
|
version = "0.12.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "log"
|
||||||
|
version = "0.4.35"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "memchr"
|
||||||
|
version = "2.8.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "mio"
|
||||||
|
version = "1.2.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
"wasi",
|
||||||
|
"windows-sys",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "multimap"
|
||||||
|
version = "0.10.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "mxgateway-worker-rust"
|
||||||
|
version = "0.1.0"
|
||||||
|
dependencies = [
|
||||||
|
"prost",
|
||||||
|
"prost-build",
|
||||||
|
"prost-types",
|
||||||
|
"tokio",
|
||||||
|
"windows-sys",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "once_cell"
|
||||||
|
version = "1.21.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "petgraph"
|
||||||
|
version = "0.7.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "3672b37090dbd86368a4145bc067582552b29c27377cad4e0a306c97f9bd7772"
|
||||||
|
dependencies = [
|
||||||
|
"fixedbitset",
|
||||||
|
"indexmap",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "pin-project-lite"
|
||||||
|
version = "0.2.18"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "prettyplease"
|
||||||
|
version = "0.2.37"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"syn 2.0.119",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "proc-macro2"
|
||||||
|
version = "1.0.107"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||||
|
dependencies = [
|
||||||
|
"unicode-ident",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "prost"
|
||||||
|
version = "0.13.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "2796faa41db3ec313a31f7624d9286acf277b52de526150b7e69f3debf891ee5"
|
||||||
|
dependencies = [
|
||||||
|
"bytes",
|
||||||
|
"prost-derive",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "prost-build"
|
||||||
|
version = "0.13.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "be769465445e8c1474e9c5dac2018218498557af32d9ed057325ec9a41ae81bf"
|
||||||
|
dependencies = [
|
||||||
|
"heck",
|
||||||
|
"itertools",
|
||||||
|
"log",
|
||||||
|
"multimap",
|
||||||
|
"once_cell",
|
||||||
|
"petgraph",
|
||||||
|
"prettyplease",
|
||||||
|
"prost",
|
||||||
|
"prost-types",
|
||||||
|
"regex",
|
||||||
|
"syn 2.0.119",
|
||||||
|
"tempfile",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "prost-derive"
|
||||||
|
version = "0.13.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "8a56d757972c98b346a9b766e3f02746cde6dd1cd1d1d563472929fdd74bec4d"
|
||||||
|
dependencies = [
|
||||||
|
"anyhow",
|
||||||
|
"itertools",
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn 2.0.119",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "prost-types"
|
||||||
|
version = "0.13.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "52c2c1bf36ddb1a1c396b3601a3cec27c2462e45f07c386894ec3ccf5332bd16"
|
||||||
|
dependencies = [
|
||||||
|
"prost",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "quote"
|
||||||
|
version = "1.0.47"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "r-efi"
|
||||||
|
version = "6.0.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "regex"
|
||||||
|
version = "1.13.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857"
|
||||||
|
dependencies = [
|
||||||
|
"aho-corasick",
|
||||||
|
"memchr",
|
||||||
|
"regex-automata",
|
||||||
|
"regex-syntax",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "regex-automata"
|
||||||
|
version = "0.4.19"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158"
|
||||||
|
dependencies = [
|
||||||
|
"aho-corasick",
|
||||||
|
"memchr",
|
||||||
|
"regex-syntax",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "regex-syntax"
|
||||||
|
version = "0.8.12"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rustix"
|
||||||
|
version = "1.1.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags",
|
||||||
|
"errno",
|
||||||
|
"libc",
|
||||||
|
"linux-raw-sys",
|
||||||
|
"windows-sys",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "socket2"
|
||||||
|
version = "0.6.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
"windows-sys",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "syn"
|
||||||
|
version = "2.0.119"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"unicode-ident",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "syn"
|
||||||
|
version = "3.0.10"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"unicode-ident",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tempfile"
|
||||||
|
version = "3.27.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
|
||||||
|
dependencies = [
|
||||||
|
"fastrand",
|
||||||
|
"getrandom",
|
||||||
|
"once_cell",
|
||||||
|
"rustix",
|
||||||
|
"windows-sys",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tokio"
|
||||||
|
version = "1.54.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3"
|
||||||
|
dependencies = [
|
||||||
|
"bytes",
|
||||||
|
"libc",
|
||||||
|
"mio",
|
||||||
|
"pin-project-lite",
|
||||||
|
"socket2",
|
||||||
|
"tokio-macros",
|
||||||
|
"windows-sys",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tokio-macros"
|
||||||
|
version = "2.7.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn 3.0.10",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "unicode-ident"
|
||||||
|
version = "1.0.27"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "wasi"
|
||||||
|
version = "0.11.1+wasi-snapshot-preview1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows-link"
|
||||||
|
version = "0.2.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows-sys"
|
||||||
|
version = "0.61.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
|
||||||
|
dependencies = [
|
||||||
|
"windows-link",
|
||||||
|
]
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
[package]
|
||||||
|
name = "mxgateway-worker-rust"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2021"
|
||||||
|
publish = false
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
prost = "0.13.5"
|
||||||
|
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"] }
|
||||||
|
windows-sys = { version = "0.61", features = [
|
||||||
|
"Win32_Foundation",
|
||||||
|
"Win32_Security",
|
||||||
|
"Win32_System_Com",
|
||||||
|
"Win32_System_Threading",
|
||||||
|
"Win32_UI_WindowsAndMessaging",
|
||||||
|
] }
|
||||||
|
|
||||||
|
[build-dependencies]
|
||||||
|
prost-build = "0.13.5"
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
tokio = { version = "1.48", features = ["macros", "rt"] }
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
# Rust MXAccess worker prototype
|
||||||
|
|
||||||
|
This crate exercises the gateway's existing worker contract with native 32-bit
|
||||||
|
Windows COM. Cargo generates the Rust protobuf types from the gateway's canonical
|
||||||
|
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, and the worker diagnostic
|
||||||
|
commands. Shutdown unregisters any remaining clients before releasing COM. The
|
||||||
|
existing C# worker is the gateway default.
|
||||||
|
|
||||||
|
COM connection points, event delivery, Advise, value and status conversion beyond
|
||||||
|
integer handles, writes, bulk commands, alarms, and record-info pinning remain to
|
||||||
|
be implemented. Unsupported commands return `InvalidRequest`. The prototype
|
||||||
|
serializes commands and does not interrupt COM calls on cancellation. If a call
|
||||||
|
exceeds the STA timeout, the worker faults the session and exits.
|
||||||
|
|
||||||
|
## Build and test
|
||||||
|
|
||||||
|
From this directory on Windows, with Rust, the x86 MSVC target and linker, and
|
||||||
|
`protoc` on PATH:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
cargo build --locked --release --target i686-pc-windows-msvc
|
||||||
|
cargo test --locked --target i686-pc-windows-msvc
|
||||||
|
```
|
||||||
|
|
||||||
|
On a development Windows host with 32-bit System Platform MXAccess registered,
|
||||||
|
run the opt-in test against a temporary pipe. Set
|
||||||
|
`MXGATEWAY_RUST_SMOKE_ITEM` to an item available in that host's Galaxy to include
|
||||||
|
AddItem and RemoveItem in the smoke test.
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$env:MXGATEWAY_RUST_SMOKE_ITEM = 'TestChildObject.TestInt'
|
||||||
|
cargo test --locked --target i686-pc-windows-msvc --test live_mxaccess -- --ignored
|
||||||
|
```
|
||||||
|
|
||||||
|
The smoke test starts and terminates its own worker and exercises the pipe
|
||||||
|
handshake, heartbeat, registration, item lifecycle when configured, and graceful
|
||||||
|
shutdown. It runs without a gateway service. Portable framing tests also run
|
||||||
|
with `cargo test --locked` on macOS and Linux.
|
||||||
|
|
||||||
|
## COM interface evidence
|
||||||
|
|
||||||
|
The native adapter uses the dual `ILMXProxyServer` interface from the installed
|
||||||
|
`ArchestrA.MxAccess` 3.2.0.0 assembly. REA inspection confirmed the declaration
|
||||||
|
order and managed signatures for Register, Unregister, AddItem, and RemoveItem.
|
||||||
|
Windows reflection confirmed the interface IID, dual-interface flag, DISPIDs, and
|
||||||
|
BSTR input annotations. The live test exercises the corresponding native calls.
|
||||||
|
|
||||||
|
- Assembly SHA-256
|
||||||
|
`cba8b607305ee0c70ca38b09eca645ae3b98c35a7b78ec051eb4381f48d9e0b1`
|
||||||
|
- REA managed member evidence
|
||||||
|
`ev_78053da509335e3e3749b8e6bb020f28c45255b54d910546659c6760eb52160b`
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
use std::{io, path::Path};
|
||||||
|
|
||||||
|
fn main() -> io::Result<()> {
|
||||||
|
let directory = Path::new("../ZB.MOM.WW.MxGateway.Contracts/Protos");
|
||||||
|
let worker = directory.join("mxaccess_worker.proto");
|
||||||
|
let gateway = directory.join("mxaccess_gateway.proto");
|
||||||
|
println!("cargo:rerun-if-changed={}", worker.display());
|
||||||
|
println!("cargo:rerun-if-changed={}", gateway.display());
|
||||||
|
prost_build::compile_protos(&[worker, gateway], &[directory])
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
#[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 mxaccess;
|
||||||
|
#[cfg(all(windows, target_arch = "x86"))]
|
||||||
|
mod session;
|
||||||
|
#[cfg(any(windows, test))]
|
||||||
|
mod wire;
|
||||||
|
|
||||||
|
#[cfg(all(windows, target_arch = "x86"))]
|
||||||
|
#[tokio::main(flavor = "current_thread")]
|
||||||
|
async fn main() -> std::process::ExitCode {
|
||||||
|
match session::run().await {
|
||||||
|
Ok(()) => std::process::ExitCode::SUCCESS,
|
||||||
|
Err(error) => {
|
||||||
|
eprintln!("Rust MXAccess worker: {error}");
|
||||||
|
std::process::ExitCode::from(error.exit_code())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
fn main() -> std::process::ExitCode {
|
||||||
|
eprintln!("The MXAccess worker requires 32-bit Windows.");
|
||||||
|
std::process::ExitCode::FAILURE
|
||||||
|
}
|
||||||
@@ -0,0 +1,351 @@
|
|||||||
|
use std::collections::BTreeSet;
|
||||||
|
use std::ffi::c_void;
|
||||||
|
use std::io;
|
||||||
|
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
|
||||||
|
use std::ptr::{null, null_mut, NonNull};
|
||||||
|
use std::sync::{mpsc, Arc};
|
||||||
|
use std::thread;
|
||||||
|
use tokio::sync::oneshot;
|
||||||
|
use windows_sys::core::{BSTR, GUID, HRESULT};
|
||||||
|
use windows_sys::Win32::Foundation::{SysAllocStringLen, SysFreeString, WAIT_OBJECT_0};
|
||||||
|
use windows_sys::Win32::System::Com::{
|
||||||
|
CoCreateInstance, CoInitializeEx, CoUninitialize, CLSCTX_INPROC_SERVER,
|
||||||
|
COINIT_APARTMENTTHREADED,
|
||||||
|
};
|
||||||
|
use windows_sys::Win32::System::Threading::{CreateEventW, SetEvent, INFINITE};
|
||||||
|
use windows_sys::Win32::UI::WindowsAndMessaging::{
|
||||||
|
DispatchMessageW, MsgWaitForMultipleObjectsEx, PeekMessageW, TranslateMessage, MSG,
|
||||||
|
MWMO_INPUTAVAILABLE, PM_REMOVE, QS_ALLINPUT, WM_QUIT,
|
||||||
|
};
|
||||||
|
|
||||||
|
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);
|
||||||
|
|
||||||
|
pub enum Command {
|
||||||
|
Probe,
|
||||||
|
Register(String),
|
||||||
|
Unregister(i32),
|
||||||
|
AddItem(i32, String),
|
||||||
|
RemoveItem(i32, i32),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub enum CommandError {
|
||||||
|
NotRegistered,
|
||||||
|
HResult(HRESULT),
|
||||||
|
}
|
||||||
|
|
||||||
|
type Outcome = Result<Option<i32>, CommandError>;
|
||||||
|
|
||||||
|
pub enum StartError {
|
||||||
|
Io(io::Error),
|
||||||
|
Com(HRESULT),
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Request {
|
||||||
|
command: Command,
|
||||||
|
reply: oneshot::Sender<Outcome>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Sta {
|
||||||
|
queue: Option<mpsc::Sender<Request>>,
|
||||||
|
wake: Arc<OwnedHandle>,
|
||||||
|
stopped: Option<oneshot::Receiver<usize>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Sta {
|
||||||
|
pub async fn start() -> Result<Self, StartError> {
|
||||||
|
// SAFETY: unnamed auto-reset event. Ownership transfers to OwnedHandle.
|
||||||
|
let event = unsafe { CreateEventW(null(), 0, 0, null()) };
|
||||||
|
if event.is_null() {
|
||||||
|
return Err(StartError::Io(io::Error::last_os_error()));
|
||||||
|
}
|
||||||
|
let wake = Arc::new(unsafe { OwnedHandle::from_raw_handle(event) });
|
||||||
|
let (queue, requests) = mpsc::channel();
|
||||||
|
let (ready, startup) = oneshot::channel();
|
||||||
|
let (finished, stopped) = oneshot::channel();
|
||||||
|
let thread_wake = Arc::clone(&wake);
|
||||||
|
thread::Builder::new()
|
||||||
|
.name("mxgateway-sta".into())
|
||||||
|
.spawn(move || run(requests, thread_wake, ready, finished))
|
||||||
|
.map_err(StartError::Io)?;
|
||||||
|
|
||||||
|
let sta = Self {
|
||||||
|
queue: Some(queue),
|
||||||
|
wake,
|
||||||
|
stopped: Some(stopped),
|
||||||
|
};
|
||||||
|
startup
|
||||||
|
.await
|
||||||
|
.map_err(|_| StartError::Io(sta_stopped()))?
|
||||||
|
.map_err(StartError::Com)?;
|
||||||
|
Ok(sta)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn execute(&self, command: Command) -> io::Result<Outcome> {
|
||||||
|
let (reply, response) = oneshot::channel();
|
||||||
|
self.queue
|
||||||
|
.as_ref()
|
||||||
|
.expect("STA is open")
|
||||||
|
.send(Request { command, reply })
|
||||||
|
.map_err(|_| sta_stopped())?;
|
||||||
|
self.signal()?;
|
||||||
|
response.await.map_err(|_| sta_stopped())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn shutdown(mut self) -> io::Result<usize> {
|
||||||
|
self.queue.take();
|
||||||
|
self.signal()?;
|
||||||
|
self.stopped
|
||||||
|
.take()
|
||||||
|
.expect("STA has a shutdown receiver")
|
||||||
|
.await
|
||||||
|
.map_err(|_| sta_stopped())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn signal(&self) -> io::Result<()> {
|
||||||
|
// SAFETY: both threads hold an owned reference to the same event.
|
||||||
|
if unsafe { SetEvent(self.wake.as_raw_handle()) } == 0 {
|
||||||
|
return Err(io::Error::last_os_error());
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for Sta {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if self.queue.take().is_some() {
|
||||||
|
let _ = self.signal();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sta_stopped() -> io::Error {
|
||||||
|
io::Error::other("MXAccess STA exited")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run(
|
||||||
|
requests: mpsc::Receiver<Request>,
|
||||||
|
wake: Arc<OwnedHandle>,
|
||||||
|
ready: oneshot::Sender<Result<(), HRESULT>>,
|
||||||
|
finished: oneshot::Sender<usize>,
|
||||||
|
) {
|
||||||
|
let apartment = match Apartment::initialize() {
|
||||||
|
Ok(apartment) => apartment,
|
||||||
|
Err(error) => {
|
||||||
|
let _ = ready.send(Err(error));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let mut proxy = match Proxy::activate() {
|
||||||
|
Ok(proxy) => proxy,
|
||||||
|
Err(error) => {
|
||||||
|
let _ = ready.send(Err(error));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if ready.send(Ok(())).is_ok() {
|
||||||
|
pump(&requests, &wake, &mut proxy);
|
||||||
|
}
|
||||||
|
let failures = proxy.cleanup();
|
||||||
|
drop(proxy);
|
||||||
|
drop(apartment);
|
||||||
|
let _ = finished.send(failures);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pump(requests: &mpsc::Receiver<Request>, wake: &OwnedHandle, proxy: &mut Proxy) {
|
||||||
|
let handle = wake.as_raw_handle();
|
||||||
|
loop {
|
||||||
|
// SAFETY: the wait uses one valid event and the current STA's message queue.
|
||||||
|
let result = unsafe {
|
||||||
|
MsgWaitForMultipleObjectsEx(1, &handle, INFINITE, QS_ALLINPUT, MWMO_INPUTAVAILABLE)
|
||||||
|
};
|
||||||
|
match result {
|
||||||
|
WAIT_OBJECT_0 => loop {
|
||||||
|
match requests.try_recv() {
|
||||||
|
Ok(request) => {
|
||||||
|
let _ = request.reply.send(proxy.execute(request.command));
|
||||||
|
}
|
||||||
|
Err(mpsc::TryRecvError::Empty) => break,
|
||||||
|
Err(mpsc::TryRecvError::Disconnected) => return,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
1 => {
|
||||||
|
let mut message = MSG::default();
|
||||||
|
// SAFETY: MSG lives across PeekMessageW and dispatch on this STA.
|
||||||
|
while unsafe { PeekMessageW(&mut message, null_mut(), 0, 0, PM_REMOVE) } != 0 {
|
||||||
|
if message.message == WM_QUIT {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
unsafe {
|
||||||
|
TranslateMessage(&message);
|
||||||
|
DispatchMessageW(&message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => return,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Apartment;
|
||||||
|
|
||||||
|
impl Apartment {
|
||||||
|
fn initialize() -> Result<Self, HRESULT> {
|
||||||
|
// SAFETY: this runs on the new dedicated thread and is balanced by Drop.
|
||||||
|
check(unsafe { CoInitializeEx(null(), COINIT_APARTMENTTHREADED as u32) })?;
|
||||||
|
Ok(Self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for Apartment {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
// SAFETY: same thread as successful CoInitializeEx. Proxy has been released.
|
||||||
|
unsafe { CoUninitialize() };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// First eleven slots of the installed dual ILMXProxyServer interface. Slots
|
||||||
|
// 0–6 are IUnknown and IDispatch. The next four slots follow the installed
|
||||||
|
// interop assembly, with HRESULT and [out, retval] for the handle results.
|
||||||
|
#[repr(C)]
|
||||||
|
struct ProxyVtable {
|
||||||
|
query_interface:
|
||||||
|
unsafe extern "system" fn(*mut c_void, *const GUID, *mut *mut c_void) -> HRESULT,
|
||||||
|
add_ref: unsafe extern "system" fn(*mut c_void) -> u32,
|
||||||
|
release: unsafe extern "system" fn(*mut c_void) -> u32,
|
||||||
|
dispatch_slots: [usize; 4],
|
||||||
|
register: unsafe extern "system" fn(*mut c_void, BSTR, *mut i32) -> HRESULT,
|
||||||
|
unregister: unsafe extern "system" fn(*mut c_void, i32) -> HRESULT,
|
||||||
|
add_item: unsafe extern "system" fn(*mut c_void, i32, BSTR, *mut i32) -> HRESULT,
|
||||||
|
remove_item: unsafe extern "system" fn(*mut c_void, i32, i32) -> HRESULT,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Proxy {
|
||||||
|
interface: NonNull<c_void>,
|
||||||
|
registrations: BTreeSet<i32>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Proxy {
|
||||||
|
fn activate() -> Result<Self, HRESULT> {
|
||||||
|
let mut interface = null_mut();
|
||||||
|
// SAFETY: the output is for the exact IID declared by ProxyVtable.
|
||||||
|
check(unsafe {
|
||||||
|
CoCreateInstance(
|
||||||
|
&CLSID,
|
||||||
|
null_mut(),
|
||||||
|
CLSCTX_INPROC_SERVER,
|
||||||
|
&IID,
|
||||||
|
&mut interface,
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
Ok(Self {
|
||||||
|
interface: NonNull::new(interface).ok_or(0x8000_4003_u32 as i32)?,
|
||||||
|
registrations: BTreeSet::new(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn execute(&mut self, command: Command) -> Outcome {
|
||||||
|
let object = self.interface.as_ptr();
|
||||||
|
let table = self.vtable();
|
||||||
|
let mut handle = 0;
|
||||||
|
// SAFETY: the proxy and temporary BSTRs are local to this STA.
|
||||||
|
match command {
|
||||||
|
Command::Probe => Ok(None),
|
||||||
|
Command::Register(name) => {
|
||||||
|
let name = AutomationString::new(&name).map_err(CommandError::HResult)?;
|
||||||
|
check(unsafe { (table.register)(object, name.0, &mut handle) })
|
||||||
|
.map_err(CommandError::HResult)?;
|
||||||
|
self.registrations.insert(handle);
|
||||||
|
Ok(Some(handle))
|
||||||
|
}
|
||||||
|
Command::Unregister(server) => {
|
||||||
|
self.require_registration(server)?;
|
||||||
|
check(unsafe { (table.unregister)(object, server) })
|
||||||
|
.map_err(CommandError::HResult)?;
|
||||||
|
self.registrations.remove(&server);
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
Command::AddItem(server, definition) => {
|
||||||
|
self.require_registration(server)?;
|
||||||
|
let definition =
|
||||||
|
AutomationString::new(&definition).map_err(CommandError::HResult)?;
|
||||||
|
check(unsafe { (table.add_item)(object, server, definition.0, &mut handle) })
|
||||||
|
.map_err(CommandError::HResult)?;
|
||||||
|
Ok(Some(handle))
|
||||||
|
}
|
||||||
|
Command::RemoveItem(server, item) => {
|
||||||
|
self.require_registration(server)?;
|
||||||
|
check(unsafe { (table.remove_item)(object, server, item) })
|
||||||
|
.map_err(CommandError::HResult)?;
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn require_registration(&self, server: i32) -> Result<(), CommandError> {
|
||||||
|
if self.registrations.contains(&server) {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(CommandError::NotRegistered)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cleanup(&mut self) -> usize {
|
||||||
|
let mut failures = 0;
|
||||||
|
for server in std::mem::take(&mut self.registrations) {
|
||||||
|
// SAFETY: the interface is still live on this STA.
|
||||||
|
let hr = unsafe { (self.vtable().unregister)(self.interface.as_ptr(), server) };
|
||||||
|
if hr < 0 {
|
||||||
|
failures += 1;
|
||||||
|
eprintln!(
|
||||||
|
"MXAccess unregister during shutdown failed (HRESULT 0x{:08X})",
|
||||||
|
hr as u32
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
failures
|
||||||
|
}
|
||||||
|
|
||||||
|
fn vtable(&self) -> &ProxyVtable {
|
||||||
|
// SAFETY: a live COM interface starts with its vtable pointer.
|
||||||
|
unsafe { &**self.interface.as_ptr().cast::<*const ProxyVtable>() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for Proxy {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
// SAFETY: release the reference returned by CoCreateInstance on this STA.
|
||||||
|
unsafe { (self.vtable().release)(self.interface.as_ptr()) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct AutomationString(BSTR);
|
||||||
|
|
||||||
|
impl AutomationString {
|
||||||
|
fn new(value: &str) -> Result<Self, HRESULT> {
|
||||||
|
let utf16: Vec<_> = value.encode_utf16().collect();
|
||||||
|
// SAFETY: SysAllocStringLen copies exactly the supplied code units.
|
||||||
|
let string = unsafe { SysAllocStringLen(utf16.as_ptr(), utf16.len() as u32) };
|
||||||
|
if string.is_null() {
|
||||||
|
return Err(0x8007_000E_u32 as i32);
|
||||||
|
}
|
||||||
|
Ok(Self(string))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for AutomationString {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
// SAFETY: this BSTR came from SysAllocStringLen.
|
||||||
|
unsafe { SysFreeString(self.0) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check(status: HRESULT) -> Result<(), HRESULT> {
|
||||||
|
if status >= 0 {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(status)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,559 @@
|
|||||||
|
use std::collections::HashMap;
|
||||||
|
use std::io;
|
||||||
|
use std::time::{Duration, SystemTime};
|
||||||
|
|
||||||
|
use prost_types::Timestamp;
|
||||||
|
use tokio::io::{split, AsyncWrite};
|
||||||
|
use tokio::net::windows::named_pipe::{ClientOptions, NamedPipeClient};
|
||||||
|
use tokio::sync::mpsc;
|
||||||
|
use tokio::time::{interval, sleep, timeout, Instant, MissedTickBehavior};
|
||||||
|
|
||||||
|
use crate::mxaccess::{Command, CommandError, Sta, StartError, CLASS_ID, PROG_ID};
|
||||||
|
use crate::wire::{
|
||||||
|
self,
|
||||||
|
mxaccess_gateway::v1::{
|
||||||
|
mx_command, mx_command_reply, mx_value, AddItemReply, DrainEventsReply, MxCommand,
|
||||||
|
MxCommandKind, MxCommandReply, MxDataType, MxValue, ProtocolStatus, ProtocolStatusCode,
|
||||||
|
RegisterReply, SessionState, SessionStateReply, WorkerInfoReply,
|
||||||
|
},
|
||||||
|
mxaccess_worker::v1::{
|
||||||
|
GatewayHello, WorkerCommand, WorkerCommandReply, WorkerFault, WorkerFaultCategory,
|
||||||
|
WorkerHeartbeat, WorkerHello, WorkerReady, WorkerShutdownAck, WorkerState,
|
||||||
|
},
|
||||||
|
Body, Writer, DEFAULT_MAX, VERSION,
|
||||||
|
};
|
||||||
|
|
||||||
|
const WORKER_VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), "-rust");
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Error(u8, String);
|
||||||
|
|
||||||
|
impl Error {
|
||||||
|
pub fn exit_code(&self) -> u8 {
|
||||||
|
self.0
|
||||||
|
}
|
||||||
|
|
||||||
|
fn protocol(message: impl Into<String>) -> Self {
|
||||||
|
Self(6, message.into())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sta(error: io::Error) -> Self {
|
||||||
|
Self(1, error.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Display for Error {
|
||||||
|
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
formatter.write_str(&self.1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<io::Error> for Error {
|
||||||
|
fn from(error: io::Error) -> Self {
|
||||||
|
if error.kind() == io::ErrorKind::InvalidData {
|
||||||
|
return Self::protocol(error.to_string());
|
||||||
|
}
|
||||||
|
Self(5, error.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Options {
|
||||||
|
session: String,
|
||||||
|
pipe_name: String,
|
||||||
|
nonce: String,
|
||||||
|
connect_timeout: Duration,
|
||||||
|
heartbeat_interval: Duration,
|
||||||
|
sta_grace: Duration,
|
||||||
|
command_ceiling: Duration,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Options {
|
||||||
|
fn load() -> Result<Self, Error> {
|
||||||
|
let invalid = || {
|
||||||
|
Error(
|
||||||
|
2,
|
||||||
|
"Expected --session-id, --pipe-name and --protocol-version".into(),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
let mut args = std::env::args().skip(1);
|
||||||
|
let mut values = HashMap::new();
|
||||||
|
while let Some(name) = args.next() {
|
||||||
|
let name = name.to_ascii_lowercase();
|
||||||
|
if !matches!(
|
||||||
|
name.as_str(),
|
||||||
|
"--session-id" | "--pipe-name" | "--protocol-version"
|
||||||
|
) {
|
||||||
|
return Err(invalid());
|
||||||
|
}
|
||||||
|
let value = args
|
||||||
|
.next()
|
||||||
|
.filter(|value| !value.trim().is_empty() && !value.starts_with("--"))
|
||||||
|
.ok_or_else(invalid)?;
|
||||||
|
if values.insert(name, value).is_some() {
|
||||||
|
return Err(invalid());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let session = values.remove("--session-id").ok_or_else(invalid)?;
|
||||||
|
let pipe_name = values.remove("--pipe-name").ok_or_else(invalid)?;
|
||||||
|
let version = values.remove("--protocol-version").ok_or_else(invalid)?;
|
||||||
|
if version.parse() != Ok(VERSION) {
|
||||||
|
return Err(Error(3, "Unsupported worker protocol version".into()));
|
||||||
|
}
|
||||||
|
let nonce = std::env::var("MXGATEWAY_WORKER_NONCE")
|
||||||
|
.ok()
|
||||||
|
.filter(|nonce| !nonce.trim().is_empty())
|
||||||
|
.ok_or_else(|| Error(4, "Worker launch nonce is missing".into()))?;
|
||||||
|
Ok(Self {
|
||||||
|
session,
|
||||||
|
pipe_name,
|
||||||
|
nonce,
|
||||||
|
connect_timeout: env_duration("MXGATEWAY_WORKER_PIPE_CONNECT_ATTEMPT_TIMEOUT_MS", 2000),
|
||||||
|
heartbeat_interval: env_duration("MXGATEWAY_WORKER_HEARTBEAT_SEND_INTERVAL_MS", 5000),
|
||||||
|
sta_grace: env_duration("MXGATEWAY_WORKER_HEARTBEAT_GRACE_MS", 15000),
|
||||||
|
command_ceiling: env_duration("MXGATEWAY_WORKER_HEARTBEAT_STUCK_CEILING_MS", 75000),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn env_duration(key: &str, default: u32) -> Duration {
|
||||||
|
let milliseconds = std::env::var(key)
|
||||||
|
.ok()
|
||||||
|
.and_then(|value| value.parse::<u32>().ok())
|
||||||
|
.filter(|value| *value > 0);
|
||||||
|
Duration::from_millis(milliseconds.unwrap_or(default).into())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn connect(options: &Options) -> io::Result<NamedPipeClient> {
|
||||||
|
let deadline = Instant::now() + options.connect_timeout;
|
||||||
|
let address = format!(r"\\.\pipe\{}", options.pipe_name);
|
||||||
|
loop {
|
||||||
|
match ClientOptions::new().open(&address) {
|
||||||
|
Ok(pipe) => return Ok(pipe),
|
||||||
|
Err(error)
|
||||||
|
if matches!(error.raw_os_error(), Some(2 | 231)) && Instant::now() < deadline =>
|
||||||
|
{
|
||||||
|
sleep(Duration::from_millis(25)).await;
|
||||||
|
}
|
||||||
|
Err(error) => return Err(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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,
|
||||||
|
Err((category, error)) => {
|
||||||
|
fault(
|
||||||
|
&mut writer,
|
||||||
|
&options.session,
|
||||||
|
DEFAULT_MAX,
|
||||||
|
category,
|
||||||
|
None,
|
||||||
|
&error.1,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
return Err(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let sta = match Sta::start().await {
|
||||||
|
Ok(sta) => sta,
|
||||||
|
Err(error) => {
|
||||||
|
let (hresult, diagnostic) = match error {
|
||||||
|
StartError::Io(error) => (None, error.to_string()),
|
||||||
|
StartError::Com(hr) => (
|
||||||
|
Some(hr),
|
||||||
|
format!("MXAccess activation failed (HRESULT 0x{:08X})", hr as u32),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
fault(
|
||||||
|
&mut writer,
|
||||||
|
&options.session,
|
||||||
|
max,
|
||||||
|
WorkerFaultCategory::MxaccessCreationFailed,
|
||||||
|
hresult,
|
||||||
|
&diagnostic,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
return Err(Error(1, diagnostic));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
writer
|
||||||
|
.send(
|
||||||
|
&options.session,
|
||||||
|
"",
|
||||||
|
Body::WorkerReady(WorkerReady {
|
||||||
|
worker_process_id: pid(),
|
||||||
|
mxaccess_progid: PROG_ID.into(),
|
||||||
|
mxaccess_clsid: CLASS_ID.into(),
|
||||||
|
ready_timestamp: Some(now()),
|
||||||
|
record_info_pin_status: String::new(),
|
||||||
|
}),
|
||||||
|
max,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
// Run the frame reader independently so a heartbeat cannot cancel a partial read.
|
||||||
|
let (incoming, mut frames) = mpsc::channel(1);
|
||||||
|
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 result = command_loop(&options, max, &sta, &mut writer, &mut frames).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 (code, message) = match shutdown {
|
||||||
|
Ok(Ok(0)) => (ProtocolStatusCode::Ok, "Graceful shutdown completed".into()),
|
||||||
|
Ok(Ok(failures)) => (
|
||||||
|
ProtocolStatusCode::Ok,
|
||||||
|
format!("Graceful shutdown completed with {failures} cleanup failure(s)"),
|
||||||
|
),
|
||||||
|
Ok(Err(error)) => (ProtocolStatusCode::MxaccessFailure, error.to_string()),
|
||||||
|
Err(_) => (
|
||||||
|
ProtocolStatusCode::Timeout,
|
||||||
|
"MXAccess shutdown timed out".into(),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
writer
|
||||||
|
.send(
|
||||||
|
&options.session,
|
||||||
|
"",
|
||||||
|
Body::WorkerShutdownAck(WorkerShutdownAck {
|
||||||
|
status: Some(status(code, message)),
|
||||||
|
}),
|
||||||
|
max,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(Error::from)
|
||||||
|
}
|
||||||
|
Err(error) => {
|
||||||
|
let _ = timeout(Duration::from_secs(2), sta.shutdown()).await;
|
||||||
|
Err(error)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
reader_task.abort();
|
||||||
|
acknowledgement
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check_hello(
|
||||||
|
body: Option<Body>,
|
||||||
|
launch_nonce: &str,
|
||||||
|
) -> Result<usize, (WorkerFaultCategory, Error)> {
|
||||||
|
use WorkerFaultCategory::{ProtocolMismatch, ProtocolViolation};
|
||||||
|
let Some(Body::GatewayHello(GatewayHello {
|
||||||
|
supported_protocol_version,
|
||||||
|
nonce,
|
||||||
|
max_frame_bytes,
|
||||||
|
..
|
||||||
|
})) = body
|
||||||
|
else {
|
||||||
|
return Err((ProtocolViolation, Error::protocol("Expected GatewayHello")));
|
||||||
|
};
|
||||||
|
if supported_protocol_version != VERSION {
|
||||||
|
return Err((
|
||||||
|
ProtocolMismatch,
|
||||||
|
Error::protocol("GatewayHello protocol version mismatch"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if nonce != launch_nonce {
|
||||||
|
return Err((
|
||||||
|
ProtocolViolation,
|
||||||
|
Error::protocol("GatewayHello nonce mismatch"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
wire::negotiated_max(max_frame_bytes).map_err(|error| (ProtocolViolation, error.into()))
|
||||||
|
}
|
||||||
|
|
||||||
|
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>>,
|
||||||
|
) -> Result<Duration, Error> {
|
||||||
|
let mut heartbeat = interval(options.heartbeat_interval);
|
||||||
|
heartbeat.set_missed_tick_behavior(MissedTickBehavior::Delay);
|
||||||
|
loop {
|
||||||
|
tokio::select! {
|
||||||
|
frame = 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.session, &correlation),
|
||||||
|
).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 shutdown = kind == MxCommandKind::ShutdownWorker as i32
|
||||||
|
&& reply.protocol_status.as_ref().is_some_and(|status| status.code() == ProtocolStatusCode::Ok);
|
||||||
|
if let Err(error) = send_reply(writer, &options.session, &correlation, reply, max).await {
|
||||||
|
if error.kind() != io::ErrorKind::InvalidData {
|
||||||
|
return Err(error.into());
|
||||||
|
}
|
||||||
|
reply = command_reply(&options.session, &correlation, kind);
|
||||||
|
set_status(&mut reply, ProtocolStatusCode::InvalidRequest, "Command reply exceeds the negotiated frame maximum");
|
||||||
|
send_reply(writer, &options.session, &correlation, reply, max).await?;
|
||||||
|
}
|
||||||
|
if shutdown {
|
||||||
|
return Ok(Duration::from_secs(10));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Body::WorkerShutdown(shutdown) => {
|
||||||
|
let grace = shutdown.grace_period.and_then(|value| Duration::try_from(value).ok())
|
||||||
|
.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;
|
||||||
|
return Err(Error::protocol(message));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ = heartbeat.tick() => {
|
||||||
|
if !matches!(timeout(options.sta_grace, sta.execute(Command::Probe)).await, Ok(Ok(Ok(_)))) {
|
||||||
|
let message = "MXAccess STA did not respond to heartbeat probe";
|
||||||
|
fault(writer, &options.session, max, WorkerFaultCategory::StaHung, None, message).await;
|
||||||
|
return Err(Error(1, message.into()));
|
||||||
|
}
|
||||||
|
writer.send(&options.session, "", Body::WorkerHeartbeat(WorkerHeartbeat {
|
||||||
|
worker_process_id: pid(),
|
||||||
|
state: WorkerState::Ready as i32,
|
||||||
|
last_sta_activity_timestamp: Some(now()),
|
||||||
|
..Default::default()
|
||||||
|
}), max).await?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn execute(
|
||||||
|
sta: &Sta,
|
||||||
|
command: Option<MxCommand>,
|
||||||
|
session: &str,
|
||||||
|
correlation: &str,
|
||||||
|
) -> Result<MxCommandReply, Error> {
|
||||||
|
use mx_command::Payload;
|
||||||
|
use mx_command_reply::Payload as Reply;
|
||||||
|
use MxCommandKind as Kind;
|
||||||
|
|
||||||
|
let mut reply = command_reply(
|
||||||
|
session,
|
||||||
|
correlation,
|
||||||
|
command.as_ref().map_or(0, |command| command.kind),
|
||||||
|
);
|
||||||
|
let Some(command) = command else {
|
||||||
|
set_status(
|
||||||
|
&mut reply,
|
||||||
|
ProtocolStatusCode::InvalidRequest,
|
||||||
|
"Command body is required",
|
||||||
|
);
|
||||||
|
return Ok(reply);
|
||||||
|
};
|
||||||
|
let kind = command.kind();
|
||||||
|
let native = match (kind, command.payload) {
|
||||||
|
(Kind::Register, Some(Payload::Register(request))) => {
|
||||||
|
Command::Register(request.client_name)
|
||||||
|
}
|
||||||
|
(Kind::Unregister, Some(Payload::Unregister(request))) => {
|
||||||
|
Command::Unregister(request.server_handle)
|
||||||
|
}
|
||||||
|
(Kind::AddItem, Some(Payload::AddItem(request))) => {
|
||||||
|
Command::AddItem(request.server_handle, request.item_definition)
|
||||||
|
}
|
||||||
|
(Kind::RemoveItem, Some(Payload::RemoveItem(request))) => {
|
||||||
|
Command::RemoveItem(request.server_handle, request.item_handle)
|
||||||
|
}
|
||||||
|
(Kind::Ping, Some(Payload::Ping(request))) => {
|
||||||
|
reply.diagnostic_message = request.message;
|
||||||
|
return Ok(reply);
|
||||||
|
}
|
||||||
|
(Kind::Ping | Kind::ShutdownWorker, None)
|
||||||
|
| (Kind::ShutdownWorker, Some(Payload::ShutdownWorker(_))) => return Ok(reply),
|
||||||
|
(Kind::GetSessionState, None | Some(Payload::GetSessionState(_))) => {
|
||||||
|
reply.payload = Some(Reply::SessionState(SessionStateReply {
|
||||||
|
state: SessionState::Ready as i32,
|
||||||
|
}));
|
||||||
|
return Ok(reply);
|
||||||
|
}
|
||||||
|
(Kind::GetWorkerInfo, None | Some(Payload::GetWorkerInfo(_))) => {
|
||||||
|
reply.payload = Some(Reply::WorkerInfo(WorkerInfoReply {
|
||||||
|
worker_process_id: pid(),
|
||||||
|
worker_version: WORKER_VERSION.into(),
|
||||||
|
mxaccess_progid: PROG_ID.into(),
|
||||||
|
mxaccess_clsid: CLASS_ID.into(),
|
||||||
|
}));
|
||||||
|
return Ok(reply);
|
||||||
|
}
|
||||||
|
(Kind::DrainEvents, None | Some(Payload::DrainEvents(_))) => {
|
||||||
|
reply.payload = Some(Reply::DrainEvents(DrainEventsReply::default()));
|
||||||
|
return Ok(reply);
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
set_status(
|
||||||
|
&mut reply,
|
||||||
|
ProtocolStatusCode::InvalidRequest,
|
||||||
|
"Unsupported command or missing matching payload",
|
||||||
|
);
|
||||||
|
return Ok(reply);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
match sta.execute(native).await.map_err(Error::sta)? {
|
||||||
|
Ok(Some(handle)) => {
|
||||||
|
reply.return_value = Some(MxValue {
|
||||||
|
data_type: MxDataType::Integer as i32,
|
||||||
|
variant_type: "VT_I4".into(),
|
||||||
|
kind: Some(mx_value::Kind::Int32Value(handle)),
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
reply.payload = Some(match kind {
|
||||||
|
Kind::Register => Reply::Register(RegisterReply {
|
||||||
|
server_handle: handle,
|
||||||
|
}),
|
||||||
|
Kind::AddItem => Reply::AddItem(AddItemReply {
|
||||||
|
item_handle: handle,
|
||||||
|
}),
|
||||||
|
_ => unreachable!("only Register and AddItem return a handle"),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(None) => {}
|
||||||
|
Err(CommandError::NotRegistered) => {
|
||||||
|
set_status(
|
||||||
|
&mut reply,
|
||||||
|
ProtocolStatusCode::InvalidRequest,
|
||||||
|
"Server handle is not registered in this session",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Err(CommandError::HResult(hr)) => {
|
||||||
|
reply.hresult = Some(hr);
|
||||||
|
let message = format!("MXAccess command failed (HRESULT 0x{:08X})", hr as u32);
|
||||||
|
set_status(&mut reply, ProtocolStatusCode::MxaccessFailure, &message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(reply)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn command_reply(session: &str, correlation: &str, kind: i32) -> MxCommandReply {
|
||||||
|
MxCommandReply {
|
||||||
|
session_id: session.into(),
|
||||||
|
correlation_id: correlation.into(),
|
||||||
|
kind,
|
||||||
|
protocol_status: Some(status(ProtocolStatusCode::Ok, "")),
|
||||||
|
hresult: Some(0),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_status(reply: &mut MxCommandReply, code: ProtocolStatusCode, message: &str) {
|
||||||
|
reply.protocol_status = Some(status(code, message));
|
||||||
|
reply.diagnostic_message = message.into();
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn send_reply(
|
||||||
|
writer: &mut Writer<impl AsyncWrite + Unpin>,
|
||||||
|
session: &str,
|
||||||
|
correlation: &str,
|
||||||
|
reply: MxCommandReply,
|
||||||
|
max: usize,
|
||||||
|
) -> io::Result<()> {
|
||||||
|
writer
|
||||||
|
.send(
|
||||||
|
session,
|
||||||
|
correlation,
|
||||||
|
Body::WorkerCommandReply(WorkerCommandReply {
|
||||||
|
reply: Some(reply),
|
||||||
|
completed_timestamp: Some(now()),
|
||||||
|
}),
|
||||||
|
max,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn fault(
|
||||||
|
writer: &mut Writer<impl AsyncWrite + Unpin>,
|
||||||
|
session: &str,
|
||||||
|
max: usize,
|
||||||
|
category: WorkerFaultCategory,
|
||||||
|
hresult: Option<i32>,
|
||||||
|
message: &str,
|
||||||
|
) {
|
||||||
|
let code = match category {
|
||||||
|
WorkerFaultCategory::ProtocolViolation | WorkerFaultCategory::ProtocolMismatch => {
|
||||||
|
ProtocolStatusCode::ProtocolViolation
|
||||||
|
}
|
||||||
|
_ => ProtocolStatusCode::MxaccessFailure,
|
||||||
|
};
|
||||||
|
let _ = writer
|
||||||
|
.send(
|
||||||
|
session,
|
||||||
|
"",
|
||||||
|
Body::WorkerFault(WorkerFault {
|
||||||
|
category: category as i32,
|
||||||
|
hresult,
|
||||||
|
diagnostic_message: message.into(),
|
||||||
|
protocol_status: Some(status(code, message)),
|
||||||
|
..Default::default()
|
||||||
|
}),
|
||||||
|
max,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn status(code: ProtocolStatusCode, message: impl Into<String>) -> ProtocolStatus {
|
||||||
|
ProtocolStatus {
|
||||||
|
code: code as i32,
|
||||||
|
message: message.into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn now() -> Timestamp {
|
||||||
|
SystemTime::now().into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pid() -> i32 {
|
||||||
|
std::process::id() as i32
|
||||||
|
}
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
use std::io;
|
||||||
|
|
||||||
|
use prost::Message;
|
||||||
|
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
|
||||||
|
|
||||||
|
// The public contract also defines RPCs the worker never originates.
|
||||||
|
#[allow(dead_code, clippy::enum_variant_names, clippy::large_enum_variant)]
|
||||||
|
pub mod mxaccess_gateway {
|
||||||
|
pub mod v1 {
|
||||||
|
include!(concat!(env!("OUT_DIR"), "/mxaccess_gateway.v1.rs"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::large_enum_variant)]
|
||||||
|
pub mod mxaccess_worker {
|
||||||
|
pub mod v1 {
|
||||||
|
include!(concat!(env!("OUT_DIR"), "/mxaccess_worker.v1.rs"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub use mxaccess_worker::v1::{worker_envelope::Body, WorkerEnvelope};
|
||||||
|
|
||||||
|
pub const VERSION: u32 = 1;
|
||||||
|
pub const DEFAULT_MAX: usize = 16 * 1024 * 1024 + 64 * 1024;
|
||||||
|
|
||||||
|
pub fn negotiated_max(value: u32) -> io::Result<usize> {
|
||||||
|
match value {
|
||||||
|
0 => Ok(DEFAULT_MAX),
|
||||||
|
1024..=268_435_456 => Ok(value as usize),
|
||||||
|
_ => Err(invalid(
|
||||||
|
"GatewayHello frame maximum is outside the supported range",
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn read(
|
||||||
|
stream: &mut (impl AsyncRead + Unpin),
|
||||||
|
session: &str,
|
||||||
|
max: usize,
|
||||||
|
) -> io::Result<WorkerEnvelope> {
|
||||||
|
let mut header = [0; 4];
|
||||||
|
stream.read_exact(&mut header).await?;
|
||||||
|
let length = u32::from_le_bytes(header) as usize;
|
||||||
|
if length == 0 || length > max {
|
||||||
|
return Err(invalid(
|
||||||
|
"Worker frame length is outside the supported range",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let mut payload = vec![0; length];
|
||||||
|
stream.read_exact(&mut payload).await?;
|
||||||
|
let frame = WorkerEnvelope::decode(payload.as_slice())
|
||||||
|
.map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
|
||||||
|
if frame.protocol_version != VERSION || frame.session_id != session || frame.body.is_none() {
|
||||||
|
return Err(invalid(
|
||||||
|
"Worker envelope has an invalid version, session, or body",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(frame)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Writer<W> {
|
||||||
|
stream: W,
|
||||||
|
sequence: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<W: AsyncWrite + Unpin> Writer<W> {
|
||||||
|
pub fn new(stream: W) -> Self {
|
||||||
|
Self {
|
||||||
|
stream,
|
||||||
|
sequence: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn send(
|
||||||
|
&mut self,
|
||||||
|
session: &str,
|
||||||
|
correlation: &str,
|
||||||
|
body: Body,
|
||||||
|
max: usize,
|
||||||
|
) -> io::Result<()> {
|
||||||
|
let frame = WorkerEnvelope {
|
||||||
|
protocol_version: VERSION,
|
||||||
|
session_id: session.into(),
|
||||||
|
sequence: self.sequence + 1,
|
||||||
|
correlation_id: correlation.into(),
|
||||||
|
body: Some(body),
|
||||||
|
};
|
||||||
|
let length = frame.encoded_len();
|
||||||
|
if length > max {
|
||||||
|
return Err(invalid(
|
||||||
|
"Outgoing worker frame exceeds the negotiated maximum",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let mut data = Vec::with_capacity(4 + length);
|
||||||
|
data.extend_from_slice(&(length as u32).to_le_bytes());
|
||||||
|
frame
|
||||||
|
.encode(&mut data)
|
||||||
|
.expect("encoding into a growable buffer");
|
||||||
|
self.stream.write_all(&data).await?;
|
||||||
|
self.stream.flush().await?;
|
||||||
|
self.sequence = frame.sequence;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn invalid(message: &'static str) -> io::Error {
|
||||||
|
io::Error::new(io::ErrorKind::InvalidData, message)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use mxaccess_worker::v1::WorkerHello;
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn round_trip_keeps_wire_order_after_size_rejection() {
|
||||||
|
let mut bytes = Vec::new();
|
||||||
|
let mut writer = Writer::new(&mut bytes);
|
||||||
|
let hello = Body::WorkerHello(WorkerHello::default());
|
||||||
|
writer.send("test", "", hello.clone(), 1).await.unwrap_err();
|
||||||
|
for _ in 0..2 {
|
||||||
|
writer
|
||||||
|
.send("test", "corr", hello.clone(), DEFAULT_MAX)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
let mut input = bytes.as_slice();
|
||||||
|
for sequence in 1..=2 {
|
||||||
|
let frame = read(&mut input, "test", DEFAULT_MAX).await.unwrap();
|
||||||
|
assert_eq!(frame.sequence, sequence);
|
||||||
|
assert_eq!(frame.correlation_id, "corr");
|
||||||
|
assert_eq!(frame.body, Some(hello.clone()));
|
||||||
|
}
|
||||||
|
assert!(input.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn rejects_oversized_and_empty_headers_before_reading_payload() {
|
||||||
|
for length in [0_u32, 1025] {
|
||||||
|
let header = length.to_le_bytes();
|
||||||
|
let error = read(&mut header.as_slice(), "test", 1024)
|
||||||
|
.await
|
||||||
|
.unwrap_err();
|
||||||
|
assert_eq!(error.kind(), io::ErrorKind::InvalidData);
|
||||||
|
}
|
||||||
|
assert_eq!(negotiated_max(0).unwrap(), DEFAULT_MAX);
|
||||||
|
assert!(negotiated_max(1023).is_err());
|
||||||
|
assert!(negotiated_max(268_435_457).is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,250 @@
|
|||||||
|
#![cfg(all(windows, target_arch = "x86"))]
|
||||||
|
|
||||||
|
#[path = "../src/wire.rs"]
|
||||||
|
mod wire;
|
||||||
|
|
||||||
|
use std::process::{Child, Command};
|
||||||
|
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||||
|
use tokio::io::{split, AsyncRead, AsyncWrite};
|
||||||
|
use tokio::net::windows::named_pipe::ServerOptions;
|
||||||
|
use tokio::time::{sleep, timeout};
|
||||||
|
use wire::mxaccess_gateway::v1::{
|
||||||
|
mx_command, mx_command_reply, AddItemCommand, MxCommand, MxCommandKind, MxCommandReply,
|
||||||
|
ProtocolStatusCode, RegisterCommand, RemoveItemCommand, UnregisterCommand,
|
||||||
|
};
|
||||||
|
use wire::mxaccess_worker::v1::{GatewayHello, WorkerCommand, WorkerShutdown};
|
||||||
|
use wire::{Body, Writer, DEFAULT_MAX, VERSION};
|
||||||
|
|
||||||
|
const DEADLINE: Duration = Duration::from_secs(20);
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
#[ignore = "requires a registered 32-bit System Platform MXAccess installation"]
|
||||||
|
async fn activates_registers_and_shuts_down_over_a_windows_pipe() {
|
||||||
|
let token = format!(
|
||||||
|
"{}-{}",
|
||||||
|
std::process::id(),
|
||||||
|
SystemTime::now()
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.unwrap()
|
||||||
|
.as_nanos()
|
||||||
|
);
|
||||||
|
let pipe_name = format!("mxgw-rust-smoke-{token}");
|
||||||
|
let pipe = ServerOptions::new()
|
||||||
|
.first_pipe_instance(true)
|
||||||
|
.create(format!(r"\\.\pipe\{pipe_name}"))
|
||||||
|
.unwrap();
|
||||||
|
let worker_path = std::env::var_os("MXGATEWAY_RUST_SMOKE_WORKER")
|
||||||
|
.unwrap_or_else(|| env!("CARGO_BIN_EXE_mxgateway-worker-rust").into());
|
||||||
|
let mut child = ChildGuard(
|
||||||
|
Command::new(worker_path)
|
||||||
|
.args([
|
||||||
|
"--session-id",
|
||||||
|
&token,
|
||||||
|
"--pipe-name",
|
||||||
|
&pipe_name,
|
||||||
|
"--protocol-version",
|
||||||
|
"1",
|
||||||
|
])
|
||||||
|
.env("MXGATEWAY_WORKER_NONCE", &token)
|
||||||
|
.env("MXGATEWAY_WORKER_HEARTBEAT_SEND_INTERVAL_MS", "100")
|
||||||
|
.spawn()
|
||||||
|
.unwrap(),
|
||||||
|
);
|
||||||
|
let session = &token;
|
||||||
|
timeout(DEADLINE, async {
|
||||||
|
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,
|
||||||
|
"",
|
||||||
|
Body::GatewayHello(GatewayHello {
|
||||||
|
supported_protocol_version: VERSION,
|
||||||
|
nonce: token.clone(),
|
||||||
|
max_frame_bytes: 4096,
|
||||||
|
..Default::default()
|
||||||
|
}),
|
||||||
|
DEFAULT_MAX,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let ready = read_body(&mut reader, session).await;
|
||||||
|
let Body::WorkerReady(ready) = ready else {
|
||||||
|
panic!("expected WorkerReady, got {ready:?}");
|
||||||
|
};
|
||||||
|
assert_eq!(ready.worker_process_id, child.0.id() as i32);
|
||||||
|
let Body::WorkerHeartbeat(heartbeat) = read_body(&mut reader, session).await else {
|
||||||
|
panic!("expected an idle heartbeat");
|
||||||
|
};
|
||||||
|
assert_eq!(heartbeat.worker_process_id, ready.worker_process_id);
|
||||||
|
|
||||||
|
let registration = invoke(
|
||||||
|
&mut reader,
|
||||||
|
&mut writer,
|
||||||
|
session,
|
||||||
|
"register",
|
||||||
|
MxCommandKind::Register,
|
||||||
|
mx_command::Payload::Register(RegisterCommand {
|
||||||
|
client_name: format!("mxgw-rust-smoke-{}", child.0.id()),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let Some(mx_command_reply::Payload::Register(registration)) = registration.payload else {
|
||||||
|
panic!("missing registration handle");
|
||||||
|
};
|
||||||
|
assert!(registration.server_handle > 0);
|
||||||
|
if let Ok(definition) = std::env::var("MXGATEWAY_RUST_SMOKE_ITEM") {
|
||||||
|
let add_item = invoke(
|
||||||
|
&mut reader,
|
||||||
|
&mut writer,
|
||||||
|
session,
|
||||||
|
"add",
|
||||||
|
MxCommandKind::AddItem,
|
||||||
|
mx_command::Payload::AddItem(AddItemCommand {
|
||||||
|
server_handle: registration.server_handle,
|
||||||
|
item_definition: definition,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let Some(mx_command_reply::Payload::AddItem(item)) = add_item.payload else {
|
||||||
|
panic!("missing item handle");
|
||||||
|
};
|
||||||
|
assert!(item.item_handle > 0);
|
||||||
|
invoke(
|
||||||
|
&mut reader,
|
||||||
|
&mut writer,
|
||||||
|
session,
|
||||||
|
"remove",
|
||||||
|
MxCommandKind::RemoveItem,
|
||||||
|
mx_command::Payload::RemoveItem(RemoveItemCommand {
|
||||||
|
server_handle: registration.server_handle,
|
||||||
|
item_handle: item.item_handle,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
invoke(
|
||||||
|
&mut reader,
|
||||||
|
&mut writer,
|
||||||
|
session,
|
||||||
|
"unregister",
|
||||||
|
MxCommandKind::Unregister,
|
||||||
|
mx_command::Payload::Unregister(UnregisterCommand {
|
||||||
|
server_handle: registration.server_handle,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
// Leave a registration active to exercise the worker's shutdown cleanup.
|
||||||
|
invoke(
|
||||||
|
&mut reader,
|
||||||
|
&mut writer,
|
||||||
|
session,
|
||||||
|
"cleanup",
|
||||||
|
MxCommandKind::Register,
|
||||||
|
mx_command::Payload::Register(RegisterCommand {
|
||||||
|
client_name: format!("mxgw-rust-cleanup-{}", child.0.id()),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
writer
|
||||||
|
.send(
|
||||||
|
session,
|
||||||
|
"",
|
||||||
|
Body::WorkerShutdown(WorkerShutdown::default()),
|
||||||
|
4096,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
loop {
|
||||||
|
match read_body(&mut reader, session).await {
|
||||||
|
Body::WorkerHeartbeat(_) => {}
|
||||||
|
Body::WorkerShutdownAck(ack) => {
|
||||||
|
let status = ack.status.unwrap();
|
||||||
|
assert_eq!(status.code(), ProtocolStatusCode::Ok);
|
||||||
|
assert_eq!(status.message, "Graceful shutdown completed");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
other => panic!("expected shutdown acknowledgement, got {other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
loop {
|
||||||
|
if let Some(status) = child.0.try_wait().unwrap() {
|
||||||
|
assert!(status.success(), "{status}");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
sleep(Duration::from_millis(10)).await;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.expect("live worker smoke test timed out");
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn invoke(
|
||||||
|
reader: &mut (impl AsyncRead + Unpin),
|
||||||
|
writer: &mut Writer<impl AsyncWrite + Unpin>,
|
||||||
|
session: &str,
|
||||||
|
correlation: &str,
|
||||||
|
kind: MxCommandKind,
|
||||||
|
payload: mx_command::Payload,
|
||||||
|
) -> MxCommandReply {
|
||||||
|
writer
|
||||||
|
.send(
|
||||||
|
session,
|
||||||
|
correlation,
|
||||||
|
Body::WorkerCommand(WorkerCommand {
|
||||||
|
command: Some(MxCommand {
|
||||||
|
kind: kind as i32,
|
||||||
|
payload: Some(payload),
|
||||||
|
}),
|
||||||
|
enqueue_timestamp: None,
|
||||||
|
}),
|
||||||
|
4096,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
loop {
|
||||||
|
let frame = wire::read(reader, session, 4096).await.unwrap();
|
||||||
|
match frame.body.unwrap() {
|
||||||
|
Body::WorkerHeartbeat(_) => {}
|
||||||
|
Body::WorkerCommandReply(result) => {
|
||||||
|
let reply = result.reply.unwrap();
|
||||||
|
assert_eq!(frame.correlation_id, correlation);
|
||||||
|
assert_eq!(reply.correlation_id, correlation);
|
||||||
|
assert_eq!(reply.kind(), kind);
|
||||||
|
assert_eq!(
|
||||||
|
reply.protocol_status.as_ref().unwrap().code(),
|
||||||
|
ProtocolStatusCode::Ok,
|
||||||
|
"{reply:?}"
|
||||||
|
);
|
||||||
|
return reply;
|
||||||
|
}
|
||||||
|
other => panic!("expected command reply, got {other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn read_body(reader: &mut (impl AsyncRead + Unpin), session: &str) -> Body {
|
||||||
|
wire::read(reader, session, 4096)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.body
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ChildGuard(Child);
|
||||||
|
|
||||||
|
impl Drop for ChildGuard {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if matches!(self.0.try_wait(), Ok(None)) {
|
||||||
|
let _ = self.0.kill();
|
||||||
|
let _ = self.0.wait();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user