diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..4aee017 --- /dev/null +++ b/.env.example @@ -0,0 +1,7 @@ +HOST=0.0.0.0 +PORT=50051 +DATA_PATH=registry/data/terminals.bin +DATA_FILE_COUNT=10 +HEALTH_INTERVAL_SECS=10 +HEALTH_TIMEOUT_SECS=3 +LOG_LEVEL=info \ No newline at end of file diff --git a/.gitignore b/.gitignore index ea8c4bf..5b70d78 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,3 @@ /target +/.env +/registry/data/ diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..8f57311 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,7 @@ +{ + "chat.tools.terminal.autoApprove": { + "cargo check": true, + "rustfmt": true, + "cargo clippy": true + } +} diff --git a/Cargo.lock b/Cargo.lock index 2b24e8e..71695f6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,14 +2,1508 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "aggregate-router" +version = "0.1.0" +dependencies = [ + "buffa", + "buffa-types", + "connectrpc", + "connectrpc-build", + "proto", + "serde", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.4", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" + +[[package]] +name = "buffa" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a92f2f5df67a9d5ccfc65237bfc954c56328aee40a04a9b92381ecba370be246" +dependencies = [ + "base64", + "bytes", + "foldhash", + "hashbrown 0.15.5", + "once_cell", + "rustversion", + "serde", + "serde_json", + "smoothutf8", + "thiserror", +] + +[[package]] +name = "buffa-codegen" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb4bea10ef85ea3d06a20412c67cb612527feb25f33367eab850139441fb5dd9" +dependencies = [ + "buffa", + "buffa-descriptor", + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.119", + "thiserror", +] + +[[package]] +name = "buffa-descriptor" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b7dd79a6898e70dac8adae959c8ad2cae51ed96397935c91c996280cedcb55e" +dependencies = [ + "buffa", + "rustversion", + "serde", + "serde_json", +] + +[[package]] +name = "buffa-types" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b15b05c8418f1e200e406e5b19df97400dffa833e2450e4392c506896cbc97ac" +dependencies = [ + "buffa", + "bytes", + "jiff", + "serde", + "serde_json", + "thiserror", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +dependencies = [ + "serde", +] + +[[package]] +name = "cbindgen" +version = "0.29.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ecb53484c9c167ba674026b656d8a27d7657a58e6066aa902bfb1a4aa00ae20" +dependencies = [ + "clap", + "heck", + "indexmap", + "log", + "proc-macro2", + "quote", + "serde", + "serde_json", + "syn 2.0.119", + "tempfile", + "toml", +] + +[[package]] +name = "cc" +version = "1.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "005ec2760ca554fae18df7a11195552ec576cd665632a881bc011d5bb2fd4d80" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "clap" +version = "4.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "473c7e07f409a8d772161724aa8db6a765a2532a70f9667eeb7b49d3d02fbdca" +dependencies = [ + "clap_builder", +] + +[[package]] +name = "clap_builder" +version = "4.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b48fea5a88e9ae728a2dcbedbfc0e730f7d60da42e1cb049a83c9fb8b789889" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_lex" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "connectrpc" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85de144722d22eb03b7985136d8cd29b89d277a2df4ae0f53ef46488c467cbaf" +dependencies = [ + "async-trait", + "axum", + "base64", + "buffa", + "bytes", + "flate2", + "futures", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "libc", + "percent-encoding", + "pin-project", + "serde", + "serde_json", + "sync_wrapper", + "thiserror", + "tokio", + "tokio-util", + "tower", + "tower-http", + "tracing", + "wasm-bindgen-futures", + "zstd", +] + +[[package]] +name = "connectrpc-build" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "603619f92fc55725d971ed9292855cd75f7a2c52ed66c181e0ec531dd7f8dd9b" +dependencies = [ + "anyhow", + "buffa", + "buffa-codegen", + "connectrpc-codegen", + "tempfile", +] + +[[package]] +name = "connectrpc-codegen" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "514a7a6fbe705d532ddf490c221db7bd52c5b94fd691cb257a7c18e5646355bb" +dependencies = [ + "anyhow", + "buffa", + "buffa-codegen", + "heck", + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "defmt" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2953bfe4f93bbd20cc71198842756f77d161884c99ebbabc41d80231ded88d1" +dependencies = [ + "bitflags 1.3.2", + "defmt-macros", +] + +[[package]] +name = "defmt-macros" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bad9c72e7ca2137e0dc3813245a0d282fd6daad32fd800af018306a9169b5fe8" +dependencies = [ + "defmt-parser", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "defmt-parser" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e" +dependencies = [ + "thiserror", +] + [[package]] name = "dispatcher" version = "0.1.0" +[[package]] +name = "dotenvy" +version = "0.15.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +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 = "find-msvc-tools" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e0f1c7c3a72c66fd80abe965175f7523475c0489a87d3ff9d6e8c87d87a9d2d" + +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "zlib-rs", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.4", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[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 = "h2" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef8e5e5a340588f4452631496976cf8636d4a7ecf600239fdc27615d2530bc16" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash", + "serde", +] + +[[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 = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-util" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +dependencies = [ + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "hyper", + "libc", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "indexmap" +version = "2.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07aa2048142242915a31d35844fb311e0e53fcca590c3a0a40dcf1b841fa09eb" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jiff" +version = "0.2.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "668b7183bd07af9a4885f5c35b0cc5c83c4607a913c16b7e17291832910d2dcc" +dependencies = [ + "defmt", + "jiff-core", + "jiff-static", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", +] + +[[package]] +name = "jiff-core" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7feca88439efe53da3754500c1851dedf3cb36c524dd5cf8225cc0794de95d09" +dependencies = [ + "defmt", +] + +[[package]] +name = "jiff-static" +version = "0.2.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a69dcb3a21cfb32ce1cd056169337ca284af0766dd766e7878819b251a49204" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce57d20d1ea864ce2ac172ab472d409214f4fd359f0b2a2775abdf522e2af99e" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[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.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mio" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8" +dependencies = [ + "libc", + "wasi", + "windows-sys", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + +[[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 = "proto" +version = "0.1.0" +dependencies = [ + "buffa", + "buffa-types", + "connectrpc", + "connectrpc-build", + "serde", +] + +[[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 = "registry" version = "0.1.0" +dependencies = [ + "axum", + "buffa", + "buffa-types", + "connectrpc", + "dotenvy", + "futures-util", + "proto", + "tempfile", + "terminal", + "tokio", + "uuid", +] + +[[package]] +name = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags 2.13.1", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.4", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_spanned" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha1_smol" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d" + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[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 = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9be42f50aa861c555654aa3a37f52f4b1074bacf4e48fe0ef7fa584e80f1f0f" + +[[package]] +name = "smoothutf8" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b4ec95892483d6d94284caccfddb9b77111a4dcac33ed25d624248def0fa5f1" +dependencies = [ + "simdutf8", +] + +[[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 = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[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.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6275cddf4610d1775e6d1fe9469b2e77d0f39fd98fb7450901b821e0c53649f" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" + +[[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 = "terminal" version = "0.1.0" +dependencies = [ + "axum", + "buffa", + "buffa-types", + "cbindgen", + "connectrpc", + "futures-util", + "proto", + "tokio", +] + +[[package]] +name = "thiserror" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.4", +] + +[[package]] +name = "tokio" +version = "1.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "signal-hook-registry", + "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.4", +] + +[[package]] +name = "tokio-util" +version = "0.7.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "toml" +version = "0.9.12+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow 0.7.15", +] + +[[package]] +name = "toml_datetime" +version = "0.7.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" +dependencies = [ + "winnow 1.0.4", +] + +[[package]] +name = "toml_writer" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2" + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tokio-util", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags 2.13.1", + "bytes", + "futures-util", + "http", + "http-body", + "http-body-util", + "pin-project-lite", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "uuid" +version = "1.26.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce" +dependencies = [ + "js-sys", + "sha1_smol", + "wasm-bindgen", +] + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aecb87a33d3b0c5e3b7aa46336eaf486cffafbd281b195e4c8b80d50df2351bf" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.78" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ef4c5d3d2cdf5c54f4231181768f5510842e350db025faf1f7163b1030ed928" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a690d511e3c1a8b3a55e33511e3c2c00c78415cd23650f32b808627f5696b9ed" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "411e4887f0071ef2d2164a9d5fdf2d20efbef78fccd3a78b0c10a1dc5295e48a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.4", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81941cd78d0c92026c33e5e01312845a4cb1e9af3407f9134b100dd03144103e" +dependencies = [ + "unicode-ident", +] + +[[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", +] + +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" + +[[package]] +name = "zlib-rs" +version = "0.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34b31d188d9d685a4f9c7b46d6e36631b07058d2cfe190267adce54dc230bf12" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zstd" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "7.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64d80649ab6db9d9f6f9c80a40becd948eda4714a0a5ac8c4d157a32231c7882" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.1.0+zstd.1.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ef0a8027ec3ee71300ab3bcbcd0393f434aa72b91ca6d635a39941deae8eea0" +dependencies = [ + "cc", + "pkg-config", +] diff --git a/Cargo.toml b/Cargo.toml index c99f03b..77dac7a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,12 +1,33 @@ [workspace] -members = [ - "dispatcher", - "registry", - "terminal" -] +members = ["dispatcher", "registry", "terminal", "proto", "aggregate-router"] resolver = "3" [workspace.package] version = "0.1.0" edition = "2024" authors = ["lain "] + +[workspace.dependencies] +proto = { path = "proto" } +connectrpc = { version = "^0.9", features = ["client", "server", "axum"] } +buffa = "^0.9" +buffa-types = { version = "^0.9", features = ["json"] } +serde = "^1" +connectrpc-build = "^0.9" +cbindgen = "^0.29" +axum = { version = "^0.8", features = ["http2"] } +futures-util = "^0.3" +dotenvy = "^0.15" +uuid = { version = "^1", features = ["v5"] } +tempfile = "^3" +tokio = { version = "^1", features = [ + "rt-multi-thread", + "macros", + "net", + "sync", + "time", + "fs", + "signal", +] } +log = "^0.4" +env_logger = "^0.11" diff --git a/TERMINAL_ARCHITECTURE.md b/TERMINAL_ARCHITECTURE.md new file mode 100644 index 0000000..945e3ea --- /dev/null +++ b/TERMINAL_ARCHITECTURE.md @@ -0,0 +1,548 @@ +# FlySim 控制系统架构设计 + +本文档基于 `proto/control` 中的协议定义、`terminal/src` 中的当前实现,以及调度服务和终端聚合路由服务的目标需求,描述系统静态边界、运行时交互及主要类型关系。图中 Terminal 和 Registry 已有代码实现;Dispatcher 和终端聚合路由子中心目前为目标架构。Registry 的配置、持久化与健康检查契约见 [registry/README.md](registry/README.md)。 + +## 1. C4 架构图 + +### 1.1 系统上下文 + +```mermaid + +C4Context + title FlySim 控制系统上下文 + + Person(operator, "控制操作员", "通过控制系统管理仿真终端和场景") + System_Ext(controlConsole, "控制系统客户端", "提交仿真任务、直接控制逻辑终端并监视状态") + System_Ext(simulator, "仿真程序", "实现具体仿真逻辑和终端回调") + + System_Boundary(flySim, "FlySim 控制域") { + System(registry, "总中心(Registry)", "登记逻辑终端并发布全局终端目录及服务状态") + System(dispatcher, "调度服务(Dispatcher)", "编排命令和事件,分配仿真任务,并根据状态动态调度") + System(subcenter, "终端聚合路由服务(子中心)", "将下辖实体终端聚合为一个逻辑终端,并统一代理 Terminal API") + System(terminal, "实体控制终端", "封装单个仿真程序,对外提供 Terminal API") + System(dataService, "数据服务", "提供场景数据查询") + } + + Rel(operator, controlConsole, "操作") + Rel(controlConsole, dispatcher, "提交、控制和跟踪仿真任务", "调度 API(待定义)") + Rel(controlConsole, registry, "发现逻辑终端", "Center gRPC") + Rel(controlConsole, subcenter, "直接控制逻辑终端和订阅聚合状态", "Terminal gRPC") + Rel(controlConsole, dataService, "查询场景", "gRPC") + Rel(dispatcher, registry, "发现可调度的逻辑终端", "Center gRPC stream") + Rel(dispatcher, subcenter, "执行调度命令、管理事件、订阅聚合状态", "Terminal gRPC") + Rel(dispatcher, dataService, "获取场景数据", "Data gRPC") + Rel(subcenter, registry, "作为单一逻辑终端注册和注销", "Center gRPC") + Rel(terminal, subcenter, "注册、注销实体终端", "Center gRPC") + Rel(subcenter, terminal, "按调度结果代理命令、事件和状态订阅", "Terminal gRPC") + Rel(terminal, simulator, "调用命令和事件回调", "C ABI") + Rel(simulator, terminal, "配置、注册回调、推送状态、完成事件", "C ABI + Protobuf") +``` + +### 1.2 容器视图 + +```mermaid +C4Container + title FlySim 两级中心容器视图 + + Person(operator, "控制操作员", "任务调度、终端控制与状态监视") + Container_Ext(controlConsole, "控制系统客户端", "桌面端或服务", "提交任务并消费调度、Center、Terminal 和 Data API") + + System_Boundary(flySim, "FlySim 控制域") { + Container(registry, "总中心(Registry)", "Rust + gRPC / Protobuf", "实现 Center API,维护子中心等逻辑终端的全局目录") + Container(dispatcher, "调度服务(Dispatcher)", "Rust,接口待定义", "执行命令与事件编排、任务分配和状态驱动调度") + Container(dataService, "Data 服务", "gRPC / Protobuf", "根据 SceneRequest 返回场景") + + Container_Boundary(subcenterNode, "终端集群") { + Container(subcenter, "终端聚合路由服务(子中心)", "Center + Terminal gRPC", "管理实体终端,对外呈现一个逻辑终端并聚合状态") + Container(routeState, "路由与聚合状态", "内存目录、连接池、句柄映射", "保存实体终端连接、调度目标和逻辑事件映射") + } + + Container_Boundary(terminalNode, "实体终端节点(多个)") { + Container(simHost, "仿真宿主", "C/C++ 或其他原生程序", "实现仿真命令和事件回调,产生状态") + Container(terminalLib, "Terminal 动态库", "Rust cdylib + ConnectRPC + Axum", "管理单个终端的生命周期、状态和事件,并托管 Terminal RPC 服务") + } + } + + Rel(operator, controlConsole, "操作") + Rel(controlConsole, dispatcher, "提交和跟踪仿真任务", "调度 API(待定义)") + Rel(controlConsole, registry, "SubscribeTerminal", "Center gRPC stream") + Rel(controlConsole, subcenter, "直接控制和订阅逻辑终端", "Terminal gRPC") + Rel(controlConsole, dataService, "GetScene", "gRPC") + Rel(dispatcher, registry, "订阅逻辑终端目录", "Center gRPC stream") + Rel(dispatcher, dataService, "GetScene", "Data gRPC") + Rel(dispatcher, subcenter, "调度逻辑终端并订阅聚合状态", "Terminal gRPC") + Rel(subcenter, registry, "以单一 TerminalInfo 注册、注销", "Center gRPC") + Rel(terminalLib, subcenter, "RegisterTerminal、DeregisterTerminal", "Center gRPC") + Rel(subcenter, terminalLib, "代理 Terminal API", "gRPC") + Rel(subcenter, routeState, "读取和更新") + Rel(simHost, terminalLib, "生命周期、配置、注册、状态和事件完成", "C ABI + Protobuf bytes") + Rel(terminalLib, simHost, "命令和事件回调", "C function pointer") +``` + +### 1.3 Terminal 组件视图 + +```mermaid +C4Component + title Terminal 动态库组件视图 + + Container_Ext(controlClient, "控制系统客户端", "Terminal gRPC 客户端") + Container_Ext(centerService, "上级 Center 服务", "子中心或总中心") + Container_Ext(simHost, "仿真宿主", "原生应用") + + Container_Boundary(terminalLib, "Terminal 动态库") { + Component(ffi, "FFI 门面", "ffi.rs", "校验指针、编解码 Protobuf、管理句柄与错误码") + Component(runtime, "运行时管理器", "runtime.rs / RunningServer", "创建 Tokio 运行时、绑定端口、启停服务并访问中心") + Component(rpc, "Terminal RPC 适配器", "rpc.rs / Terminal trait", "将五个 RPC 映射到 Service,并把 watch 转换为流") + Component(core, "终端领域服务", "terminal.rs / Service", "维护生命周期与仿真状态,编排命令和事件") + Component(callback, "宿主回调适配器", "callback.rs", "编码请求、调用 C 回调、通过 sink 接收并解码响应") + Component(eventTask, "事件任务", "Tokio task", "处理延迟、显式完成、重复和取消") + Component(statusBus, "状态总线", "tokio::sync::watch", "发布高频状态、变更触发的元状态及关闭信号") + } + + Rel(simHost, ffi, "调用导出的 terminal_service_* API", "C ABI") + Rel(ffi, runtime, "启动和停止") + Rel(ffi, core, "配置、注册、推送状态、完成事件") + Rel(runtime, centerService, "注册和注销", "CenterClient / gRPC") + Rel(runtime, rpc, "挂载到 Axum 服务") + Rel(controlClient, rpc, "调用 Terminal API", "gRPC") + Rel(rpc, core, "委托业务操作") + Rel(core, callback, "串行调用宿主回调") + Rel(callback, simHost, "调用函数指针并接收 sink 响应", "C ABI") + Rel(core, eventTask, "创建和管理") + Rel(core, statusBus, "发布快照") + Rel(statusBus, rpc, "提供订阅数据") +``` + +### 1.4 调度与聚合路由组件视图(目标设计) + +```mermaid +C4Component + title Dispatcher、Registry 与终端聚合路由组件视图 + + Container_Ext(controlClient, "控制系统客户端", "提交任务并查看执行状态") + Container_Ext(dataService, "Data 服务", "提供场景数据") + Container_Ext(terminals, "实体终端集群", "各自提供 Center 注册客户端和 Terminal 服务") + + Container_Boundary(registryBoundary, "总中心(Registry)") { + Component(globalDirectory, "全局终端目录", "Center API", "登记子中心等逻辑终端并发布 TerminalInfos") + } + + Container_Boundary(dispatcherBoundary, "调度服务(Dispatcher)") { + Component(dispatchApi, "调度 API", "协议待定义", "接收任务、编排及控制请求") + Component(planner, "调度规划器", "任务与能力匹配", "依据任务、终端能力和状态选择逻辑终端及执行步骤") + Component(orchestrator, "执行编排器", "异步任务执行", "执行命令序列、发布或取消事件并跟踪结果") + Component(stateObserver, "状态观察器", "流订阅", "消费终端目录、聚合状态和元状态,触发重调度") + } + + Container_Boundary(subcenterBoundary, "终端聚合路由服务(子中心)") { + Component(childCenter, "下级 Center 接口", "Center gRPC server", "接受实体终端注册、注销并发布下级目录") + Component(terminalFacade, "逻辑 Terminal 门面", "Terminal gRPC server", "以单一逻辑终端对外提供完整 Terminal API") + Component(router, "终端路由器", "能力与状态路由", "根据调度意图选择一个或多个实体终端并代理调用") + Component(statusAggregator, "状态聚合器", "流处理", "把多个实体状态和元状态归并为逻辑终端快照") + Component(connectionPool, "终端目录与连接池", "内存状态", "维护实体 terminal_id、地址、健康状态和客户端连接") + Component(handleMap, "逻辑事件句柄表", "内存状态", "映射逻辑事件实例与下游事件句柄") + Component(upstreamRegistration, "上级注册客户端", "Center gRPC client", "将子中心作为一个 TerminalInfo 注册到总中心") + } + + Rel(controlClient, dispatchApi, "提交和跟踪任务", "调度 API(待定义)") + Rel(dispatchApi, planner, "创建调度计划") + Rel(planner, dataService, "读取场景", "GetScene") + Rel(planner, stateObserver, "读取可用能力和状态") + Rel(stateObserver, globalDirectory, "订阅逻辑终端目录", "SubscribeTerminal") + Rel(stateObserver, terminalFacade, "订阅聚合状态和元状态", "Terminal streams") + Rel(planner, orchestrator, "提交执行计划") + Rel(orchestrator, terminalFacade, "执行命令和事件", "Terminal RPC") + + Rel(terminals, childCenter, "注册和注销", "Center RPC") + Rel(childCenter, connectionPool, "更新实体终端目录") + Rel(terminalFacade, router, "委托控制请求") + Rel(router, connectionPool, "选择连接") + Rel(router, terminals, "转发命令和事件", "Terminal RPC") + Rel(router, handleMap, "维护事件句柄映射") + Rel(statusAggregator, connectionPool, "遍历活动终端") + Rel(statusAggregator, terminals, "订阅实体状态", "Terminal streams") + Rel(statusAggregator, terminalFacade, "发布单一逻辑状态") + Rel(upstreamRegistration, globalDirectory, "注册和注销单一逻辑终端", "Center RPC") + Rel(connectionPool, upstreamRegistration, "触发能力元信息更新") +``` + +## 2. 运行时序图 + +### 2.1 配置、启动注册与停止注销 + +```mermaid + +sequenceDiagram + autonumber + participant Host as 仿真宿主 + participant FFI as FFI 门面 + participant Handle as ServiceHandle + participant Core as Service + participant Runtime as RunningServer + participant RPC as Axum + Terminal RPC + participant Center as 上级中心(子中心或总中心) + + Host->>FFI: terminal_service_create() + FFI->>Handle: 创建句柄和 Service + FFI-->>Host: opaque handle + Host->>FFI: terminal_service_configure(TerminalInfo bytes) + FFI->>FFI: 解码并校验输入 + FFI->>Core: configure(TerminalInfo) + Core->>Core: Created/Stopped -> Configured + Host->>FFI: register_command / register_event + FFI->>Core: 保存回调与 user_data + + Host->>FFI: terminal_service_start(center, port) + FFI->>Runtime: start(Service, center) + Runtime->>Core: registration_info(), reset_shutdown(), set_starting() + Runtime->>Runtime: 创建 Tokio Runtime 并绑定监听端口 + Runtime->>Core: set_bound_port(actual_port) + Runtime->>RPC: 挂载 Service 并启动 Axum + loop 最多 3 次,递增退避 + Runtime->>Center: RegisterTerminal(actual TerminalInfo) + Center-->>Runtime: TerminalRegisterResponse + end + Runtime->>Core: set_ready(center_assigned_id) + Core->>Core: 发布 TerminalMetaStatus + Runtime-->>FFI: RunningServer + bound_port + FFI-->>Host: TERMINAL_OK + bound_port + + Host->>FFI: terminal_service_stop() + FFI->>Runtime: stop(Service) + Runtime->>Core: set_stopping() + Runtime->>Center: DeregisterTerminal(terminal_id) + Center-->>Runtime: InvokeResponse + Runtime->>Core: signal_shutdown() + Runtime->>RPC: 等待优雅关闭,超时则中止 + Runtime->>Core: set_stopped() + Runtime-->>Host: 注销结果 +``` + +### 2.2 命令执行与状态订阅 + +```mermaid +sequenceDiagram + autonumber + participant Client as 控制系统客户端 + participant RPC as Terminal RPC + participant Core as Service + participant Gate as callback_gate + participant Adapter as CommandCallback + participant Host as 仿真宿主 + participant Bus as status watch + + Client->>RPC: SubscribeStatus(Empty) + RPC->>Core: status_receiver() + shutdown_receiver() + Core-->>RPC: watch receivers + RPC-->>Client: 初始 TerminalStatus 快照 + + Client->>RPC: Execute(Command) + RPC->>Core: execute_command(Command) + Core->>Core: 校验 Ready、命令注册和仿真状态迁移合法性 + Core->>Gate: spawn_blocking 后获取全局回调锁 + Gate->>Adapter: invoke(Command) + Adapter->>Adapter: Protobuf 编码 + Adapter->>Host: TerminalCommandCallback(..., sink) + Host-->>Adapter: sink(InvokeResponse bytes) + Adapter->>Adapter: 校验单次响应并解码 + Adapter-->>Core: InvokeResponse + opt success + Core->>Core: 应用 init/start/stop/suspend/resume/reset 状态迁移 + end + Core-->>RPC: InvokeResponse + RPC-->>Client: InvokeResponse + + Host->>Core: terminal_service_push_status(TerminalStatus bytes) + Core->>Core: 覆盖 sequence 和 timestamp + Core->>Bus: send_replace(status) + Bus-->>RPC: receiver.changed() + RPC-->>Client: TerminalStatus stream item +``` + +### 2.3 事件发布、完成、重复与取消 + +```mermaid +sequenceDiagram + autonumber + participant Client as 控制系统客户端 + participant RPC as Terminal RPC + participant Core as Service + participant Meta as meta_status watch + participant Task as 事件 Tokio task + participant Gate as callback_gate + participant Host as 仿真宿主 + + Client->>RPC: PublishEvent(TerminalEvent) + RPC->>Core: publish_event(event) + Core->>Core: 校验状态和事件定义,分配 instance_id + Core->>Meta: 发布 active_events 快照 + Core->>Task: spawn_event_task(event, handle, callback) + Core-->>Client: InvokeResponse(TerminalEventHandle) + Meta-->>Client: TerminalMetaStatus stream item + + Task->>Task: 等待 trigger_delay_ms + loop 首次执行及每个成功的重复周期 + Task->>Core: 标记 awaiting_completion + Task->>Gate: spawn_blocking 后获取全局回调锁 + Gate->>Host: TerminalEventCallback(event, instance_id, sink) + Host-->>Task: sink(InvokeResponse bytes) + alt 回调失败或拒绝 + Task->>Core: 移除 active event + else 回调接受 + Task->>Task: 等待显式完成、取消或关闭 + Host->>Core: terminal_service_complete_event(handle, response) + Core-->>Task: EventSignal::Complete(response) + alt 完成失败或 repeat_period_ms 为 0 + Task->>Core: 移除 active event + else 完成成功且需要重复 + Task->>Task: 等待 repeat_period_ms + end + end + end + Core->>Meta: active_events 变化时发布新快照 + + opt 控制系统主动取消 + Client->>RPC: CancelEvent(event_id, instance_id) + RPC->>Core: cancel_event(request) + Core-->>Task: EventSignal::Cancelled + Core->>Meta: 发布移除后的快照 + Core-->>Client: InvokeResponse(TerminalEventHandle) + end +``` + +### 2.4 两级注册、状态驱动调度与聚合路由 + +```mermaid +sequenceDiagram + autonumber + participant Terminal as 实体终端 + participant SubCenter as 聚合路由子中心 + participant Registry as 总中心 Registry + participant Dispatcher as 调度服务 + participant Data as Data 服务 + participant Client as 控制系统客户端 + + Terminal->>SubCenter: RegisterTerminal(entity TerminalInfo) + SubCenter->>SubCenter: 更新实体目录与连接池 + SubCenter-->>Terminal: 实体 terminal_id + SubCenter->>Terminal: SubscribeStatus + SubscribeMetaStatus + Terminal-->>SubCenter: 实体状态流 + SubCenter->>SubCenter: 归并为单一逻辑状态和能力 + + SubCenter->>Registry: RegisterTerminal(logical TerminalInfo) + Registry-->>SubCenter: logical terminal_id + Dispatcher->>Registry: SubscribeTerminal(Empty) + Registry-->>Dispatcher: 包含子中心的 TerminalInfos 流 + Dispatcher->>SubCenter: SubscribeStatus + SubscribeMetaStatus + SubCenter-->>Dispatcher: 单一逻辑终端状态流 + + Client->>Dispatcher: 提交仿真任务(调度 API 待定义) + Dispatcher->>Data: GetScene(SceneRequest) + Data-->>Dispatcher: SceneResponse + Dispatcher->>Dispatcher: 根据任务、能力和聚合状态生成计划 + Dispatcher->>SubCenter: Execute / PublishEvent + SubCenter->>SubCenter: 根据计划和实时状态选择一个或多个实体终端 + par 转发到目标终端 + SubCenter->>Terminal: Execute / PublishEvent + Terminal-->>SubCenter: InvokeResponse / downstream handle + and 持续观察状态 + Terminal-->>SubCenter: TerminalStatus / TerminalMetaStatus + SubCenter-->>Dispatcher: 聚合状态变化 + end + SubCenter->>SubCenter: 聚合响应并维护逻辑事件句柄映射 + SubCenter-->>Dispatcher: InvokeResponse / logical handle + Dispatcher-->>Client: 任务进度或结果 + + opt 状态变化要求重调度 + Dispatcher->>Dispatcher: 重新选择目标并调整命令或事件 + Dispatcher->>SubCenter: Execute / PublishEvent / CancelEvent + end +``` + +## 3. Terminal 类图 + +```mermaid +classDiagram + direction LR + + class TerminalRpc { + <> + +execute(Command) InvokeResponse + +publish_event(TerminalEvent) InvokeResponse + +cancel_event(TerminalCancelEvent) InvokeResponse + +subscribe_status(Empty) Stream + +subscribe_meta_status(Empty) Stream + } + + class ServiceHandle { + -service Service + -running MutexOptionRunningServer + -last_error MutexString + +new() ServiceHandle + -set_error(TerminalError) + -clear_error() + } + + class RunningServer { + -runtime Runtime + -server_task JoinHandle + -center_host String + -center_port u16 + -bound_port u16 + +start(Service, String, u16) RunningServer + +stop(Service) + +bound_port() u16 + } + + class Service { + -inner ArcInner + +new() BoxService + +closed() bool + +configure(TerminalInfo) + +register_command(String, CommandCallback) + +register_event(TerminalEventInfo, EventCallback) + +push_status(TerminalStatus) + +execute_command(Command) InvokeResponse + +publish_event(TerminalEvent) InvokeResponse + +cancel_event(TerminalCancelEvent) InvokeResponse + +complete_event(TerminalEventHandle, InvokeResponse) + } + + class Inner { + -context MutexContext + -callback_gate ArcMutex + -status WatchSenderTerminalStatus + -meta_status WatchSenderTerminalMetaStatus + -shutdown MutexWatchSenderBool + } + + class Context { + -service_state ServiceState + -simulation_state SimulationState + -terminal_info TerminalInfo + -terminal_id String + -commands HashMapCommandCallback + -event_definitions HashMapEventDefinition + -active_events HashMapActiveEvent + -next_instance_id u64 + -status_sequence u64 + } + + class ServiceState { + <> + Created + Configured + Starting + Ready + Stopping + Stopped + } + + class SimulationState { + <> + Uninitialized + Initialized + Running + Suspended + Stopped + } + + class EventDefinition { + -info TerminalEventInfo + -callback EventCallback + } + + class ActiveEvent { + -event_id String + -awaiting_completion bool + -signal WatchSenderEventSignal + } + + class EventSignal { + <> + Pending + Complete + Cancelled + } + + class CommandCallback { + -callback TerminalCommandCallback + -user_data usize + +new(callback, user_data) CommandCallback + +invoke(Command) InvokeResponse + } + + class EventCallback { + -callback TerminalEventCallback + -user_data usize + +new(callback, user_data) EventCallback + +invoke(TerminalEvent, u64) InvokeResponse + } + + class SinkState { + -response OptionBytes + -duplicate bool + } + + class TerminalError { + +code str + +message String + +into_response() InvokeResponse + +display_message() String + } + + class CenterClient { + +register_terminal(TerminalInfo) TerminalRegisterResponse + +deregister_terminal(StringValue) InvokeResponse + } + + ServiceHandle "1" *-- "1" Service + ServiceHandle "1" *-- "0..1" RunningServer + Service "1" *-- "1" Inner + Service ..|> TerminalRpc + Inner "1" *-- "1" Context + Context --> ServiceState + Context --> SimulationState + Context "1" o-- "0..*" CommandCallback + Context "1" o-- "0..*" EventDefinition + Context "1" o-- "0..*" ActiveEvent + EventDefinition "1" *-- "1" EventCallback + ActiveEvent --> EventSignal + CommandCallback ..> SinkState : response sink + EventCallback ..> SinkState : response sink + CommandCallback ..> TerminalError + EventCallback ..> TerminalError + RunningServer --> Service : lifecycle + RunningServer ..> CenterClient : registration +``` + +## 4. 协议与实现映射 + +| 关注点 | 协议或实现位置 | 说明 | +| ------------ | ------------------------------------------------------------------------ | ------------------------------------------- | +| 中心 API | [`proto/control/center.proto`](proto/control/center.proto) | 总中心与子中心复用的注册、注销和目录流 | +| 终端 API | [`proto/control/terminal.proto`](proto/control/terminal.proto) | 命令、事件、高频状态和元状态流 | +| 数据 API | [`proto/control/data.proto`](proto/control/data.proto) | 当前仅定义 `GetScene` | +| 公共消息 | [`proto/control/common/common.proto`](proto/control/common/common.proto) | 参数、参数模式、命令元信息和统一调用响应 | +| 调度服务 | [`dispatcher/src/main.rs`](dispatcher/src/main.rs) | 当前为占位程序,调度 API 和实现待补充 | +| 总中心 | [`registry/src/main.rs`](registry/src/main.rs) | 已实现 Center API、持久化目录和主动健康检查 | +| 聚合路由 | 尚无对应模块 | 同时实现下级 Center 和上级 Terminal | +| FFI 生命周期 | [`terminal/src/ffi.rs`](terminal/src/ffi.rs) | C ABI、句柄、输入校验和错误码 | +| 服务运行时 | [`terminal/src/runtime.rs`](terminal/src/runtime.rs) | Tokio/Axum 服务以及中心注册和注销 | +| RPC 适配 | [`terminal/src/rpc.rs`](terminal/src/rpc.rs) | `Terminal` trait 实现和 watch 流转换 | +| 领域状态 | [`terminal/src/terminal.rs`](terminal/src/terminal.rs) | 生命周期、仿真状态机、事件任务和状态发布 | +| 回调桥接 | [`terminal/src/callback.rs`](terminal/src/callback.rs) | C 回调、响应 sink 和 Protobuf 编解码 | + +## 5. 约束与说明 + +- Registry 是总中心的实现,维护全局逻辑终端目录;终端聚合路由服务是子中心,对下实现 Center API,对上实现 Terminal API。 +- 实体终端向子中心注册;子中心把下辖终端聚合为一个逻辑终端,再向总中心注册一个 `TerminalInfo`。 +- Dispatcher 负责命令编排、事件编排、仿真任务分配和状态驱动调度,并通过总中心发现逻辑终端。 +- 子中心内部可选择一个或多个实体终端,但对上只发布单一逻辑终端状态;事件需维护逻辑句柄到下游句柄的映射。 +- Dispatcher 和聚合路由目前没有业务实现;调度 API、调度意图如何传入子中心、响应聚合规则和逻辑状态模式仍需在编码前协议化。 +- Registry 持久化活动终端目录,按规范化 MAC 生成稳定 UUID v5;启动恢复后状态先为 UNKNOWN,再主动调用 Terminal 的标准 Health.Check。离线项保留为 NOT_SERVING,直到恢复或显式注销。 +- Terminal 使用 ConnectRPC 的 gRPC 协议并通过 HTTP/2 明文连接中心;服务端由 Axum 承载。 +- 命令与事件共用一个 `callback_gate`,因此同一终端实例上的宿主回调被串行执行。 +- `SubscribeStatus` 和 `SubscribeMetaStatus` 会先返回当前快照,之后再发送变更;关闭信号会结束流。 +- 高频状态的 `sequence` 和 `timestamp` 由 Rust 服务覆盖;元状态由事件定义、活动事件和中心分配的终端 ID 派生。 +- 事件回调成功只表示宿主接受了本次触发。重复事件必须再通过 `terminal_service_complete_event` 显式完成,才会进入下一周期。 diff --git a/aggregate-router/Cargo.toml b/aggregate-router/Cargo.toml new file mode 100644 index 0000000..60a5fb9 --- /dev/null +++ b/aggregate-router/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "aggregate-router" +version.workspace = true +edition.workspace = true +authors.workspace = true + +[dependencies] +connectrpc.workspace = true +buffa.workspace = true +buffa-types.workspace = true +serde.workspace = true +proto.workspace = true + +[build-dependencies] +connectrpc-build.workspace = true diff --git a/aggregate-router/src/main.rs b/aggregate-router/src/main.rs new file mode 100644 index 0000000..58e377e --- /dev/null +++ b/aggregate-router/src/main.rs @@ -0,0 +1 @@ +fn main() {} diff --git a/dispatcher/Cargo.toml b/dispatcher/Cargo.toml index ebab4f8..3ea0311 100644 --- a/dispatcher/Cargo.toml +++ b/dispatcher/Cargo.toml @@ -2,4 +2,4 @@ name = "dispatcher" version.workspace = true edition.workspace = true -author.workspace = true \ No newline at end of file +author.workspace = true diff --git a/dispatcher/src/main.rs b/dispatcher/src/main.rs index 20c767b..6868c15 100644 --- a/dispatcher/src/main.rs +++ b/dispatcher/src/main.rs @@ -1,4 +1,3 @@ - fn main() { println!("Hello, dispatcher!"); -} \ No newline at end of file +} diff --git a/proto/Cargo.toml b/proto/Cargo.toml new file mode 100644 index 0000000..1d4b9e9 --- /dev/null +++ b/proto/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "proto" +version.workspace = true +edition.workspace = true +authors.workspace = true + +[dependencies] +connectrpc.workspace = true +buffa.workspace = true +buffa-types.workspace = true +serde.workspace = true + +[build-dependencies] +connectrpc-build.workspace = true diff --git a/proto/build.rs b/proto/build.rs new file mode 100644 index 0000000..48d595a --- /dev/null +++ b/proto/build.rs @@ -0,0 +1,14 @@ +// 用于生成proto相关代码 +fn main() { + connectrpc_build::Config::new() + .files(&[ + "control/center.proto", + "control/terminal.proto", + "control/common/common.proto", + "third/grpc/health/v1/health.proto", + ]) + .includes(&["third/", "control/"]) + .include_file("proto_gen.rs") + .compile() + .unwrap(); +} diff --git a/proto/control/center.proto b/proto/control/center.proto new file mode 100644 index 0000000..52ef261 --- /dev/null +++ b/proto/control/center.proto @@ -0,0 +1,106 @@ +syntax = "proto3"; + +import "common/common.proto"; +import "google/protobuf/wrappers.proto"; +import "google/protobuf/any.proto"; +import "google/protobuf/empty.proto"; +import "grpc/health/v1/health.proto"; + +package control; + +/** + * 控制服务器 + * 作为控制系统的核心组件, 对控制终端服务提供注册接口, 对其他组件提供查询和状态订阅接口 + */ +service Center{ + + // 注册控制终端, 供控制终端调用, 通过该接口控制终端可以注册自己的信息 + rpc RegisterTerminal(TerminalInfo) returns (TerminalRegisterResponse); + + // 注销控制终端, 供控制终端调用, 通过该接口控制终端可以注销自己的信息, 入参为终端ID + rpc DeregisterTerminal(google.protobuf.StringValue) returns (control.InvokeResponse); + + // 订阅控制终端列表, 供控制系统调用, 通过该接口控制系统可以订阅控制终端列表的变化, 返回值为控制终端列表的流式数据 + rpc SubscribeTerminal(google.protobuf.Empty) returns (stream TerminalInfos); +} + +/** + * @brief TerminalRegisterResponse 代表控制终端注册的响应结果, 包含注册是否成功和响应信息 + * @details + * success 字段用于表示控制终端注册是否成功, true 表示成功, false 表示失败 + * message 字段用于提供控制终端注册的响应信息, 供控制系统展示使用, 如果注册成功则该字段为id, 如果注册失败则该字段为错误信息 + */ +message TerminalRegisterResponse { + bool success = 1; + string message = 2; +} + +/** + * @brief TerminalType 代表控制终端支持的模拟类型, 包含类型名称, 类型描述, 图标URL和配置参数列表 + * @details + * type_name 字段用于标识模拟类型的名称 + * description 字段用于模拟类型的描述信息 + * icon_url 字段用于模拟类型的图标URL, 供控制系统展示使用 + * param_schema 字段用于描述模拟器的状态参数定义, 以键值对的形式存储, 键为参数名, 值为参数类型. 参数类型使用 ParameterType 枚举类型进行定义 + * supported_commands 字段用于描述模拟器支持的命令列表 + * @implementation_note 虽然目前设计中命令是动态的, 但是我们依然要求控制终端提供以下几个基础命令的支持, 以便控制系统进行基本的控制操作: + * - "init": 初始化终端的仿真功能, 该命令的参数定义与注册至中心的meta_info中的supported_commands中的parameter保持一致 + * - "reset": 重置终端的仿真功能, 该命令的参数定义与注册至中心的meta_info中的supported_commands中的parameter保持一致 + * - "start": 启动终端的仿真功能, 该命令的参数定义与注册至中心的meta_info中的supported_commands中的parameter保持一致 + * - "stop": 停止终端的仿真功能, 该命令的参数定义与注册至中心的meta_info中的supported_commands中的parameter保持一致 + * - "suspend": 暂停终端的仿真功能, 该命令的参数定义与注册至中心的meta_info中的supported_commands中的parameter保持一致 + * - "resume": 恢复终端的仿真功能, 该命令的参数定义与注册至中心的meta_info中的supported_commands中的parameter保持一致 + */ +message TerminalType{ + string type_name = 1; + string description = 2; + string icon_url = 3; + map param_schema = 4; + repeated TerminalCommandInfo supported_commands = 5; +} + +/** + * @brief TerminalMetaInfo 代表控制终端的元信息, 包含支持的命令列表, 支持的终端类型列表和支持的事件列表 + * @details + * supported_type 字段列出了控制终端支持的模拟类型 + * extra_info 字段列出了控制终端提供的额外元信息 + * @description extra_info 字段用于后续拓展, 基于后面可能的需求进行拓展 + */ +message TerminalMetaInfo{ + TerminalType supported_type = 1; + google.protobuf.Any extra_info = 2; +} + +/** + * @brief TerminalInfo 代表控制终端的注册信息, 包含终端元信息, 终端主机地址和终端主机端口 + * @details + * meta_info 字段包含了控制终端的元信息, 包括支持的终端类型以及此类型支持的命令列表 + * terminal_host 和 terminal_port 同时用于终端服务监听和向中心注册地址. + * terminal_port 为0时, 终端绑定后应使用实际监听端口注册. + * 中心应按 terminal_mac 幂等注册或更新终端, 以支持安全重试. + */ +message TerminalInfo { + string terminal_host = 1; + uint32 terminal_port = 2; + string terminal_mac = 3; + TerminalMetaInfo meta_info = 4; +} + +/** + * @brief TerminalRuntimeInfo 代表控制终端的运行时信息, 包含终端注册信息和终端状态 + * @details + * info 字段包含了控制终端的注册信息, 包括终端元信息以及终端主机地址和端口 + */ +message TerminalRuntimeInfo{ + TerminalInfo info = 1; + grpc.health.v1.HealthCheckResponse.ServingStatus status = 2; +} + +/** + * @brief TerminalInfos 代表多个控制终端的信息列表, 以键值对的形式存储, 键为终端ID, 值为终端信息 + * @details + * infos 字段包含了多个控制终端的信息列表, 键为终端ID, 值为终端信息 + */ +message TerminalInfos { + map infos = 1; +} diff --git a/proto/control/common/common.proto b/proto/control/common/common.proto new file mode 100644 index 0000000..497f271 --- /dev/null +++ b/proto/control/common/common.proto @@ -0,0 +1,101 @@ +syntax = "proto3"; + +import "google/protobuf/any.proto"; + +package control; + +/** + * @brief Parameter 代表一个可以封装任意类型值的消息, 包含字符串值, 整数值, 浮点数值和布尔值以及嵌套的子表和选择值 + * @details + * Parameter 消息类型使用 oneof 字段来封装不同类型的值, 以支持多种参数类型的传递. + * 通过使用 Parameter 类型, 可以实现命令参数的灵活定义和扩展, 以适应不同命令的需求. + */ +message Parameter{ + message Simple{ + oneof value{ + string string_value = 1; + int64 int_value = 2; + double double_value = 3; + bool bool_value = 4; + } + } + message SubTable{ + map table = 1; + } + message Selected{ + repeated string options = 1; + } + oneof value { + Simple simple_value = 1; + SubTable sub_table_value = 2; + Selected selected_value = 3; + } +} + +/** + * @brief ParameterType 代表命令参数的类型 + * @details + * ParameterType 消息类型使用枚举类型 Type 来定义参数的基本类型, 包括字符串, 整数, 浮点数和布尔值. + * 另外, ParameterType 还支持 Select 和 SubTable 类型, 以支持参数的选择和嵌套结构. + */ +message ParameterType{ + enum Type { + STRING = 0; + INT = 1; + DOUBLE = 2; + BOOL = 3; + } + message Select{ + repeated string options = 1; + } + message SubTable{ + map schema = 1; + } + oneof value{ + Type type = 1; + Select select = 2; + SubTable sub_table = 3; + } +} + +/*! + * @brief AsyncCommandResponse 代表控制终端异步命令的响应消息, 包含命令ID, 进度和消息 + * @details + * cmd_id 字段用于唯一标识一个命令, 供控制系统进行命令的跟踪和管理 + * progress 字段用于表示命令的执行进度, 范围为0.0到1.0 + * message 字段用于提供命令执行的响应消息, 可以包含错误信息或者成功提示等内容 + */ +message AsyncCommandResponse{ + uint64 cmd_id = 1; + float progress = 2; + optional google.protobuf.Any data = 3; +} + +/** + * @brief InvokeResponse 代表命令调用的响应结果, 包含调用是否成功和响应消息 + * @details + * success 字段用于表示命令调用是否成功, true 表示成功, false 表示失败 + * message 字段用于提供命令调用的响应消息, 可以包含错误信息或者成功提示等内容, 具体定义在extra路径下的proto文件中, 以便控制系统根据实际需求进行定制化设计. + */ +message InvokeResponse{ + bool success = 1; + google.protobuf.Any message = 2; +} + +/** + * @brief TerminalCommandInfo 代表控制终端支持的命令信息, 包含命令类型, 命令描述和命令参数类型列表 + * @details + * id 字段用于标识命令的类型, 例如 "move", "stop"等等 + * type 字段用于标识命令的可读类型, 例如 "移动", "停止"等等, 供控制系统展示使用 + * description 字段用于描述命令的具体内容, 供控制系统展示使用 + * icon_url 字段用于描述命令的图标URL, 供控制系统展示使用 + * parameter 字段用于描述命令的参数类型列表, 以键值对的形式存储, 键为参数名, 值为参数类型. + * 参数类型使用 ParameterType 枚举类型进行定义 + */ +message TerminalCommandInfo{ + string id = 1; + string type = 2; + string description = 3; + string icon_url = 4; + map parameter = 5; +} diff --git a/proto/control/common/model.proto b/proto/control/common/model.proto new file mode 100644 index 0000000..54cb3cf --- /dev/null +++ b/proto/control/common/model.proto @@ -0,0 +1,9 @@ +syntax = "proto3"; + +package control; + +message SceneRequest { + +} + +message SceneResponse{} \ No newline at end of file diff --git a/proto/control/data.proto b/proto/control/data.proto new file mode 100644 index 0000000..c70d663 --- /dev/null +++ b/proto/control/data.proto @@ -0,0 +1,9 @@ +syntax = "proto3"; + +import "common/model.proto"; + +package control; + +service Data{ + rpc GetScene(SceneRequest) returns (SceneResponse); +} diff --git a/proto/control/extra/terminal.proto b/proto/control/extra/terminal.proto new file mode 100644 index 0000000..a643d8d --- /dev/null +++ b/proto/control/extra/terminal.proto @@ -0,0 +1,7 @@ +syntax = "proto3"; + +package terminal.extra; + +message SimExtra{ + int64 sim_id = 1; +} \ No newline at end of file diff --git a/proto/control/terminal.proto b/proto/control/terminal.proto new file mode 100644 index 0000000..d3906bb --- /dev/null +++ b/proto/control/terminal.proto @@ -0,0 +1,120 @@ +syntax = "proto3"; + +import "common/common.proto"; +import "google/protobuf/empty.proto"; + +package control; + +/** + * 控制终端服务 + * 作为仿真端控制组件, 对外提供控制接口, 供控制系统调用 + * @implementation_note 订阅接口保持空入参, 推送频率由终端实现统一控制. + */ +service Terminal{ + + // 执行命令, 供控制系统调用 + rpc Execute(Command) returns (control.InvokeResponse); + + // 发布事件, 供控制系统调用 + // 此时的返回值中的message字段为事件运行时ID, 供控制系统进行事件的跟踪和管理 + rpc PublishEvent(TerminalEvent) returns (control.InvokeResponse); + + // 取消事件, 供控制系统调用, 入参为事件ID + rpc CancelEvent(TerminalCancelEvent) returns (control.InvokeResponse); + + // 订阅终端状态, 供控制系统调用 + rpc SubscribeStatus(google.protobuf.Empty) returns (stream TerminalStatus); + + // 订阅终端元状态, 供控制系统调用 + rpc SubscribeMetaStatus(google.protobuf.Empty) returns (stream TerminalMetaStatus); +} + +/** + * @brief Command 代表控制系统发送给控制终端的命令, 包含命令类型和命令载荷 + * @details + * id 字段用于标识命令的类型, 例如 "start", "stop"等等 + * payload 字段用于携带命令的具体内容, 以键值对的形式存储, 键为参数名, 值为参数值. + * timestamp 字段用于标识命令的时间戳, 以毫秒为单位的Unix时间戳, 供控制终端进行命令的排序和处理 + */ +message Command { + string id = 1; + int64 timestamp = 2; + map payload = 3; +} + +/** + * @brief TerminalEventInfo 代表控制终端支持的事件信息, 包含事件ID, 事件类型, 事件名称, 事件描述, 事件载荷的参数定义 + * @details + * event_id 字段用于唯一标识一个事件 + * event_type 字段用于标识事件的类型, 例如 "critical", "emergency"等等 + * event_name 字段用于事件的名称, 供控制系统展示使用 + * description 字段用于描述事件的具体内容, 供控制系统展示使用 + * payload_schema 字段用于描述事件载荷的参数定义, 以键值对的形式存储, 键为参数名, 值为参数类型. 参数类型使用 ParameterType 枚举类型进行定义 + * @implementation_note 目前设计中, 事件的定义是动态的, 由终端在运行时根据实际情况进行定义和更新. 但是我们要求终端实现中不进行特情("emergency")类型的事件的实现与注册 + * 特情事件是控制系统预定义的一类事件, 具有特殊的含义和处理逻辑. 在提供的动态库中通过外挂脚本的形式进行特情事件的定义和注册, 以便控制系统根据实际需求进行特情事件的定制化设计. + * 终端实现中不进行特情事件的定义和注册, 可以避免终端实现与控制系统预定义的特情事件发生冲突, 同时也可以简化终端实现的设计和开发. + */ +message TerminalEventInfo{ + string event_id = 1; + string event_type = 2; + string event_category = 3; + string event_name = 4; + string description = 5; + map payload_schema = 6; +} + +/** + * @brief TerminalEvent 代表控制终端的事件信息, 包含事件ID, 触发延迟, 重复周期和事件载荷 + * @details + * event_id 字段用于唯一标识一个事件 + * trigger_delay_ms 字段用于表示事件触发的延迟时间, 单位为毫秒, 如果该字段值为0, 则表示事件立即触发 + * repeat_period_ms 字段用于表示事件的重复周期, 单位为毫秒, 如果该字段值为0, 则表示该事件不重复 + * payload 字段用于携带事件的具体内容, 以键值对的形式存储, 键为参数名, 值为参数值. + */ +message TerminalEvent{ + string event_id = 1; + uint64 trigger_delay_ms = 2; + uint64 repeat_period_ms = 3; + map payload = 4; +} + +message TerminalCancelEvent{ + string event_id = 1; + uint64 instance_id = 2; +} + +message TerminalEventHandle{ + string event_id = 1; + uint64 instance_id = 2; +} + +/** + * @brief TerminalStatus 控制终端高频状态的消息格式, 包含当前参数列表, 状态序列号和状态时间戳 + * @details + * sequence 字段表示状态的序列号, 每次状态更新时递增, 供控制系统跟踪状态的变化 + * timestamp 字段表示状态的时间戳, 以毫秒为单位的Unix时间戳, 供控制系统跟踪状态的变化时间 + * current_param 字段表示当前终端的参数, 与注册至中心的meta_info中的param_schema保持一致 + * @implementation_note 目前设计中, 状态信息推送频率由终端实现进行控制, 最大推送频率为 100hz + * @implementation_note 状态字段保持动态参数表, 以支持不同仿真类型的状态模型. + */ +message TerminalStatus{ + uint64 sequence = 1; + int64 timestamp = 2; + map current_param = 3; +} + +/** + * @brief TerminalMetaStatus 代表控制终端的元状态信息, 包含终端ID, 可发布事件列表和已触发事件列表 + * @details + * terminal_id 字段用于唯一标识一个控制终端 + * publishable_events 字段表示终端当前可发布的事件列表, 供控制系统展示使用 + * triggered_events 字段表示终端当前已触发的事件列表, 供控制系统展示使用, key为instance_id, value为事件信息 + * @implementation_note 目前设计中, 终端的元状态信息推送为低频推送, 即push_on_change策略, 以降低系统的负载. + * - 终端可发布的事件列表发生变化时, 例如新增了一个 "critical" 类型的事件 + * - 终端已触发的事件列表发生变化时, 例如触发了一个 "emergency" 类型的事件 + */ +message TerminalMetaStatus{ + string terminal_id = 1; + repeated TerminalEventInfo publishable_events = 2; + map triggered_events = 3; +} diff --git a/proto/src/lib.rs b/proto/src/lib.rs new file mode 100644 index 0000000..0b26f66 --- /dev/null +++ b/proto/src/lib.rs @@ -0,0 +1,3 @@ +pub mod proto { + connectrpc::include_generated!("proto_gen.rs"); +} diff --git a/proto/third/google/api/annotations.proto b/proto/third/google/api/annotations.proto new file mode 100644 index 0000000..adafc78 --- /dev/null +++ b/proto/third/google/api/annotations.proto @@ -0,0 +1,3 @@ +syntax = "proto3"; +package google.api; +// Placeholder for option definitions; kept minimal for tooling. diff --git a/proto/third/google/api/client.proto b/proto/third/google/api/client.proto new file mode 100644 index 0000000..ef16a89 --- /dev/null +++ b/proto/third/google/api/client.proto @@ -0,0 +1,16 @@ +syntax = "proto3"; +package google.api; +enum ClientLibraryOrganization { + CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED = 0; + GOOGLE = 1; + CLOUD = 2; +} +enum ClientLibraryDestination { + CLIENT_LIBRARY_DESTINATION_UNSPECIFIED = 0; + GITHUB = 10; + PACKAGE_MANAGER = 20; +} +message CommonLanguageSettings { + string reference_docs_uri = 1; + repeated string destinations = 2; +} diff --git a/proto/third/google/api/field_behavior.proto b/proto/third/google/api/field_behavior.proto new file mode 100644 index 0000000..d959519 --- /dev/null +++ b/proto/third/google/api/field_behavior.proto @@ -0,0 +1,10 @@ +syntax = "proto3"; +package google.api; +enum FieldBehavior { + FIELD_BEHAVIOR_UNSPECIFIED = 0; + OPTIONAL = 1; + REQUIRED = 2; + OUTPUT_ONLY = 3; + INPUT_ONLY = 4; + IMMUTABLE = 5; +} diff --git a/proto/third/google/api/http.proto b/proto/third/google/api/http.proto new file mode 100644 index 0000000..37f0813 --- /dev/null +++ b/proto/third/google/api/http.proto @@ -0,0 +1,20 @@ +syntax = "proto3"; +package google.api; +message Http { + repeated HttpRule rules = 1; + bool fully_decode_reserved_expansion = 2; +} +message HttpRule { + string selector = 1; + string get = 2; + string put = 3; + string post = 4; + string delete = 5; + string patch = 6; + CustomHttpPattern custom = 8; + repeated HttpRule additional_bindings = 11; +} +message CustomHttpPattern { + string kind = 1; + string path = 2; +} diff --git a/proto/third/google/api/launch_stage.proto b/proto/third/google/api/launch_stage.proto new file mode 100644 index 0000000..9d6d574 --- /dev/null +++ b/proto/third/google/api/launch_stage.proto @@ -0,0 +1,12 @@ +syntax = "proto3"; +package google.api; +enum LaunchStage { + LAUNCH_STAGE_UNSPECIFIED = 0; + UNIMPLEMENTED = 6; + PRELAUNCH = 7; + EARLY_ACCESS = 1; + ALPHA = 2; + BETA = 3; + GA = 4; + DEPRECATED = 5; +} diff --git a/proto/third/google/api/resource.proto b/proto/third/google/api/resource.proto new file mode 100644 index 0000000..fa1789a --- /dev/null +++ b/proto/third/google/api/resource.proto @@ -0,0 +1,14 @@ +syntax = "proto3"; +package google.api; +message ResourceDescriptor { + string type = 1; + repeated string pattern = 2; + string name_field = 3; + string history = 4; + repeated string plural = 5; + string singular = 6; +} +message ResourceReference { + string type = 1; + string child_type = 2; +} diff --git a/proto/third/google/api/visibility.proto b/proto/third/google/api/visibility.proto new file mode 100644 index 0000000..358be9f --- /dev/null +++ b/proto/third/google/api/visibility.proto @@ -0,0 +1,9 @@ +syntax = "proto3"; +package google.api; +message VisibilityRule { + string selector = 1; + string restriction = 2; +} +message Visibility { + repeated VisibilityRule rules = 1; +} diff --git a/proto/third/google/cloud/audit/audit_log.proto b/proto/third/google/cloud/audit/audit_log.proto new file mode 100644 index 0000000..ef7b960 --- /dev/null +++ b/proto/third/google/cloud/audit/audit_log.proto @@ -0,0 +1,10 @@ +syntax = "proto3"; +package google.cloud.audit; +import "google/rpc/status.proto"; +message AuditLog { + string service_name = 7; + string method_name = 8; + string resource_name = 11; + string principal_subject = 13; + google.rpc.Status status = 2; +} diff --git a/proto/third/google/logging/type/http_request.proto b/proto/third/google/logging/type/http_request.proto new file mode 100644 index 0000000..1b73c05 --- /dev/null +++ b/proto/third/google/logging/type/http_request.proto @@ -0,0 +1,13 @@ +syntax = "proto3"; +package google.logging.type; +message HttpRequest { + string request_method = 1; + string request_url = 2; + int64 status = 3; + int64 response_size = 4; + string user_agent = 5; + string remote_ip = 6; + string referer = 7; + bool cache_hit = 8; + bool cache_validated_with_origin_server = 9; +} diff --git a/proto/third/google/logging/type/log_severity.proto b/proto/third/google/logging/type/log_severity.proto new file mode 100644 index 0000000..96fdd61 --- /dev/null +++ b/proto/third/google/logging/type/log_severity.proto @@ -0,0 +1,13 @@ +syntax = "proto3"; +package google.logging.type; +enum LogSeverity { + DEFAULT = 0; + DEBUG = 100; + INFO = 200; + NOTICE = 300; + WARNING = 400; + ERROR = 500; + CRITICAL = 600; + ALERT = 700; + EMERGENCY = 800; +} diff --git a/proto/third/google/longrunning/operations.proto b/proto/third/google/longrunning/operations.proto new file mode 100644 index 0000000..9b20ce4 --- /dev/null +++ b/proto/third/google/longrunning/operations.proto @@ -0,0 +1,11 @@ +syntax = "proto3"; +package google.longrunning; +import "google/protobuf/any.proto"; +import "google/rpc/status.proto"; +message Operation { + string name = 1; + google.protobuf.Any metadata = 2; + bool done = 3; + google.rpc.Status error = 4; + google.protobuf.Any response = 5; +} diff --git a/proto/third/google/protobuf/any.proto b/proto/third/google/protobuf/any.proto new file mode 100644 index 0000000..45776b8 --- /dev/null +++ b/proto/third/google/protobuf/any.proto @@ -0,0 +1,6 @@ +syntax = "proto3"; +package google.protobuf; +message Any { + string type_url = 1; + bytes value = 2; +} diff --git a/proto/third/google/protobuf/descriptor.proto b/proto/third/google/protobuf/descriptor.proto new file mode 100644 index 0000000..5dca6de --- /dev/null +++ b/proto/third/google/protobuf/descriptor.proto @@ -0,0 +1,396 @@ +syntax = "proto2"; +package google.protobuf; + +message FileDescriptorSet { + repeated FileDescriptorProto file = 1; +} + +message FileDescriptorProto { + optional string name = 1; + optional string package = 2; + repeated string dependency = 3; + repeated int32 public_dependency = 10; + repeated int32 weak_dependency = 11; + repeated DescriptorProto message_type = 4; + repeated EnumDescriptorProto enum_type = 5; + repeated ServiceDescriptorProto service = 6; + repeated FieldDescriptorProto extension = 7; + optional FileOptions options = 8; + optional SourceCodeInfo source_code_info = 9; + optional string syntax = 12; + optional Edition edition = 14; +} + +message DescriptorProto { + optional string name = 1; + repeated FieldDescriptorProto field = 2; + repeated FieldDescriptorProto extension = 6; + repeated DescriptorProto nested_type = 3; + repeated EnumDescriptorProto enum_type = 4; + repeated ExtensionRange extension_range = 5; + repeated OneofDescriptorProto oneof_decl = 8; + optional MessageOptions options = 7; + repeated ReservedRange reserved_range = 9; + repeated string reserved_name = 10; + + message ExtensionRange { + optional int32 start = 1; + optional int32 end = 2; + optional ExtensionRangeOptions options = 3; + } + + message ReservedRange { + optional int32 start = 1; + optional int32 end = 2; + } +} + +message ExtensionRangeOptions { + repeated UninterpretedOption uninterpreted_option = 999; + repeated Declaration declaration = 2; + optional FeatureSet features = 50; + enum VerificationState { + DECLARATION = 0; + UNVERIFIED = 1; + } + optional VerificationState verification = 3 [default = UNVERIFIED]; + + message Declaration { + optional int32 number = 1; + optional string full_name = 2; + optional string type = 3; + optional bool reserved = 5; + optional bool repeated = 6; + } +} + +message FieldDescriptorProto { + enum Type { + TYPE_DOUBLE = 1; + TYPE_FLOAT = 2; + TYPE_INT64 = 3; + TYPE_UINT64 = 4; + TYPE_INT32 = 5; + TYPE_FIXED64 = 6; + TYPE_FIXED32 = 7; + TYPE_BOOL = 8; + TYPE_STRING = 9; + TYPE_GROUP = 10; + TYPE_MESSAGE = 11; + TYPE_BYTES = 12; + TYPE_UINT32 = 13; + TYPE_ENUM = 14; + TYPE_SFIXED32 = 15; + TYPE_SFIXED64 = 16; + TYPE_SINT32 = 17; + TYPE_SINT64 = 18; + } + + enum Label { + LABEL_OPTIONAL = 1; + LABEL_REQUIRED = 2; + LABEL_REPEATED = 3; + } + + optional string name = 1; + optional int32 number = 3; + optional Label label = 4; + optional Type type = 5; + optional string type_name = 6; + optional string extendee = 2; + optional string default_value = 7; + optional int32 oneof_index = 9; + optional string json_name = 10; + optional FieldOptions options = 8; + optional bool proto3_optional = 17; +} + +message OneofDescriptorProto { + optional string name = 1; + optional OneofOptions options = 2; +} + +message EnumDescriptorProto { + optional string name = 1; + repeated EnumValueDescriptorProto value = 2; + optional EnumOptions options = 3; + repeated EnumReservedRange reserved_range = 4; + repeated string reserved_name = 5; + + message EnumReservedRange { + optional int32 start = 1; + optional int32 end = 2; + } +} + +message EnumValueDescriptorProto { + optional string name = 1; + optional int32 number = 2; + optional EnumValueOptions options = 3; +} + +message ServiceDescriptorProto { + optional string name = 1; + repeated MethodDescriptorProto method = 2; + optional ServiceOptions options = 3; +} + +message MethodDescriptorProto { + optional string name = 1; + optional string input_type = 2; + optional string output_type = 3; + optional MethodOptions options = 4; + optional bool client_streaming = 5 [default = false]; + optional bool server_streaming = 6 [default = false]; +} + +enum Edition { + EDITION_UNKNOWN = 0; + EDITION_PROTO2 = 998; + EDITION_PROTO3 = 999; + EDITION_2023 = 1000; + EDITION_2024 = 1001; + EDITION_1_TEST_ONLY = 1; + EDITION_2_TEST_ONLY = 2; + EDITION_99997_TEST_ONLY = 99997; + EDITION_99998_TEST_ONLY = 99998; + EDITION_99999_TEST_ONLY = 99999; + EDITION_MAX = 2147483647; +} + +message FileOptions { + optional string java_package = 1; + optional string java_outer_classname = 8; + optional bool java_multiple_files = 10 [default = false]; + optional bool java_generate_equals_and_hash = 20 [deprecated = true]; + optional bool java_string_check_utf8 = 27 [default = false]; + enum OptimizeMode { + SPEED = 1; + CODE_SIZE = 2; + LITE_RUNTIME = 3; + } + optional OptimizeMode optimize_for = 9 [default = SPEED]; + optional string go_package = 11; + optional bool cc_generic_services = 16 [default = false]; + optional bool java_generic_services = 17 [default = false]; + optional bool py_generic_services = 18 [default = false]; + optional bool deprecated = 23 [default = false]; + optional bool cc_enable_arenas = 31 [default = true]; + optional string objc_class_prefix = 36; + optional string csharp_namespace = 37; + optional string swift_prefix = 39; + optional string php_class_prefix = 40; + optional string php_namespace = 41; + optional string php_metadata_namespace = 44; + optional string ruby_package = 45; + optional FeatureSet features = 50; + repeated UninterpretedOption uninterpreted_option = 999; + extensions 1000 to max; +} + +message MessageOptions { + optional bool message_set_wire_format = 1 [default = false]; + optional bool no_standard_descriptor_accessor = 2 [default = false]; + optional bool deprecated = 3 [default = false]; + optional bool map_entry = 7; + optional bool deprecated_legacy_json_field_conflicts = 11 [deprecated = true]; + optional FeatureSet features = 12; + repeated UninterpretedOption uninterpreted_option = 999; + extensions 1000 to max; +} + +message FieldOptions { + enum CType { + STRING = 0; + CORD = 1; + STRING_PIECE = 2; + } + optional CType ctype = 1 [default = STRING]; + optional bool packed = 2; + enum JSType { + JS_NORMAL = 0; + JS_STRING = 1; + JS_NUMBER = 2; + } + optional JSType jstype = 6 [default = JS_NORMAL]; + optional bool lazy = 5 [default = false]; + optional bool unverified_lazy = 15 [default = false]; + optional bool deprecated = 3 [default = false]; + optional bool weak = 10 [default = false]; + optional bool debug_redact = 16 [default = false]; + enum OptionRetention { + RETENTION_UNKNOWN = 0; + RETENTION_RUNTIME = 1; + RETENTION_SOURCE = 2; + } + optional OptionRetention retention = 17; + enum OptionTargetType { + TARGET_TYPE_UNKNOWN = 0; + TARGET_TYPE_FILE = 1; + TARGET_TYPE_EXTENSION_RANGE = 2; + TARGET_TYPE_MESSAGE = 3; + TARGET_TYPE_FIELD = 4; + TARGET_TYPE_ONEOF = 5; + TARGET_TYPE_ENUM = 6; + TARGET_TYPE_ENUM_ENTRY = 7; + TARGET_TYPE_SERVICE = 8; + TARGET_TYPE_METHOD = 9; + } + repeated OptionTargetType targets = 19; + repeated EditionDefault edition_defaults = 20; + optional FeatureSet features = 21; + optional FeatureSupport feature_support = 22; + repeated UninterpretedOption uninterpreted_option = 999; + extensions 1000 to max; + + message EditionDefault { + optional Edition edition = 3; + optional string value = 2; + } + + message FeatureSupport { + optional Edition edition_introduced = 1; + optional Edition edition_deprecated = 2; + optional string deprecation_warning = 3; + optional Edition edition_removed = 4; + } +} + +message OneofOptions { + optional FeatureSet features = 1; + repeated UninterpretedOption uninterpreted_option = 999; + extensions 1000 to max; +} + +message EnumOptions { + optional bool allow_alias = 2; + optional bool deprecated = 3 [default = false]; + optional bool deprecated_legacy_json_field_conflicts = 6 [deprecated = true]; + optional FeatureSet features = 7; + repeated UninterpretedOption uninterpreted_option = 999; + extensions 1000 to max; +} + +message EnumValueOptions { + optional bool deprecated = 1 [default = false]; + optional FeatureSet features = 2; + optional bool debug_redact = 3 [default = false]; + optional FieldOptions.FeatureSupport feature_support = 4; + repeated UninterpretedOption uninterpreted_option = 999; + extensions 1000 to max; +} + +message ServiceOptions { + optional FeatureSet features = 34; + optional bool deprecated = 33 [default = false]; + repeated UninterpretedOption uninterpreted_option = 999; + extensions 1000 to max; +} + +message MethodOptions { + optional bool deprecated = 33 [default = false]; + enum IdempotencyLevel { + IDEMPOTENCY_UNKNOWN = 0; + NO_SIDE_EFFECTS = 1; + IDEMPOTENT = 2; + } + optional IdempotencyLevel idempotency_level = 34 [default = IDEMPOTENCY_UNKNOWN]; + optional FeatureSet features = 35; + repeated UninterpretedOption uninterpreted_option = 999; + extensions 1000 to max; +} + +message UninterpretedOption { + message NamePart { + required string name_part = 1; + required bool is_extension = 2; + } + repeated NamePart name = 2; + optional string identifier_value = 3; + optional uint64 positive_int_value = 4; + optional int64 negative_int_value = 5; + optional double double_value = 6; + optional bytes string_value = 7; + optional string aggregate_value = 8; +} + +message FeatureSet { + enum FieldPresence { + FIELD_PRESENCE_UNKNOWN = 0; + EXPLICIT = 1; + IMPLICIT = 2; + LEGACY_REQUIRED = 3; + } + optional FieldPresence field_presence = 1; + enum EnumType { + ENUM_TYPE_UNKNOWN = 0; + OPEN = 1; + CLOSED = 2; + } + optional EnumType enum_type = 2; + enum RepeatedFieldEncoding { + REPEATED_FIELD_ENCODING_UNKNOWN = 0; + PACKED = 1; + EXPANDED = 2; + } + optional RepeatedFieldEncoding repeated_field_encoding = 3; + enum Utf8Validation { + UTF8_VALIDATION_UNKNOWN = 0; + VERIFY = 2; + NONE = 3; + } + optional Utf8Validation utf8_validation = 4; + enum MessageEncoding { + MESSAGE_ENCODING_UNKNOWN = 0; + LENGTH_PREFIXED = 1; + DELIMITED = 2; + } + optional MessageEncoding message_encoding = 5; + enum JsonFormat { + JSON_FORMAT_UNKNOWN = 0; + ALLOW = 1; + LEGACY_BEST_EFFORT = 2; + } + optional JsonFormat json_format = 6; + extensions 1000 to 9994; + extensions 9995 to 9999; + extensions 10000; +} + +message FeatureSetDefaults { + message FeatureSetEditionDefault { + optional Edition edition = 3; + optional FeatureSet overridable_features = 4; + optional FeatureSet fixed_features = 5; + } + repeated FeatureSetEditionDefault defaults = 1; + optional Edition minimum_edition = 4; + optional Edition maximum_edition = 5; +} + +message SourceCodeInfo { + repeated Location location = 1; + message Location { + repeated int32 path = 1 [packed = true]; + repeated int32 span = 2 [packed = true]; + optional string leading_comments = 3; + optional string trailing_comments = 4; + repeated string leading_detached_comments = 6; + } +} + +message GeneratedCodeInfo { + repeated Annotation annotation = 1; + message Annotation { + repeated int32 path = 1 [packed = true]; + optional string source_file = 2; + optional int32 begin = 3; + optional int32 end = 4; + enum Semantic { + NONE = 0; + SET = 1; + ALIAS = 2; + } + optional Semantic semantic = 5; + } +} diff --git a/proto/third/google/protobuf/duration.proto b/proto/third/google/protobuf/duration.proto new file mode 100644 index 0000000..1d6bd6d --- /dev/null +++ b/proto/third/google/protobuf/duration.proto @@ -0,0 +1,6 @@ +syntax = "proto3"; +package google.protobuf; +message Duration { + int64 seconds = 1; + int32 nanos = 2; +} diff --git a/proto/third/google/protobuf/empty.proto b/proto/third/google/protobuf/empty.proto new file mode 100644 index 0000000..98c95fc --- /dev/null +++ b/proto/third/google/protobuf/empty.proto @@ -0,0 +1,3 @@ +syntax = "proto3"; +package google.protobuf; +message Empty {} diff --git a/proto/third/google/protobuf/field_mask.proto b/proto/third/google/protobuf/field_mask.proto new file mode 100644 index 0000000..a5faa00 --- /dev/null +++ b/proto/third/google/protobuf/field_mask.proto @@ -0,0 +1,5 @@ +syntax = "proto3"; +package google.protobuf; +message FieldMask { + repeated string paths = 1; +} diff --git a/proto/third/google/protobuf/struct.proto b/proto/third/google/protobuf/struct.proto new file mode 100644 index 0000000..5c4fafa --- /dev/null +++ b/proto/third/google/protobuf/struct.proto @@ -0,0 +1,21 @@ +syntax = "proto3"; +package google.protobuf; +enum NullValue { + NULL_VALUE = 0; +} +message Struct { + map fields = 1; +} +message Value { + oneof kind { + NullValue null_value = 1; + double number_value = 2; + string string_value = 3; + bool bool_value = 4; + Struct struct_value = 5; + ListValue list_value = 6; + } +} +message ListValue { + repeated Value values = 1; +} diff --git a/proto/third/google/protobuf/timestamp.proto b/proto/third/google/protobuf/timestamp.proto new file mode 100644 index 0000000..3d4b6d5 --- /dev/null +++ b/proto/third/google/protobuf/timestamp.proto @@ -0,0 +1,6 @@ +syntax = "proto3"; +package google.protobuf; +message Timestamp { + int64 seconds = 1; + int32 nanos = 2; +} diff --git a/proto/third/google/protobuf/wrappers.proto b/proto/third/google/protobuf/wrappers.proto new file mode 100644 index 0000000..c77fbe1 --- /dev/null +++ b/proto/third/google/protobuf/wrappers.proto @@ -0,0 +1,11 @@ +syntax = "proto3"; +package google.protobuf; +message DoubleValue { double value = 1; } +message FloatValue { float value = 1; } +message Int64Value { int64 value = 1; } +message UInt64Value { uint64 value = 1; } +message Int32Value { int32 value = 1; } +message UInt32Value { uint32 value = 1; } +message BoolValue { bool value = 1; } +message StringValue { string value = 1; } +message BytesValue { bytes value = 1; } diff --git a/proto/third/google/rpc/code.proto b/proto/third/google/rpc/code.proto new file mode 100644 index 0000000..4371359 --- /dev/null +++ b/proto/third/google/rpc/code.proto @@ -0,0 +1,21 @@ +syntax = "proto3"; +package google.rpc; +enum Code { + OK = 0; + CANCELLED = 1; + UNKNOWN = 2; + INVALID_ARGUMENT = 3; + DEADLINE_EXCEEDED = 4; + NOT_FOUND = 5; + ALREADY_EXISTS = 6; + PERMISSION_DENIED = 7; + RESOURCE_EXHAUSTED = 8; + FAILED_PRECONDITION = 9; + ABORTED = 10; + OUT_OF_RANGE = 11; + UNIMPLEMENTED = 12; + INTERNAL = 13; + UNAVAILABLE = 14; + DATA_LOSS = 15; + UNAUTHENTICATED = 16; +} diff --git a/proto/third/google/rpc/error_details.proto b/proto/third/google/rpc/error_details.proto new file mode 100644 index 0000000..639abc9 --- /dev/null +++ b/proto/third/google/rpc/error_details.proto @@ -0,0 +1,58 @@ +syntax = "proto3"; +package google.rpc; +import "google/protobuf/duration.proto"; +message RetryInfo { + google.protobuf.Duration retry_delay = 1; +} +message DebugInfo { + repeated string stack_entries = 1; + string detail = 2; +} +message QuotaFailure { + message Violation { + string subject = 1; + string description = 2; + } + repeated Violation violations = 1; +} +message ErrorInfo { + string reason = 1; + string domain = 2; + map metadata = 3; +} +message PreconditionFailure { + message Violation { + string type = 1; + string subject = 2; + string description = 3; + } + repeated Violation violations = 1; +} +message BadRequest { + message FieldViolation { + string field = 1; + string description = 2; + } + repeated FieldViolation field_violations = 1; +} +message RequestInfo { + string request_id = 1; + string serving_data = 2; +} +message ResourceInfo { + string resource_type = 1; + string resource_name = 2; + string owner = 3; + string description = 4; +} +message Help { + message Link { + string description = 1; + string url = 2; + } + repeated Link links = 1; +} +message LocalizedMessage { + string locale = 1; + string message = 2; +} diff --git a/proto/third/google/rpc/status.proto b/proto/third/google/rpc/status.proto new file mode 100644 index 0000000..b4693be --- /dev/null +++ b/proto/third/google/rpc/status.proto @@ -0,0 +1,8 @@ +syntax = "proto3"; +package google.rpc; +import "google/protobuf/any.proto"; +message Status { + int32 code = 1; + string message = 2; + repeated google.protobuf.Any details = 3; +} diff --git a/proto/third/google/type/color.proto b/proto/third/google/type/color.proto new file mode 100644 index 0000000..2c2cb77 --- /dev/null +++ b/proto/third/google/type/color.proto @@ -0,0 +1,8 @@ +syntax = "proto3"; +package google.type; +message Color { + float red = 1; + float green = 2; + float blue = 3; + float alpha = 4; +} diff --git a/proto/third/google/type/date.proto b/proto/third/google/type/date.proto new file mode 100644 index 0000000..17f94e6 --- /dev/null +++ b/proto/third/google/type/date.proto @@ -0,0 +1,7 @@ +syntax = "proto3"; +package google.type; +message Date { + int32 year = 1; + int32 month = 2; + int32 day = 3; +} diff --git a/proto/third/google/type/datetime.proto b/proto/third/google/type/datetime.proto new file mode 100644 index 0000000..a5523cd --- /dev/null +++ b/proto/third/google/type/datetime.proto @@ -0,0 +1,19 @@ +syntax = "proto3"; +package google.type; +message TimeZone { + string id = 1; + int32 version = 2; +} +message DateTime { + int32 year = 1; + int32 month = 2; + int32 day = 3; + int32 hours = 4; + int32 minutes = 5; + int32 seconds = 6; + int32 nanos = 7; + oneof time_offset { + int32 utc_offset = 8; + TimeZone time_zone = 9; + } +} diff --git a/proto/third/google/type/expr.proto b/proto/third/google/type/expr.proto new file mode 100644 index 0000000..888b567 --- /dev/null +++ b/proto/third/google/type/expr.proto @@ -0,0 +1,8 @@ +syntax = "proto3"; +package google.type; +message Expr { + string expression = 1; + string title = 2; + string description = 3; + string location = 4; +} diff --git a/proto/third/google/type/latlng.proto b/proto/third/google/type/latlng.proto new file mode 100644 index 0000000..2429631 --- /dev/null +++ b/proto/third/google/type/latlng.proto @@ -0,0 +1,6 @@ +syntax = "proto3"; +package google.type; +message LatLng { + double latitude = 1; + double longitude = 2; +} diff --git a/proto/third/google/type/localized_text.proto b/proto/third/google/type/localized_text.proto new file mode 100644 index 0000000..ccec2d7 --- /dev/null +++ b/proto/third/google/type/localized_text.proto @@ -0,0 +1,6 @@ +syntax = "proto3"; +package google.type; +message LocalizedText { + string text = 1; + string language_code = 2; +} diff --git a/proto/third/google/type/money.proto b/proto/third/google/type/money.proto new file mode 100644 index 0000000..2d53c0b --- /dev/null +++ b/proto/third/google/type/money.proto @@ -0,0 +1,7 @@ +syntax = "proto3"; +package google.type; +message Money { + string currency_code = 1; + int64 units = 2; + int32 nanos = 3; +} diff --git a/proto/third/google/type/phone_number.proto b/proto/third/google/type/phone_number.proto new file mode 100644 index 0000000..2dc31b2 --- /dev/null +++ b/proto/third/google/type/phone_number.proto @@ -0,0 +1,6 @@ +syntax = "proto3"; +package google.type; +message PhoneNumber { + string e164_number = 1; + string extension = 2; +} diff --git a/proto/third/google/type/postal_address.proto b/proto/third/google/type/postal_address.proto new file mode 100644 index 0000000..90ee885 --- /dev/null +++ b/proto/third/google/type/postal_address.proto @@ -0,0 +1,13 @@ +syntax = "proto3"; +package google.type; +message PostalAddress { + string region_code = 1; + string language_code = 2; + string postal_code = 3; + string administrative_area = 4; + string locality = 5; + string sublocality = 6; + repeated string address_lines = 7; + repeated string recipients = 8; + string organization = 9; +} diff --git a/proto/third/google/type/timeofday.proto b/proto/third/google/type/timeofday.proto new file mode 100644 index 0000000..06e44c5 --- /dev/null +++ b/proto/third/google/type/timeofday.proto @@ -0,0 +1,8 @@ +syntax = "proto3"; +package google.type; +message TimeOfDay { + int32 hours = 1; + int32 minutes = 2; + int32 seconds = 3; + int32 nanos = 4; +} diff --git a/proto/third/grpc/health/v1/health.proto b/proto/third/grpc/health/v1/health.proto new file mode 100644 index 0000000..db426f1 --- /dev/null +++ b/proto/third/grpc/health/v1/health.proto @@ -0,0 +1,63 @@ +// Copyright 2015 The gRPC Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// The canonical version of this proto can be found at +// https://github.com/grpc/grpc-proto/blob/master/grpc/health/v1/health.proto + +syntax = "proto3"; + +package grpc.health.v1; + +option csharp_namespace = "Grpc.Health.V1"; +option go_package = "google.golang.org/grpc/health/grpc_health_v1"; +option java_multiple_files = true; +option java_outer_classname = "HealthProto"; +option java_package = "io.grpc.health.v1"; + +message HealthCheckRequest { + string service = 1; +} + +message HealthCheckResponse { + enum ServingStatus { + UNKNOWN = 0; + SERVING = 1; + NOT_SERVING = 2; + SERVICE_UNKNOWN = 3; // Used only by the Watch method. + } + ServingStatus status = 1; +} + +service Health { + // If the requested service is unknown, the call will fail with status + // NOT_FOUND. + rpc Check(HealthCheckRequest) returns (HealthCheckResponse); + + // Performs a watch for the serving status of the requested service. + // The server will immediately send back a message indicating the current + // serving status. It will then subsequently send a new message whenever + // the service's serving status changes. + // + // If the requested service is unknown when the call is received, the + // server will send a message setting the serving status to + // SERVICE_UNKNOWN but will *not* terminate the call. If at some + // future point, the serving status of the service becomes known, the + // server will send a new message with the service's serving status. + // + // If the call terminates with status UNIMPLEMENTED, then clients + // should assume this method is not supported and should not retry the + // call. If the call terminates with any other status (including OK), + // clients should retry the call with appropriate exponential backoff. + rpc Watch(HealthCheckRequest) returns (stream HealthCheckResponse); +} \ No newline at end of file diff --git a/registry/Cargo.toml b/registry/Cargo.toml index 06c1e6a..e6e73b5 100644 --- a/registry/Cargo.toml +++ b/registry/Cargo.toml @@ -2,4 +2,19 @@ name = "registry" version.workspace = true edition.workspace = true -author.workspace = true \ No newline at end of file +authors.workspace = true + +[dependencies] +proto.workspace = true +connectrpc.workspace = true +buffa.workspace = true +buffa-types.workspace = true +axum.workspace = true +futures-util.workspace = true +tokio.workspace = true +dotenvy.workspace = true +uuid.workspace = true +tempfile.workspace = true + +[dev-dependencies] +terminal = { path = "../terminal" } diff --git a/registry/README.md b/registry/README.md new file mode 100644 index 0000000..7f9f399 --- /dev/null +++ b/registry/README.md @@ -0,0 +1,120 @@ +# Registry + +The registry implements the `control.Center` service over plaintext HTTP/2 gRPC +using ConnectRPC and Axum. It stores the active terminal directory and checks +each terminal through `grpc.health.v1.Health/Check` on its registered port. + +## Run + +Run from the workspace root: + +```powershell +Copy-Item .env.example .env +cargo run -p registry +``` + +The `.env` file is optional and is read from the current working directory. +Process environment variables override file values. Relative data paths are +also resolved against the current working directory. Invalid configuration +stops startup. The actual `.env` and default data directory are git-ignored. + +| Variable | Default | +| ------------------------------- | ----------------------------- | +| `REGISTRY_HOST` | `0.0.0.0` | +| `REGISTRY_PORT` | `50051` | +| `REGISTRY_DATA_PATH` | `registry/data/terminals.bin` | +| `REGISTRY_HEALTH_INTERVAL_SECS` | `10` | +| `REGISTRY_HEALTH_TIMEOUT_SECS` | `3` | + +Ports must be in `1..=65535`; health durations must be positive integer seconds. +Ctrl+C stops new work, closes subscription streams, cancels active health checks, +and allows up to five seconds for HTTP connections to drain after directory +transactions finish. + +## Directory Contract + +- Registration requires a nonempty host, a reachable port in `1..=65535`, and a + nonempty MAC. Metadata is stored as provided; it is not interpreted here. +- MAC identity is `trim().to_ascii_lowercase()`. Separator characters are not + rewritten. Logical identifiers are accepted as well as physical MAC addresses. +- IDs are UUID v5 values in namespace `9a55cb17-4014-5712-8c2a-64d47c9b613a`, using + the normalized MAC's UTF-8 bytes. Do not change this namespace or normalization: + the same identity retains its ID across restarts and explicit deregistration. +- Identical registration retries return the existing ID without writing or + publishing. Changed information retains the ID, resets health to `UNKNOWN`, + and requests a new check. Deregistering an absent ID succeeds without publishing. +- Business failures use `success=false`. Registration errors are strings; + deregistration errors are `google.protobuf.StringValue` packed into `Any`. +- Subscribers immediately receive the full current directory, including an empty + directory. Later messages are complete replacement snapshots, not deltas. + Slow readers may skip intermediate snapshots and receive the latest state. +- Directory mutations serialize, persist first, then publish. Once accepted, + a mutation completes even if its requesting client disconnects, so a retry + can safely discover the committed outcome. + +## Storage And Recovery + +The data file contains a Protobuf `TerminalInfos` message. Health is always +written and restored as `UNKNOWN`; runtime health changes do not write to disk. +Missing snapshots start an empty directory. Undecodable or semantically invalid +snapshots are renamed to `terminals.bin.corrupt--` and reported +on stderr before starting empty. Ordinary I/O or backup failures stop startup. + +Writes use a synchronized temporary file in the same directory and `tempfile`'s +atomic replacement API, including on Windows. There is no delete/rename gap and +no separate backup recovery state. A process crash leaves either the previous +or committed snapshot. Uncommitted `.registry-snapshot-*` files are ignored and +can be removed while the registry is stopped. This is not a guarantee against +filesystem damage or sudden power loss; keep operational backups separately. + +Only one registry process may own a data path. Shared storage, replication, +configuration hot reload, authentication, and TLS are not implemented. Deploy +on a trusted network or behind an appropriately secured proxy; registration +authorizes outbound health connections to the supplied host and port. + +## Health + +Checks start immediately on startup and after directory changes, then run at the +configured interval with at most 32 concurrent probes. The timeout includes DNS, +TCP/HTTP2 connection setup and the RPC. Requests use an empty service name. +Responses update health; connection errors, RPC errors and timeouts become +`NOT_SERVING`. Offline terminals remain registered until explicitly removed. +Version checks discard results from a previous registration or address update. + +Terminal exposes both Health RPCs on its existing port. Empty service names and +`control.Terminal` report `SERVING` only when the terminal lifecycle is `Ready`. +Unknown names return `NotFound` from Check and a persistent `SERVICE_UNKNOWN` +stream from Watch. Health describes service readiness, not simulation state. + +## Verify + +All test implementations and test-only helpers live under `tests/`: + +- `tests/unit/{config,health,rpc,service,storage}.rs` contains module-level tests. + [tests/unit/mod.rs](tests/unit/mod.rs) declares these modules as `unit_tests`. +- [tests/integration/runtime.rs](tests/integration/runtime.rs) tests real RPC + calls and Terminal interoperability; [tests/integration/mod.rs](tests/integration/mod.rs) + declares it under `integration_tests`. + +Like Terminal, [src/lib.rs](src/lib.rs) loads both test groups through `#[cfg(test)]` +and `#[path]`. Production modules do not declare individual test modules. Tests +use explicit crate imports and narrowly scoped `pub(crate)` functions, without +adding public library APIs or exposing the directory's private state. +The cancellation test uses a current-thread runtime to drop a polled caller +before its spawned transaction is scheduled, without accessing internal locks. + +Both test groups run in the library test target; there is no standalone +`--test integration` target. Each test module is loaded exactly once. + +```powershell +cargo test -p registry +cargo test -p registry --lib unit_tests +cargo test -p registry --lib integration_tests::runtime +cargo test -p registry -p terminal +cargo test --workspace +``` + +Tests cover configuration, identity, persistence failures and corruption, +request cancellation, stale probe results, subscriptions, health recovery and +timeouts, real CenterClient calls, and a real Terminal started through its C ABI +that remains online while the registry restarts. diff --git a/registry/src/config.rs b/registry/src/config.rs new file mode 100644 index 0000000..e38cc85 --- /dev/null +++ b/registry/src/config.rs @@ -0,0 +1,110 @@ +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use crate::RegistryError; + +const KEYS: [&str; 7] = [ + "HOST", + "PORT", + "DATA_PATH", + "HEALTH_INTERVAL_SECS", + "HEALTH_TIMEOUT_SECS", + "DATA_FILE_COUNT", + "LOG_LEVEL", +]; + +#[derive(Clone, Debug)] +pub struct Config { + pub host: String, + pub port: u16, + pub data_path: PathBuf, + pub health_interval: Duration, + pub health_timeout: Duration, + pub data_file_count: u64, + pub log_level: String, +} + +impl Config { + pub fn load() -> Result { + let mut environment = HashMap::new(); + for key in KEYS { + match std::env::var(key) { + Ok(value) => { + environment.insert(key.to_owned(), value); + } + Err(std::env::VarError::NotPresent) => {} + Err(error) => return Err(RegistryError::new("CONFIG_ERROR", error.to_string())), + } + } + Self::from_file(Path::new(".env"), environment) + } + + pub(crate) fn from_file( + path: &Path, + environment: HashMap, + ) -> Result { + let mut values = HashMap::new(); + match dotenvy::from_path_iter(path) { + Ok(entries) => { + for entry in entries { + let (key, value) = entry + .map_err(|error| RegistryError::new("CONFIG_ERROR", error.to_string()))?; + values.insert(key, value); + } + } + Err(dotenvy::Error::Io(error)) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(RegistryError::new("CONFIG_ERROR", error.to_string())), + } + values.extend(environment); + let value = |key: &str, default: &str| { + values + .get(key) + .map(String::as_str) + .unwrap_or(default) + .trim() + .to_owned() + }; + let positive = |key: &str, default: &str| -> Result { + value(key, default) + .parse::() + .ok() + .filter(|number| *number > 0) + .ok_or_else(|| { + RegistryError::new("CONFIG_ERROR", format!("{key} must be a positive integer")) + }) + }; + let port = u16::try_from(positive("PORT", "50051")?) + .map_err(|_| RegistryError::new("CONFIG_ERROR", "PORT exceeds 65535"))?; + let host = value("HOST", "0.0.0.0"); + let data_path = value("DATA_PATH", "registry/data/terminals.bin"); + if host.is_empty() || data_path.is_empty() { + return Err(RegistryError::new( + "CONFIG_ERROR", + "host and data path must not be empty", + )); + } + let health_interval = Duration::from_secs(positive("HEALTH_INTERVAL_SECS", "10")?); + let health_timeout = Duration::from_secs(positive("HEALTH_TIMEOUT_SECS", "3")?); + if std::time::Instant::now() + .checked_add(health_interval.max(health_timeout)) + .is_none() + { + return Err(RegistryError::new( + "CONFIG_ERROR", + "health duration is too large", + )); + } + let data_file_count = positive("DATA_FILE_COUNT", "10")?; + let log_level = value("LOG_LEVEL", "info"); + Ok(Self { + host, + port, + data_path: data_path.into(), + health_interval, + health_timeout, + data_file_count: data_file_count, + log_level, + }) + } +} diff --git a/registry/src/error.rs b/registry/src/error.rs new file mode 100644 index 0000000..74edeab --- /dev/null +++ b/registry/src/error.rs @@ -0,0 +1,52 @@ +use std::fmt; + +use buffa::MessageField; +use buffa_types::google::protobuf::{Any, StringValue}; +use proto::proto::control::InvokeResponse; + +#[derive(Debug)] +pub struct RegistryError { + pub code: &'static str, + pub message: String, +} + +impl RegistryError { + pub(crate) fn new(code: &'static str, message: impl Into) -> Self { + Self { + code, + message: message.into(), + } + } + + pub(crate) fn into_response(self) -> InvokeResponse { + let message = StringValue { + value: self.to_string(), + ..Default::default() + }; + InvokeResponse { + success: false, + message: MessageField::some(Any::pack(&message, StringValue::TYPE_URL)), + ..Default::default() + } + } +} + +impl fmt::Display for RegistryError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(formatter, "{}: {}", self.code, self.message) + } +} + +impl std::error::Error for RegistryError {} + +impl From for RegistryError { + fn from(error: std::io::Error) -> Self { + Self::new("IO_ERROR", error.to_string()) + } +} + +impl From for RegistryError { + fn from(error: tokio::task::JoinError) -> Self { + Self::new("INTERNAL", error.to_string()) + } +} diff --git a/registry/src/health.rs b/registry/src/health.rs new file mode 100644 index 0000000..7ee6533 --- /dev/null +++ b/registry/src/health.rs @@ -0,0 +1,88 @@ +use std::net::Ipv6Addr; +use std::time::Duration; + +use axum::http::Uri; +use buffa::EnumValue; +use connectrpc::Protocol; +use connectrpc::client::{ClientConfig, Http2Connection}; +use futures_util::{StreamExt, stream}; +use proto::proto::control::TerminalInfo; +use proto::proto::grpc::health::v1::{ + HealthCheckRequest, HealthClient, health_check_response::ServingStatus, +}; + +use crate::RegistryService; + +pub(crate) fn endpoint(info: &TerminalInfo) -> Option { + let host = if info.terminal_host.parse::().is_ok() { + format!("[{}]", info.terminal_host) + } else { + info.terminal_host.clone() + }; + Uri::builder() + .scheme("http") + .authority(format!("{host}:{}", info.terminal_port)) + .path_and_query("/") + .build() + .ok() +} + +pub(crate) async fn check(info: &TerminalInfo, timeout: Duration) -> EnumValue { + let Some(uri) = endpoint(info) else { + return ServingStatus::NOT_SERVING.into(); + }; + let result = tokio::time::timeout(timeout, async { + let connection = Http2Connection::connect_plaintext(uri.clone()).await?; + let client = HealthClient::new( + connection.shared(1), + ClientConfig::new(uri) + .with_protocol(Protocol::Grpc) + .with_default_timeout(timeout), + ); + client + .check(HealthCheckRequest::default()) + .await + .map(|response| response.into_owned().status) + }) + .await; + match result { + Ok(Ok(status)) => status, + _ => ServingStatus::NOT_SERVING.into(), + } +} + +pub(crate) async fn monitor(service: RegistryService, interval: Duration, timeout: Duration) { + let mut shutdown = service.shutdown_receiver(); + let mut timer = tokio::time::interval(interval); + timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + loop { + if *shutdown.borrow() { + return; + } + tokio::select! { + biased; + _ = shutdown.wait_for(|stopped| *stopped) => return, + _ = service.probe_requested() => {}, + _ = timer.tick() => {}, + } + let targets = service.probe_targets().await; + let checks = stream::iter(targets) + .map(|target| async move { + let status = check(&target.info, timeout).await; + (target, status) + }) + .buffer_unordered(32); + tokio::pin!(checks); + loop { + let result = tokio::select! { + biased; + _ = shutdown.wait_for(|stopped| *stopped) => return, + result = checks.next() => result, + }; + match result { + Some((target, status)) => service.update_health(&target, status).await, + None => break, + } + } + } +} diff --git a/registry/src/lib.rs b/registry/src/lib.rs new file mode 100644 index 0000000..7bf488a --- /dev/null +++ b/registry/src/lib.rs @@ -0,0 +1,19 @@ +pub mod config; +pub mod error; +mod health; +mod rpc; +pub mod runtime; +pub mod service; +mod storage; + +pub use config::Config; +pub use error::RegistryError; +pub use service::RegistryService; + +#[cfg(test)] +#[path = "../tests/unit/mod.rs"] +mod unit_tests; + +#[cfg(test)] +#[path = "../tests/integration/mod.rs"] +mod integration_tests; diff --git a/registry/src/main.rs b/registry/src/main.rs index 5a8b974..e5f683d 100644 --- a/registry/src/main.rs +++ b/registry/src/main.rs @@ -1,4 +1,27 @@ - -fn main() { - println!("Hello, registry!"); -} \ No newline at end of file +use registry::{Config, RegistryService, runtime}; + +#[tokio::main] +async fn main() -> Result<(), Box> { + let config = Config::load()?; + let service = RegistryService::open(&config.data_path).await?; + let listener = tokio::net::TcpListener::bind((config.host.as_str(), config.port)).await?; + println!( + "registry listening on {}; restored {} terminals from {}", + listener.local_addr()?, + service.subscribe().borrow().infos.len(), + config.data_path.display() + ); + runtime::serve( + listener, + service, + config.health_interval, + config.health_timeout, + async { + if let Err(error) = tokio::signal::ctrl_c().await { + eprintln!("failed to listen for shutdown signal: {error}"); + } + }, + ) + .await?; + Ok(()) +} diff --git a/registry/src/rpc.rs b/registry/src/rpc.rs new file mode 100644 index 0000000..0f7e735 --- /dev/null +++ b/registry/src/rpc.rs @@ -0,0 +1,77 @@ +use buffa_types::google::protobuf::{Empty, StringValue}; +use connectrpc::{ + ConnectError, RequestContext, Response, ServiceRequest, ServiceResult, ServiceStream, +}; +use futures_util::{Stream, stream}; +use proto::proto::control::{ + Center, InvokeResponse, TerminalInfo, TerminalInfos, TerminalRegisterResponse, +}; +use tokio::sync::watch; + +use crate::RegistryService; + +#[allow(refining_impl_trait)] +impl Center for RegistryService { + async fn register_terminal( + &self, + _context: RequestContext, + request: ServiceRequest<'_, TerminalInfo>, + ) -> ServiceResult { + let (success, message) = match self.register(request.to_owned_message()).await { + Ok(id) => (true, id), + Err(error) => (false, error.to_string()), + }; + Response::ok(TerminalRegisterResponse { + success, + message, + ..Default::default() + }) + } + + async fn deregister_terminal( + &self, + _context: RequestContext, + request: ServiceRequest<'_, StringValue>, + ) -> ServiceResult { + Response::ok( + match self.deregister(request.to_owned_message().value).await { + Ok(()) => InvokeResponse { + success: true, + ..Default::default() + }, + Err(error) => error.into_response(), + }, + ) + } + + async fn subscribe_terminal( + &self, + _context: RequestContext, + _request: ServiceRequest<'_, Empty>, + ) -> ServiceResult> { + Response::stream_ok(snapshots(self.subscribe(), self.shutdown_receiver())) + } +} + +pub(crate) fn snapshots( + receiver: watch::Receiver, + shutdown: watch::Receiver, +) -> impl Stream> + Send { + stream::unfold( + (receiver, shutdown, true), + |(mut receiver, mut shutdown, initial)| async move { + if *shutdown.borrow() { + return None; + } + if !initial { + tokio::select! { + biased; + _ = shutdown.wait_for(|stopped| *stopped) => return None, + changed = receiver.changed() => { if changed.is_err() { return None; } } + } + } + let snapshot = receiver.borrow_and_update().clone(); + Some((Ok(snapshot), (receiver, shutdown, false))) + }, + ) +} diff --git a/registry/src/runtime.rs b/registry/src/runtime.rs new file mode 100644 index 0000000..96f1d87 --- /dev/null +++ b/registry/src/runtime.rs @@ -0,0 +1,72 @@ +use std::future::{Future, IntoFuture}; +use std::io; +use std::sync::Arc; +use std::time::Duration; + +use tokio::net::TcpListener; + +use crate::{RegistryService, health}; + +pub async fn serve( + listener: TcpListener, + service: RegistryService, + health_interval: Duration, + health_timeout: Duration, + stop: impl Future + Send, +) -> io::Result<()> { + if health_interval.is_zero() + || health_timeout.is_zero() + || std::time::Instant::now() + .checked_add(health_interval.max(health_timeout)) + .is_none() + { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "health durations must be positive", + )); + } + let rpc = connectrpc::Router::new().add_service(Arc::new(service.clone())); + let app = axum::Router::new().fallback_service(rpc.into_axum_service()); + let mut shutdown = service.shutdown_receiver(); + let server = axum::serve(listener, app) + .with_graceful_shutdown(async move { + let _ = shutdown.wait_for(|stopped| *stopped).await; + }) + .into_future(); + tokio::pin!(server); + let mut monitor = tokio::spawn(health::monitor( + service.clone(), + health_interval, + health_timeout, + )); + let mut monitor_finished = false; + let mut server_finished = false; + let completed = tokio::select! { + result = &mut server => { server_finished = true; result }, + _ = stop => Ok(()), + result = &mut monitor => { + monitor_finished = true; + if result.is_ok() && *service.shutdown_receiver().borrow() { + Ok(()) + } else { + Err(io::Error::other(format!("health monitor stopped unexpectedly: {result:?}"))) + } + } + }; + service.shutdown().await; + let drained = if server_finished { + Ok(()) + } else { + match tokio::time::timeout(Duration::from_secs(5), &mut server).await { + Ok(result) => result, + Err(_) => Err(io::Error::new( + io::ErrorKind::TimedOut, + "registry shutdown timed out", + )), + } + }; + if !monitor_finished { + monitor.await.map_err(io::Error::other)?; + } + completed.and(drained) +} diff --git a/registry/src/service.rs b/registry/src/service.rs new file mode 100644 index 0000000..c0f1361 --- /dev/null +++ b/registry/src/service.rs @@ -0,0 +1,206 @@ +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::Arc; + +use buffa::{EnumValue, MessageField}; +use proto::proto::control::{TerminalInfo, TerminalInfos, TerminalRuntimeInfo}; +use proto::proto::grpc::health::v1::health_check_response::ServingStatus; +use tokio::sync::{Mutex, Notify, watch}; +use uuid::Uuid; + +use crate::{RegistryError, storage}; + +const ID_NAMESPACE: Uuid = Uuid::from_u128(0x9a55cb17401457128c2a64d47c9b613a); + +struct Directory { + snapshot: TerminalInfos, + revisions: HashMap, + next_revision: u64, +} + +struct Inner { + directory: Mutex, + data_path: PathBuf, + snapshots: watch::Sender, + shutdown: watch::Sender, + probe_requested: Notify, +} + +#[derive(Clone)] +pub struct RegistryService { + inner: Arc, +} + +#[derive(Clone)] +pub(crate) struct ProbeTarget { + pub id: String, + pub info: TerminalInfo, + revision: u64, +} + +impl RegistryService { + pub async fn open(data_path: impl Into) -> Result { + let data_path = data_path.into(); + let load_path = data_path.clone(); + let snapshot = tokio::task::spawn_blocking(move || storage::load(&load_path)).await??; + let revisions = snapshot.infos.keys().map(|id| (id.clone(), 0)).collect(); + let (snapshots, _) = watch::channel(snapshot.clone()); + let (shutdown, _) = watch::channel(false); + Ok(Self { + inner: Arc::new(Inner { + directory: Mutex::new(Directory { + snapshot, + revisions, + next_revision: 1, + }), + data_path, + snapshots, + shutdown, + probe_requested: Notify::new(), + }), + }) + } + + pub fn subscribe(&self) -> watch::Receiver { + self.inner.snapshots.subscribe() + } + + pub fn shutdown_receiver(&self) -> watch::Receiver { + self.inner.shutdown.subscribe() + } + + pub async fn shutdown(&self) { + let _directory = self.inner.directory.lock().await; + self.inner.shutdown.send_replace(true); + } + + pub async fn register(&self, info: TerminalInfo) -> Result { + let info = normalize_info(info)?; + let service = self.clone(); + tokio::spawn(async move { service.register_transaction(info).await }).await? + } + + async fn register_transaction(&self, info: TerminalInfo) -> Result { + let mut directory = self.inner.directory.lock().await; + self.ensure_running()?; + let id = terminal_id(&info.terminal_mac); + if directory + .snapshot + .infos + .get(&id) + .and_then(|runtime| runtime.info.as_option()) + == Some(&info) + { + return Ok(id); + } + let mut candidate = directory.snapshot.clone(); + candidate.infos.insert( + id.clone(), + TerminalRuntimeInfo { + info: MessageField::some(info), + status: ServingStatus::UNKNOWN.into(), + ..Default::default() + }, + ); + self.persist(candidate.clone()).await?; + let revision = directory.next_revision; + directory.next_revision += 1; + directory.revisions.insert(id.clone(), revision); + directory.snapshot = candidate.clone(); + self.inner.snapshots.send_replace(candidate); + self.inner.probe_requested.notify_one(); + Ok(id) + } + + pub async fn deregister(&self, id: String) -> Result<(), RegistryError> { + let service = self.clone(); + tokio::spawn(async move { + let mut directory = service.inner.directory.lock().await; + service.ensure_running()?; + let mut candidate = directory.snapshot.clone(); + if candidate.infos.remove(&id).is_none() { + return Ok(()); + } + service.persist(candidate.clone()).await?; + directory.revisions.remove(&id); + directory.snapshot = candidate.clone(); + service.inner.snapshots.send_replace(candidate); + service.inner.probe_requested.notify_one(); + Ok(()) + }) + .await? + } + + async fn persist(&self, snapshot: TerminalInfos) -> Result<(), RegistryError> { + let path = self.inner.data_path.clone(); + tokio::task::spawn_blocking(move || storage::save(&path, snapshot)).await? + } + + fn ensure_running(&self) -> Result<(), RegistryError> { + if *self.inner.shutdown.borrow() { + Err(RegistryError::new( + "UNAVAILABLE", + "registry is shutting down", + )) + } else { + Ok(()) + } + } + + pub(crate) async fn probe_requested(&self) { + self.inner.probe_requested.notified().await; + } + + pub(crate) async fn probe_targets(&self) -> Vec { + let directory = self.inner.directory.lock().await; + directory + .snapshot + .infos + .iter() + .map(|(id, runtime)| ProbeTarget { + id: id.clone(), + info: runtime.info.as_option().unwrap().clone(), + revision: directory.revisions[id], + }) + .collect() + } + + pub(crate) async fn update_health( + &self, + target: &ProbeTarget, + status: EnumValue, + ) { + let mut directory = self.inner.directory.lock().await; + if *self.inner.shutdown.borrow() + || directory.revisions.get(&target.id) != Some(&target.revision) + { + return; + } + if let Some(runtime) = directory.snapshot.infos.get_mut(&target.id) { + if runtime.status != status { + runtime.status = status; + self.inner + .snapshots + .send_replace(directory.snapshot.clone()); + } + } + } +} + +pub(crate) fn terminal_id(mac: &str) -> String { + Uuid::new_v5(&ID_NAMESPACE, mac.as_bytes()).to_string() +} + +pub(crate) fn normalize_info(mut info: TerminalInfo) -> Result { + info.terminal_mac = info.terminal_mac.trim().to_ascii_lowercase(); + if info.terminal_mac.is_empty() + || info.terminal_host.trim().is_empty() + || !(1..=65535).contains(&info.terminal_port) + { + return Err(RegistryError::new( + "INVALID_ARGUMENT", + "host and MAC must be nonempty and port must be 1..=65535", + )); + } + Ok(info) +} diff --git a/registry/src/storage.rs b/registry/src/storage.rs new file mode 100644 index 0000000..bd036ff --- /dev/null +++ b/registry/src/storage.rs @@ -0,0 +1,92 @@ +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use buffa::Message; +use proto::proto::control::TerminalInfos; +use proto::proto::grpc::health::v1::health_check_response::ServingStatus; + +use crate::RegistryError; +use crate::service::{normalize_info, terminal_id}; + +pub(crate) fn load(path: &Path) -> Result { + let bytes = match std::fs::read(path) { + Ok(bytes) => bytes, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + return Ok(TerminalInfos::default()); + } + Err(error) => return Err(error.into()), + }; + match decode(&bytes) { + Ok(snapshot) => Ok(snapshot), + Err(error) => { + let backup = corrupt_path(path); + std::fs::rename(path, &backup)?; + eprintln!( + "invalid registry snapshot ({error}); moved to {}", + backup.display() + ); + Ok(TerminalInfos::default()) + } + } +} + +pub(crate) fn decode(bytes: &[u8]) -> Result { + let mut snapshot = TerminalInfos::decode_from_slice(bytes) + .map_err(|error| RegistryError::new("INVALID_SNAPSHOT", error.to_string()))?; + for (id, runtime) in &mut snapshot.infos { + let info = runtime + .info + .as_option() + .ok_or_else(|| RegistryError::new("INVALID_SNAPSHOT", "terminal info is missing"))?; + let normalized = normalize_info(info.clone())?; + if &normalized != info || *id != terminal_id(&normalized.terminal_mac) { + return Err(RegistryError::new( + "INVALID_SNAPSHOT", + "noncanonical terminal identity", + )); + } + runtime.status = ServingStatus::UNKNOWN.into(); + } + Ok(snapshot) +} + +fn corrupt_path(path: &Path) -> PathBuf { + let timestamp = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_nanos(); + let mut suffix = 0_u64; + loop { + let mut name = path.as_os_str().to_os_string(); + name.push(format!(".corrupt-{timestamp}-{suffix}")); + let candidate = PathBuf::from(name); + if !candidate.exists() { + return candidate; + } + suffix += 1; + } +} + +pub(crate) fn save(path: &Path, mut snapshot: TerminalInfos) -> Result<(), RegistryError> { + for runtime in snapshot.infos.values_mut() { + runtime.status = ServingStatus::UNKNOWN.into(); + } + let bytes = snapshot + .try_encode_to_vec() + .map_err(|error| RegistryError::new("ENCODE_FAILED", error.to_string()))?; + let parent = path + .parent() + .filter(|parent| !parent.as_os_str().is_empty()) + .unwrap_or(Path::new(".")); + std::fs::create_dir_all(parent)?; + let mut temporary = tempfile::Builder::new() + .prefix(".registry-snapshot-") + .tempfile_in(parent)?; + temporary.write_all(&bytes)?; + temporary.as_file().sync_all()?; + temporary + .persist(path) + .map_err(|error| RegistryError::from(error.error))?; + Ok(()) +} diff --git a/registry/tests/integration/mod.rs b/registry/tests/integration/mod.rs new file mode 100644 index 0000000..4a59515 --- /dev/null +++ b/registry/tests/integration/mod.rs @@ -0,0 +1 @@ +mod runtime; diff --git a/registry/tests/integration/runtime.rs b/registry/tests/integration/runtime.rs new file mode 100644 index 0000000..a4a4cca --- /dev/null +++ b/registry/tests/integration/runtime.rs @@ -0,0 +1,281 @@ +use std::ffi::c_void; +use std::time::Duration; + +use buffa::Message; +use buffa_types::google::protobuf::{Empty, StringValue}; +use connectrpc::Protocol; +use connectrpc::client::{ClientConfig, Http2Connection}; +use proto::proto::control::{CenterClient, TerminalInfo}; +use proto::proto::grpc::health::v1::health_check_response::ServingStatus; +use terminal::ffi::*; +use tokio::net::TcpListener; +use tokio::sync::oneshot; + +use crate::{RegistryService, runtime::serve}; + +#[tokio::test] +async fn center_rpc_register_update_subscribe_deregister_and_shutdown() { + tokio::time::timeout(Duration::from_secs(10), async { + let directory = tempfile::tempdir().unwrap(); + let service = RegistryService::open(directory.path().join("terminals.bin")) + .await + .unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let uri: axum::http::Uri = format!("http://{}", listener.local_addr().unwrap()) + .parse() + .unwrap(); + let (stop, stopped) = oneshot::channel(); + let server = tokio::spawn(serve( + listener, + service.clone(), + Duration::from_secs(10), + Duration::from_millis(100), + async { + let _ = stopped.await; + }, + )); + let connection = Http2Connection::connect_plaintext(uri.clone()) + .await + .unwrap(); + let client = CenterClient::new( + connection.shared(32), + ClientConfig::new(uri) + .with_protocol(Protocol::Grpc) + .with_default_timeout(Duration::from_secs(5)), + ); + let mut first = client.subscribe_terminal(Empty::default()).await.unwrap(); + let mut second = client.subscribe_terminal(Empty::default()).await.unwrap(); + assert!( + first + .message() + .await + .unwrap() + .unwrap() + .to_owned_message() + .infos + .is_empty() + ); + assert!( + second + .message() + .await + .unwrap() + .unwrap() + .to_owned_message() + .infos + .is_empty() + ); + let invalid = client + .register_terminal(TerminalInfo::default()) + .await + .unwrap() + .into_owned(); + assert!(!invalid.success); + assert!(invalid.message.starts_with("INVALID_ARGUMENT:")); + let mut info = TerminalInfo { + terminal_host: "127.0.0.1".into(), + terminal_port: 1234, + terminal_mac: " AA:BB ".into(), + ..Default::default() + }; + let response = client + .register_terminal(info.clone()) + .await + .unwrap() + .into_owned(); + assert!(response.success); + let id = response.message; + assert_eq!( + first + .message() + .await + .unwrap() + .unwrap() + .to_owned_message() + .infos[&id] + .info + .terminal_mac, + "aa:bb" + ); + assert!( + second + .message() + .await + .unwrap() + .unwrap() + .to_owned_message() + .infos + .contains_key(&id) + ); + info.terminal_port = 4321; + let updated = client + .register_terminal(info.clone()) + .await + .unwrap() + .into_owned(); + assert!(updated.success); + assert_eq!(updated.message, id); + loop { + let snapshot = first.message().await.unwrap().unwrap().to_owned_message(); + if snapshot.infos[&id].info.terminal_port == 4321 { + break; + } + } + for _attempt in 0..2 { + assert!( + client + .deregister_terminal(StringValue { + value: id.clone(), + ..Default::default() + }) + .await + .unwrap() + .into_owned() + .success + ); + } + loop { + if first + .message() + .await + .unwrap() + .unwrap() + .to_owned_message() + .infos + .is_empty() + { + break; + } + } + stop.send(()).unwrap(); + assert!(first.message().await.unwrap().is_none()); + drop(second); + drop(first); + drop(client); + server.await.unwrap().unwrap(); + }) + .await + .unwrap(); +} + +struct TerminalHandle(*mut c_void); + +impl Drop for TerminalHandle { + fn drop(&mut self) { + unsafe { + terminal_service_destroy(self.0); + } + } +} + +#[test] +fn real_terminal_survives_registry_restart_and_deregisters() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("terminals.bin"); + let runtime = tokio::runtime::Runtime::new().unwrap(); + let service = runtime.block_on(RegistryService::open(&path)).unwrap(); + let listener = runtime.block_on(TcpListener::bind("127.0.0.1:0")).unwrap(); + let address = listener.local_addr().unwrap(); + let (stop, stopped) = oneshot::channel(); + let server = runtime.spawn(serve( + listener, + service.clone(), + Duration::from_millis(20), + Duration::from_secs(1), + async { + let _ = stopped.await; + }, + )); + let handle = TerminalHandle(terminal_service_create()); + let info = TerminalInfo { + terminal_host: "127.0.0.1".into(), + terminal_port: 0, + terminal_mac: "real-terminal".into(), + ..Default::default() + } + .encode_to_vec(); + assert_eq!( + unsafe { terminal_service_configure(handle.0, info.as_ptr(), info.len()) }, + TERMINAL_OK + ); + let host = b"127.0.0.1"; + let mut bound_port = 0; + assert_eq!( + unsafe { + terminal_service_start( + handle.0, + host.as_ptr(), + host.len(), + address.port(), + &mut bound_port, + ) + }, + TERMINAL_OK + ); + assert_ne!(bound_port, 0); + let id = runtime.block_on(async { + let mut receiver = service.subscribe(); + let snapshot = tokio::time::timeout( + Duration::from_secs(3), + receiver.wait_for(|snapshot| { + snapshot + .infos + .values() + .any(|runtime| runtime.status == ServingStatus::SERVING) + }), + ) + .await + .unwrap() + .unwrap(); + snapshot.infos.keys().next().unwrap().clone() + }); + stop.send(()).unwrap(); + runtime.block_on(async { + tokio::time::timeout(Duration::from_secs(6), server) + .await + .unwrap() + .unwrap() + .unwrap(); + }); + let restored = runtime.block_on(RegistryService::open(path)).unwrap(); + assert_eq!( + restored.subscribe().borrow().infos[&id].status, + ServingStatus::UNKNOWN + ); + assert_eq!( + restored.subscribe().borrow().infos[&id].info.terminal_port, + u32::from(bound_port) + ); + let listener = runtime.block_on(TcpListener::bind(address)).unwrap(); + let (stop, stopped) = oneshot::channel(); + let server = runtime.spawn(serve( + listener, + restored.clone(), + Duration::from_millis(20), + Duration::from_secs(1), + async { + let _ = stopped.await; + }, + )); + runtime.block_on(async { + let mut receiver = restored.subscribe(); + tokio::time::timeout( + Duration::from_secs(3), + receiver.wait_for(|snapshot| snapshot.infos[&id].status == ServingStatus::SERVING), + ) + .await + .unwrap() + .unwrap(); + }); + assert_eq!(unsafe { terminal_service_stop(handle.0) }, TERMINAL_OK); + assert!(restored.subscribe().borrow().infos.is_empty()); + drop(handle); + stop.send(()).unwrap(); + runtime.block_on(async { + tokio::time::timeout(Duration::from_secs(6), server) + .await + .unwrap() + .unwrap() + .unwrap(); + }); +} diff --git a/registry/tests/unit/config.rs b/registry/tests/unit/config.rs new file mode 100644 index 0000000..cf75dcd --- /dev/null +++ b/registry/tests/unit/config.rs @@ -0,0 +1,39 @@ +use std::collections::HashMap; +use std::time::Duration; + +use crate::Config; + +#[test] +fn defaults_file_and_environment_precedence() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join(".env"); + let config = Config::from_file(&path, HashMap::new()).unwrap(); + assert_eq!(config.port, 50051); + assert_eq!(config.health_interval, Duration::from_secs(10)); + std::fs::write(&path, "REGISTRY_PORT=1234\nREGISTRY_HOST=localhost\n").unwrap(); + let config = Config::from_file( + &path, + HashMap::from([("REGISTRY_PORT".into(), "4321".into())]), + ) + .unwrap(); + assert_eq!(config.port, 4321); + assert_eq!(config.host, "localhost"); +} + +#[test] +fn invalid_configuration_fails() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join(".env"); + for (key, value) in [ + ("REGISTRY_PORT", "0"), + ("REGISTRY_PORT", "65536"), + ("REGISTRY_HEALTH_INTERVAL_SECS", "0"), + ("REGISTRY_HEALTH_TIMEOUT_SECS", "abc"), + ("REGISTRY_HOST", " "), + ("REGISTRY_DATA_PATH", ""), + ] { + assert!(Config::from_file(&path, HashMap::from([(key.into(), value.into())])).is_err()); + } + std::fs::write(&path, "REGISTRY_PORT='unterminated").unwrap(); + assert!(Config::from_file(&path, HashMap::new()).is_err()); +} diff --git a/registry/tests/unit/health.rs b/registry/tests/unit/health.rs new file mode 100644 index 0000000..53aaaf4 --- /dev/null +++ b/registry/tests/unit/health.rs @@ -0,0 +1,141 @@ +use std::sync::Arc; +use std::time::Duration; + +use connectrpc::{ + ConnectError, RequestContext, Response, ServiceRequest, ServiceResult, ServiceStream, +}; +use futures_util::stream; +use proto::proto::control::TerminalInfo; +use proto::proto::grpc::health::v1::{ + Health, HealthCheckRequest, HealthCheckResponse, health_check_response::ServingStatus, +}; +use tokio::sync::{oneshot, watch}; + +use crate::RegistryService; +use crate::health::{check, endpoint, monitor}; + +struct FakeHealth(watch::Receiver); + +#[allow(refining_impl_trait)] +impl Health for FakeHealth { + async fn check( + &self, + _: RequestContext, + request: ServiceRequest<'_, HealthCheckRequest>, + ) -> ServiceResult { + assert!(request.to_owned_message().service.is_empty()); + Response::ok(HealthCheckResponse { + status: (*self.0.borrow()).into(), + ..Default::default() + }) + } + async fn watch( + &self, + _: RequestContext, + _: ServiceRequest<'_, HealthCheckRequest>, + ) -> ServiceResult> { + Response::stream_ok(stream::empty::>()) + } +} + +async fn wait_status( + receiver: &mut watch::Receiver, + id: &str, + status: ServingStatus, +) { + tokio::time::timeout( + Duration::from_secs(3), + receiver.wait_for(|snapshot| { + snapshot + .infos + .get(id) + .is_some_and(|runtime| runtime.status == status) + }), + ) + .await + .unwrap() + .unwrap(); +} + +#[tokio::test] +async fn health_monitor_tracks_failure_and_recovery_without_removal() { + let directory = tempfile::tempdir().unwrap(); + let service = RegistryService::open(directory.path().join("terminals.bin")) + .await + .unwrap(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let (status, receiver) = watch::channel(ServingStatus::SERVING); + let rpc = connectrpc::Router::new().add_service(Arc::new(FakeHealth(receiver))); + let (stop, stopped) = oneshot::channel(); + let server = tokio::spawn(async move { + axum::serve( + listener, + axum::Router::new().fallback_service(rpc.into_axum_service()), + ) + .with_graceful_shutdown(async { + let _ = stopped.await; + }) + .await + .unwrap(); + }); + let id = service + .register(TerminalInfo { + terminal_host: "127.0.0.1".into(), + terminal_port: address.port().into(), + terminal_mac: "probe".into(), + ..Default::default() + }) + .await + .unwrap(); + let mut snapshots = service.subscribe(); + let worker = tokio::spawn(monitor( + service.clone(), + Duration::from_millis(20), + Duration::from_millis(100), + )); + wait_status(&mut snapshots, &id, ServingStatus::SERVING).await; + status.send_replace(ServingStatus::NOT_SERVING); + wait_status(&mut snapshots, &id, ServingStatus::NOT_SERVING).await; + status.send_replace(ServingStatus::SERVING); + wait_status(&mut snapshots, &id, ServingStatus::SERVING).await; + stop.send(()).unwrap(); + server.await.unwrap(); + wait_status(&mut snapshots, &id, ServingStatus::NOT_SERVING).await; + assert_eq!(snapshots.borrow().infos.len(), 1); + service.shutdown().await; + tokio::time::timeout(Duration::from_secs(1), worker) + .await + .unwrap() + .unwrap(); +} + +#[tokio::test] +async fn timeout_covers_http2_connection_setup() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let info = TerminalInfo { + terminal_host: "127.0.0.1".into(), + terminal_port: listener.local_addr().unwrap().port().into(), + ..Default::default() + }; + let status = tokio::time::timeout( + Duration::from_secs(1), + check(&info, Duration::from_millis(20)), + ) + .await + .unwrap(); + assert_eq!(status, ServingStatus::NOT_SERVING); +} + +#[test] +fn endpoint_supports_ipv6_and_hostnames() { + for host in ["::1", "[::1]", "localhost"] { + let uri = endpoint(&TerminalInfo { + terminal_host: host.into(), + terminal_port: 1234, + ..Default::default() + }) + .unwrap(); + assert_eq!(uri.port_u16(), Some(1234)); + } +} diff --git a/registry/tests/unit/mod.rs b/registry/tests/unit/mod.rs new file mode 100644 index 0000000..b9bfeca --- /dev/null +++ b/registry/tests/unit/mod.rs @@ -0,0 +1,5 @@ +mod config; +mod health; +mod rpc; +mod service; +mod storage; diff --git a/registry/tests/unit/rpc.rs b/registry/tests/unit/rpc.rs new file mode 100644 index 0000000..3839fd1 --- /dev/null +++ b/registry/tests/unit/rpc.rs @@ -0,0 +1,57 @@ +use futures_util::StreamExt; +use proto::proto::control::TerminalInfo; + +use crate::RegistryService; +use crate::rpc::snapshots; + +#[tokio::test] +async fn subscribers_receive_initial_and_changed_snapshots_then_close() { + let directory = tempfile::tempdir().unwrap(); + let service = RegistryService::open(directory.path().join("terminals.bin")) + .await + .unwrap(); + let mut first = Box::pin(snapshots(service.subscribe(), service.shutdown_receiver())); + let mut second = Box::pin(snapshots(service.subscribe(), service.shutdown_receiver())); + assert!(first.next().await.unwrap().unwrap().infos.is_empty()); + assert!(second.next().await.unwrap().unwrap().infos.is_empty()); + let info = TerminalInfo { + terminal_host: "localhost".into(), + terminal_port: 1234, + terminal_mac: "aa".into(), + ..Default::default() + }; + let id = service.register(info.clone()).await.unwrap(); + assert!(first.next().await.unwrap().unwrap().infos.contains_key(&id)); + assert!( + second + .next() + .await + .unwrap() + .unwrap() + .infos + .contains_key(&id) + ); + service.register(info).await.unwrap(); + assert!( + tokio::time::timeout(std::time::Duration::from_millis(20), first.next()) + .await + .is_err() + ); + service.deregister(id).await.unwrap(); + assert!(first.next().await.unwrap().unwrap().infos.is_empty()); + assert!(second.next().await.unwrap().unwrap().infos.is_empty()); + service.shutdown().await; + assert!(first.next().await.is_none()); + assert!(second.next().await.is_none()); + assert!( + service + .register(TerminalInfo { + terminal_host: "localhost".into(), + terminal_port: 1234, + terminal_mac: "aa".into(), + ..Default::default() + }) + .await + .is_err() + ); +} diff --git a/registry/tests/unit/service.rs b/registry/tests/unit/service.rs new file mode 100644 index 0000000..ef0585d --- /dev/null +++ b/registry/tests/unit/service.rs @@ -0,0 +1,177 @@ +use proto::proto::control::TerminalInfo; +use proto::proto::grpc::health::v1::health_check_response::ServingStatus; + +use crate::RegistryService; +use crate::service::normalize_info; + +fn info() -> TerminalInfo { + TerminalInfo { + terminal_host: "127.0.0.1".into(), + terminal_port: 1234, + terminal_mac: " AA:BB ".into(), + ..Default::default() + } +} + +#[tokio::test] +async fn identity_idempotency_restart_and_deregistration() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("terminals.bin"); + let service = RegistryService::open(&path).await.unwrap(); + let mut receiver = service.subscribe(); + let id = service.register(info()).await.unwrap(); + receiver.borrow_and_update(); + let mut normalized = info(); + normalized.terminal_mac = "aa:bb".into(); + assert_eq!(service.register(normalized).await.unwrap(), id); + assert!(!receiver.has_changed().unwrap()); + let target = service.probe_targets().await.pop().unwrap(); + service + .update_health(&target, ServingStatus::SERVING.into()) + .await; + let mut healthy = service.subscribe(); + let persisted = std::fs::read(&path).unwrap(); + service + .update_health(&target, ServingStatus::SERVING.into()) + .await; + assert!(!healthy.has_changed().unwrap()); + assert_eq!(std::fs::read(&path).unwrap(), persisted); + healthy.borrow_and_update(); + let restored = RegistryService::open(&path).await.unwrap(); + assert_eq!( + restored.subscribe().borrow().infos[&id].status, + ServingStatus::UNKNOWN + ); + assert_eq!(restored.register(info()).await.unwrap(), id); + restored.deregister(id.clone()).await.unwrap(); + let receiver = restored.subscribe(); + restored.deregister(id.clone()).await.unwrap(); + assert!(!receiver.has_changed().unwrap()); + assert_eq!(restored.register(info()).await.unwrap(), id); + assert_eq!( + RegistryService::open(path) + .await + .unwrap() + .register(info()) + .await + .unwrap(), + id + ); +} + +#[tokio::test] +async fn concurrent_registration_and_stale_probe_results() { + let directory = tempfile::tempdir().unwrap(); + let service = RegistryService::open(directory.path().join("terminals.bin")) + .await + .unwrap(); + let (first, second) = tokio::join!(service.register(info()), service.register(info())); + let id = first.unwrap(); + assert_eq!(id, second.unwrap()); + assert_eq!(service.subscribe().borrow().infos.len(), 1); + let old = service.probe_targets().await.pop().unwrap(); + let mut updated = info(); + updated.terminal_port += 1; + assert_eq!(service.register(updated).await.unwrap(), id); + service + .update_health(&old, ServingStatus::SERVING.into()) + .await; + assert_eq!( + service.subscribe().borrow().infos[&id].status, + ServingStatus::UNKNOWN + ); + service.deregister(id.clone()).await.unwrap(); + service.register(info()).await.unwrap(); + service + .update_health(&old, ServingStatus::SERVING.into()) + .await; + assert_eq!( + service.subscribe().borrow().infos[&id].status, + ServingStatus::UNKNOWN + ); +} + +#[tokio::test] +async fn failed_persistence_does_not_commit_memory() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("terminals.bin"); + let service = RegistryService::open(&path).await.unwrap(); + let receiver = service.subscribe(); + std::fs::create_dir(&path).unwrap(); + assert!(service.register(info()).await.is_err()); + assert!(receiver.borrow().infos.is_empty()); + assert!(!receiver.has_changed().unwrap()); + std::fs::remove_dir(&path).unwrap(); + let id = service.register(info()).await.unwrap(); + std::fs::remove_file(&path).unwrap(); + std::fs::create_dir(&path).unwrap(); + let mut updated = info(); + updated.terminal_port = 4321; + assert!(service.register(updated).await.is_err()); + assert_eq!(receiver.borrow().infos[&id].info.terminal_port, 1234); + assert!(service.deregister(id.clone()).await.is_err()); + assert!(receiver.borrow().infos.contains_key(&id)); +} + +#[tokio::test(flavor = "current_thread")] +async fn cancelled_caller_does_not_interrupt_an_accepted_transaction() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("terminals.bin"); + let service = RegistryService::open(&path).await.unwrap(); + let mut receiver = service.subscribe(); + let mut registration = Box::pin(service.register(info())); + assert!(futures_util::poll!(registration.as_mut()).is_pending()); + drop(registration); + tokio::time::timeout(std::time::Duration::from_secs(2), receiver.changed()) + .await + .unwrap() + .unwrap(); + let committed = receiver.borrow().clone(); + let restored = RegistryService::open(&path).await.unwrap(); + assert_eq!(committed, *restored.subscribe().borrow()); + let id = committed.infos.keys().next().unwrap().clone(); + let mut deregistration = Box::pin(service.deregister(id)); + assert!(futures_util::poll!(deregistration.as_mut()).is_pending()); + drop(deregistration); + tokio::time::timeout(std::time::Duration::from_secs(2), receiver.changed()) + .await + .unwrap() + .unwrap(); + assert!(receiver.borrow().infos.is_empty()); + assert!( + RegistryService::open(path) + .await + .unwrap() + .subscribe() + .borrow() + .infos + .is_empty() + ); +} + +#[test] +fn invalid_registration_is_rejected() { + for port in [0, 65536] { + assert!( + normalize_info(TerminalInfo { + terminal_port: port, + ..info() + }) + .is_err() + ); + } + assert!( + normalize_info(TerminalInfo { + terminal_mac: " ".into(), + ..info() + }) + .is_err() + ); + assert!( + normalize_info(TerminalInfo { + terminal_host: " ".into(), + ..info() + }) + .is_err() + ); +} diff --git a/registry/tests/unit/storage.rs b/registry/tests/unit/storage.rs new file mode 100644 index 0000000..e75bfaf --- /dev/null +++ b/registry/tests/unit/storage.rs @@ -0,0 +1,45 @@ +use buffa::Message; +use proto::proto::control::TerminalInfos; + +use crate::storage::{decode, load, save}; + +#[test] +fn corrupt_snapshot_is_preserved_and_uncommitted_temporary_is_ignored() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("terminals.bin"); + std::fs::write(&path, [0xff]).unwrap(); + assert!(load(&path).unwrap().infos.is_empty()); + let backup = std::fs::read_dir(directory.path()) + .unwrap() + .next() + .unwrap() + .unwrap() + .path(); + assert!( + backup + .file_name() + .unwrap() + .to_string_lossy() + .contains(".corrupt-") + ); + assert_eq!(std::fs::read(backup).unwrap(), [0xff]); + std::fs::write( + directory.path().join(".registry-snapshot-interrupted"), + [0xff], + ) + .unwrap(); + save(&path, TerminalInfos::default()).unwrap(); + assert!(load(&path).unwrap().infos.is_empty()); + assert_eq!(std::fs::read(path).unwrap(), Vec::::new()); +} + +#[test] +fn semantic_corruption_is_rejected() { + let snapshot = TerminalInfos { + infos: [("wrong-id".into(), Default::default())] + .into_iter() + .collect(), + ..Default::default() + }; + assert!(decode(&snapshot.try_encode_to_vec().unwrap()).is_err()); +} diff --git a/terminal/Cargo.toml b/terminal/Cargo.toml index 7a99b3f..b2a34fc 100644 --- a/terminal/Cargo.toml +++ b/terminal/Cargo.toml @@ -2,4 +2,19 @@ name = "terminal" version.workspace = true edition.workspace = true -author.workspace = true \ No newline at end of file +authors.workspace = true + +[lib] +crate-type = ["lib", "cdylib"] + +[dependencies] +proto.workspace = true +connectrpc.workspace = true +buffa.workspace = true +buffa-types.workspace = true +axum.workspace = true +futures-util.workspace = true +tokio.workspace = true + +[build-dependencies] +cbindgen.workspace = true diff --git a/terminal/README.md b/terminal/README.md new file mode 100644 index 0000000..454e815 --- /dev/null +++ b/terminal/README.md @@ -0,0 +1,297 @@ +# Terminal + +An embeddable simulation terminal library. A host application supplies simulation +logic through C callbacks; Rust owns the RPC server, center registration, +lifecycle, event scheduling, and subscription snapshots. + +This crate builds a Rust library and a `cdylib`, not a standalone executable. +There is no `cargo run -p terminal` entry point or automatic `.env` loading. +Configuration and lifecycle are controlled by the host through [terminal.h](terminal.h). + +## Build + +Run from the workspace root with a Rust toolchain supporting edition 2024 and +the native linker for your target platform: + +```powershell +cargo build -p terminal +cargo build -p terminal --release +``` + +[build.rs](build.rs) uses cbindgen and [cbindgen.toml](cbindgen.toml) to regenerate +[terminal.h](terminal.h). Do not edit the generated header manually. The shared +`proto` crate generates the Rust RPC/message types during the build. + +Default shared-library outputs are `target/debug/terminal.dll` on Windows, +`target/debug/libterminal.so` on Linux, and `target/debug/libterminal.dylib` on +macOS. Release builds use `target/release`. The host must provide a compatible +Protobuf implementation for the messages in [the control protocols](../proto/control). +The C header declares functions and callbacks, not C Protobuf message structs. + +## Host Integration + +1. Call `terminal_service_create` to obtain an opaque handle. +2. Serialize `control.TerminalInfo` and call `terminal_service_configure`. +3. Register command callbacks and event definitions/callbacks. Keep callback code + and user data alive for every possible invocation. +4. Call `terminal_service_start` with the center host, center port, and a writable + `uint16_t` output for the actual terminal port. A successful return means both + the listener and center registration are ready. +5. Push simulation snapshots with `terminal_service_push_status`; report event + completion with `terminal_service_complete_event` when host work finishes. +6. Call `terminal_service_stop`, inspect any error, then destroy the stopped + handle with `terminal_service_destroy`. + +All functions are synchronous at the ABI boundary. In particular, start and stop +perform blocking network work. Invoke them from a normal host/control thread, +not from a Tokio async task or a terminal callback: they create, block on, and +drop an owned Tokio runtime. Serialize lifecycle operations and do not destroy +a handle while another thread may still use it. + +### Configuration + +| Field or argument | Behavior | +| ---------------------------- | ------------------------------------------------------------------------ | +| `TerminalInfo.terminal_host` | Nonempty host used for both binding and center registration. | +| `TerminalInfo.terminal_port` | `0..=65535`; zero lets the OS choose a port. | +| `TerminalInfo.terminal_mac` | Nonempty identity sent to the center for idempotent registration. | +| `TerminalInfo.meta_info` | Host-provided capability description; keep it consistent with callbacks. | +| `center_host`, `center_port` | Supplied separately to start; host must be nonempty and port nonzero. | + +Use an address that the center and control clients can reach. There is no separate +bind/advertised address, NAT discovery, or automatic conversion of wildcard hosts. +The center URI is built as `http://:`; bracket an IPv6 +literal in `center_host`, for example `[::1]`. + +When the requested terminal port is zero, the actual bound port is written into +the stored `TerminalInfo` before registration and returned to the host. This also +means a later restart reuses that stored port; configure port zero again while +stopped to request another OS-assigned port. + +Command callback registration does not populate `meta_info.supported_type` or +its command descriptions automatically. The host must supply matching metadata. + +## Runtime Lifecycle + +[RunningServer](src/runtime.rs) owns one multithreaded Tokio runtime, the Axum +server task, the center address, and the bound port per running terminal. +[Service](src/terminal.rs) is cloneable shared state backed by `Arc`, mutexes and +Tokio watch channels; it outlives an individual start/stop cycle. + +```mermaid +sequenceDiagram + participant Host + participant Runtime as RunningServer + participant Service + participant Center + Host->>Service: configure TerminalInfo and callbacks + Host->>Runtime: start(center, bound_port) + Runtime->>Service: new shutdown channel; Starting + Runtime->>Runtime: bind TCP listener; record actual port + Runtime->>Runtime: serve Terminal and Health on one port + Runtime->>Center: RegisterTerminal(actual TerminalInfo) + Center-->>Runtime: success + terminal_id + Runtime->>Service: Ready; publish metadata and SERVING + Runtime-->>Host: success + bound_port + Host->>Runtime: stop() + Runtime->>Service: Stopping; NOT_SERVING + Runtime->>Center: DeregisterTerminal(terminal_id) + Runtime->>Service: signal shutdown + Runtime->>Runtime: wait for server; abort task on timeout + Runtime->>Service: Stopped; clear ID and active events + Runtime-->>Host: deregistration result +``` + +### Startup And Registration + +The normal lifecycle is `Created -> Configured -> Starting -> Ready -> Stopping +-> Stopped`. Start accepts `Configured` or `Stopped`; configure rejects changes +while starting, ready, or stopping. + +The server starts listening before registration so it can already answer Health +requests. Until registration succeeds, command/event execution is not ready and +Health reports `NOT_SERVING`. Registration succeeds only when the center returns +`success=true` with a nonempty ID. The ID is then exposed in `TerminalMetaStatus`. +Bind or registration failure returns an error and restores `Configured`; after a +registration failure the server is signaled to close. + +Center communication uses ConnectRPC's gRPC protocol over plaintext HTTP/2. +Registration and deregistration each make at most three attempts, with 250 ms +and 500 ms waits before retries. Each RPC has a three-second timeout. Connection +setup occurs outside that timeout, so these values do not bound the total time +spent in start or stop. A new center connection is created for each attempt. + +There is no background re-registration or center heartbeat after startup. +The [Registry](../registry/README.md) persists registrations and probes Terminal's +Health service; a different center that loses its directory needs an external +recovery policy or a host-managed terminal restart. + +### Shutdown And Restart + +Stop first switches to `Stopping`, then attempts deregistration. Even when that +RPC fails, stop signals local shutdown, waits up to five seconds for the Axum +server task, aborts that task if necessary, and sets `Stopped`. The deregistration +error is still returned to the host; a failure does not mean the listener was +left intentionally running. + +Subscriptions observe shutdown and close. Event waits observe cancellation or +shutdown. Already-running `spawn_blocking` callbacks cannot be forcibly stopped; +dropping the Tokio runtime can wait for them. Consequently the five-second +server-task timeout is not a hard bound on total stop latency. Callbacks must +return promptly and cooperate with the host's own cancellation policy. + +Destroy rejects a handle that still owns a running server; it does not implicitly +stop the terminal. Stop clears the registered ID and active-event table, but +retains configuration, callback registrations, event definitions and the latest +status snapshot. Reconfiguration resets the simulation state; a new handle gives +a fully fresh service. Lifecycle errors and ordinary RPC failures are distinct. + +## RPC And Host Work + +Terminal and standard Health RPCs share a single ConnectRPC router and Axum +listener. [rpc.rs](src/rpc.rs) adapts generated RPC traits to the domain service; +[callback.rs](src/callback.rs) bridges messages to the host ABI. + +### Commands + +`Execute` requires a ready service, a registered callback and a valid simulation +state transition. The callback runs via `spawn_blocking`, under a per-terminal +mutex shared by command and event callbacks. This serializes callback invocation, +but it does not impose FIFO ordering or provide a transaction over concurrent +RPC validation, callbacks and state updates. Control clients should sequence +lifecycle-sensitive commands. + +Only a successful callback response applies a built-in simulation transition: + +| Command | Accepted simulation states | Result on success | +| ------------------------ | ------------------------------------- | ------------------------------------------------------------- | +| `init` | Any | `Initialized`; reset event instance counter and active table. | +| `reset` | Any except `Uninitialized` | `Initialized`. | +| `start` | `Initialized`, `Stopped` | `Running`. | +| `stop` | `Initialized`, `Running`, `Suspended` | `Stopped`. | +| `suspend` | `Running` | `Suspended`. | +| `resume` | `Suspended` | `Running`. | +| Other registered command | Any | No built-in simulation-state change. | + +Simulation state is separate from service readiness: the `stop` command does not +shut down networking or deregister the terminal. The protocol expects the six +basic commands above; the library does not create their callbacks or validate +the entire advertised command set at startup. Parameter validation and command +timestamp ordering are the host/controller's responsibility. + +### Events + +`PublishEvent` requires a ready service, an initialized simulation and a registered +event definition. It returns an `InvokeResponse` whose `Any` contains a +`TerminalEventHandle { event_id, instance_id }`. This acknowledges scheduling, +not successful completion of the simulation work. + +After `trigger_delay_ms`, the host event callback receives the event and instance +ID. Its successful response only accepts that trigger. The host must also report +completion through `terminal_service_complete_event`, passing the encoded handle +and an encoded `InvokeResponse`. This applies to both one-shot and repeated events. +No completion timeout is imposed by the library. + +A successful completion ends a one-shot event. For a repeated event, the next +trigger waits `repeat_period_ms` after completion; this is not a fixed wall-clock +schedule. Callback failure, completion failure, cancellation, unregistration or +shutdown ends the instance. `CancelEvent` matches both ID fields and fails for a +missing instance. Successful publish/cancel responses carry the handle in `Any`. + +Cancellation does not forcibly interrupt a callback already executing. Keep its +user data valid until in-flight work has returned, even after unregistering an +event. Instance IDs are local to the service and reset by successful `init`; do +not reuse handles across reinitialization. The protocol's reserved `emergency` +event-type rule is a host-side contract, not currently enforced at registration. + +### Callback ABI And Errors + +- Requests and responses crossing the ABI are serialized Protobuf bytes, not JSON + or Rust-owned structs. String arguments are UTF-8 pointer/length pairs. +- Request pointers and the response sink/context are valid only during that + callback. Do not retain them or submit a response asynchronously through the sink. +- Submit exactly one encoded `InvokeResponse` to the sink before returning. The + sink copies the bytes immediately. Return zero from the callback for bridge + success; use `InvokeResponse.success` for the business result. +- Missing, duplicate or undecodable sink responses, and nonzero callback return + codes, become business failures. C++ exceptions must not cross the ABI. +- Callbacks execute on blocking worker threads, not the host UI thread. The host + must safely synchronize callback state with its other threads and avoid blocking + a callback while waiting for another callback from the same terminal. + +Ordinary Terminal RPC business failures use `InvokeResponse.success=false`, with +an error string of the form `CODE: message` packed as `google.protobuf.StringValue` +inside `Any`. Transport failures and unknown Health service names use RPC errors. + +- `TERMINAL_OK` (`0`): success. +- `TERMINAL_ERROR_NULL` (`-1`): null handle, or null length pointer for last-error retrieval. +- `TERMINAL_ERROR_INVALID_ARGUMENT` (`-2`): invalid argument, including null input bytes or bound-port output. +- `TERMINAL_ERROR_INVALID_STATE` (`-3`): operation invalid for the lifecycle state. +- `TERMINAL_ERROR_DECODE` (`-4`): input Protobuf cannot be decoded. +- `TERMINAL_ERROR_INTERNAL` (`-5`): other failures, including start/registration failures. +- `TERMINAL_ERROR_BUFFER_TOO_SMALL` (`-6`): error-text buffer is too small. + +For error details, call `terminal_service_last_error` with a null buffer to obtain +the required length, allocate that many bytes, then call again. The length includes +the trailing NUL. Error text is handle-wide, not thread-local, and successful +operations generally clear it. Catching Rust panics does not make invalid or freed +host pointers safe; all pointer/lifetime preconditions in the header still apply. + +## Subscriptions And Health + +`SubscribeStatus` immediately returns the latest `TerminalStatus`, then follows +host pushes. Rust assigns `sequence` and Unix-millisecond `timestamp`, overriding +the host's values; it preserves `current_param`. Pushes require `Ready`. +The protocol specifies a maximum 100 Hz, but the current implementation has no +rate limiter: the host must enforce that limit. + +`SubscribeMetaStatus` immediately returns the current terminal ID, registered event +definitions and active instance map, then sends changed snapshots. These fields +are derived by Rust rather than pushed independently by the host. Watch channels +retain only the latest value: slow subscribers may skip intermediate states. +Neither subscription is a durable event log. + +For Health, empty service names and `control.Terminal` are known. `Check` reports +`SERVING` only in lifecycle `Ready`; all other lifecycle states are `NOT_SERVING`. +`Watch` sends an initial value and later changes. An unknown name returns +`NotFound` from Check and a persistent `SERVICE_UNKNOWN` stream from Watch. +Streams terminate at shutdown. Health describes readiness, not simulation state, +and does not actively test the host callback or simulation engine. + +TLS, authentication, terminal-side persistence, automatic callback cancellation, +automatic re-registration and process signal handling are not implemented here. +The host owns process lifetime and should deploy on a trusted network or use an +appropriately secured transport boundary. + +## Source And Tests + +| File | Responsibility | +| ---------------------------------- | ---------------------------------------------------------------------- | +| [src/ffi.rs](src/ffi.rs) | Opaque handle, C ABI, byte decoding and last-error storage. | +| [src/runtime.rs](src/runtime.rs) | Tokio runtime, TCP binding, RPC hosting, center registration and stop. | +| [src/terminal.rs](src/terminal.rs) | Lifecycle, simulation state, callbacks, event instances and snapshots. | +| [src/rpc.rs](src/rpc.rs) | Terminal RPC adapters and shutdown-aware watch streams. | +| [src/health.rs](src/health.rs) | Standard Health Check/Watch adapters. | +| [src/callback.rs](src/callback.rs) | Host callback invocation and response sink validation. | +| [src/error.rs](src/error.rs) | Business error and event-handle response encoding. | + +All test implementations and helpers are under `tests/`. Existing unit and runtime +integration modules are included by [src/lib.rs](src/lib.rs) through `#[cfg(test)]` +and `#[path]`. [tests/unit/mod.rs](tests/unit/mod.rs) declares the FFI, terminal and +Health unit tests. [tests/unit/health.rs](tests/unit/health.rs) uses explicit crate +imports and the crate-visible `TerminalHealth::responses` method; it is not loaded +separately by the production Health module. No public library API is added. + +```powershell +cargo test -p terminal +cargo test -p terminal --lib unit_tests::health +cargo test -p terminal --lib integration_tests::runtime +cargo test -p registry --lib integration_tests::runtime +``` + +Terminal's runtime integration test runs inside the library test target, not a +standalone `--test integration` target. It verifies the actual registered port, +center-assigned ID, same-port Terminal/Health RPCs and deregistration. Registry's +integration tests additionally run a real Terminal through the C ABI while the +registry restarts. Unit tests cover FFI errors, state/metadata updates, explicit +event completion, Health transitions and stream shutdown. diff --git a/terminal/build.rs b/terminal/build.rs new file mode 100644 index 0000000..b88dc51 --- /dev/null +++ b/terminal/build.rs @@ -0,0 +1,17 @@ +fn main() { + let crate_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap(); + let output_file = std::path::PathBuf::from(&crate_dir).join("terminal.h"); + let config_file = std::path::PathBuf::from(&crate_dir).join("cbindgen.toml"); + + println!("cargo:rerun-if-changed=cbindgen.toml"); + println!("cargo:rerun-if-changed=src"); + + let config = cbindgen::Config::from_file(config_file).expect("Unable to read cbindgen config"); + + cbindgen::Builder::new() + .with_crate(crate_dir) + .with_config(config) + .generate() + .expect("Unable to generate bindings") + .write_to_file(output_file); +} diff --git a/terminal/cbindgen.toml b/terminal/cbindgen.toml new file mode 100644 index 0000000..c885a14 --- /dev/null +++ b/terminal/cbindgen.toml @@ -0,0 +1,8 @@ +language = "C" +include_guard = "FLYSIM_TERMINAL_H" +pragma_once = true +usize_is_size_t = true +documentation = true + +[parse] +parse_deps = false diff --git a/terminal/src/callback.rs b/terminal/src/callback.rs new file mode 100644 index 0000000..c05f6e5 --- /dev/null +++ b/terminal/src/callback.rs @@ -0,0 +1,184 @@ +use std::ffi::c_void; + +use buffa::Message; +use proto::proto::control::{Command, InvokeResponse, TerminalEvent}; + +use crate::error::TerminalError; + +pub type TerminalResponseSink = + unsafe extern "C" fn(context: *mut c_void, response: *const u8, response_len: usize) -> i32; + +pub type TerminalCommandCallback = Option< + unsafe extern "C" fn( + user_data: *mut c_void, + command: *const u8, + command_len: usize, + sink: TerminalResponseSink, + sink_context: *mut c_void, + ) -> i32, +>; + +pub type TerminalEventCallback = Option< + unsafe extern "C" fn( + user_data: *mut c_void, + event: *const u8, + event_len: usize, + instance_id: u64, + sink: TerminalResponseSink, + sink_context: *mut c_void, + ) -> i32, +>; + +#[derive(Clone, Copy)] +pub(crate) struct CommandCallback { + callback: TerminalCommandCallback, + user_data: usize, +} + +#[derive(Clone, Copy)] +pub(crate) struct EventCallback { + callback: TerminalEventCallback, + user_data: usize, +} + +impl CommandCallback { + pub(crate) fn new( + callback: TerminalCommandCallback, + user_data: *mut c_void, + ) -> Result { + if callback.is_none() { + return Err(TerminalError::new( + "INVALID_ARGUMENT", + "command callback must not be null", + )); + } + Ok(Self { + callback, + user_data: user_data as usize, + }) + } + + pub(crate) fn invoke(self, command: &Command) -> Result { + let request = command.try_encode_to_vec().map_err(|error| { + TerminalError::new( + "ENCODE_FAILED", + format!("failed to encode command: {error}"), + ) + })?; + let callback = self.callback.expect("callback validated at registration"); + invoke_with_sink(|sink, sink_context| unsafe { + callback( + self.user_data as *mut c_void, + request.as_ptr(), + request.len(), + sink, + sink_context, + ) + }) + } +} + +impl EventCallback { + pub(crate) fn new( + callback: TerminalEventCallback, + user_data: *mut c_void, + ) -> Result { + if callback.is_none() { + return Err(TerminalError::new( + "INVALID_ARGUMENT", + "event callback must not be null", + )); + } + Ok(Self { + callback, + user_data: user_data as usize, + }) + } + + pub(crate) fn invoke( + self, + event: &TerminalEvent, + instance_id: u64, + ) -> Result { + let request = event.try_encode_to_vec().map_err(|error| { + TerminalError::new("ENCODE_FAILED", format!("failed to encode event: {error}")) + })?; + let callback = self.callback.expect("callback validated at registration"); + invoke_with_sink(|sink, sink_context| unsafe { + callback( + self.user_data as *mut c_void, + request.as_ptr(), + request.len(), + instance_id, + sink, + sink_context, + ) + }) + } +} + +struct SinkState { + response: Option>, + duplicate: bool, +} + +unsafe extern "C" fn response_sink( + context: *mut c_void, + response: *const u8, + response_len: usize, +) -> i32 { + if context.is_null() || (response.is_null() && response_len != 0) { + return -1; + } + + let state = unsafe { &mut *(context as *mut SinkState) }; + if state.response.is_some() { + state.duplicate = true; + return -2; + } + + let bytes = if response_len == 0 { + Vec::new() + } else { + unsafe { std::slice::from_raw_parts(response, response_len) }.to_vec() + }; + state.response = Some(bytes); + 0 +} + +fn invoke_with_sink( + invoke: impl FnOnce(TerminalResponseSink, *mut c_void) -> i32, +) -> Result { + let mut state = SinkState { + response: None, + duplicate: false, + }; + let status = invoke( + response_sink, + (&mut state as *mut SinkState).cast::(), + ); + if status != 0 { + return Err(TerminalError::new( + "CALLBACK_FAILED", + format!("host callback returned status {status}"), + )); + } + if state.duplicate { + return Err(TerminalError::new( + "INVALID_CALLBACK_RESPONSE", + "host callback submitted more than one response", + )); + } + let response = state.response.ok_or_else(|| { + TerminalError::new( + "INVALID_CALLBACK_RESPONSE", + "host callback did not submit a response", + ) + })?; + InvokeResponse::decode_from_slice(&response).map_err(|error| { + TerminalError::new( + "INVALID_CALLBACK_RESPONSE", + format!("failed to decode callback response: {error}"), + ) + }) +} diff --git a/terminal/src/error.rs b/terminal/src/error.rs new file mode 100644 index 0000000..75d820a --- /dev/null +++ b/terminal/src/error.rs @@ -0,0 +1,43 @@ +use buffa::MessageField; +use buffa_types::google::protobuf::{Any, StringValue}; +use proto::proto::control::{InvokeResponse, TerminalEventHandle}; + +#[derive(Debug, Clone)] +pub(crate) struct TerminalError { + pub(crate) code: &'static str, + pub(crate) message: String, +} + +impl TerminalError { + pub(crate) fn new(code: &'static str, message: impl Into) -> Self { + Self { + code, + message: message.into(), + } + } + + pub(crate) fn into_response(self) -> InvokeResponse { + let error = StringValue { + value: format!("{}: {}", self.code, self.message), + ..Default::default() + }; + + InvokeResponse { + success: false, + message: MessageField::some(Any::pack(&error, StringValue::TYPE_URL)), + ..Default::default() + } + } + + pub(crate) fn display_message(&self) -> String { + format!("{}: {}", self.code, self.message) + } +} + +pub(crate) fn success_handle(handle: &TerminalEventHandle) -> InvokeResponse { + InvokeResponse { + success: true, + message: MessageField::some(Any::pack(handle, TerminalEventHandle::TYPE_URL)), + ..Default::default() + } +} diff --git a/terminal/src/ffi.rs b/terminal/src/ffi.rs new file mode 100644 index 0000000..ee1fa23 --- /dev/null +++ b/terminal/src/ffi.rs @@ -0,0 +1,361 @@ +use std::ffi::c_void; +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::ptr; +use std::sync::Mutex; + +use buffa::Message; +use proto::proto::control::{ + InvokeResponse, TerminalEventHandle, TerminalEventInfo, TerminalInfo, TerminalStatus, +}; + +use crate::callback::{CommandCallback, EventCallback}; +use crate::error::TerminalError; +use crate::runtime::RunningServer; +use crate::terminal::Service; +use crate::{TerminalCommandCallback, TerminalEventCallback}; + +pub const TERMINAL_OK: i32 = 0; +pub const TERMINAL_ERROR_NULL: i32 = -1; +pub const TERMINAL_ERROR_INVALID_ARGUMENT: i32 = -2; +pub const TERMINAL_ERROR_INVALID_STATE: i32 = -3; +pub const TERMINAL_ERROR_DECODE: i32 = -4; +pub const TERMINAL_ERROR_INTERNAL: i32 = -5; +pub const TERMINAL_ERROR_BUFFER_TOO_SMALL: i32 = -6; + +struct ServiceHandle { + service: Service, + running: Mutex>, + last_error: Mutex, +} + +impl ServiceHandle { + fn new() -> Self { + Self { + service: Service::new_value(), + running: Mutex::new(None), + last_error: Mutex::new(String::new()), + } + } + + fn set_error(&self, error: &TerminalError) { + if let Ok(mut message) = self.last_error.lock() { + *message = error.display_message(); + } + } + + fn clear_error(&self) { + if let Ok(mut message) = self.last_error.lock() { + message.clear(); + } + } +} + +#[unsafe(no_mangle)] +pub extern "C" fn terminal_service_create() -> *mut c_void { + Box::into_raw(Box::new(ServiceHandle::new())).cast::() +} + +/// # Safety +/// `handle` must be a live pointer returned by `terminal_service_create` and must not be used +/// after this function succeeds. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn terminal_service_destroy(handle: *mut c_void) -> i32 { + if handle.is_null() { + return TERMINAL_ERROR_NULL; + } + catch_unwind(AssertUnwindSafe(|| { + let handle_ref = unsafe { &*handle.cast::() }; + let running = match handle_ref.running.lock() { + Ok(running) => running, + Err(_) => return TERMINAL_ERROR_INTERNAL, + }; + if running.is_some() { + let error = + TerminalError::new("INVALID_STATE", "terminal must be stopped before destroy"); + handle_ref.set_error(&error); + return TERMINAL_ERROR_INVALID_STATE; + } + drop(running); + unsafe { + drop(Box::from_raw(handle.cast::())); + } + TERMINAL_OK + })) + .unwrap_or(TERMINAL_ERROR_INTERNAL) +} + +/// # Safety +/// `handle` must be live, and `terminal_info` must reference `terminal_info_len` readable bytes. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn terminal_service_configure( + handle: *mut c_void, + terminal_info: *const u8, + terminal_info_len: usize, +) -> i32 { + ffi_call(handle, |handle| { + let bytes = unsafe { input_bytes(terminal_info, terminal_info_len)? }; + let info = TerminalInfo::decode_from_slice(bytes).map_err(|error| { + TerminalError::new( + "DECODE_FAILED", + format!("failed to decode TerminalInfo: {error}"), + ) + })?; + handle.service.configure(info) + }) +} + +/// # Safety +/// `handle` must be live; `command_id` must reference `command_id_len` readable UTF-8 bytes. +/// The callback and `user_data` must remain valid until the service is destroyed. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn terminal_service_register_command( + handle: *mut c_void, + command_id: *const u8, + command_id_len: usize, + callback: TerminalCommandCallback, + user_data: *mut c_void, +) -> i32 { + ffi_call(handle, |handle| { + let command_id = unsafe { input_str(command_id, command_id_len)? }; + handle.service.register_command( + command_id.to_owned(), + CommandCallback::new(callback, user_data)?, + ) + }) +} + +/// # Safety +/// `handle` must be live; `event_info` must reference `event_info_len` readable bytes. The +/// callback and `user_data` must remain valid until the event is unregistered or service destroyed. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn terminal_service_register_event( + handle: *mut c_void, + event_info: *const u8, + event_info_len: usize, + callback: TerminalEventCallback, + user_data: *mut c_void, +) -> i32 { + ffi_call(handle, |handle| { + let bytes = unsafe { input_bytes(event_info, event_info_len)? }; + let info = TerminalEventInfo::decode_from_slice(bytes).map_err(|error| { + TerminalError::new( + "DECODE_FAILED", + format!("failed to decode TerminalEventInfo: {error}"), + ) + })?; + handle + .service + .register_event(info, EventCallback::new(callback, user_data)?) + }) +} + +/// # Safety +/// `handle` must be live, and `event_id` must reference `event_id_len` readable UTF-8 bytes. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn terminal_service_unregister_event( + handle: *mut c_void, + event_id: *const u8, + event_id_len: usize, +) -> i32 { + ffi_call(handle, |handle| { + let event_id = unsafe { input_str(event_id, event_id_len)? }; + handle.service.unregister_event(event_id) + }) +} + +/// # Safety +/// `handle` must be live, and `status` must reference `status_len` readable bytes. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn terminal_service_push_status( + handle: *mut c_void, + status: *const u8, + status_len: usize, +) -> i32 { + ffi_call(handle, |handle| { + let bytes = unsafe { input_bytes(status, status_len)? }; + let status = TerminalStatus::decode_from_slice(bytes).map_err(|error| { + TerminalError::new( + "DECODE_FAILED", + format!("failed to decode TerminalStatus: {error}"), + ) + })?; + handle.service.push_status(status) + }) +} + +/// # Safety +/// `handle` must be live. Both protobuf pointers must reference their declared readable lengths. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn terminal_service_complete_event( + handle: *mut c_void, + event_handle: *const u8, + event_handle_len: usize, + response: *const u8, + response_len: usize, +) -> i32 { + ffi_call(handle, |handle| { + let event_handle = TerminalEventHandle::decode_from_slice(unsafe { + input_bytes(event_handle, event_handle_len)? + }) + .map_err(|error| { + TerminalError::new( + "DECODE_FAILED", + format!("failed to decode TerminalEventHandle: {error}"), + ) + })?; + let response = + InvokeResponse::decode_from_slice(unsafe { input_bytes(response, response_len)? }) + .map_err(|error| { + TerminalError::new( + "DECODE_FAILED", + format!("failed to decode InvokeResponse: {error}"), + ) + })?; + handle.service.complete_event(&event_handle, &response) + }) +} + +/// # Safety +/// `handle` must be live; `center_host` must reference `center_host_len` readable UTF-8 bytes; +/// `bound_port` must be writable. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn terminal_service_start( + handle: *mut c_void, + center_host: *const u8, + center_host_len: usize, + center_port: u16, + bound_port: *mut u16, +) -> i32 { + ffi_call(handle, |handle| { + if bound_port.is_null() { + return Err(TerminalError::new( + "INVALID_ARGUMENT", + "bound port output must not be null", + )); + } + let center_host = unsafe { input_str(center_host, center_host_len)? }.to_owned(); + let mut running = handle.running.lock().map_err(internal_lock_error)?; + if running.is_some() { + return Err(TerminalError::new( + "INVALID_STATE", + "terminal is already running", + )); + } + let server = RunningServer::start(&handle.service, center_host, center_port)?; + unsafe { + *bound_port = server.bound_port(); + } + *running = Some(server); + Ok(()) + }) +} + +/// # Safety +/// `handle` must be a live pointer returned by `terminal_service_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn terminal_service_stop(handle: *mut c_void) -> i32 { + ffi_call(handle, |handle| { + let server = handle + .running + .lock() + .map_err(internal_lock_error)? + .take() + .ok_or_else(|| TerminalError::new("INVALID_STATE", "terminal is not running"))?; + server.stop(&handle.service) + }) +} + +/// # Safety +/// `handle` must be live and `buffer_len` writable. A non-null `buffer` must reference at least +/// the input value of `*buffer_len` writable bytes. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn terminal_service_last_error( + handle: *mut c_void, + buffer: *mut u8, + buffer_len: *mut usize, +) -> i32 { + if handle.is_null() || buffer_len.is_null() { + return TERMINAL_ERROR_NULL; + } + let result = catch_unwind(AssertUnwindSafe(|| { + let handle = unsafe { &*handle.cast::() }; + let message = handle + .last_error + .lock() + .map_err(|_| TERMINAL_ERROR_INTERNAL)?; + let required = message.len().saturating_add(1); + let available = unsafe { *buffer_len }; + unsafe { + *buffer_len = required; + } + if buffer.is_null() { + return Ok(TERMINAL_OK); + } + if available < required { + return Ok(TERMINAL_ERROR_BUFFER_TOO_SMALL); + } + unsafe { + ptr::copy_nonoverlapping(message.as_ptr(), buffer, message.len()); + *buffer.add(message.len()) = 0; + } + Ok(TERMINAL_OK) + })); + match result { + Ok(Ok(code)) => code, + Ok(Err(code)) => code, + Err(_) => TERMINAL_ERROR_INTERNAL, + } +} + +fn ffi_call( + handle: *mut c_void, + operation: impl FnOnce(&ServiceHandle) -> Result<(), TerminalError>, +) -> i32 { + if handle.is_null() { + return TERMINAL_ERROR_NULL; + } + let result = catch_unwind(AssertUnwindSafe(|| { + let handle = unsafe { &*handle.cast::() }; + match operation(handle) { + Ok(()) => { + handle.clear_error(); + TERMINAL_OK + } + Err(error) => { + let code = error_code(&error); + handle.set_error(&error); + code + } + } + })); + result.unwrap_or(TERMINAL_ERROR_INTERNAL) +} + +fn error_code(error: &TerminalError) -> i32 { + match error.code { + "INVALID_ARGUMENT" => TERMINAL_ERROR_INVALID_ARGUMENT, + "INVALID_STATE" => TERMINAL_ERROR_INVALID_STATE, + "DECODE_FAILED" => TERMINAL_ERROR_DECODE, + _ => TERMINAL_ERROR_INTERNAL, + } +} + +fn internal_lock_error(_: std::sync::PoisonError) -> TerminalError { + TerminalError::new("INTERNAL", "terminal lock is poisoned") +} + +unsafe fn input_bytes<'a>(input: *const u8, len: usize) -> Result<&'a [u8], TerminalError> { + if input.is_null() { + return Err(TerminalError::new( + "INVALID_ARGUMENT", + "input pointer must not be null", + )); + } + Ok(unsafe { std::slice::from_raw_parts(input, len) }) +} + +unsafe fn input_str<'a>(input: *const u8, len: usize) -> Result<&'a str, TerminalError> { + std::str::from_utf8(unsafe { input_bytes(input, len)? }).map_err(|error| { + TerminalError::new("INVALID_ARGUMENT", format!("input is not UTF-8: {error}")) + }) +} diff --git a/terminal/src/health.rs b/terminal/src/health.rs new file mode 100644 index 0000000..cf3b1ee --- /dev/null +++ b/terminal/src/health.rs @@ -0,0 +1,67 @@ +use connectrpc::{ + ConnectError, ErrorCode, RequestContext, Response, ServiceRequest, ServiceResult, ServiceStream, +}; +use futures_util::{StreamExt, stream}; +use proto::proto::grpc::health::v1::{ + Health, HealthCheckRequest, HealthCheckResponse, health_check_response::ServingStatus, +}; + +use crate::{rpc::watch_stream, terminal::Service}; + +pub(crate) struct TerminalHealth(pub(crate) Service); + +fn known_service(name: &str) -> bool { + name.is_empty() || name == "control.Terminal" +} + +impl TerminalHealth { + pub(crate) fn responses( + &self, + name: &str, + ) -> futures_util::stream::BoxStream<'static, Result> { + if known_service(name) { + return watch_stream(self.0.health_receiver(), self.0.shutdown_receiver()).boxed(); + } + let mut shutdown = self.0.shutdown_receiver(); + stream::once(async { + Ok(HealthCheckResponse { + status: ServingStatus::SERVICE_UNKNOWN.into(), + ..Default::default() + }) + }) + .chain(stream::pending()) + .take_until(async move { + if *shutdown.borrow() { + return; + } + while shutdown.changed().await.is_ok() { + if *shutdown.borrow() { + return; + } + } + }) + .boxed() + } +} + +#[allow(refining_impl_trait)] +impl Health for TerminalHealth { + async fn check( + &self, + _context: RequestContext, + request: ServiceRequest<'_, HealthCheckRequest>, + ) -> ServiceResult { + if !known_service(&request.to_owned_message().service) { + return Err(ConnectError::new(ErrorCode::NotFound, "unknown service")); + } + Response::ok(self.0.health_receiver().borrow().clone()) + } + + async fn watch( + &self, + _context: RequestContext, + request: ServiceRequest<'_, HealthCheckRequest>, + ) -> ServiceResult> { + Response::stream_ok(self.responses(&request.to_owned_message().service)) + } +} diff --git a/terminal/src/lib.rs b/terminal/src/lib.rs index e69de29..0e704ad 100644 --- a/terminal/src/lib.rs +++ b/terminal/src/lib.rs @@ -0,0 +1,19 @@ +mod callback; +mod error; +mod health; +mod rpc; +mod runtime; + +pub use callback::{TerminalCommandCallback, TerminalEventCallback, TerminalResponseSink}; + +pub mod terminal; + +pub mod ffi; + +#[cfg(test)] +#[path = "../tests/unit/mod.rs"] +mod unit_tests; + +#[cfg(test)] +#[path = "../tests/integration/mod.rs"] +mod integration_tests; diff --git a/terminal/src/rpc.rs b/terminal/src/rpc.rs new file mode 100644 index 0000000..16816bf --- /dev/null +++ b/terminal/src/rpc.rs @@ -0,0 +1,100 @@ +use buffa_types::google::protobuf::Empty; +use connectrpc::{ + ConnectError, RequestContext, Response, ServiceRequest, ServiceResult, ServiceStream, +}; +use futures_util::{Stream, stream}; +use proto::proto::control::{ + Command, InvokeResponse, Terminal, TerminalCancelEvent, TerminalEvent, TerminalMetaStatus, + TerminalStatus, +}; +use tokio::sync::watch; + +use crate::terminal::Service; + +#[allow(refining_impl_trait)] +impl Terminal for Service { + async fn execute( + &self, + _context: RequestContext, + request: ServiceRequest<'_, Command>, + ) -> ServiceResult { + Response::ok(self.execute_command(request.to_owned_message()).await) + } + + async fn publish_event( + &self, + _context: RequestContext, + request: ServiceRequest<'_, TerminalEvent>, + ) -> ServiceResult { + Response::ok(self.publish_event(request.to_owned_message()).await) + } + + async fn cancel_event( + &self, + _context: RequestContext, + request: ServiceRequest<'_, TerminalCancelEvent>, + ) -> ServiceResult { + Response::ok(self.cancel_event(request.to_owned_message())) + } + + async fn subscribe_status( + &self, + _context: RequestContext, + _request: ServiceRequest<'_, Empty>, + ) -> ServiceResult> { + Response::stream_ok(watch_stream( + self.status_receiver(), + self.shutdown_receiver(), + )) + } + + async fn subscribe_meta_status( + &self, + _context: RequestContext, + _request: ServiceRequest<'_, Empty>, + ) -> ServiceResult> { + Response::stream_ok(watch_stream( + self.meta_status_receiver(), + self.shutdown_receiver(), + )) + } +} + +pub(crate) fn watch_stream( + receiver: watch::Receiver, + shutdown: watch::Receiver, +) -> impl Stream> + Send +where + T: Clone + Send + Sync + 'static, +{ + stream::unfold( + (receiver, shutdown, true), + |(mut receiver, mut shutdown, initial)| async move { + if *shutdown.borrow() { + return None; + } + if initial { + let item = receiver.borrow_and_update().clone(); + return Some((Ok(item), (receiver, shutdown, false))); + } + + loop { + tokio::select! { + biased; + changed = shutdown.changed() => { + if changed.is_err() || *shutdown.borrow() { + return None; + } + } + changed = receiver.changed() => { + if changed.is_err() { + return None; + } + let item = receiver.borrow_and_update().clone(); + return Some((Ok(item), (receiver, shutdown, false))); + } + } + } + }, + ) +} diff --git a/terminal/src/runtime.rs b/terminal/src/runtime.rs new file mode 100644 index 0000000..2efe8b2 --- /dev/null +++ b/terminal/src/runtime.rs @@ -0,0 +1,262 @@ +use std::sync::Arc; +use std::time::Duration; + +use axum::Router; +use buffa_types::google::protobuf::StringValue; +use connectrpc::Protocol; +use connectrpc::client::{CallOptions, ClientConfig, Http2Connection}; +use proto::proto::control::{CenterClient, TerminalInfo}; +use tokio::runtime::Runtime; +use tokio::task::JoinHandle; + +use crate::error::TerminalError; +use crate::health::TerminalHealth; +use crate::terminal::Service; + +const CENTER_ATTEMPTS: usize = 3; +const CENTER_RPC_TIMEOUT: Duration = Duration::from_secs(3); +const CENTER_RETRY_DELAY: Duration = Duration::from_millis(250); +const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5); + +pub(crate) struct RunningServer { + runtime: Runtime, + server_task: Option>>, + center_host: String, + center_port: u16, + bound_port: u16, +} + +impl RunningServer { + pub(crate) fn start( + service: &Service, + center_host: String, + center_port: u16, + ) -> Result { + if center_host.is_empty() || center_port == 0 { + return Err(TerminalError::new( + "INVALID_ARGUMENT", + "center host and port must be valid", + )); + } + let info = service.registration_info()?; + let runtime = Runtime::new().map_err(|error| { + TerminalError::new("START_FAILED", format!("failed to create runtime: {error}")) + })?; + service.reset_shutdown()?; + service.set_starting()?; + let host = info.terminal_host.clone(); + let port = u16::try_from(info.terminal_port).map_err(|_| { + TerminalError::new( + "INVALID_ARGUMENT", + "terminal port is outside the valid range", + ) + })?; + + let listener = match runtime.block_on(tokio::net::TcpListener::bind((host.as_str(), port))) + { + Ok(listener) => listener, + Err(error) => { + service.set_configured(); + return Err(TerminalError::new( + "START_FAILED", + format!("failed to bind terminal listener: {error}"), + )); + } + }; + let bound_port = match listener.local_addr() { + Ok(address) => address.port(), + Err(error) => { + service.set_configured(); + return Err(TerminalError::new( + "START_FAILED", + format!("failed to read bound address: {error}"), + )); + } + }; + if let Err(error) = service.set_bound_port(bound_port) { + service.set_configured(); + return Err(error); + } + + let rpc = connectrpc::Router::new() + .add_service(Arc::new(service.clone())) + .add_service(Arc::new(TerminalHealth(service.clone()))); + let app = Router::new().fallback_service(rpc.into_axum_service()); + let mut shutdown = service.shutdown_receiver(); + let server_task = runtime.spawn(async move { + axum::serve(listener, app) + .with_graceful_shutdown(async move { + if *shutdown.borrow() { + return; + } + while shutdown.changed().await.is_ok() { + if *shutdown.borrow() { + return; + } + } + }) + .await + }); + + let register_result = runtime.block_on(register_terminal( + ¢er_host, + center_port, + service.registration_info()?, + )); + let terminal_id = match register_result { + Ok(terminal_id) => terminal_id, + Err(error) => { + service.signal_shutdown(); + runtime.block_on(async { + let _ = tokio::time::timeout(SHUTDOWN_TIMEOUT, server_task).await; + }); + service.set_configured(); + return Err(error); + } + }; + service.set_ready(terminal_id)?; + + Ok(Self { + runtime, + server_task: Some(server_task), + center_host, + center_port, + bound_port, + }) + } + + pub(crate) fn bound_port(&self) -> u16 { + self.bound_port + } + + pub(crate) fn stop(mut self, service: &Service) -> Result<(), TerminalError> { + service.set_stopping()?; + let terminal_id = service.terminal_id()?; + let deregister_result = self.runtime.block_on(deregister_terminal( + &self.center_host, + self.center_port, + terminal_id, + )); + + service.signal_shutdown(); + if let Some(mut task) = self.server_task.take() { + let completed = self + .runtime + .block_on(async { tokio::time::timeout(SHUTDOWN_TIMEOUT, &mut task).await }); + if completed.is_err() { + task.abort(); + self.runtime.block_on(async { + let _ = task.await; + }); + } + } + service.set_stopped(); + deregister_result + } +} + +async fn register_terminal( + center_host: &str, + center_port: u16, + info: TerminalInfo, +) -> Result { + let uri = center_uri(center_host, center_port)?; + let mut last_error = String::new(); + for attempt in 0..CENTER_ATTEMPTS { + match Http2Connection::connect_plaintext(uri.clone()).await { + Ok(connection) => { + let client = CenterClient::new( + connection.shared(1024), + ClientConfig::new(uri.clone()) + .with_protocol(Protocol::Grpc) + .with_default_timeout(CENTER_RPC_TIMEOUT), + ); + match client + .register_terminal_with_options( + info.clone(), + CallOptions::default().with_timeout(CENTER_RPC_TIMEOUT), + ) + .await + { + Ok(response) => { + let response = response.into_owned(); + if response.success && !response.message.is_empty() { + return Ok(response.message); + } + last_error = if response.message.is_empty() { + "center rejected registration".to_owned() + } else { + response.message + }; + } + Err(error) => last_error = error.to_string(), + } + } + Err(error) => last_error = error.to_string(), + } + if attempt + 1 < CENTER_ATTEMPTS { + tokio::time::sleep(CENTER_RETRY_DELAY * (attempt as u32 + 1)).await; + } + } + Err(TerminalError::new("REGISTER_FAILED", last_error)) +} + +async fn deregister_terminal( + center_host: &str, + center_port: u16, + terminal_id: String, +) -> Result<(), TerminalError> { + if terminal_id.is_empty() { + return Ok(()); + } + let uri = center_uri(center_host, center_port)?; + let mut last_error = String::new(); + for attempt in 0..CENTER_ATTEMPTS { + match Http2Connection::connect_plaintext(uri.clone()).await { + Ok(connection) => { + let client = CenterClient::new( + connection.shared(1024), + ClientConfig::new(uri.clone()) + .with_protocol(Protocol::Grpc) + .with_default_timeout(CENTER_RPC_TIMEOUT), + ); + let request = StringValue { + value: terminal_id.clone(), + ..Default::default() + }; + match client + .deregister_terminal_with_options( + request, + CallOptions::default().with_timeout(CENTER_RPC_TIMEOUT), + ) + .await + { + Ok(response) => { + let response = response.into_owned(); + if response.success { + return Ok(()); + } + last_error = "center rejected deregistration".to_owned(); + } + Err(error) => last_error = error.to_string(), + } + } + Err(error) => last_error = error.to_string(), + } + if attempt + 1 < CENTER_ATTEMPTS { + tokio::time::sleep(CENTER_RETRY_DELAY * (attempt as u32 + 1)).await; + } + } + Err(TerminalError::new("DEREGISTER_FAILED", last_error)) +} + +fn center_uri(center_host: &str, center_port: u16) -> Result { + format!("http://{center_host}:{center_port}") + .parse() + .map_err(|error| { + TerminalError::new( + "INVALID_ARGUMENT", + format!("invalid center address: {error}"), + ) + }) +} diff --git a/terminal/src/terminal.rs b/terminal/src/terminal.rs new file mode 100644 index 0000000..4331e92 --- /dev/null +++ b/terminal/src/terminal.rs @@ -0,0 +1,803 @@ +use std::collections::HashMap; +use std::sync::{Arc, Mutex, MutexGuard}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use proto::proto::control::{ + Command, InvokeResponse, TerminalCancelEvent, TerminalEvent, TerminalEventHandle, + TerminalEventInfo, TerminalInfo, TerminalMetaStatus, TerminalStatus, +}; +use proto::proto::grpc::health::v1::{HealthCheckResponse, health_check_response::ServingStatus}; +use tokio::sync::watch; + +use crate::callback::{CommandCallback, EventCallback}; +use crate::error::{TerminalError, success_handle}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ServiceState { + Created, + Configured, + Starting, + Ready, + Stopping, + Stopped, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum SimulationState { + Uninitialized, + Initialized, + Running, + Suspended, + Stopped, +} + +#[derive(Clone)] +struct EventDefinition { + info: TerminalEventInfo, + callback: EventCallback, +} + +struct ActiveEvent { + event_id: String, + awaiting_completion: bool, + signal: watch::Sender, +} + +#[derive(Clone)] +enum EventSignal { + Pending, + Complete(InvokeResponse), + Cancelled, +} + +struct Context { + service_state: ServiceState, + simulation_state: SimulationState, + terminal_info: Option, + terminal_id: String, + commands: HashMap, + event_definitions: HashMap, + active_events: HashMap, + next_instance_id: u64, + status_sequence: u64, +} + +struct Inner { + context: Mutex, + callback_gate: Arc>, + status: watch::Sender, + meta_status: watch::Sender, + health: watch::Sender, + shutdown: Mutex>, +} + +#[derive(Clone)] +pub struct Service { + inner: Arc, +} + +impl Default for Service { + fn default() -> Self { + Self::new_value() + } +} + +impl Service { + pub fn new() -> Box { + Box::new(Self::new_value()) + } + + pub(crate) fn new_value() -> Self { + let (status, _) = watch::channel(TerminalStatus::default()); + let (meta_status, _) = watch::channel(TerminalMetaStatus::default()); + let (shutdown, _) = watch::channel(false); + let (health, _) = watch::channel(HealthCheckResponse { + status: ServingStatus::NOT_SERVING.into(), + ..Default::default() + }); + Self { + inner: Arc::new(Inner { + context: Mutex::new(Context { + service_state: ServiceState::Created, + simulation_state: SimulationState::Uninitialized, + terminal_info: None, + terminal_id: String::new(), + commands: HashMap::new(), + event_definitions: HashMap::new(), + active_events: HashMap::new(), + next_instance_id: 1, + status_sequence: 0, + }), + callback_gate: Arc::new(Mutex::new(())), + status, + meta_status, + health, + shutdown: Mutex::new(shutdown), + }), + } + } + + pub fn closed(&self) -> bool { + self.state() + .map(|state| { + !matches!( + state, + ServiceState::Starting | ServiceState::Ready | ServiceState::Stopping + ) + }) + .unwrap_or(false) + } + + pub(crate) fn configure(&self, terminal_info: TerminalInfo) -> Result<(), TerminalError> { + validate_terminal_info(&terminal_info)?; + let mut context = self.lock_context()?; + if matches!( + context.service_state, + ServiceState::Starting | ServiceState::Ready | ServiceState::Stopping + ) { + return Err(TerminalError::new( + "INVALID_STATE", + "terminal cannot be configured while running", + )); + } + context.terminal_info = Some(terminal_info); + context.terminal_id.clear(); + context.simulation_state = SimulationState::Uninitialized; + context.service_state = ServiceState::Configured; + self.publish_health(context.service_state); + drop(context); + self.publish_meta_status(); + Ok(()) + } + + pub(crate) fn register_command( + &self, + command_id: String, + callback: CommandCallback, + ) -> Result<(), TerminalError> { + if command_id.is_empty() { + return Err(TerminalError::new( + "INVALID_ARGUMENT", + "command id must not be empty", + )); + } + self.lock_context()?.commands.insert(command_id, callback); + Ok(()) + } + + pub(crate) fn register_event( + &self, + info: TerminalEventInfo, + callback: EventCallback, + ) -> Result<(), TerminalError> { + if info.event_id.is_empty() { + return Err(TerminalError::new( + "INVALID_ARGUMENT", + "event id must not be empty", + )); + } + self.lock_context()? + .event_definitions + .insert(info.event_id.clone(), EventDefinition { info, callback }); + self.publish_meta_status(); + Ok(()) + } + + pub(crate) fn unregister_event(&self, event_id: &str) -> Result<(), TerminalError> { + let cancelled = { + let mut context = self.lock_context()?; + context.event_definitions.remove(event_id); + let instance_ids = context + .active_events + .iter() + .filter_map(|(instance_id, active)| { + (active.event_id == event_id).then_some(*instance_id) + }) + .collect::>(); + instance_ids + .into_iter() + .filter_map(|instance_id| context.active_events.remove(&instance_id)) + .map(|active| active.signal) + .collect::>() + }; + for signal in cancelled { + let _ = signal.send(EventSignal::Cancelled); + } + self.publish_meta_status(); + Ok(()) + } + + pub(crate) fn push_status(&self, mut status: TerminalStatus) -> Result<(), TerminalError> { + let sequence = { + let mut context = self.lock_context()?; + if context.service_state != ServiceState::Ready { + return Err(TerminalError::new("INVALID_STATE", "terminal is not ready")); + } + context.status_sequence = context.status_sequence.saturating_add(1); + context.status_sequence + }; + status.sequence = sequence; + status.timestamp = unix_timestamp_millis(); + self.inner.status.send_replace(status); + Ok(()) + } + + pub(crate) async fn execute_command(&self, command: Command) -> InvokeResponse { + let callback = match self.prepare_command(&command) { + Ok(callback) => callback, + Err(error) => return error.into_response(), + }; + let command_id = command.id.clone(); + let gate = Arc::clone(&self.inner.callback_gate); + let response = tokio::task::spawn_blocking(move || { + let _guard = gate + .lock() + .map_err(|_| TerminalError::new("INTERNAL", "callback lock is poisoned"))?; + callback.invoke(&command) + }) + .await + .map_err(|error| TerminalError::new("CALLBACK_FAILED", error.to_string())) + .and_then(|response| response); + + match response { + Ok(response) => { + if response.success + && let Err(error) = self.apply_command_transition(&command_id) + { + return error.into_response(); + } + response + } + Err(error) => error.into_response(), + } + } + + pub(crate) async fn publish_event(&self, event: TerminalEvent) -> InvokeResponse { + let (handle, callback, signal) = match self.create_event_instance(&event) { + Ok(value) => value, + Err(error) => return error.into_response(), + }; + self.publish_meta_status(); + self.spawn_event_task(event, handle.clone(), callback, signal); + success_handle(&handle) + } + + pub(crate) fn cancel_event(&self, request: TerminalCancelEvent) -> InvokeResponse { + let handle = TerminalEventHandle { + event_id: request.event_id, + instance_id: request.instance_id, + ..Default::default() + }; + let removed = { + let mut context = match self.lock_context() { + Ok(context) => context, + Err(error) => return error.into_response(), + }; + match context.active_events.get(&handle.instance_id) { + Some(active) if active.event_id == handle.event_id => { + context.active_events.remove(&handle.instance_id) + } + Some(_) => { + return TerminalError::new( + "INVALID_ARGUMENT", + "event id does not match the active instance", + ) + .into_response(); + } + None => None, + } + }; + let Some(active) = removed else { + return TerminalError::new("NOT_FOUND", "event instance was not found").into_response(); + }; + let _ = active.signal.send(EventSignal::Cancelled); + self.publish_meta_status(); + success_handle(&handle) + } + + pub(crate) fn complete_event( + &self, + handle: &TerminalEventHandle, + response: &InvokeResponse, + ) -> Result<(), TerminalError> { + let signal = { + let mut context = self.lock_context()?; + let active = context + .active_events + .get_mut(&handle.instance_id) + .ok_or_else(|| TerminalError::new("NOT_FOUND", "event instance was not found"))?; + if active.event_id != handle.event_id { + return Err(TerminalError::new( + "INVALID_ARGUMENT", + "event id does not match the active instance", + )); + } + if !active.awaiting_completion { + return Err(TerminalError::new( + "INVALID_STATE", + "event instance is not awaiting completion", + )); + } + active.awaiting_completion = false; + active.signal.clone() + }; + signal + .send(EventSignal::Complete(response.clone())) + .map_err(|_| TerminalError::new("NOT_FOUND", "event task has already stopped")) + } + + pub(crate) fn status_receiver(&self) -> watch::Receiver { + self.inner.status.subscribe() + } + + pub(crate) fn meta_status_receiver(&self) -> watch::Receiver { + self.inner.meta_status.subscribe() + } + + pub(crate) fn shutdown_receiver(&self) -> watch::Receiver { + self.inner + .shutdown + .lock() + .expect("shutdown lock poisoned") + .subscribe() + } + + pub(crate) fn health_receiver(&self) -> watch::Receiver { + self.inner.health.subscribe() + } + + fn publish_health(&self, state: ServiceState) { + let status = if state == ServiceState::Ready { + ServingStatus::SERVING + } else { + ServingStatus::NOT_SERVING + }; + self.inner.health.send_if_modified(|response| { + if response.status == status { + return false; + } + response.status = status.into(); + true + }); + } + + pub(crate) fn reset_shutdown(&self) -> Result<(), TerminalError> { + let (sender, _) = watch::channel(false); + *self + .inner + .shutdown + .lock() + .map_err(|_| TerminalError::new("INTERNAL", "shutdown lock is poisoned"))? = sender; + Ok(()) + } + + pub(crate) fn signal_shutdown(&self) { + if let Ok(sender) = self.inner.shutdown.lock() { + sender.send_replace(true); + } + } + + pub(crate) fn set_starting(&self) -> Result<(), TerminalError> { + let mut context = self.lock_context()?; + if !matches!( + context.service_state, + ServiceState::Configured | ServiceState::Stopped + ) { + return Err(TerminalError::new( + "INVALID_STATE", + "terminal must be configured before starting", + )); + } + context.service_state = ServiceState::Starting; + self.publish_health(context.service_state); + Ok(()) + } + + pub(crate) fn set_ready(&self, terminal_id: String) -> Result<(), TerminalError> { + if terminal_id.is_empty() { + return Err(TerminalError::new( + "REGISTER_FAILED", + "center returned an empty terminal id", + )); + } + let mut context = self.lock_context()?; + context.terminal_id = terminal_id; + context.service_state = ServiceState::Ready; + self.publish_health(context.service_state); + drop(context); + self.publish_meta_status(); + Ok(()) + } + + pub(crate) fn set_configured(&self) { + if let Ok(mut context) = self.inner.context.lock() { + context.terminal_id.clear(); + context.service_state = ServiceState::Configured; + self.publish_health(context.service_state); + } + self.publish_meta_status(); + } + + pub(crate) fn set_stopping(&self) -> Result<(), TerminalError> { + let mut context = self.lock_context()?; + if context.service_state != ServiceState::Ready { + return Err(TerminalError::new( + "INVALID_STATE", + "terminal is not running", + )); + } + context.service_state = ServiceState::Stopping; + self.publish_health(context.service_state); + Ok(()) + } + + pub(crate) fn set_stopped(&self) { + if let Ok(mut context) = self.inner.context.lock() { + context.terminal_id.clear(); + context.service_state = ServiceState::Stopped; + self.publish_health(context.service_state); + context.simulation_state = SimulationState::Stopped; + context.active_events.clear(); + } + self.publish_meta_status(); + } + + pub(crate) fn registration_info(&self) -> Result { + self.lock_context()? + .terminal_info + .clone() + .ok_or_else(|| TerminalError::new("INVALID_STATE", "terminal is not configured")) + } + + pub(crate) fn set_bound_port(&self, port: u16) -> Result<(), TerminalError> { + let mut context = self.lock_context()?; + let info = context + .terminal_info + .as_mut() + .ok_or_else(|| TerminalError::new("INVALID_STATE", "terminal is not configured"))?; + info.terminal_port = u32::from(port); + Ok(()) + } + + pub(crate) fn terminal_id(&self) -> Result { + Ok(self.lock_context()?.terminal_id.clone()) + } + + fn state(&self) -> Result { + Ok(self.lock_context()?.service_state) + } + + fn lock_context(&self) -> Result, TerminalError> { + self.inner + .context + .lock() + .map_err(|_| TerminalError::new("INTERNAL", "terminal state lock is poisoned")) + } + + fn prepare_command(&self, command: &Command) -> Result { + if command.id.is_empty() { + return Err(TerminalError::new( + "INVALID_ARGUMENT", + "command id must not be empty", + )); + } + let context = self.lock_context()?; + if context.service_state != ServiceState::Ready { + return Err(TerminalError::new("INVALID_STATE", "terminal is not ready")); + } + validate_command_transition(context.simulation_state, &command.id)?; + context.commands.get(&command.id).copied().ok_or_else(|| { + TerminalError::new( + "NOT_FOUND", + format!("command '{}' is not registered", command.id), + ) + }) + } + + fn apply_command_transition(&self, command_id: &str) -> Result<(), TerminalError> { + let mut context = self.lock_context()?; + match command_id { + "init" => { + context.simulation_state = SimulationState::Initialized; + context.next_instance_id = 1; + context.active_events.clear(); + } + "reset" => context.simulation_state = SimulationState::Initialized, + "start" | "resume" => context.simulation_state = SimulationState::Running, + "stop" => context.simulation_state = SimulationState::Stopped, + "suspend" => context.simulation_state = SimulationState::Suspended, + _ => {} + } + drop(context); + if command_id == "init" { + self.publish_meta_status(); + } + Ok(()) + } + + fn create_event_instance( + &self, + event: &TerminalEvent, + ) -> Result< + ( + TerminalEventHandle, + EventCallback, + watch::Receiver, + ), + TerminalError, + > { + if event.event_id.is_empty() { + return Err(TerminalError::new( + "INVALID_ARGUMENT", + "event id must not be empty", + )); + } + let mut context = self.lock_context()?; + if context.service_state != ServiceState::Ready { + return Err(TerminalError::new("INVALID_STATE", "terminal is not ready")); + } + if context.simulation_state == SimulationState::Uninitialized { + return Err(TerminalError::new( + "INVALID_STATE", + "simulation must be initialized before publishing events", + )); + } + let callback = context + .event_definitions + .get(&event.event_id) + .map(|definition| definition.callback) + .ok_or_else(|| { + TerminalError::new( + "NOT_FOUND", + format!("event '{}' is not registered", event.event_id), + ) + })?; + let instance_id = context.next_instance_id; + context.next_instance_id = context + .next_instance_id + .checked_add(1) + .ok_or_else(|| TerminalError::new("RESOURCE_EXHAUSTED", "event id space exhausted"))?; + let (signal, receiver) = watch::channel(EventSignal::Pending); + context.active_events.insert( + instance_id, + ActiveEvent { + event_id: event.event_id.clone(), + awaiting_completion: false, + signal, + }, + ); + Ok(( + TerminalEventHandle { + event_id: event.event_id.clone(), + instance_id, + ..Default::default() + }, + callback, + receiver, + )) + } + + fn spawn_event_task( + &self, + event: TerminalEvent, + handle: TerminalEventHandle, + callback: EventCallback, + mut signal: watch::Receiver, + ) { + let service = self.clone(); + let mut shutdown = self.shutdown_receiver(); + tokio::spawn(async move { + if wait_for_event( + Duration::from_millis(event.trigger_delay_ms), + &mut signal, + &mut shutdown, + ) + .await + .is_none() + { + service.remove_active_event(handle.instance_id); + return; + } + + loop { + if service + .set_event_awaiting(handle.instance_id, true) + .is_err() + { + return; + } + let callback_event = event.clone(); + let gate = Arc::clone(&service.inner.callback_gate); + let callback_response = tokio::task::spawn_blocking(move || { + let _guard = gate + .lock() + .map_err(|_| TerminalError::new("INTERNAL", "callback lock is poisoned"))?; + callback.invoke(&callback_event, handle.instance_id) + }) + .await; + if !matches!(callback_response, Ok(Ok(response)) if response.success) { + service.remove_active_event(handle.instance_id); + return; + } + + let completion = wait_for_completion(&mut signal, &mut shutdown).await; + let Some(response) = completion else { + service.remove_active_event(handle.instance_id); + return; + }; + if !response.success || event.repeat_period_ms == 0 { + service.remove_active_event(handle.instance_id); + return; + } + if wait_for_event( + Duration::from_millis(event.repeat_period_ms), + &mut signal, + &mut shutdown, + ) + .await + .is_none() + { + service.remove_active_event(handle.instance_id); + return; + } + } + }); + } + + fn set_event_awaiting(&self, instance_id: u64, awaiting: bool) -> Result<(), TerminalError> { + let mut context = self.lock_context()?; + let active = context + .active_events + .get_mut(&instance_id) + .ok_or_else(|| TerminalError::new("NOT_FOUND", "event instance was not found"))?; + active.awaiting_completion = awaiting; + if awaiting { + active.signal.send_replace(EventSignal::Pending); + } + Ok(()) + } + + fn remove_active_event(&self, instance_id: u64) { + let removed = self + .inner + .context + .lock() + .map(|mut context| context.active_events.remove(&instance_id).is_some()) + .unwrap_or(false); + if removed { + self.publish_meta_status(); + } + } + + fn publish_meta_status(&self) { + let snapshot = match self.inner.context.lock() { + Ok(context) => { + let mut publishable_events = context + .event_definitions + .values() + .map(|definition| definition.info.clone()) + .collect::>(); + publishable_events.sort_by(|left, right| left.event_id.cmp(&right.event_id)); + TerminalMetaStatus { + terminal_id: context.terminal_id.clone(), + publishable_events, + triggered_events: context + .active_events + .iter() + .map(|(instance_id, active)| (*instance_id, active.event_id.clone())) + .collect(), + ..Default::default() + } + } + Err(_) => return, + }; + if *self.inner.meta_status.borrow() != snapshot { + self.inner.meta_status.send_replace(snapshot); + } + } +} + +fn validate_terminal_info(info: &TerminalInfo) -> Result<(), TerminalError> { + if info.terminal_host.is_empty() { + return Err(TerminalError::new( + "INVALID_ARGUMENT", + "terminal host must not be empty", + )); + } + if info.terminal_port > u16::MAX as u32 { + return Err(TerminalError::new( + "INVALID_ARGUMENT", + "terminal port is outside the valid range", + )); + } + if info.terminal_mac.is_empty() { + return Err(TerminalError::new( + "INVALID_ARGUMENT", + "terminal mac must not be empty", + )); + } + Ok(()) +} + +fn validate_command_transition( + state: SimulationState, + command_id: &str, +) -> Result<(), TerminalError> { + let allowed = match command_id { + "init" => true, + "reset" => state != SimulationState::Uninitialized, + "start" => matches!( + state, + SimulationState::Initialized | SimulationState::Stopped + ), + "stop" => matches!( + state, + SimulationState::Initialized | SimulationState::Running | SimulationState::Suspended + ), + "suspend" => state == SimulationState::Running, + "resume" => state == SimulationState::Suspended, + _ => true, + }; + if allowed { + Ok(()) + } else { + Err(TerminalError::new( + "INVALID_STATE", + format!("command '{command_id}' is not valid in state {state:?}"), + )) + } +} + +fn unix_timestamp_millis() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|duration| duration.as_millis().min(i64::MAX as u128) as i64) + .unwrap_or_default() +} + +async fn wait_for_completion( + signal: &mut watch::Receiver, + shutdown: &mut watch::Receiver, +) -> Option { + loop { + match signal.borrow_and_update().clone() { + EventSignal::Complete(response) => return Some(response), + EventSignal::Cancelled => return None, + EventSignal::Pending => {} + } + tokio::select! { + changed = signal.changed() => { + if changed.is_err() { + return None; + } + } + changed = shutdown.changed() => { + if changed.is_err() || *shutdown.borrow() { + return None; + } + } + } + } +} + +async fn wait_for_event( + duration: Duration, + signal: &mut watch::Receiver, + shutdown: &mut watch::Receiver, +) -> Option<()> { + tokio::select! { + _ = tokio::time::sleep(duration) => Some(()), + changed = signal.changed() => { + match changed { + Ok(()) if !matches!(*signal.borrow(), EventSignal::Cancelled) => Some(()), + _ => None, + } + } + changed = shutdown.changed() => { + match changed { + Ok(()) if !*shutdown.borrow() => Some(()), + _ => None, + } + } + } +} diff --git a/terminal/terminal.h b/terminal/terminal.h new file mode 100644 index 0000000..a7fba51 --- /dev/null +++ b/terminal/terminal.h @@ -0,0 +1,128 @@ +#ifndef FLYSIM_TERMINAL_H +#define FLYSIM_TERMINAL_H + +#pragma once + +#include +#include +#include +#include +#include + +#define TERMINAL_OK 0 + +#define TERMINAL_ERROR_NULL -1 + +#define TERMINAL_ERROR_INVALID_ARGUMENT -2 + +#define TERMINAL_ERROR_INVALID_STATE -3 + +#define TERMINAL_ERROR_DECODE -4 + +#define TERMINAL_ERROR_INTERNAL -5 + +#define TERMINAL_ERROR_BUFFER_TOO_SMALL -6 + +typedef int32_t (*TerminalResponseSink)(void *context, const uint8_t *response, size_t response_len); + +typedef int32_t (*TerminalCommandCallback)(void *user_data, + const uint8_t *command, + size_t command_len, + TerminalResponseSink sink, + void *sink_context); + +typedef int32_t (*TerminalEventCallback)(void *user_data, + const uint8_t *event, + size_t event_len, + uint64_t instance_id, + TerminalResponseSink sink, + void *sink_context); + +void *terminal_service_create(void); + +/** + * # Safety + * `handle` must be a live pointer returned by `terminal_service_create` and must not be used + * after this function succeeds. + */ +int32_t terminal_service_destroy(void *handle); + +/** + * # Safety + * `handle` must be live, and `terminal_info` must reference `terminal_info_len` readable bytes. + */ +int32_t terminal_service_configure(void *handle, + const uint8_t *terminal_info, + size_t terminal_info_len); + +/** + * # Safety + * `handle` must be live; `command_id` must reference `command_id_len` readable UTF-8 bytes. + * The callback and `user_data` must remain valid until the service is destroyed. + */ +int32_t terminal_service_register_command(void *handle, + const uint8_t *command_id, + size_t command_id_len, + TerminalCommandCallback callback, + void *user_data); + +/** + * # Safety + * `handle` must be live; `event_info` must reference `event_info_len` readable bytes. The + * callback and `user_data` must remain valid until the event is unregistered or service destroyed. + */ +int32_t terminal_service_register_event(void *handle, + const uint8_t *event_info, + size_t event_info_len, + TerminalEventCallback callback, + void *user_data); + +/** + * # Safety + * `handle` must be live, and `event_id` must reference `event_id_len` readable UTF-8 bytes. + */ +int32_t terminal_service_unregister_event(void *handle, + const uint8_t *event_id, + size_t event_id_len); + +/** + * # Safety + * `handle` must be live, and `status` must reference `status_len` readable bytes. + */ +int32_t terminal_service_push_status(void *handle, const uint8_t *status, size_t status_len); + +/** + * # Safety + * `handle` must be live. Both protobuf pointers must reference their declared readable lengths. + */ +int32_t terminal_service_complete_event(void *handle, + const uint8_t *event_handle, + size_t event_handle_len, + const uint8_t *response, + size_t response_len); + +/** + * # Safety + * `handle` must be live; `center_host` must reference `center_host_len` readable UTF-8 bytes; + * `bound_port` must be writable. + */ +int32_t terminal_service_start(void *handle, + const uint8_t *center_host, + size_t center_host_len, + uint16_t center_port, + uint16_t *bound_port); + +/** + * # Safety + * `handle` must be a live pointer returned by `terminal_service_create`. + */ +int32_t terminal_service_stop(void *handle); + +/** + * # Safety + * `handle` must be live and `buffer_len` writable. A non-null `buffer` must reference at least + * the input value of `*buffer_len` writable bytes. + */ +int32_t terminal_service_last_error(void *handle, uint8_t *buffer, size_t *buffer_len); + +#endif /* FLYSIM_TERMINAL_H */ diff --git a/terminal/tests/integration/mod.rs b/terminal/tests/integration/mod.rs new file mode 100644 index 0000000..4a59515 --- /dev/null +++ b/terminal/tests/integration/mod.rs @@ -0,0 +1 @@ +mod runtime; diff --git a/terminal/tests/integration/runtime.rs b/terminal/tests/integration/runtime.rs new file mode 100644 index 0000000..9be4daa --- /dev/null +++ b/terminal/tests/integration/runtime.rs @@ -0,0 +1,191 @@ +use std::sync::{Arc, Mutex, mpsc}; +use std::time::Duration; + +use axum::Router; +use buffa_types::google::protobuf::{Empty, StringValue}; +use connectrpc::client::{ClientConfig, Http2Connection}; +use connectrpc::{ + ConnectError, Protocol, RequestContext, Response, ServiceRequest, ServiceResult, ServiceStream, +}; +use futures_util::stream; +use proto::proto::control::{ + Center, Command, InvokeResponse, TerminalClient, TerminalInfo, TerminalInfos, + TerminalRegisterResponse, +}; +use proto::proto::grpc::health::v1::{ + HealthCheckRequest, HealthClient, health_check_response::ServingStatus, +}; +use tokio::runtime::Runtime; +use tokio::sync::oneshot; + +use crate::runtime::RunningServer; +use crate::terminal::Service; + +const CENTER_ASSIGNED_ID: &str = "center-terminal-1"; + +#[derive(Default)] +struct FakeCenter { + registered: Mutex>, + deregistered_id: Mutex>, +} + +#[allow(refining_impl_trait)] +impl Center for FakeCenter { + async fn register_terminal( + &self, + _context: RequestContext, + request: ServiceRequest<'_, TerminalInfo>, + ) -> ServiceResult { + *self.registered.lock().unwrap() = Some(request.to_owned_message()); + Response::ok(TerminalRegisterResponse { + success: true, + message: CENTER_ASSIGNED_ID.to_owned(), + ..Default::default() + }) + } + + async fn deregister_terminal( + &self, + _context: RequestContext, + request: ServiceRequest<'_, StringValue>, + ) -> ServiceResult { + *self.deregistered_id.lock().unwrap() = Some(request.to_owned_message().value); + Response::ok(InvokeResponse { + success: true, + ..Default::default() + }) + } + + async fn subscribe_terminal( + &self, + _context: RequestContext, + _request: ServiceRequest<'_, Empty>, + ) -> ServiceResult> { + Response::stream_ok(stream::empty::>()) + } +} + +#[test] +fn start_registers_actual_port_and_stop_deregisters_same_id() { + let center = Arc::new(FakeCenter::default()); + let center_runtime = Runtime::new().unwrap(); + let listener = center_runtime + .block_on(tokio::net::TcpListener::bind(("127.0.0.1", 0))) + .unwrap(); + let center_port = listener.local_addr().unwrap().port(); + + let rpc = connectrpc::Router::new().add_service(Arc::clone(¢er)); + let app = Router::new().fallback_service(rpc.into_axum_service()); + let (shutdown_tx, shutdown_rx) = oneshot::channel(); + let (started_tx, started_rx) = mpsc::sync_channel(1); + let center_task = center_runtime.spawn(async move { + started_tx.send(()).unwrap(); + axum::serve(listener, app) + .with_graceful_shutdown(async move { + let _ = shutdown_rx.await; + }) + .await + }); + started_rx.recv_timeout(Duration::from_secs(1)).unwrap(); + + let service = Service::new_value(); + service + .configure(TerminalInfo { + terminal_host: "127.0.0.1".to_owned(), + terminal_port: 0, + terminal_mac: "00:11:22:33:44:55".to_owned(), + ..Default::default() + }) + .unwrap(); + let server = RunningServer::start(&service, "127.0.0.1".to_owned(), center_port).unwrap(); + + let registered = center.registered.lock().unwrap().clone().unwrap(); + assert_ne!(registered.terminal_port, 0); + assert_eq!(registered.terminal_port, u32::from(server.bound_port())); + assert_eq!( + service.meta_status_receiver().borrow().terminal_id, + CENTER_ASSIGNED_ID + ); + + let terminal_uri: axum::http::Uri = format!("http://127.0.0.1:{}", server.bound_port()) + .parse() + .unwrap(); + center_runtime.block_on(async { + let connection = Http2Connection::connect_plaintext(terminal_uri.clone()) + .await + .unwrap(); + let connection = connection.shared(32); + let config = ClientConfig::new(terminal_uri) + .with_protocol(Protocol::Grpc) + .with_default_timeout(Duration::from_secs(2)); + let health = HealthClient::new(connection.clone(), config.clone()); + for name in ["", "control.Terminal"] { + let response = health + .check(HealthCheckRequest { + service: name.into(), + ..Default::default() + }) + .await + .unwrap() + .into_owned(); + assert_eq!(response.status, ServingStatus::SERVING); + } + let error = health + .check(HealthCheckRequest { + service: "missing".into(), + ..Default::default() + }) + .await + .unwrap_err(); + assert_eq!(error.code, connectrpc::ErrorCode::NotFound); + let mut watcher = health.watch(HealthCheckRequest::default()).await.unwrap(); + assert_eq!( + watcher + .message() + .await + .unwrap() + .unwrap() + .to_owned_message() + .status, + ServingStatus::SERVING + ); + drop(watcher); + let mut watcher = health + .watch(HealthCheckRequest { + service: "missing".into(), + ..Default::default() + }) + .await + .unwrap(); + assert_eq!( + watcher + .message() + .await + .unwrap() + .unwrap() + .to_owned_message() + .status, + ServingStatus::SERVICE_UNKNOWN + ); + drop(watcher); + let client = TerminalClient::new(connection, config); + let response = client + .execute(Command { + id: "not-registered".to_owned(), + ..Default::default() + }) + .await + .unwrap() + .into_owned(); + assert!(!response.success); + }); + + server.stop(&service).unwrap(); + assert_eq!( + center.deregistered_id.lock().unwrap().as_deref(), + Some(CENTER_ASSIGNED_ID) + ); + + shutdown_tx.send(()).unwrap(); + center_runtime.block_on(center_task).unwrap().unwrap(); +} diff --git a/terminal/tests/unit/ffi.rs b/terminal/tests/unit/ffi.rs new file mode 100644 index 0000000..0687c2d --- /dev/null +++ b/terminal/tests/unit/ffi.rs @@ -0,0 +1,79 @@ +use std::ptr; + +use buffa::Message; +use proto::proto::control::TerminalInfo; + +use crate::ffi::*; + +#[test] +fn null_handles_are_rejected() { + assert_eq!( + unsafe { terminal_service_configure(ptr::null_mut(), ptr::null(), 0) }, + TERMINAL_ERROR_NULL + ); + assert_eq!( + unsafe { terminal_service_destroy(ptr::null_mut()) }, + TERMINAL_ERROR_NULL + ); +} + +#[test] +fn invalid_protobuf_is_reported_through_last_error() { + let handle = terminal_service_create(); + let invalid = [0xff_u8, 0xff]; + assert_eq!( + unsafe { terminal_service_configure(handle, invalid.as_ptr(), invalid.len()) }, + TERMINAL_ERROR_DECODE + ); + + let mut required = 0; + assert_eq!( + unsafe { terminal_service_last_error(handle, ptr::null_mut(), &mut required) }, + TERMINAL_OK + ); + assert!(required > 1); + let mut buffer = vec![0_u8; required]; + assert_eq!( + unsafe { terminal_service_last_error(handle, buffer.as_mut_ptr(), &mut required) }, + TERMINAL_OK + ); + let message = std::str::from_utf8(&buffer[..required - 1]).unwrap(); + assert!(message.starts_with("DECODE_FAILED:")); + assert_eq!(unsafe { terminal_service_destroy(handle) }, TERMINAL_OK); +} + +#[test] +fn configured_service_can_be_destroyed() { + let handle = terminal_service_create(); + let info = TerminalInfo { + terminal_host: "127.0.0.1".to_owned(), + terminal_port: 0, + terminal_mac: "00:11:22:33:44:55".to_owned(), + ..Default::default() + } + .encode_to_vec(); + assert_eq!( + unsafe { terminal_service_configure(handle, info.as_ptr(), info.len()) }, + TERMINAL_OK + ); + assert_eq!(unsafe { terminal_service_destroy(handle) }, TERMINAL_OK); +} + +#[test] +fn null_callback_is_rejected() { + let handle = terminal_service_create(); + let command_id = b"init"; + assert_eq!( + unsafe { + terminal_service_register_command( + handle, + command_id.as_ptr(), + command_id.len(), + None, + ptr::null_mut(), + ) + }, + TERMINAL_ERROR_INVALID_ARGUMENT + ); + assert_eq!(unsafe { terminal_service_destroy(handle) }, TERMINAL_OK); +} diff --git a/terminal/tests/unit/health.rs b/terminal/tests/unit/health.rs new file mode 100644 index 0000000..61b6fa7 --- /dev/null +++ b/terminal/tests/unit/health.rs @@ -0,0 +1,67 @@ +use futures_util::StreamExt; +use proto::proto::control::TerminalInfo; +use proto::proto::grpc::health::v1::health_check_response::ServingStatus; + +use crate::health::TerminalHealth; +use crate::terminal::Service; + +#[tokio::test] +async fn lifecycle_health_stream_and_shutdown() { + let service = Service::new_value(); + let health = TerminalHealth(service.clone()); + let mut responses = health.responses(""); + assert_eq!( + responses.next().await.unwrap().unwrap().status, + ServingStatus::NOT_SERVING + ); + service + .configure(TerminalInfo { + terminal_host: "127.0.0.1".into(), + terminal_mac: "test".into(), + ..Default::default() + }) + .unwrap(); + service.set_starting().unwrap(); + assert_eq!( + service.health_receiver().borrow().status, + ServingStatus::NOT_SERVING + ); + service.set_ready("id".into()).unwrap(); + assert_eq!( + responses.next().await.unwrap().unwrap().status, + ServingStatus::SERVING + ); + service.set_stopping().unwrap(); + assert_eq!( + responses.next().await.unwrap().unwrap().status, + ServingStatus::NOT_SERVING + ); + service.set_stopped(); + service.set_starting().unwrap(); + service.set_configured(); + assert_eq!( + service.health_receiver().borrow().status, + ServingStatus::NOT_SERVING + ); + service.signal_shutdown(); + assert!(responses.next().await.is_none()); + assert!(health.responses("").next().await.is_none()); +} + +#[tokio::test] +async fn unknown_watch_stays_open_until_shutdown() { + let service = Service::new_value(); + let health = TerminalHealth(service.clone()); + let mut responses = health.responses("missing"); + assert_eq!( + responses.next().await.unwrap().unwrap().status, + ServingStatus::SERVICE_UNKNOWN + ); + assert!( + tokio::time::timeout(std::time::Duration::from_millis(20), responses.next()) + .await + .is_err() + ); + service.signal_shutdown(); + assert!(responses.next().await.is_none()); +} diff --git a/terminal/tests/unit/mod.rs b/terminal/tests/unit/mod.rs new file mode 100644 index 0000000..4e0b82c --- /dev/null +++ b/terminal/tests/unit/mod.rs @@ -0,0 +1,3 @@ +mod ffi; +mod health; +mod terminal; diff --git a/terminal/tests/unit/terminal.rs b/terminal/tests/unit/terminal.rs new file mode 100644 index 0000000..e5821c0 --- /dev/null +++ b/terminal/tests/unit/terminal.rs @@ -0,0 +1,228 @@ +use std::ffi::c_void; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::Duration; + +use buffa::Message; +use proto::proto::control::{ + Command, InvokeResponse, TerminalCancelEvent, TerminalEvent, TerminalEventHandle, + TerminalEventInfo, TerminalInfo, TerminalStatus, +}; + +use crate::callback::{CommandCallback, EventCallback, TerminalResponseSink}; +use crate::terminal::Service; + +unsafe extern "C" fn successful_command( + _user_data: *mut c_void, + _command: *const u8, + _command_len: usize, + sink: TerminalResponseSink, + sink_context: *mut c_void, +) -> i32 { + send_response(sink, sink_context, true) +} + +unsafe extern "C" fn counted_event( + user_data: *mut c_void, + _event: *const u8, + _event_len: usize, + _instance_id: u64, + sink: TerminalResponseSink, + sink_context: *mut c_void, +) -> i32 { + unsafe { &*(user_data as *const AtomicUsize) }.fetch_add(1, Ordering::SeqCst); + send_response(sink, sink_context, true) +} + +fn send_response(sink: TerminalResponseSink, sink_context: *mut c_void, success: bool) -> i32 { + let response = InvokeResponse { + success, + ..Default::default() + } + .encode_to_vec(); + unsafe { sink(sink_context, response.as_ptr(), response.len()) } +} + +fn ready_service() -> Service { + let service = Service::new_value(); + service + .configure(TerminalInfo { + terminal_host: "127.0.0.1".to_owned(), + terminal_port: 0, + terminal_mac: "00:11:22:33:44:55".to_owned(), + ..Default::default() + }) + .unwrap(); + service.set_starting().unwrap(); + service.set_ready("terminal-1".to_owned()).unwrap(); + service +} + +async fn initialize(service: &Service) { + service + .register_command( + "init".to_owned(), + CommandCallback::new(Some(successful_command), std::ptr::null_mut()).unwrap(), + ) + .unwrap(); + let response = service + .execute_command(Command { + id: "init".to_owned(), + ..Default::default() + }) + .await; + assert!(response.success); +} + +#[test] +fn status_sequence_and_timestamp_are_managed_by_rust() { + let service = ready_service(); + let receiver = service.status_receiver(); + + service + .push_status(TerminalStatus { + sequence: 999, + timestamp: -1, + ..Default::default() + }) + .unwrap(); + let first = receiver.borrow().clone(); + assert_eq!(first.sequence, 1); + assert!(first.timestamp > 0); + + service.push_status(TerminalStatus::default()).unwrap(); + assert_eq!(receiver.borrow().sequence, 2); +} + +#[tokio::test] +async fn meta_status_is_derived_from_rust_owned_state() { + let service = ready_service(); + initialize(&service).await; + let counter = AtomicUsize::new(0); + service + .register_event( + TerminalEventInfo { + event_id: "engine-fire".to_owned(), + ..Default::default() + }, + EventCallback::new( + Some(counted_event), + (&counter as *const AtomicUsize).cast_mut().cast::(), + ) + .unwrap(), + ) + .unwrap(); + + let receiver = service.meta_status_receiver(); + assert_eq!(receiver.borrow().terminal_id, "terminal-1"); + assert_eq!(receiver.borrow().publishable_events.len(), 1); + + let response = service + .publish_event(TerminalEvent { + event_id: "engine-fire".to_owned(), + trigger_delay_ms: 10_000, + ..Default::default() + }) + .await; + let handle = response + .message + .as_option() + .unwrap() + .unpack_if::(TerminalEventHandle::TYPE_URL) + .unwrap() + .unwrap(); + assert_eq!( + receiver.borrow().triggered_events.get(&handle.instance_id), + Some(&handle.event_id) + ); + + let cancelled = service.cancel_event(TerminalCancelEvent { + event_id: handle.event_id, + instance_id: handle.instance_id, + ..Default::default() + }); + assert!(cancelled.success); + assert!(receiver.borrow().triggered_events.is_empty()); +} + +#[tokio::test] +async fn repeating_event_waits_for_explicit_completion() { + let service = ready_service(); + initialize(&service).await; + let counter = AtomicUsize::new(0); + service + .register_event( + TerminalEventInfo { + event_id: "repeat".to_owned(), + ..Default::default() + }, + EventCallback::new( + Some(counted_event), + (&counter as *const AtomicUsize).cast_mut().cast::(), + ) + .unwrap(), + ) + .unwrap(); + + let response = service + .publish_event(TerminalEvent { + event_id: "repeat".to_owned(), + trigger_delay_ms: 10, + repeat_period_ms: 10, + ..Default::default() + }) + .await; + let handle = response + .message + .as_option() + .unwrap() + .unpack_if::(TerminalEventHandle::TYPE_URL) + .unwrap() + .unwrap(); + + wait_for_count(&counter, 1).await; + tokio::time::sleep(Duration::from_millis(30)).await; + assert_eq!(counter.load(Ordering::SeqCst), 1); + + service + .complete_event( + &handle, + &InvokeResponse { + success: true, + ..Default::default() + }, + ) + .unwrap(); + wait_for_count(&counter, 2).await; + + service + .complete_event( + &handle, + &InvokeResponse { + success: false, + ..Default::default() + }, + ) + .unwrap(); + tokio::time::timeout(Duration::from_secs(1), async { + while service + .meta_status_receiver() + .borrow() + .triggered_events + .contains_key(&handle.instance_id) + { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); +} + +async fn wait_for_count(counter: &AtomicUsize, expected: usize) { + tokio::time::timeout(Duration::from_secs(1), async { + while counter.load(Ordering::SeqCst) < expected { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); +}