diff --git a/.env.example b/.env.registry.example similarity index 67% rename from .env.example rename to .env.registry.example index 4aee017..8b34773 100644 --- a/.env.example +++ b/.env.registry.example @@ -4,4 +4,6 @@ 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 +LOG_LEVEL=info +LOG_DIR=logs/registry +LOG_MAX_FILES=10 \ No newline at end of file diff --git a/.gitignore b/.gitignore index 5b70d78..1698b0a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ /target /.env /registry/data/ +/logs/ diff --git a/Cargo.lock b/Cargo.lock index 71695f6..0080baf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -364,6 +364,21 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "crossbeam-channel" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + [[package]] name = "defmt" version = "1.1.1" @@ -395,6 +410,12 @@ dependencies = [ "thiserror", ] +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" + [[package]] name = "dispatcher" version = "0.1.0" @@ -442,6 +463,18 @@ dependencies = [ "zlib-rs", ] +[[package]] +name = "flysim-log" +version = "0.1.0" +dependencies = [ + "log", + "tempfile", + "tracing", + "tracing-appender", + "tracing-log", + "tracing-subscriber", +] + [[package]] name = "fnv" version = "1.0.7" @@ -769,6 +802,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + [[package]] name = "libc" version = "0.2.189" @@ -816,6 +855,21 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + [[package]] name = "once_cell" version = "1.21.4" @@ -881,6 +935,12 @@ dependencies = [ "portable-atomic", ] +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + [[package]] name = "prettyplease" version = "0.2.37" @@ -904,11 +964,14 @@ dependencies = [ name = "proto" version = "0.1.0" dependencies = [ + "axum", "buffa", "buffa-types", "connectrpc", "connectrpc-build", + "futures-util", "serde", + "tokio", ] [[package]] @@ -935,11 +998,14 @@ dependencies = [ "buffa-types", "connectrpc", "dotenvy", + "flysim-log", "futures-util", + "log", "proto", "tempfile", "terminal", "tokio", + "tracing", "uuid", ] @@ -1049,6 +1115,15 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d" +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + [[package]] name = "shlex" version = "2.0.1" @@ -1108,6 +1183,12 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" +[[package]] +name = "symlink" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7973cce6668464ea31f176d85b13c7ab3bba2cb3b77a2ed26abd7801688010a" + [[package]] name = "syn" version = "2.0.119" @@ -1158,9 +1239,14 @@ dependencies = [ "buffa-types", "cbindgen", "connectrpc", + "flysim-log", "futures-util", + "log", "proto", + "tempfile", "tokio", + "tracing", + "tracing-subscriber", ] [[package]] @@ -1183,6 +1269,45 @@ dependencies = [ "syn 3.0.4", ] +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + [[package]] name = "tokio" version = "1.53.1" @@ -1322,6 +1447,19 @@ dependencies = [ "tracing-core", ] +[[package]] +name = "tracing-appender" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "050686193eb999b4bb3bc2acfa891a13da00f79734704c4b8b4ef1a10b368a3c" +dependencies = [ + "crossbeam-channel", + "symlink", + "thiserror", + "time", + "tracing-subscriber", +] + [[package]] name = "tracing-attributes" version = "0.1.31" @@ -1340,6 +1478,31 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" dependencies = [ "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "nu-ansi-term", + "sharded-slab", + "thread_local", + "tracing-core", + "tracing-log", ] [[package]] @@ -1371,6 +1534,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + [[package]] name = "want" version = "0.3.1" diff --git a/Cargo.toml b/Cargo.toml index 77dac7a..9e0b923 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [workspace] -members = ["dispatcher", "registry", "terminal", "proto", "aggregate-router"] +members = ["dispatcher", "registry", "terminal", "proto", "aggregate-router", "log"] resolver = "3" [workspace.package] @@ -8,6 +8,7 @@ edition = "2024" authors = ["lain "] [workspace.dependencies] +flysim-log = { path = "log" } proto = { path = "proto" } connectrpc = { version = "^0.9", features = ["client", "server", "axum"] } buffa = "^0.9" @@ -31,3 +32,7 @@ tokio = { version = "^1", features = [ ] } log = "^0.4" env_logger = "^0.11" +tracing = "^0.1" +tracing-log = "^0.2" +tracing-subscriber = { version = "^0.3", default-features = false, features = ["fmt", "ansi", "registry", "std", "tracing-log"] } +tracing-appender = "^0.2" diff --git a/TERMINAL_ARCHITECTURE.md b/TERMINAL_ARCHITECTURE.md index 945e3ea..7e5c47c 100644 --- a/TERMINAL_ARCHITECTURE.md +++ b/TERMINAL_ARCHITECTURE.md @@ -1,171 +1,185 @@ # FlySim 控制系统架构设计 -本文档基于 `proto/control` 中的协议定义、`terminal/src` 中的当前实现,以及调度服务和终端聚合路由服务的目标需求,描述系统静态边界、运行时交互及主要类型关系。图中 Terminal 和 Registry 已有代码实现;Dispatcher 和终端聚合路由子中心目前为目标架构。Registry 的配置、持久化与健康检查契约见 [registry/README.md](registry/README.md)。 +## 架构总览 -## 1. C4 架构图 - -### 1.1 系统上下文 +下图采用分层架构框图,仅展示系统组成与职责分区,不包含调用、注册或数据流连线。标注区分当前已有实现、占位组件和外部系统;分区顺序不代表调用顺序。 ```mermaid +block-beta + columns 3 -C4Context - title FlySim 控制系统上下文 + Client["控制系统客户端(外部)"]:3 - Person(operator, "控制操作员", "通过控制系统管理仿真终端和场景") - System_Ext(controlConsole, "控制系统客户端", "提交仿真任务、直接控制逻辑终端并监视状态") - System_Ext(simulator, "仿真程序", "实现具体仿真逻辑和终端回调") + ControlTitle["控制服务层"]:3 + Registry["Registry 总中心
目录与健康检查
已实现"] + Dispatcher["Dispatcher 调度
任务与执行编排
占位,待实现"] + Data["Data 场景查询
协议占位
后续扩展"] - System_Boundary(flySim, "FlySim 控制域") { - System(registry, "总中心(Registry)", "登记逻辑终端并发布全局终端目录及服务状态") - System(dispatcher, "调度服务(Dispatcher)", "编排命令和事件,分配仿真任务,并根据状态动态调度") - System(subcenter, "终端聚合路由服务(子中心)", "将下辖实体终端聚合为一个逻辑终端,并统一代理 Terminal API") - System(terminal, "实体控制终端", "封装单个仿真程序,对外提供 Terminal API") - System(dataService, "数据服务", "提供场景数据查询") - } + AggregationTitle["聚合层(可递归、按作用域部署)"]:3 + Router["aggregate-router 聚合中心
逻辑终端 / 任务绑定 / 状态聚合
占位,待实现"]:3 - 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") + SimulationTitle["仿真宿主进程(每个实体终端实例)"]:3 + Host["宿主仿真逻辑
命令与事件回调 / 状态生成
外部实现"] + Terminal["Terminal 嵌入式动态库
生命周期 / 事件 / RPC / FFI
已实现"]:2 + + FoundationTitle["公共基础设施"]:3 + Proto["proto / proto::rpc
协议 / RPC 传输 / Health
已实现"]:2 + Logging["flysim-log
日志桥接 / 滚动输出
已实现"] + + classDef heading fill:#e8eef0,stroke:#a4b3b8,color:#26383e + class ControlTitle,AggregationTitle,SimulationTitle,FoundationTitle heading ``` -### 1.2 容器视图 +聚合中心可以包含下级聚合中心或实体终端;全局独立终端也可直接归属总中心,并非所有终端都必须经过聚合层。图中的公共基础设施是共享库,不是独立服务进程;具体树形归属见第 7.2 节。 + +本文档基于当前工作区的协议和实现,描述系统静态边界、运行时交互及主要类型关系。2026-10-06 核对并确认的目标为:按资源作用域部署的严格树形多级注册、异构协同聚合,以及经 Dispatcher 统一进入的控制写操作。 + +Terminal、Registry、公共日志与 RPC 基础设施已有实现;Dispatcher 和 aggregate-router 仅有占位入口。第 1.1、1.2、1.4、2.4 节为目标设计,不代表现有协议已支持任务绑定、结果查询或恢复。第 1.3、2.1 至 2.3、3 节描述当前 Terminal 实现。实现差异见第 6 节,已确认决策及部署约定见第 7 节,仍待协议化的事项见第 8 节。本次仅更新架构文档,不修改协议或业务代码。 + +组件契约详见 [terminal/README.md](terminal/README.md)、[registry/README.md](registry/README.md) 和 [proto/README.md](proto/README.md)。 + +## 1. 分层架构图 + +各图按控制、注册、执行和状态分别展开,不在同一张图中叠加所有连线。同名节点在不同图中表示同一类组件;箭头含义以每张图的说明为准,返回响应与非关键依赖省略。 + +### 1.1 控制与只读访问(目标设计) + +#### 控制写入路径 + +箭头表示控制请求方向。操作员通过客户端提交任务及场景配置;所有写操作经 Dispatcher,内部终端只能沿父子链访问。聚合层可继续递归,图中仅展示两层。 ```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") +flowchart TB + Client["控制系统客户端"] -->|"调度 API(待定义)"| Dispatcher["Dispatcher"] + Dispatcher -->|"Terminal RPC"| TopCenter["顶层聚合终端"] + Dispatcher -->|"Terminal RPC"| Global["全局独立终端"] + TopCenter -->|"按任务绑定"| ChildCenter["下级聚合终端"] + ChildCenter -->|"代理调用"| Terminal["实体终端"] ``` -### 1.3 Terminal 组件视图 +#### 只读数据路径 + +箭头表示订阅数据流向,不表示控制权限。客户端与 Dispatcher 均可读取顶层目录和状态;内部状态由各级中心聚合后上报。 ```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, "提供订阅数据") +flowchart TB + Registry["Registry"] -->|"顶层目录"| Readers["客户端 / Dispatcher"] + TopCenter["顶层聚合终端"] -->|"聚合状态与元状态"| Readers + Global["全局独立终端"] -->|"状态与元状态"| Readers ``` -### 1.4 调度与聚合路由组件视图(目标设计) +首版场景配置随任务提交;Data 仅为后续场景查询扩展,不参与首版必经路径。 + +### 1.2 注册层级与部署边界(目标设计) + +箭头统一表示通过 Center API 向唯一直接上级注册或注销,不表示控制请求方向。Registry 只维护直接登记的顶层条目,不展开子树。具体资源的作用域示例见第 7.2 节。 ```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, "触发能力元信息更新") +flowchart BT + Terminal["实体终端"] --> ChildCenter["下级聚合中心"] + ChildCenter --> TopCenter["顶层聚合中心"] + TopCenter --> Registry["总中心 Registry"] + Global["全局独立终端"] --> Registry ``` +- Registry 是独立服务,已持久化直接下级目录并主动检查健康状态。 +- Dispatcher 是独立服务,目标持久化任务和执行结果;每个聚合中心独立持有目录、连接池及绑定、句柄和结果记录。存储方案待定,连接与快照在恢复时重建。 +- 聚合中心对下提供 Center API,对上提供一个逻辑 Terminal API;异构角色、能力和参数通过显式映射组合。 +- Terminal 是嵌入仿真宿主的 Rust 动态库,宿主与库通过 C ABI 和 Protobuf 字节交互,并非两个独立服务进程。RPC 使用 ConnectRPC,由 Tokio/Axum 承载。 + +### 1.3 Terminal 内部职责(当前实现) + +#### 生命周期与服务承载 + +```mermaid +flowchart TB + Host["仿真宿主"] -->|"C ABI"| FFI["FFI 门面"] + FFI -->|"启动 / 停止"| Runtime["RunningServer"] + Runtime -->|"注册 / 注销"| Center["直接上级 Center"] + Runtime -->|"同端口承载"| Server["Terminal RPC + Health"] +``` + +FFI 校验输入并管理句柄和错误码。RunningServer 管理 Tokio 运行时、监听端口及关闭过程;Service 的生命周期驱动 HealthReporter,每次运行创建新的 HealthService 并绑定本次关闭信号。 + +#### 命令与事件回调 + +```mermaid +flowchart TB + Caller["RPC 调用方"] --> RPC["Terminal RPC 适配器"] + RPC --> Core["Service:状态与校验"] + Core -->|"命令"| Callback["回调适配器"] + Core -->|"事件"| Task["事件任务"] + Task --> Callback + Callback -->|"C 回调 + 响应 sink"| Host["仿真宿主"] +``` + +事件任务处理延迟、显式完成、重复与取消。命令和事件共用实例级回调锁,但整条命令流程不是串行事务;当前 RPC 不校验调用方身份。目标写入方为直接上级,或总中心直辖终端的 Dispatcher。 + +#### 状态与元状态发布 + +```mermaid +flowchart TB + Host["仿真宿主"] -->|"FFI 推送状态 / 完成事件"| Core["Service"] + Core -->|"发布快照"| Bus["watch 状态通道"] + Bus --> RPC["RPC 快照流"] + RPC --> Subscribers["订阅方"] +``` + +宿主也经 FFI 配置终端并注册回调。Service 维护生命周期、仿真状态和事件,生成元状态;流先返回当前快照,慢订阅者可能跳过中间值,关闭信号结束流。详细交互见第 2.1 至 2.3 节。 + +### 1.4 调度与聚合路由职责(目标设计) + +以下按处理阶段拆图。聚合组件适用于每一级中心;顶层的直接上级为 Registry,内部层级的直接上级为另一个聚合中心。Dispatcher 只调用顶层终端。 + +#### Dispatcher:计划与执行 + +```mermaid +flowchart TB + API["调度 API"] --> Planner["调度规划器"] + Observer["目录与状态观察器"] -->|"能力 / 状态"| Planner + Planner -->|"执行计划"| Orchestrator["执行编排器"] + Orchestrator -->|"命令 / 事件"| Top["顶层终端"] + Orchestrator -->|"执行记录"| Store[("任务与结果存储")] +``` + +API 接收客户端任务、场景配置与控制请求,并提供进度和结果查询。观察器订阅 Registry 目录及顶层终端状态;编排器负责命令序列、事件发布与取消、结果跟踪和恢复对账。顶层终端包括聚合终端与全局独立终端,任务上下文和查询协议均待定义。 + +#### 聚合中心:下级登记与上级注册 + +```mermaid +flowchart TB + Child["直接下级终端"] -->|"注册 / 注销"| CenterAPI["下级 Center 接口"] + CenterAPI --> Directory["目录与连接池"] + Directory -->|"能力映射更新"| Registration["上级注册客户端"] + Registration -->|"单一 TerminalInfo"| Parent["直接上级 Center"] +``` + +下级可以是实体或聚合终端。目录记录 ID、地址与健康状态,连接池管理客户端;对外能力按明确的角色和参数映射生成,不直接求下级能力的并集。 + +#### 聚合中心:绑定与控制代理 + +```mermaid +flowchart TB + Facade["逻辑 Terminal 门面"] --> Router["任务路由器"] + Directory["目录与连接池"] -->|"候选连接"| Router + Router -->|"沿任务绑定调用"| Child["直接下级终端"] + Router -->|"记录与对账"| Store[("绑定 / 句柄 / 结果")] +``` + +门面接收 Dispatcher 或父中心的控制请求。路由器首次选择并记录目标,后续调用复用绑定;迁移需显式协调。每一级持久化自身的绑定、逻辑事件映射与逐目标结果,全部目标成功才聚合成功,不自动回滚。 + +#### 聚合中心:状态归并 + +```mermaid +flowchart TB + Child["直接下级状态流"] --> Aggregator["状态聚合器"] + Directory["目录与健康状态"] --> Aggregator + Aggregator -->|"显式模式映射"| Snapshot["单一逻辑快照"] + Snapshot --> Facade["Terminal 订阅接口"] +``` + +上级或只读客户端经门面订阅逻辑状态与元状态;各级逐层归并,不绕过中心暴露内部实体。能力映射、状态过期规则和可调度性计算仍待协议化。 + ## 2. 运行时序图 ### 2.1 配置、启动注册与停止注销 @@ -179,7 +193,7 @@ sequenceDiagram participant Handle as ServiceHandle participant Core as Service participant Runtime as RunningServer - participant RPC as Axum + Terminal RPC + participant RPC as Axum + Terminal 和 Health RPC participant Center as 上级中心(子中心或总中心) Host->>FFI: terminal_service_create() @@ -192,26 +206,30 @@ sequenceDiagram 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 并绑定监听端口 + Host->>FFI: terminal_service_start(handle, center_host, center_port, bound_port_out) + FFI->>Runtime: start(Service, center_host, center_port) + Runtime->>Core: registration_info() + Runtime->>Runtime: 创建 Tokio Runtime + Runtime->>Core: reset_shutdown(), set_starting() + Runtime->>Runtime: 绑定监听端口 Runtime->>Core: set_bound_port(actual_port) - Runtime->>RPC: 挂载 Service 并启动 Axum + Runtime->>RPC: 挂载 Service 和本次 HealthService,启动 Axum loop 最多 3 次,递增退避 Runtime->>Center: RegisterTerminal(actual TerminalInfo) Center-->>Runtime: TerminalRegisterResponse end Runtime->>Core: set_ready(center_assigned_id) - Core->>Core: 发布 TerminalMetaStatus + Core->>Core: 发布 TerminalMetaStatus 和 SERVING 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: set_stopping(),发布 NOT_SERVING + loop 最多 3 次,递增退避 + Runtime->>Center: DeregisterTerminal(terminal_id) + Center-->>Runtime: InvokeResponse + end Runtime->>Core: signal_shutdown() Runtime->>RPC: 等待优雅关闭,超时则中止 Runtime->>Core: set_stopped() @@ -220,10 +238,12 @@ sequenceDiagram ### 2.2 命令执行与状态订阅 +以下为当前 Terminal RPC 内部行为;调用方身份尚未校验。目标部署中,叶子终端的写调用来自直接上级,总中心直辖终端的写调用来自 Dispatcher,控制客户端可直接只读订阅。 + ```mermaid sequenceDiagram autonumber - participant Client as 控制系统客户端 + participant Client as Terminal RPC 调用方 participant RPC as Terminal RPC participant Core as Service participant Gate as callback_gate @@ -239,7 +259,7 @@ sequenceDiagram Client->>RPC: Execute(Command) RPC->>Core: execute_command(Command) Core->>Core: 校验 Ready、命令注册和仿真状态迁移合法性 - Core->>Gate: spawn_blocking 后获取全局回调锁 + Core->>Gate: spawn_blocking 后获取实例级回调锁 Gate->>Adapter: invoke(Command) Adapter->>Adapter: Protobuf 编码 Adapter->>Host: TerminalCommandCallback(..., sink) @@ -261,10 +281,12 @@ sequenceDiagram ### 2.3 事件发布、完成、重复与取消 +此图描述当前活动事件管理,不包含目标设计中的可靠终态记录。一次性事件与重复事件都需要显式完成;发布成功仅确认调度,取消成功不保证宿主工作已经停止。 + ```mermaid sequenceDiagram autonumber - participant Client as 控制系统客户端 + participant Client as Terminal RPC 调用方 participant RPC as Terminal RPC participant Core as Service participant Meta as meta_status watch @@ -283,7 +305,7 @@ sequenceDiagram Task->>Task: 等待 trigger_delay_ms loop 首次执行及每个成功的重复周期 Task->>Core: 标记 awaiting_completion - Task->>Gate: spawn_blocking 后获取全局回调锁 + Task->>Gate: spawn_blocking 后获取实例级回调锁 Gate->>Host: TerminalEventCallback(event, instance_id, sink) Host-->>Task: sink(InvokeResponse bytes) alt 回调失败或拒绝 @@ -310,16 +332,18 @@ sequenceDiagram end ``` -### 2.4 两级注册、状态驱动调度与聚合路由 +### 2.4 多级注册、任务绑定与聚合路由(目标设计) + +下图以两个聚合层级为例,更深层级重复相同的父子关系。任务上下文、绑定、逐目标结果和终态查询均待协议化;图中的记录与查询不表示现有 Terminal API 已具备这些能力。首版场景配置由任务请求携带,不调用 Data。 ```mermaid sequenceDiagram autonumber participant Terminal as 实体终端 - participant SubCenter as 聚合路由子中心 + participant SubCenter as 下级聚合中心 + participant TopCenter as 顶层聚合中心 participant Registry as 总中心 Registry participant Dispatcher as 调度服务 - participant Data as Data 服务 participant Client as 控制系统客户端 Terminal->>SubCenter: RegisterTerminal(entity TerminalInfo) @@ -329,33 +353,53 @@ sequenceDiagram Terminal-->>SubCenter: 实体状态流 SubCenter->>SubCenter: 归并为单一逻辑状态和能力 - SubCenter->>Registry: RegisterTerminal(logical TerminalInfo) - Registry-->>SubCenter: logical terminal_id + SubCenter->>TopCenter: RegisterTerminal(logical TerminalInfo) + TopCenter-->>SubCenter: 下级 logical terminal_id + TopCenter->>SubCenter: SubscribeStatus + SubscribeMetaStatus + TopCenter->>Registry: RegisterTerminal(top-level TerminalInfo) + Registry-->>TopCenter: 顶层 logical terminal_id Dispatcher->>Registry: SubscribeTerminal(Empty) - Registry-->>Dispatcher: 包含子中心的 TerminalInfos 流 - Dispatcher->>SubCenter: SubscribeStatus + SubscribeMetaStatus - SubCenter-->>Dispatcher: 单一逻辑终端状态流 + Registry-->>Dispatcher: 顶层聚合终端及全局独立终端目录 + Dispatcher->>TopCenter: SubscribeStatus + SubscribeMetaStatus + TopCenter-->>Dispatcher: 单一逻辑终端状态流 - Client->>Dispatcher: 提交仿真任务(调度 API 待定义) - Dispatcher->>Data: GetScene(SceneRequest) - Data-->>Dispatcher: SceneResponse - Dispatcher->>Dispatcher: 根据任务、能力和聚合状态生成计划 - Dispatcher->>SubCenter: Execute / PublishEvent - SubCenter->>SubCenter: 根据计划和实时状态选择一个或多个实体终端 + Client->>Dispatcher: 提交任务与场景配置(调度 API 待定义) + Dispatcher->>Dispatcher: 选择顶层逻辑终端,记录任务和执行意图 + Dispatcher->>TopCenter: 任务上下文 + Execute / PublishEvent(待扩展) + TopCenter->>TopCenter: 建立或复用任务到直接下级的绑定 + TopCenter->>SubCenter: 沿绑定代理任务与控制请求 + SubCenter->>SubCenter: 建立或复用任务到实体的绑定 par 转发到目标终端 SubCenter->>Terminal: Execute / PublishEvent Terminal-->>SubCenter: InvokeResponse / downstream handle and 持续观察状态 Terminal-->>SubCenter: TerminalStatus / TerminalMetaStatus - SubCenter-->>Dispatcher: 聚合状态变化 + SubCenter-->>TopCenter: 下级聚合状态变化 + TopCenter-->>Dispatcher: 顶层聚合状态变化 + end + SubCenter->>SubCenter: 保存逐目标调用结果与逻辑事件映射 + SubCenter-->>TopCenter: 聚合调用结果 / logical handle + TopCenter->>TopCenter: 逐级聚合并持久化映射 + TopCenter-->>Dispatcher: 聚合调用结果 / top-level handle + Note over Terminal,Dispatcher: 全部目标成功才聚合成功;超时记为结果未知;发布成功不等于执行完成 + Dispatcher-->>Client: 任务进度或调用结果 + + opt 事件结果跟踪或断线补查 + Dispatcher->>TopCenter: 查询执行状态与终态(契约待定义) + TopCenter->>SubCenter: 按逐级映射对账与补查 + SubCenter->>Terminal: 查询事件终态(现有协议不支持) + Terminal-->>SubCenter: 实体执行结果或未知 + SubCenter-->>TopCenter: 下级聚合执行结果 + TopCenter-->>Dispatcher: 顶层聚合执行结果 + Dispatcher->>Dispatcher: 保存任务与事件终态 + Client->>Dispatcher: 查询结果或恢复跟踪 + Dispatcher-->>Client: 已知终态或结果未知 end - SubCenter->>SubCenter: 聚合响应并维护逻辑事件句柄映射 - SubCenter-->>Dispatcher: InvokeResponse / logical handle - Dispatcher-->>Client: 任务进度或结果 opt 状态变化要求重调度 - Dispatcher->>Dispatcher: 重新选择目标并调整命令或事件 - Dispatcher->>SubCenter: Execute / PublishEvent / CancelEvent + Dispatcher->>TopCenter: 发起显式调整计划 + TopCenter->>SubCenter: 协调旧绑定、在途事件与新绑定 + Note over SubCenter,Dispatcher: 不逐请求随意换目标,不盲目重放,不自动回滚已成功目标 end ``` @@ -413,13 +457,14 @@ classDiagram -callback_gate ArcMutex -status WatchSenderTerminalStatus -meta_status WatchSenderTerminalMetaStatus + -health HealthReporter -shutdown MutexWatchSenderBool } class Context { -service_state ServiceState -simulation_state SimulationState - -terminal_info TerminalInfo + -terminal_info OptionTerminalInfo -terminal_id String -commands HashMapCommandCallback -event_definitions HashMapEventDefinition @@ -518,31 +563,133 @@ classDiagram ## 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 编解码 | +| 关注点 | 协议或实现位置 | 说明 | +| ------------ | ------------------------------------------------------------------------ | ------------------------------------------------ | +| 中心 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、持久化目录和主动健康检查 | +| 聚合路由 | [`aggregate-router/src/main.rs`](aggregate-router/src/main.rs) | 已有空入口;下级 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、调度意图如何传入子中心、响应聚合规则和逻辑状态模式仍需在编码前协议化。 +### 公共基础设施 + +- [flysim-log](log/README.md) 统一日志配置校验、log/tracing 桥接、双输出和滚动文件。Registry 持有进程级守卫;Terminal 保留显式 C ABI 初始化/关闭状态机。公共库不反向依赖业务组件。 +- [proto::rpc](proto/README.md) 提供生成类型的简洁导出、客户端连接工厂、服务承载、快照流和标准 Health 服务;旧的 `proto::proto::*` 导入仍兼容。 +- HealthReporter 持有按服务名划分的健康状态,HealthService 绑定单次运行的关闭信号;未知名称的 Watch 支持后续登记、移除与重新登记。Terminal 每次重启重新构造 HealthService。 +- Registry 在自身就绪后为 `""` 和 `control.Center` 报告 SERVING,关闭前报告 NOT_SERVING;该状态不随目录中的下游终端离线而改变。 +- Terminal 的中心客户端显式使用 3 秒建连上限和独立的 3 秒 RPC 超时;注册重试次数与退避保持不变。公共客户端不自动重试业务调用,不为长订阅设置默认短截止时间。 +- 业务 RPC trait 适配、状态机、持久化、探活调度和错误降级仍留在各组件;公共服务器函数不创建运行时或管理进程信号。本次不实现或修改聚合路由与 Dispatcher。 + +### 业务约定 + +- 目标拓扑为严格树形多级注册。Registry 维护自身直接下级的顶层目录,不递归展开内部实体;子中心对下实现 Center API,对上实现 Terminal API。 +- 子中心将异构实体或下级聚合终端组成一个逻辑仿真单元,向唯一直接上级注册一个 `TerminalInfo`。复用资源按作用域选择上级,具体部署约定见第 7.2 节。 +- 所有外部控制写请求经 Dispatcher;Dispatcher 只调度 Registry 直接登记的顶层终端,各级子中心按任务绑定递归代理,不绕过上级控制内部实体。注册、注销和宿主本地 FFI 不属于这里的控制写入口。 +- 子中心对上发布单一逻辑能力及状态,维护任务绑定、逐目标结果和逐级事件句柄映射。模式转换和恢复协议仍待定义。 +- Dispatcher 和聚合路由目前没有业务实现。第 7 节确认业务语义,第 8 节记录尚未落实到协议和机制的事项,不应将目标能力视为已实现保证。 - 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` 显式完成,才会进入下一周期。 +- 命令与事件共用实例级 `callback_gate`,仅保证同一实例的宿主回调串行;校验、回调、状态提交并非一个串行事务,也不保证 FIFO 或按命令时间戳排序。 +- `SubscribeStatus` 和 `SubscribeMetaStatus` 先返回当前快照,随后返回观察到的更新;慢消费者可跳过中间值,关闭信号结束流。它们不是事件日志或可靠结果通道。 +- 高频状态的 `sequence` 和 `timestamp` 由 Rust 服务覆盖;元状态由事件定义、活动事件和中心分配的终端 ID 派生。100 Hz 是协议约定,当前 `push_status` 没有强制限频或参数模式校验。 +- 一次性与重复事件都必须由宿主调用 `terminal_service_complete_event` 显式完成。重复周期从成功完成后开始计时,不是固定墙钟周期;当前没有完成超时。 +- 发布成功仅表示事件已调度。`triggered_events` 实际包含等待延迟、执行或等待完成等活动实例;移除不能区分完成成功、失败和取消。取消不能强制中断已执行的宿主回调。 +- Terminal 停止时清除 ID 和活动事件、将仿真状态设为 Stopped,但保留配置、回调、事件定义及最新状态。重新配置将仿真状态重置为 Uninitialized;`init` 成功会重置事件实例计数,不应跨初始化复用旧句柄。 +- Terminal 启动后没有后台重注册。注销失败仍执行本地停止;服务器任务等待上限为 5 秒,但已运行的阻塞回调不可强制中断,故这不是完整停止过程的硬时限。 + +## 6. 当前实现与架构差异(2026-10-06) + +核对基线是当前工作区,包含已有未提交修改。以下区分文档遗漏、协议占位与目标能力缺口,不将设计缺口等同于已修复的代码问题。 + +| 关注点 | 核对结果 | 文档修正或剩余差距 | +| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | +| 实现边界 | Terminal、Registry 和共享基础设施已有实现;Dispatcher 与 aggregate-router 只有入口 | 修正原“聚合路由尚无模块”;多级调度图统一标为目标 | +| 注册拓扑 | 当前 Terminal 每次运行只保存一个中心地址;Registry 接收任何合法 `TerminalInfo`,没有角色、父子层级或树形校验 | 原两级图改为多级树形;当前只能靠部署约定,聚合业务和拓扑约束未实现 | +| 目录边界 | Registry 的 `TerminalInfos` 仅包含直接注册项,是全量替换快照 | 不代表递归全局资源目录;允许全局独立实体作为顶层条目 | +| 写入口 | Terminal RPC 不校验调用方;回调锁不提供完整命令事务串行性 | 客户端直写改为全部经 Dispatcher;访问控制与多调度实例的写入归属尚缺 | +| 场景数据 | [proto/control/common/model.proto](proto/control/common/model.proto) 中 `SceneRequest`、`SceneResponse` 为空;[proto/build.rs](proto/build.rs) 未生成 Data | 首版请求携带场景配置;Data 是后续扩展,不是已有服务 | +| 异构聚合 | `TerminalMetaInfo.supported_type` 为单值,状态是动态参数表 | 将组合体定义为一种逻辑类型可沿用外形,但角色、能力、参数和事件映射仍需契约,不能机械求并集 | +| 任务与路由 | `Command.id` 是命令类型,`timestamp` 不负责排序;请求没有任务或执行实例标识 | 缺任务上下文、稳定绑定、幂等键及显式迁移机制 | +| 结果与重试 | `InvokeResponse` 仅为 `success + Any`;Terminal 只自动重试中心注册和注销 | 多目标响应类型、未知结果、查询与去重均待定义;不能把超时当作未执行后直接重放 | +| 事件可观测性 | `TerminalEventHandle` 只有事件 ID 和本地实例号;元状态只保留活动表,终态不留存 | 可靠终态查询与断线补查需要协议和存储扩展;快照中的事件消失不证明成功 | +| 恢复范围 | Registry 持久化目录,健康状态恢复为 UNKNOWN;Terminal 状态、事件与句柄在内存 | 目录恢复不等于任务恢复;Dispatcher 和各级聚合中心需新增持久化与对账 | +| 健康与状态 | Health 已共端口实现;Terminal Health 表示 Ready,Registry Health 独立于下级健康 | 补入 Terminal 组件图;聚合服务就绪、子树可用性与任务可调度性仍需区分 | +| 宿主约束 | 六个基础命令的完整性、`emergency` 类型禁注册、参数模式和命令时间戳语义未由库统一强制 | 属于协议或宿主契约;脚本注入能力尚不能视为已实现 | +| 部署与安全 | 明文 HTTP/2,无鉴权、TLS、选主或复制;Registry 每个数据路径只能由一个进程拥有 | 已确认受信内网与独立多实例,不承诺同一逻辑服务主备或多活 | + +## 7. 已确认的设计决策与部署约定 + +### 7.1 调度与执行语义 + +| 决策 | 已确认约定 | 尚需实现 | +| ---------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | +| 聚合模型 | 多种实体协同形成一种逻辑仿真类型,不是同构副本池 | 显式角色、能力及参数映射 | +| 调度边界 | Dispatcher 选顶层逻辑终端;各级子中心按任务绑定直接下级,递归到实体 | 任务上下文传递、绑定生命周期及显式迁移 | +| 控制入口 | 所有外部命令、事件发布和取消经 Dispatcher;客户端可直接只读订阅 | 写入方限制、顺序保证与独立调度实例的归属规则 | +| 多目标响应 | 本次调用的全部目标成功才聚合成功,保留逐目标结果;不自动回滚 | 结果类型须区分成功、失败及未知;事件发布成功和最终执行成功分别记录 | +| 事件结果 | 需要实例终态查询、断线补查和可恢复跟踪 | 稳定执行身份、终态持久化、查询和保留策略 | +| 重启恢复 | 恢复记录并与下级对账,不盲目重放控制请求 | Dispatcher 记录任务与结果;各级子中心记录绑定、句柄映射及逐目标结果 | +| 首版场景 | 任务请求直接携带场景配置 | 任务配置模式及向各角色初始化参数的转换;Data 后续引入 | + +“全部成功”不意味着分布式事务或同时生效。已成功目标的副作用不会因其他目标失败而自动撤销;未知结果必须对账,补偿或重新初始化由显式编排决定。事件取消的调度确认也不能冒充宿主已经停止执行的证明。 + +### 7.2 按资源作用域部署的严格树形 + +- 每个运行实例只有一个直接上级,禁止重复挂载、环路或同时注册到多个中心。聚合中心可递归包含实体终端及下级聚合中心,并以一个逻辑终端向自己的直接上级注册。 +- 组件代码和类型可以复用;不同运行实例拥有各自身份与状态。复用同一个运行实例时,将其上移为所属共享作用域中心的独立直接下级,而不是让多个分支重复持有它。 +- **复用不意味着必须直达总中心。** 注册位置由资源的归属、生命周期和共享范围决定。共享仅发生在某座舱内部时,资源留在座舱中心;资源属于整个仿真世界时,才独立注册到总中心。 +- **虚拟兵力模拟器**是仿真世界唯一资源,作为独立终端向总中心注册,由 Dispatcher 在顶层编排。该唯一性是部署约定,当前 Registry 不会按业务类型阻止重复资源。 +- **音频播放终端**与座舱模拟器绑定,向座舱中心注册,与雷达、武器等子系统聚合中心同级。即使雷达与武器都需要音频,也不把同一音频实例同时挂在两者下面,更不因此强制注册到总中心。 +- 上移后,原分支不再把该资源声明为自己的独占下级。跨分支依赖由共同作用域的中心协调;全局资源由 Dispatcher 协调。具体依赖表达和调用契约待定义,不能推导出子终端可以绕过上级直接写入同级资源。 +- Dispatcher 只调度总中心直接登记的顶层终端,不绕过座舱中心控制内部音频或子系统。内部资源的请求和结果沿父子链递归传递;上级对外能力与状态必须体现真实资源依赖。 + +部署示例:箭头表示“向唯一直接上级注册”,不是控制请求方向。实例均有独立身份;同一座舱内只有一个音频节点。 + +```mermaid +flowchart BT + World["虚拟兵力模拟器:仿真世界唯一"] --> Registry["总中心 Registry"] + Cockpit["座舱中心:对外为一个逻辑终端"] --> Registry + Audio["音频播放终端:绑定该座舱"] --> Cockpit + Radar["雷达聚合中心"] --> Cockpit + Weapon["武器聚合中心"] --> Cockpit + Identification["敌我识别终端"] --> Radar + WeaponManagement["武器管理终端"] --> Weapon + Calculation["打击计算终端"] --> Weapon +``` + +选择树形而非共享实体 DAG 的理由:父子归属、任务绑定、注销和恢复可逐级处理,避免多个父中心同时拥有同一实例及跨分支的重复控制。代价是必须显式处理上移资源的依赖与仲裁;树形只约束注册关系,不会自动解决物理设备争用、并发音频请求或全局资源的任务冲突。 + +### 7.3 网络、多实例与开发例外 + +- 首版按受信内网部署,但“受信”不等于已经落实写入权限。目标只允许 Dispatcher 写顶层、直接上级写下级;读写共端口时,仅靠端口隔离不能保留客户端直读又禁止直写,需确定方法级网关或服务端校验机制。 +- 允许多个独立实例,各自拥有身份、目录、状态与持久化路径。例如多个座舱中心及其音频实例;这不是同一逻辑服务的主备或多活,不共享 Registry 数据文件。 +- 当前 Registry 按 `terminal_mac.trim().to_ascii_lowercase()` 生成稳定 UUID v5,不重写 MAC 分隔符,也接受逻辑身份字符串。同一身份会更新同一条记录,不能将多个独立实例配置为同一身份。作用域、仿真世界标识与身份命名规则仍待协议化。 +- 开发和联调允许普通实体绕过聚合层直连 Registry;这不改变生产的作用域归属。生产中的全局独立终端直连 Registry 本身就是合法拓扑,不属于开发例外。 +- 部署时应校验唯一父节点、无环、作用域归属及独立存储;当前尚无自动拓扑校验。Terminal 只有一个中心地址和同一套监听/注册地址,不提供 NAT 发现或自动多中心注册。 + +## 8. 编码前仍需明确的协议与机制 + +以下业务方向已在第 7 节确定,但细节尚未决策。建议逐项形成协议契约与验收用例后,再实现 Dispatcher 和聚合路由,不能默认为已有保证。 + +| 编号 | 尚不明确的问题 | 需要固化的契约或验证点 | +| ---- | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | +| Q1 | 任务上下文如何传入各级中心,初始化和重调度如何划分会话? | 调度 API、任务/执行 ID、路由上下文的承载方式、幂等键、绑定释放和显式迁移;验证 init/start/stop 不因实时路由落到不同目标 | +| Q2 | 一个异构逻辑类型如何声明内部角色和资源依赖? | 必选/可选角色、命令与事件的目标展开、同名冲突、参数转换、能力版本;特别明确雷达/武器如何请求座舱级音频而不绕过树形控制链 | +| Q3 | 聚合状态、健康状态与可调度性如何计算? | 字段归并规则、缺失/过期阈值、时间戳与序列语义、采样频率;区分中心可服务、某角色离线、任务可运行,不把旧快照当新状态 | +| Q4 | 多目标部分失败、未知及取消的响应如何编码? | 逐目标执行身份、三态或等价结果模型、聚合层级、超时预算、查询与去重;不得因网络超时直接重发不可幂等操作 | +| Q5 | 如何建立可恢复的事件终态跟踪? | 执行代次、重复事件每轮结果、完成超时、取消确认、结果查询与保留期;解决 init 后实例号复用、终态丢失及旧句柄误关联 | +| Q6 | Dispatcher/子中心崩溃时记录和下游副作用如何对账? | 存储介质、写入顺序、恢复阶段、中心目录恢复/重注册、断线重订阅、遗留事件处置;持久化记录本身不提供恰好一次执行 | +| Q7 | 独立多实例与作用域唯一资源如何协调? | 仿真世界/座舱/实例身份、任务归属、不同 Dispatcher 的写入域、音频并发策略及全局资源的独占或共享规则;注册为一个条目并不自动形成资源锁 | +| Q8 | 如何强制统一写入口与树形归属? | 调用方身份、方法级读写授权、注册权限、父节点与环路校验;开发例外的启用范围,不能仅依赖内网可信假设 | +| Q9 | 首版任务携带的场景配置是什么? | 配置模式、标识/版本、大小限制、校验和逐角色初始化映射;后续 Data 接入时的兼容契约 | + +本次核对方式为源码、协议及组件契约对照,不宣称验证了未实现的调度行为。文档更新应检查本地链接、图块结构和新旧术语一致性;上述目标能力需在对应代码实现后补充行为测试。 diff --git a/log/Cargo.toml b/log/Cargo.toml new file mode 100644 index 0000000..ff3dc37 --- /dev/null +++ b/log/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "flysim-log" +version.workspace = true +edition.workspace = true +authors.workspace = true + +[dependencies] +log.workspace = true +tracing.workspace = true +tracing-log.workspace = true +tracing-subscriber.workspace = true +tracing-appender.workspace = true + +[dev-dependencies] +tempfile.workspace = true \ No newline at end of file diff --git a/log/README.md b/log/README.md new file mode 100644 index 0000000..5fea732 --- /dev/null +++ b/log/README.md @@ -0,0 +1,87 @@ +# FlySim Log + +`flysim-log` is the shared logging infrastructure crate in the `log/` workspace +directory. Import it as `flysim_log`; keep using the third-party `log` crate's +`log::info!`, `warn!` and `error!` macros for business records. + +It has no dependency on `proto`, Registry or Terminal, reads no environment +variables, and performs no initialization merely by being linked. + +## API And Ownership + +```rust +use flysim_log::{LoggingConfig, build_subscriber, install_log_bridge, install_subscriber, parse_level}; + +fn initialize() -> Result { + let config = LoggingConfig { + level: parse_level("info")?, + directory: "logs/my-service".into(), + file_prefix: "my-service".into(), + max_files: 10, + }; + let (subscriber, guard) = build_subscriber(&config)?; + install_log_bridge()?; + install_subscriber(subscriber)?; + Ok(guard) +} +``` + +Keep the returned guard alive until all producers have stopped and the final +record has been emitted. Dropping it drains the file worker during normal exit; +it does not uninstall global logging. Do not use `process::exit` to bypass it. + +- `LoggingConfig` selects level, directory, filename prefix and retention count. + Levels are `off/error/warn/info/debug/trace` (case-insensitive when parsed). + The directory/prefix must be nonempty, the count positive, and the prefix a + portable single filename component rather than a path. +- `build_subscriber` constructs a `tracing::Dispatch` and `LoggingGuard` without + installing globals. `build_with_writer` permits an injected console writer + for scoped tests or embedding. +- `install_log_bridge` installs `tracing-log::LogTracer` for `log` records; + `install_subscriber` installs the prepared tracing subscriber. Native tracing + fields and spans are supported as well. Do not also initialize `env_logger`. +- `stderr_subscriber` constructs a temporary console-only dispatcher. Registry + uses it after bridge installation to report failures before file logging is + ready. The caller supplies the contextual message and exit policy. +- `LoggingError` distinguishes invalid configuration, appender failure and + already-installed globals, preserving backend error sources. Components map + these errors into their own public/FFI error models. + +The two global installations are not an atomic operation and cannot be rolled +back. Serialize initialization with other host logging setup. A failed second +installation can leave the first global installed; drop the new guard on failure, +report the conflict, and never silently replace an existing logger/subscriber. + +## Output Contract + +Each record is written to stderr and a daily UTC file named +`.YYYY-MM-DD.log`. Both include timestamp, level and target; files never +contain ANSI codes. The default console writer detects terminal color support. +The chosen level filters both outputs. + +Retention removes old matching prefix/suffix files at initialization or rotation. +`max_files` is an upper bound, not an exact count or a number of days. Use a +dedicated directory per process. Daily rotation does not limit individual file +size and is driven by arriving records rather than an idle timer. + +File output uses an 8192-entry bounded queue with `lossy(false)`. Full queues +block producers; stderr is synchronous. Slow output can delay RPC or host +threads. Guard cleanup is not a durability guarantee against forced exit, disk +failure, a stalled writer or power loss. + +Registry retains the guard in its process entry point. Terminal retains it in +its FFI lifecycle state until explicit logging shutdown. Extracting this crate +does not make independently linked DLLs share Rust globals; keep a DLL that +installed global logging loaded until host process exit. + +## Tests + +Tests live under [tests/unit](tests/unit) and are loaded by the library's test-only +entry. They cover configuration, filtering, retention, append/flush and queue +backpressure. Registry keeps the end-to-end `log` bridge/dual-output test; +Terminal keeps isolated initialization-conflict and real DLL ABI tests. + +```powershell +cargo test -p flysim-log +cargo test -p registry -p terminal logging +``` diff --git a/log/src/config.rs b/log/src/config.rs new file mode 100644 index 0000000..596bd68 --- /dev/null +++ b/log/src/config.rs @@ -0,0 +1,43 @@ +use std::path::PathBuf; + +use crate::LoggingError; + +#[derive(Clone, Debug)] +pub struct LoggingConfig { + pub level: log::LevelFilter, + pub directory: PathBuf, + pub file_prefix: String, + pub max_files: usize, +} + +impl LoggingConfig { + pub fn validate(&self) -> Result<(), LoggingError> { + if self.directory.as_os_str().is_empty() || self.max_files == 0 { + return Err(LoggingError::InvalidConfig( + "log directory must be nonempty and file count positive", + )); + } + if self.file_prefix.trim().is_empty() + || self.file_prefix == "." + || self.file_prefix == ".." + || self + .file_prefix + .chars() + .any(|character| character.is_control() || "/\\:*?\"<>|".contains(character)) + { + return Err(LoggingError::InvalidConfig( + "log prefix must be a nonempty portable filename component", + )); + } + Ok(()) + } +} + +pub fn parse_level(value: &str) -> Result { + if value.trim().is_empty() { + return Err(LoggingError::InvalidConfig("log level must not be empty")); + } + value.trim().parse().map_err(|_| { + LoggingError::InvalidConfig("log level must be off, error, warn, info, debug or trace") + }) +} diff --git a/log/src/error.rs b/log/src/error.rs new file mode 100644 index 0000000..83b2ddc --- /dev/null +++ b/log/src/error.rs @@ -0,0 +1,38 @@ +use std::fmt; + +#[derive(Debug)] +pub enum LoggingError { + InvalidConfig(&'static str), + Appender(tracing_appender::rolling::InitError), + BridgeAlreadyInstalled(log::SetLoggerError), + SubscriberAlreadyInstalled(tracing::dispatcher::SetGlobalDefaultError), +} + +impl fmt::Display for LoggingError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidConfig(message) => formatter.write_str(message), + Self::Appender(error) => { + write!(formatter, "failed to initialize file logging: {error}") + } + Self::BridgeAlreadyInstalled(error) => { + write!(formatter, "a log logger is already installed: {error}") + } + Self::SubscriberAlreadyInstalled(error) => write!( + formatter, + "a tracing subscriber is already installed: {error}" + ), + } + } +} + +impl std::error::Error for LoggingError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::InvalidConfig(_) => None, + Self::Appender(error) => Some(error), + Self::BridgeAlreadyInstalled(error) => Some(error), + Self::SubscriberAlreadyInstalled(error) => Some(error), + } + } +} diff --git a/log/src/lib.rs b/log/src/lib.rs new file mode 100644 index 0000000..0190665 --- /dev/null +++ b/log/src/lib.rs @@ -0,0 +1,93 @@ +mod config; +mod error; + +use std::io::{self, IsTerminal}; + +use tracing::Dispatch; +use tracing_appender::non_blocking::{NonBlocking, WorkerGuard}; +use tracing_appender::rolling::{RollingFileAppender, Rotation}; +use tracing_log::AsTrace; +use tracing_subscriber::{fmt::MakeWriter, prelude::*}; + +pub use config::{LoggingConfig, parse_level}; +pub use error::LoggingError; + +#[must_use = "keep this guard alive until all logging has finished"] +pub struct LoggingGuard { + _worker: WorkerGuard, +} + +pub fn install_log_bridge() -> Result<(), LoggingError> { + tracing_log::LogTracer::init().map_err(LoggingError::BridgeAlreadyInstalled) +} + +pub fn install_subscriber(subscriber: Dispatch) -> Result<(), LoggingError> { + tracing::dispatcher::set_global_default(subscriber) + .map_err(LoggingError::SubscriberAlreadyInstalled) +} + +pub fn stderr_subscriber() -> Dispatch { + Dispatch::new( + tracing_subscriber::fmt() + .with_writer(io::stderr) + .with_ansi(io::stderr().is_terminal()) + .finish(), + ) +} + +pub fn build_subscriber(config: &LoggingConfig) -> Result<(Dispatch, LoggingGuard), LoggingError> { + build_with_writer(config, io::stderr, io::stderr().is_terminal()) +} + +pub fn build_with_writer( + config: &LoggingConfig, + console: W, + ansi: bool, +) -> Result<(Dispatch, LoggingGuard), LoggingError> +where + W: for<'writer> MakeWriter<'writer> + Send + Sync + 'static, +{ + config.validate()?; + let appender = RollingFileAppender::builder() + .rotation(Rotation::DAILY) + .filename_prefix(&config.file_prefix) + .filename_suffix("log") + .max_log_files(config.max_files) + .build(&config.directory) + .map_err(LoggingError::Appender)?; + let (writer, guard) = file_writer( + appender, + 8192, + &format!("{}-log-writer", config.file_prefix), + ); + let subscriber = tracing_subscriber::registry() + .with(config.level.as_trace()) + .with( + tracing_subscriber::fmt::layer() + .with_ansi(ansi) + .with_writer(console), + ) + .with( + tracing_subscriber::fmt::layer() + .with_ansi(false) + .with_writer(writer), + ); + Ok((Dispatch::new(subscriber), guard)) +} + +pub(crate) fn file_writer( + writer: W, + capacity: usize, + thread_name: &str, +) -> (NonBlocking, LoggingGuard) { + let (writer, worker) = tracing_appender::non_blocking::NonBlockingBuilder::default() + .buffered_lines_limit(capacity) + .lossy(false) + .thread_name(thread_name) + .finish(writer); + (writer, LoggingGuard { _worker: worker }) +} + +#[cfg(test)] +#[path = "../tests/unit/mod.rs"] +mod unit_tests; diff --git a/log/tests/unit/logging.rs b/log/tests/unit/logging.rs new file mode 100644 index 0000000..a9a9eb7 --- /dev/null +++ b/log/tests/unit/logging.rs @@ -0,0 +1,160 @@ +use crate::{LoggingConfig, build_with_writer, parse_level}; +use std::{io, path::Path}; + +fn config(directory: &Path, level: &str, max_files: usize) -> LoggingConfig { + LoggingConfig { + level: parse_level(level).unwrap(), + directory: directory.into(), + file_prefix: "registry".into(), + max_files, + } +} + +#[test] +fn validates_configuration_and_flushes_without_installing_globals() { + let directory = tempfile::tempdir().unwrap(); + let mut config = LoggingConfig { + level: parse_level("INFO").unwrap(), + directory: directory.path().into(), + file_prefix: "test".into(), + max_files: 10, + }; + let (subscriber, guard) = build_with_writer(&config, std::io::sink, false).unwrap(); + tracing::dispatcher::with_default(&subscriber, || { + tracing::info!("visible-record"); + tracing::debug!("hidden-record"); + }); + drop(guard); + let path = std::fs::read_dir(directory.path()) + .unwrap() + .next() + .unwrap() + .unwrap() + .path(); + let text = std::fs::read_to_string(path).unwrap(); + assert_eq!(text.matches("visible-record").count(), 1); + assert!(!text.contains("hidden-record")); + for prefix in ["", " ", "..", "../escape", "a\\b", "a:b"] { + config.file_prefix = prefix.into(); + assert!(config.validate().is_err()); + } + assert!(parse_level("").is_err()); + assert!(parse_level("verbose").is_err()); +} +#[test] +fn rotation_retention_off_and_reopen() { + let directory = tempfile::tempdir().unwrap(); + for day in 1..=12 { + std::fs::write( + directory + .path() + .join(format!("registry.2000-01-{day:02}.log")), + b"old", + ) + .unwrap(); + } + let unrelated = directory.path().join("terminal.keep.log"); + std::fs::write(&unrelated, b"keep").unwrap(); + let (subscriber, guard) = + crate::build_with_writer(&config(directory.path(), "info", 3), io::sink, false).unwrap(); + tracing::dispatcher::with_default(&subscriber, || tracing::info!("first-session")); + drop(guard); + let (subscriber, guard) = + crate::build_with_writer(&config(directory.path(), "info", 3), io::sink, false).unwrap(); + tracing::dispatcher::with_default(&subscriber, || tracing::info!("second-session")); + drop(guard); + let (subscriber, guard) = + crate::build_with_writer(&config(directory.path(), "off", 3), io::sink, false).unwrap(); + tracing::dispatcher::with_default(&subscriber, || tracing::error!("off-hidden")); + drop(guard); + let files = std::fs::read_dir(directory.path()) + .unwrap() + .map(|entry| entry.unwrap().path()) + .filter(|path| { + path.file_name() + .unwrap() + .to_string_lossy() + .starts_with("registry.") + }) + .collect::>(); + assert!(files.len() <= 3); + assert_eq!(std::fs::read(unrelated).unwrap(), b"keep"); + let text = files + .iter() + .map(|path| std::fs::read_to_string(path).unwrap()) + .collect::(); + assert_eq!(text.matches("first-session").count(), 1); + assert_eq!(text.matches("second-session").count(), 1); + assert!(!text.contains("off-hidden")); +} + +#[test] +fn invalid_logging_configuration_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + assert!(crate::parse_level("invalid").is_err()); + assert!( + crate::build_with_writer(&config(directory.path(), "info", 0), io::sink, false).is_err() + ); + let file = directory.path().join("not-a-directory"); + std::fs::write(&file, b"file").unwrap(); + assert!(crate::build_with_writer(&config(&file, "info", 10), io::sink, false).is_err()); +} + +#[test] +fn bounded_file_queue_applies_backpressure_without_dropping() { + use std::io::Write; + use std::sync::{Arc, Mutex, mpsc}; + use std::time::Duration; + + struct PausedWriter { + bytes: Arc>>, + entered: mpsc::Sender<()>, + release: Option>, + } + + impl Write for PausedWriter { + fn write(&mut self, bytes: &[u8]) -> io::Result { + if let Some(release) = self.release.take() { + self.entered.send(()).unwrap(); + release.recv_timeout(Duration::from_secs(3)).unwrap(); + } + self.bytes.lock().unwrap().extend_from_slice(bytes); + Ok(bytes.len()) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + } + + let bytes = Arc::new(Mutex::new(Vec::new())); + let (entered, wait_entered) = mpsc::channel(); + let (release, wait_release) = mpsc::channel(); + let (mut writer, guard) = crate::file_writer( + PausedWriter { + bytes: bytes.clone(), + entered, + release: Some(wait_release), + }, + 1, + "test-log-writer", + ); + writer.write_all(b"first\n").unwrap(); + wait_entered.recv_timeout(Duration::from_secs(1)).unwrap(); + writer.write_all(b"second\n").unwrap(); + let (started, wait_started) = mpsc::channel(); + let (completed, wait_completed) = mpsc::channel(); + let producer = std::thread::spawn(move || { + started.send(()).unwrap(); + writer.write_all(b"third\n").unwrap(); + completed.send(()).unwrap(); + }); + wait_started.recv_timeout(Duration::from_secs(1)).unwrap(); + let blocked = wait_completed + .recv_timeout(Duration::from_millis(30)) + .is_err(); + release.send(()).unwrap(); + producer.join().unwrap(); + drop(guard); + assert!(blocked); + assert_eq!(&*bytes.lock().unwrap(), b"first\nsecond\nthird\n"); +} diff --git a/log/tests/unit/mod.rs b/log/tests/unit/mod.rs new file mode 100644 index 0000000..1200190 --- /dev/null +++ b/log/tests/unit/mod.rs @@ -0,0 +1 @@ +mod logging; diff --git a/proto/Cargo.toml b/proto/Cargo.toml index 1d4b9e9..85194fe 100644 --- a/proto/Cargo.toml +++ b/proto/Cargo.toml @@ -9,6 +9,9 @@ connectrpc.workspace = true buffa.workspace = true buffa-types.workspace = true serde.workspace = true +axum.workspace = true +tokio.workspace = true +futures-util.workspace = true [build-dependencies] connectrpc-build.workspace = true diff --git a/proto/README.md b/proto/README.md new file mode 100644 index 0000000..c153112 --- /dev/null +++ b/proto/README.md @@ -0,0 +1,121 @@ +# Protocol And RPC Infrastructure + +This crate owns generated Protobuf types and reusable ConnectRPC transport and +Health mechanisms. It does not own simulation logic, terminal registration +policy, a Tokio runtime, process signals, logging initialization or persistence. + +## Generated Types + +[build.rs](build.rs) generates Center, Terminal, common messages and standard +gRPC Health types. Use `proto::control` and `proto::grpc`; the previous +`proto::proto::control` and `proto::proto::grpc` paths remain compatible aliases +to the same generated types. Do not edit generated files under `target`. +Data protocol generation and protocol wire definitions are unchanged. + +## Clients + +```rust +use std::time::Duration; +use proto::rpc::client::{CallOptions, RpcChannel, RpcClientOptions, RpcEndpoint}; + +async fn register(info: proto::control::TerminalInfo) + -> Result<(), Box> +{ + let endpoint = RpcEndpoint::from_host_port("127.0.0.1", 50051)?; + let channel = RpcChannel::connect(&endpoint, RpcClientOptions::default()).await?; + let response = channel.center_client().register_terminal_with_options( + info, CallOptions::default().with_timeout(Duration::from_secs(3)), + ).await?.into_owned(); + if !response.success { return Err(response.message.into()); } + Ok(()) +} +``` + +`RpcEndpoint` accepts DNS names, IPv4, and raw or bracketed IPv6 hosts with an +explicit nonzero port. `from_uri` requires an `http` origin with a valid explicit +port and no credentials, query or non-root path. Only plaintext HTTP/2 gRPC is +supported; unsupported schemes fail instead of silently downgrading to plaintext. +Listener port zero is still supported separately by Tokio's bind API. + +`RpcClientOptions` defaults to a three-second connection establishment timeout, +no default RPC deadline, and a 1024-entry transport buffer. The capacity is a +queue bound, not a business concurrency limit. Timeouts must be positive and +representable. The establishment budget covers the connection operation, with +the same bound configured for transport reconnects. HTTP/2 connection construction +may finish before a peer replies; response waiting is governed by RPC deadlines. + +`center_client`, `terminal_client` and `health_client` return the existing +generated clients sharing one transport. Their normal methods and `CallOptions` +remain available. Long-lived subscriptions have no short default deadline unless +the caller explicitly supplies one. This crate adds no automatic method retries +or connection pool; it retains the transport's own reconnect behavior. + +`health::check_health(endpoint, service_name, total_timeout)` bounds connection +and Check together and returns `Result`. It preserves +RPC error codes and unknown Protobuf enum values. Mapping failures to a business +status, retries, polling intervals and stale-result checks belong to the caller. + +## Servers And Streams + +`rpc::Router` re-exports the existing ConnectRPC router. Register generated service +implementations normally with `add_service`, then call +`rpc::server::serve(listener, router, shutdown_future)` on an existing runtime. +The helper builds the Axum adapter and graceful-shutdown future; it does not bind, +spawn, register the service with a center, install logs, or impose an exit timeout. +The caller retains ownership of server tasks and shutdown policy. + +`rpc::stream::watch_stream(receiver, shutdown)` sends an initial latest snapshot, +then each observed watch update. It marks the initial value consumed and gives +shutdown priority. Closed shutdown/data channels end the stream. Slow consumers +may skip intermediate values; there is no history queue or implicit equality +filter. The sender decides when an application snapshot has changed. + +## Shared Health + +```rust +use proto::rpc::health::{HealthReporter, HealthService, ServingStatus}; + +let reporter = HealthReporter::new(); +reporter.set_statuses(&[ + ("", ServingStatus::NOT_SERVING), + ("control.Center", ServingStatus::NOT_SERVING), +])?; +let (shutdown, receiver) = tokio::sync::watch::channel(false); +let health = HealthService::new(&reporter, receiver); +let router = proto::rpc::Router::new().add_service(std::sync::Arc::new(health)); +``` + +`HealthReporter` is the state owner; it starts with no registered names. Reporters +can be cloned. `set_statuses` atomically updates a batch, `remove_service` removes +a name, and `status` reads it. Repeating a state is a no-op. Registered statuses +are UNKNOWN, SERVING and NOT_SERVING; SERVICE_UNKNOWN is reserved for absent names. +Empty service name `""` is explicit state, not an automatic aggregate of others. + +`HealthService` holds receivers only and implements the generated `Health` trait: + +- Check returns the named state, or gRPC NotFound for an unregistered name. +- Watch immediately returns the named state (SERVICE_UNKNOWN if absent), and + follows registration, changes, removal and re-registration on that same stream. +- Only the selected service's visible state changes produce records. Watching + arbitrary unknown names does not permanently add them to the status table. +- Shutdown, a closed shutdown channel or loss of all reporters ends the stream. + Publish NOT_SERVING before shutdown when appropriate, but do not assume every + slow client receives the final state before stream termination. + +Reporter lifetime is independent of a single server run. For a restart, construct +a new HealthService with the retained reporter and the new shutdown receiver. +Do not reuse the old closed signal. Components define readiness: Terminal uses +its Ready lifecycle; Registry reports its own service readiness independently of +downstream terminals. No business crate is a dependency of this crate. + +## Verify + +Tests are grouped under `tests/unit` and `tests/integration`, loaded by +[src/lib.rs](src/lib.rs). They exercise address validation, compatibility aliases, +watch shutdown/latest-value semantics, real Health RPCs, dynamic registrations, +error-code preservation and deadlines. + +```powershell +cargo test -p proto +cargo test -p registry -p terminal +``` diff --git a/proto/src/lib.rs b/proto/src/lib.rs index 0b26f66..96dd8f4 100644 --- a/proto/src/lib.rs +++ b/proto/src/lib.rs @@ -1,3 +1,14 @@ pub mod proto { connectrpc::include_generated!("proto_gen.rs"); } + +pub use proto::{control, grpc}; +pub mod rpc; + +#[cfg(test)] +#[path = "../tests/unit/mod.rs"] +mod unit_tests; + +#[cfg(test)] +#[path = "../tests/integration/mod.rs"] +mod integration_tests; diff --git a/proto/src/rpc/client.rs b/proto/src/rpc/client.rs new file mode 100644 index 0000000..ad9b2b5 --- /dev/null +++ b/proto/src/rpc/client.rs @@ -0,0 +1,158 @@ +use std::net::Ipv6Addr; +use std::time::{Duration, Instant}; + +use axum::http::Uri; +use connectrpc::Protocol; +use connectrpc::client::{ClientConfig, Http2Connection, SharedHttp2Connection}; + +use super::RpcError; +use crate::control::{CenterClient, TerminalClient}; +use crate::grpc::health::v1::HealthClient; + +pub use connectrpc::client::CallOptions; +pub type CenterRpcClient = CenterClient; +pub type TerminalRpcClient = TerminalClient; +pub type HealthRpcClient = HealthClient; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RpcEndpoint(Uri); + +impl RpcEndpoint { + pub fn from_host_port(host: &str, port: u16) -> Result { + if port == 0 || host.is_empty() || host.trim() != host { + return Err(RpcError::InvalidEndpoint( + "host must be nonempty and port nonzero".into(), + )); + } + let literal = host + .strip_prefix('[') + .and_then(|value| value.strip_suffix(']')) + .unwrap_or(host); + let authority = if let Ok(address) = literal.parse::() { + format!("[{address}]:{port}") + } else { + if !host + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || b".-_".contains(&byte)) + { + return Err(RpcError::InvalidEndpoint( + "host must be a DNS name, IPv4 or IPv6 address".into(), + )); + } + format!("{host}:{port}") + }; + Uri::builder() + .scheme("http") + .authority(authority) + .path_and_query("/") + .build() + .map(Self) + .map_err(|error| RpcError::InvalidEndpoint(error.to_string())) + } + + pub fn from_uri(uri: Uri) -> Result { + if uri.scheme_str() != Some("http") + || uri + .path_and_query() + .is_some_and(|path| path.as_str() != "/" && !path.as_str().is_empty()) + || uri + .authority() + .is_some_and(|authority| authority.as_str().contains('@')) + { + return Err(RpcError::InvalidEndpoint( + "expected http origin without credentials, path or query".into(), + )); + } + let host = uri + .host() + .ok_or_else(|| RpcError::InvalidEndpoint("missing host".into()))?; + let port = uri + .port_u16() + .ok_or_else(|| RpcError::InvalidEndpoint("explicit valid port is required".into()))?; + Self::from_host_port(host, port) + } + + pub fn uri(&self) -> &Uri { + &self.0 + } +} + +#[derive(Clone, Debug)] +pub struct RpcClientOptions { + pub connect_timeout: Duration, + pub request_timeout: Option, + pub buffer_capacity: usize, +} + +impl Default for RpcClientOptions { + fn default() -> Self { + Self { + connect_timeout: Duration::from_secs(3), + request_timeout: None, + buffer_capacity: 1024, + } + } +} + +pub(crate) fn validate_duration(duration: Duration) -> Result<(), RpcError> { + if duration.is_zero() || Instant::now().checked_add(duration).is_none() { + Err(RpcError::InvalidOptions( + "timeouts must be positive and representable", + )) + } else { + Ok(()) + } +} + +#[derive(Clone)] +pub struct RpcChannel { + transport: SharedHttp2Connection, + config: ClientConfig, +} + +impl RpcChannel { + pub async fn connect( + endpoint: &RpcEndpoint, + options: RpcClientOptions, + ) -> Result { + validate_duration(options.connect_timeout)?; + if let Some(timeout) = options.request_timeout { + validate_duration(timeout)?; + } + if options.buffer_capacity == 0 + || options.buffer_capacity > tokio::sync::Semaphore::MAX_PERMITS + { + return Err(RpcError::InvalidOptions( + "invalid connection buffer capacity", + )); + } + let connection = tokio::time::timeout( + options.connect_timeout, + Http2Connection::builder() + .establishment_timeout(options.connect_timeout) + .tcp_connect_timeout(options.connect_timeout) + .connect_plaintext(endpoint.0.clone()), + ) + .await + .map_err(RpcError::ConnectTimeout)? + .map_err(RpcError::Connect)?; + let mut config = ClientConfig::new(endpoint.0.clone()).with_protocol(Protocol::Grpc); + if let Some(timeout) = options.request_timeout { + config = config.with_default_timeout(timeout); + } + Ok(Self { + transport: connection.shared(options.buffer_capacity), + config, + }) + } + + pub fn center_client(&self) -> CenterRpcClient { + CenterClient::new(self.transport.clone(), self.config.clone()) + } + pub fn terminal_client(&self) -> TerminalRpcClient { + TerminalClient::new(self.transport.clone(), self.config.clone()) + } + pub fn health_client(&self) -> HealthRpcClient { + HealthClient::new(self.transport.clone(), self.config.clone()) + } +} diff --git a/proto/src/rpc/error.rs b/proto/src/rpc/error.rs new file mode 100644 index 0000000..f3991d4 --- /dev/null +++ b/proto/src/rpc/error.rs @@ -0,0 +1,38 @@ +use std::fmt; + +#[derive(Debug)] +pub enum RpcError { + InvalidEndpoint(String), + InvalidOptions(&'static str), + InvalidHealthStatus, + Connect(connectrpc::ConnectError), + ConnectTimeout(tokio::time::error::Elapsed), + Call(connectrpc::ConnectError), + HealthTimeout(tokio::time::error::Elapsed), +} + +impl fmt::Display for RpcError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidEndpoint(message) => write!(formatter, "invalid RPC endpoint: {message}"), + Self::InvalidOptions(message) => write!(formatter, "invalid RPC options: {message}"), + Self::InvalidHealthStatus => { + formatter.write_str("SERVICE_UNKNOWN is reserved for unregistered Health services") + } + Self::Connect(error) => write!(formatter, "RPC connection failed: {error}"), + Self::ConnectTimeout(error) => write!(formatter, "RPC connection timed out: {error}"), + Self::Call(error) => write!(formatter, "RPC call failed: {error}"), + Self::HealthTimeout(error) => write!(formatter, "health check timed out: {error}"), + } + } +} + +impl std::error::Error for RpcError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Connect(error) | Self::Call(error) => Some(error), + Self::ConnectTimeout(error) | Self::HealthTimeout(error) => Some(error), + _ => None, + } + } +} diff --git a/proto/src/rpc/health.rs b/proto/src/rpc/health.rs new file mode 100644 index 0000000..eb77be4 --- /dev/null +++ b/proto/src/rpc/health.rs @@ -0,0 +1,176 @@ +use std::collections::HashMap; +use std::time::Duration; + +use connectrpc::{ + ConnectError, ErrorCode, RequestContext, Response, ServiceRequest, ServiceResult, ServiceStream, +}; +use futures_util::{Stream, stream}; +use tokio::sync::watch; + +use super::{ + RpcError, + client::{RpcChannel, RpcClientOptions, RpcEndpoint, validate_duration}, +}; +pub use crate::grpc::health::v1::health_check_response::ServingStatus; +use crate::grpc::health::v1::{Health, HealthCheckRequest, HealthCheckResponse}; + +#[derive(Clone)] +pub struct HealthReporter { + states: watch::Sender>, +} + +impl Default for HealthReporter { + fn default() -> Self { + Self::new() + } +} + +impl HealthReporter { + pub fn new() -> Self { + Self { + states: watch::channel(HashMap::new()).0, + } + } + + pub fn set_status(&self, service: &str, status: ServingStatus) -> Result<(), RpcError> { + self.set_statuses(&[(service, status)]) + } + + pub fn set_statuses(&self, updates: &[(&str, ServingStatus)]) -> Result<(), RpcError> { + if updates + .iter() + .any(|(_, status)| *status == ServingStatus::SERVICE_UNKNOWN) + { + return Err(RpcError::InvalidHealthStatus); + } + self.states.send_if_modified(|states| { + let mut next = states.clone(); + for (service, status) in updates { + next.insert((*service).to_owned(), *status); + } + if *states == next { + return false; + } + *states = next; + true + }); + Ok(()) + } + + pub fn remove_service(&self, service: &str) { + self.states + .send_if_modified(|states| states.remove(service).is_some()); + } + + pub fn status(&self, service: &str) -> Option { + self.states.borrow().get(service).copied() + } +} + +#[derive(Clone)] +pub struct HealthService { + states: watch::Receiver>, + shutdown: watch::Receiver, +} + +impl HealthService { + pub fn new(reporter: &HealthReporter, shutdown: watch::Receiver) -> Self { + Self { + states: reporter.states.subscribe(), + shutdown, + } + } + + fn responses( + &self, + service: String, + ) -> impl Stream> + Send + 'static { + stream::unfold( + (self.states.clone(), self.shutdown.clone(), service, None), + |(mut states, mut shutdown, service, mut previous)| async move { + loop { + if *shutdown.borrow() || shutdown.has_changed().is_err() { + return None; + } + let status = states + .borrow_and_update() + .get(&service) + .copied() + .unwrap_or(ServingStatus::SERVICE_UNKNOWN); + if previous != Some(status) { + previous = Some(status); + let response = HealthCheckResponse { + status: status.into(), + ..Default::default() + }; + return Some((Ok(response), (states, shutdown, service, previous))); + } + tokio::select! { + biased; + _ = shutdown.wait_for(|stopped| *stopped) => return None, + changed = states.changed() => { if changed.is_err() { return None; } } + } + } + }, + ) + } +} + +#[allow(refining_impl_trait)] +impl Health for HealthService { + async fn check( + &self, + _: RequestContext, + request: ServiceRequest<'_, HealthCheckRequest>, + ) -> ServiceResult { + let service = request.to_owned_message().service; + let status = self + .states + .borrow() + .get(&service) + .copied() + .ok_or_else(|| ConnectError::new(ErrorCode::NotFound, "unknown service"))?; + Response::ok(HealthCheckResponse { + status: status.into(), + ..Default::default() + }) + } + + async fn watch( + &self, + _: RequestContext, + request: ServiceRequest<'_, HealthCheckRequest>, + ) -> ServiceResult> { + Response::stream_ok(self.responses(request.to_owned_message().service)) + } +} + +pub async fn check_health( + endpoint: &RpcEndpoint, + service: &str, + total_timeout: Duration, +) -> Result { + validate_duration(total_timeout)?; + tokio::time::timeout(total_timeout, async { + let channel = RpcChannel::connect( + endpoint, + RpcClientOptions { + connect_timeout: total_timeout, + request_timeout: None, + buffer_capacity: 1, + }, + ) + .await?; + channel + .health_client() + .check(HealthCheckRequest { + service: service.into(), + ..Default::default() + }) + .await + .map(|response| response.into_owned()) + .map_err(RpcError::Call) + }) + .await + .map_err(RpcError::HealthTimeout)? +} diff --git a/proto/src/rpc/mod.rs b/proto/src/rpc/mod.rs new file mode 100644 index 0000000..69d4dd9 --- /dev/null +++ b/proto/src/rpc/mod.rs @@ -0,0 +1,8 @@ +pub mod client; +pub mod error; +pub mod health; +pub mod server; +pub mod stream; + +pub use connectrpc::Router; +pub use error::RpcError; diff --git a/proto/src/rpc/server.rs b/proto/src/rpc/server.rs new file mode 100644 index 0000000..a9e8c04 --- /dev/null +++ b/proto/src/rpc/server.rs @@ -0,0 +1,12 @@ +use std::{future::Future, io}; + +pub async fn serve( + listener: tokio::net::TcpListener, + router: connectrpc::Router, + shutdown: impl Future + Send + 'static, +) -> io::Result<()> { + let app = axum::Router::new().fallback_service(router.into_axum_service()); + axum::serve(listener, app) + .with_graceful_shutdown(shutdown) + .await +} diff --git a/proto/src/rpc/stream.rs b/proto/src/rpc/stream.rs new file mode 100644 index 0000000..95a5ab1 --- /dev/null +++ b/proto/src/rpc/stream.rs @@ -0,0 +1,29 @@ +use connectrpc::ConnectError; +use futures_util::{Stream, stream}; +use tokio::sync::watch; + +pub 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() || shutdown.has_changed().is_err() { + return None; + } + if !initial { + tokio::select! { + biased; + _ = shutdown.wait_for(|stopped| *stopped) => return None, + changed = receiver.changed() => { if changed.is_err() { return None; } } + } + } + let item = receiver.borrow_and_update().clone(); + Some((Ok(item), (receiver, shutdown, false))) + }, + ) +} diff --git a/proto/tests/integration/health.rs b/proto/tests/integration/health.rs new file mode 100644 index 0000000..df458f9 --- /dev/null +++ b/proto/tests/integration/health.rs @@ -0,0 +1,312 @@ +use std::sync::Arc; +use std::time::Duration; + +use crate::grpc::health::v1::HealthCheckRequest; +use crate::rpc::{ + Router, RpcError, + client::{CallOptions, RpcChannel, RpcClientOptions, RpcEndpoint}, + health::{HealthReporter, HealthService, ServingStatus, check_health}, + server, +}; +use connectrpc::ErrorCode; +use tokio::sync::watch; + +async fn launch() -> ( + HealthReporter, + watch::Sender, + RpcChannel, + RpcEndpoint, + tokio::task::JoinHandle>, +) { + let reporter = HealthReporter::new(); + let (stop, mut shutdown) = watch::channel(false); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = + RpcEndpoint::from_host_port("127.0.0.1", listener.local_addr().unwrap().port()).unwrap(); + let router = + Router::new().add_service(Arc::new(HealthService::new(&reporter, shutdown.clone()))); + let task = tokio::spawn(server::serve(listener, router, async move { + let _ = shutdown.wait_for(|stopped| *stopped).await; + })); + let channel = RpcChannel::connect(&endpoint, RpcClientOptions::default()) + .await + .unwrap(); + (reporter, stop, channel, endpoint, task) +} + +#[tokio::test] +async fn dynamic_service_watch_and_independent_statuses() { + tokio::time::timeout(Duration::from_secs(5), async { + let (reporter, stop, channel, endpoint, task) = launch().await; + let client = channel.health_client(); + let error = client + .check(HealthCheckRequest::default()) + .await + .unwrap_err(); + assert_eq!(error.code, ErrorCode::NotFound); + let probe = check_health(&endpoint, "", Duration::from_secs(1)) + .await + .unwrap_err(); + assert!(matches!(probe, RpcError::Call(error) if error.code == ErrorCode::NotFound)); + let mut stream = client + .watch(HealthCheckRequest { + service: "dynamic".into(), + ..Default::default() + }) + .await + .unwrap(); + assert_eq!( + stream + .message() + .await + .unwrap() + .unwrap() + .to_owned_message() + .status, + ServingStatus::SERVICE_UNKNOWN + ); + assert!(reporter.status("dynamic").is_none()); + reporter.set_status("", ServingStatus::NOT_SERVING).unwrap(); + reporter + .set_status("dynamic", ServingStatus::SERVING) + .unwrap(); + assert_eq!( + stream + .message() + .await + .unwrap() + .unwrap() + .to_owned_message() + .status, + ServingStatus::SERVING + ); + assert_eq!( + check_health(&endpoint, "", Duration::from_secs(1)) + .await + .unwrap() + .status, + ServingStatus::NOT_SERVING + ); + reporter + .set_status("dynamic", ServingStatus::SERVING) + .unwrap(); + reporter + .set_status("other", ServingStatus::SERVING) + .unwrap(); + assert!( + tokio::time::timeout(Duration::from_millis(20), stream.message()) + .await + .is_err() + ); + reporter + .set_status("dynamic", ServingStatus::NOT_SERVING) + .unwrap(); + assert_eq!( + stream + .message() + .await + .unwrap() + .unwrap() + .to_owned_message() + .status, + ServingStatus::NOT_SERVING + ); + reporter.remove_service("dynamic"); + assert_eq!( + stream + .message() + .await + .unwrap() + .unwrap() + .to_owned_message() + .status, + ServingStatus::SERVICE_UNKNOWN + ); + reporter + .set_status("dynamic", ServingStatus::UNKNOWN) + .unwrap(); + assert_eq!( + stream + .message() + .await + .unwrap() + .unwrap() + .to_owned_message() + .status, + ServingStatus::UNKNOWN + ); + assert!( + reporter + .set_statuses(&[ + ("dynamic", ServingStatus::SERVING), + ("invalid", ServingStatus::SERVICE_UNKNOWN) + ]) + .is_err() + ); + assert_eq!(reporter.status("dynamic"), Some(ServingStatus::UNKNOWN)); + drop(reporter); + assert!(stream.message().await.unwrap().is_none()); + stop.send_replace(true); + task.await.unwrap().unwrap(); + }) + .await + .unwrap(); +} + +#[tokio::test] +async fn shutdown_and_explicit_stream_deadline() { + tokio::time::timeout(Duration::from_secs(5), async { + let (reporter, stop, channel, _, task) = launch().await; + let client = channel.health_client(); + let mut ordinary = client.watch(HealthCheckRequest::default()).await.unwrap(); + ordinary.message().await.unwrap().unwrap(); + let mut limited = client + .watch_with_options( + HealthCheckRequest::default(), + CallOptions::default().with_timeout(Duration::from_millis(30)), + ) + .await + .unwrap(); + limited.message().await.unwrap().unwrap(); + assert_eq!( + limited.message().await.unwrap_err().code, + ErrorCode::DeadlineExceeded + ); + reporter.set_status("", ServingStatus::SERVING).unwrap(); + assert_eq!( + ordinary + .message() + .await + .unwrap() + .unwrap() + .to_owned_message() + .status, + ServingStatus::SERVING + ); + stop.send_replace(true); + assert!(ordinary.message().await.unwrap().is_none()); + task.await.unwrap().unwrap(); + }) + .await + .unwrap(); +} + +#[tokio::test] +async fn connection_and_probe_budgets_are_bounded() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = + RpcEndpoint::from_host_port("127.0.0.1", listener.local_addr().unwrap().port()).unwrap(); + let accept = tokio::spawn(async move { + let (socket, _) = listener.accept().await.unwrap(); + std::future::pending::<()>().await; + drop(socket); + }); + let timeout = Duration::from_millis(30); + let result = tokio::time::timeout( + Duration::from_secs(1), + RpcChannel::connect( + &endpoint, + RpcClientOptions { + connect_timeout: timeout, + ..Default::default() + }, + ), + ) + .await + .unwrap(); + match result { + Ok(channel) => { + let response = tokio::time::timeout( + Duration::from_secs(1), + channel.health_client().check_with_options( + HealthCheckRequest::default(), + CallOptions::default().with_timeout(timeout), + ), + ) + .await + .unwrap(); + assert!(matches!(response, Err(error) if error.code == ErrorCode::DeadlineExceeded)); + } + Err(RpcError::ConnectTimeout(_) | RpcError::Connect(_)) => {} + Err(error) => panic!("unexpected connect error: {error}"), + } + accept.abort(); + let _ = accept.await; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = + RpcEndpoint::from_host_port("127.0.0.1", listener.local_addr().unwrap().port()).unwrap(); + assert!( + tokio::time::timeout(Duration::from_secs(1), check_health(&endpoint, "", timeout)) + .await + .unwrap() + .is_err() + ); + drop(listener); + assert!(matches!( + check_health(&endpoint, "", timeout).await, + Err(RpcError::Connect(_)) + )); +} + +enum ProbeBehavior { + Unimplemented, + NoResponse, + FutureStatus, +} + +#[allow(refining_impl_trait)] +impl crate::grpc::health::v1::Health for ProbeBehavior { + async fn check( + &self, + _: connectrpc::RequestContext, + _: connectrpc::ServiceRequest<'_, HealthCheckRequest>, + ) -> connectrpc::ServiceResult { + use buffa::Message; + match self { + Self::Unimplemented => Err(connectrpc::ConnectError::new( + ErrorCode::Unimplemented, + "not supported", + )), + Self::NoResponse => std::future::pending().await, + Self::FutureStatus => connectrpc::Response::ok( + crate::grpc::health::v1::HealthCheckResponse::decode_from_slice(&[8, 99]).unwrap(), + ), + } + } + + async fn watch( + &self, + _: connectrpc::RequestContext, + _: connectrpc::ServiceRequest<'_, HealthCheckRequest>, + ) -> connectrpc::ServiceResult< + connectrpc::ServiceStream, + > { + Err(connectrpc::ConnectError::new( + ErrorCode::Unimplemented, + "not supported", + )) + } +} + +#[tokio::test] +async fn probes_preserve_rpc_codes_unknown_enum_values_and_total_deadline() { + use buffa::Message; + tokio::time::timeout(Duration::from_secs(5), async { + for (behavior, expected) in [(ProbeBehavior::Unimplemented, "unimplemented"), (ProbeBehavior::FutureStatus, "future"), (ProbeBehavior::NoResponse, "timeout")] { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = RpcEndpoint::from_host_port("127.0.0.1", listener.local_addr().unwrap().port()).unwrap(); + let (stop, mut shutdown) = watch::channel(false); + let router = Router::new().add_service(Arc::new(behavior)); + let task = tokio::spawn(server::serve(listener, router, async move { let _ = shutdown.wait_for(|stopped| *stopped).await; })); + let response = check_health(&endpoint, "", Duration::from_millis(100)).await; + match expected { + "unimplemented" => assert!(matches!(response, Err(RpcError::Call(error)) if error.code == ErrorCode::Unimplemented)), + "future" => assert_eq!(response.unwrap().encode_to_vec(), [8, 99]), + _ => assert!(matches!(response, Err(RpcError::HealthTimeout(_)))), + } + stop.send_replace(true); + if expected == "timeout" { task.abort(); let _ = task.await; } + else { task.await.unwrap().unwrap(); } + } + }).await.unwrap(); +} diff --git a/proto/tests/integration/mod.rs b/proto/tests/integration/mod.rs new file mode 100644 index 0000000..2f47ceb --- /dev/null +++ b/proto/tests/integration/mod.rs @@ -0,0 +1 @@ +mod health; diff --git a/proto/tests/unit/client.rs b/proto/tests/unit/client.rs new file mode 100644 index 0000000..5c80518 --- /dev/null +++ b/proto/tests/unit/client.rs @@ -0,0 +1,68 @@ +use crate::rpc::client::{RpcChannel, RpcClientOptions, RpcEndpoint}; +use std::time::Duration; + +#[test] +fn validates_endpoints_and_preserves_compatibility_exports() { + let defaults = RpcClientOptions::default(); + assert_eq!(defaults.connect_timeout, Duration::from_secs(3)); + assert!(defaults.request_timeout.is_none()); + for host in ["localhost", "127.0.0.1", "::1", "[::1]"] { + let endpoint = RpcEndpoint::from_host_port(host, 1234).unwrap(); + assert_eq!(endpoint.uri().port_u16(), Some(1234)); + assert_eq!( + RpcEndpoint::from_uri(endpoint.uri().clone()).unwrap(), + endpoint + ); + } + for host in [ + "", + " foo ", + "user@host", + "host/path", + "host?query", + "host:99", + "[foo]", + ] { + assert!(RpcEndpoint::from_host_port(host, 1234).is_err()); + } + assert!(RpcEndpoint::from_host_port("localhost", 0).is_err()); + for uri in [ + "https://localhost:99/", + "http://localhost/", + "http://localhost:0/", + "http://localhost:65536/", + "http://localhost:99/path", + "http://localhost:99/?q=1", + "http://user@localhost:99/", + ] { + assert!( + RpcEndpoint::from_uri(uri.parse().unwrap()).is_err(), + "{uri}" + ); + } + let _: crate::control::TerminalInfo = crate::proto::control::TerminalInfo::default(); +} + +#[tokio::test] +async fn invalid_options_fail_before_connecting() { + let endpoint = RpcEndpoint::from_host_port("localhost", 1234).unwrap(); + for options in [ + RpcClientOptions { + connect_timeout: Duration::ZERO, + ..Default::default() + }, + RpcClientOptions { + request_timeout: Some(Duration::ZERO), + ..Default::default() + }, + RpcClientOptions { + buffer_capacity: 0, + ..Default::default() + }, + ] { + assert!(matches!( + RpcChannel::connect(&endpoint, options).await, + Err(crate::rpc::RpcError::InvalidOptions(_)) + )); + } +} diff --git a/proto/tests/unit/mod.rs b/proto/tests/unit/mod.rs new file mode 100644 index 0000000..f4c85ae --- /dev/null +++ b/proto/tests/unit/mod.rs @@ -0,0 +1,2 @@ +mod client; +mod stream; diff --git a/proto/tests/unit/stream.rs b/proto/tests/unit/stream.rs new file mode 100644 index 0000000..0c6c1ff --- /dev/null +++ b/proto/tests/unit/stream.rs @@ -0,0 +1,42 @@ +use crate::rpc::stream::watch_stream; +use futures_util::StreamExt; +use tokio::sync::watch; + +#[tokio::test] +async fn initial_latest_multiple_subscribers_and_shutdown() { + let (sender, receiver) = watch::channel(0); + let (stop, shutdown) = watch::channel(false); + let mut first = Box::pin(watch_stream(receiver.clone(), shutdown.clone())); + let mut second = Box::pin(watch_stream(receiver, shutdown.clone())); + sender.send_replace(1); + assert_eq!(first.next().await.unwrap().unwrap(), 1); + assert_eq!(second.next().await.unwrap().unwrap(), 1); + sender.send_replace(2); + sender.send_replace(3); + assert_eq!(first.next().await.unwrap().unwrap(), 3); + assert_eq!(second.next().await.unwrap().unwrap(), 3); + stop.send_replace(true); + assert!(first.next().await.is_none()); + assert!(second.next().await.is_none()); + assert!( + Box::pin(watch_stream(sender.subscribe(), shutdown)) + .next() + .await + .is_none() + ); +} + +#[tokio::test] +async fn channel_closure_ends_stream() { + let (sender, receiver) = watch::channel(0); + let (stop, shutdown) = watch::channel(false); + let mut stream = Box::pin(watch_stream(receiver, shutdown)); + stream.next().await.unwrap().unwrap(); + drop(sender); + assert!(stream.next().await.is_none()); + let (sender, receiver) = watch::channel(0); + let mut stream = Box::pin(watch_stream(receiver, stop.subscribe())); + drop(stop); + assert!(stream.next().await.is_none()); + drop(sender); +} diff --git a/registry/Cargo.toml b/registry/Cargo.toml index e6e73b5..29d09a5 100644 --- a/registry/Cargo.toml +++ b/registry/Cargo.toml @@ -9,12 +9,15 @@ 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 +log.workspace = true +tracing.workspace = true +flysim-log.workspace = true [dev-dependencies] terminal = { path = "../terminal" } +axum.workspace = true diff --git a/registry/README.md b/registry/README.md index 7f9f399..20e6a5b 100644 --- a/registry/README.md +++ b/registry/README.md @@ -18,19 +18,59 @@ 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` | +- `HOST`: `0.0.0.0`. +- `PORT`: `50051`. +- `DATA_PATH`: `registry/data/terminals.bin`. +- `HEALTH_INTERVAL_SECS`: `10`. +- `HEALTH_TIMEOUT_SECS`: `3`. +- `DATA_FILE_COUNT`: `10`, independent of logging retention. +- `LOG_LEVEL`: `info`. +- `LOG_DIR`: `logs/registry`. +- `LOG_MAX_FILES`: `10`. 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. +## Logging + +The backend is provided by [flysim-log](../log/README.md). This component only +maps configuration/errors and controls the process-owned logging guard. + +Business messages use `log::info!`, `log::warn!` and `log::error!`. `tracing-log` +forwards these records to `tracing-subscriber`; native tracing events/spans use +the same subscriber. `env_logger` is not initialized. Each event is formatted +once for stderr and once for the file, with UTC timestamp, level and target. +Native tracing fields are preserved. Files contain no ANSI color sequences; +stderr colors are enabled only when connected to a terminal. + +`LOG_LEVEL` accepts `off`, `error`, `warn`, `info`, `debug` or `trace`, ignoring +case. `LOG_DIR` must be nonempty and `LOG_MAX_FILES` must be positive. Environment +variables override `.env` values; `RUST_LOG` is not used by this configuration. +Relative log paths resolve against the working directory. + +Files are named `registry.YYYY-MM-DD.log` and roll daily on UTC boundaries when +new records arrive. The appender retains at most `LOG_MAX_FILES` matching files; +this is a file-count cap, not a guarantee of exactly that many files or days. +Old matching files can be removed on initialization and rotation. Use a dedicated +directory per process: do not share it with another registry or place unrelated +files with the same `registry` prefix and `.log` suffix there. The default `logs/` +directory is git-ignored. Rotation does not cap individual file size. + +File writes use an 8192-entry bounded queue and a worker thread. The producer +blocks when the queue is full instead of dropping logs; stderr writes are +synchronous. Slow storage or consoles can therefore delay the calling thread. +The worker guard is retained until shutdown and dropped after the final log +record to drain buffered writes. This is not a durability guarantee for disk +errors, process termination, power loss, or a stalled writer at shutdown. + +Logging is initialized before snapshot recovery, so corruption warnings reach +both outputs. Configuration/appender initialization failures are reported using +`log` through a temporary stderr-only subscriber and exit unsuccessfully. +Runtime failures are logged before releasing the file worker. The binary owns +global logging; library consumers must configure their own logging explicitly. + ## Directory Contract - Registration requires a nonempty host, a reachable port in `1..=65535`, and a @@ -58,7 +98,7 @@ 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. +as warning logs 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 @@ -74,6 +114,19 @@ authorizes outbound health connections to the supplied host and port. ## Health +Registry exposes `grpc.health.v1.Health` on the same port as `control.Center`, +using [proto's shared Health service](../proto/README.md). Empty service name and +`control.Center` start as NOT_SERVING and become SERVING once the directory is +loaded, the listener is bound and the serving runtime starts. Shutdown marks +both NOT_SERVING before signaling streams to close. Readiness and shutdown use +the same state lock, so a concurrent startup cannot undo shutdown. + +This describes Registry readiness, not downstream health: an empty directory +or offline terminals do not make Registry unhealthy. It does not continuously +probe disk writability. Background monitor/server failures trigger the existing +shutdown path. A slow watcher is not guaranteed to receive the final NOT_SERVING +message before the stream ends. + 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. @@ -81,6 +134,10 @@ 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. +Endpoint construction, the single Health call, server hosting and watch streams +come from `proto::rpc`. Polling, concurrency, error-to-NOT_SERVING mapping, +registration business logic and stale-result checks remain in Registry. + 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` @@ -90,7 +147,7 @@ stream from Watch. Health describes service readiness, not simulation state. All test implementations and test-only helpers live under `tests/`: -- `tests/unit/{config,health,rpc,service,storage}.rs` contains module-level tests. +- `tests/unit/{config,health,logging,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) @@ -109,6 +166,7 @@ Both test groups run in the library test target; there is no standalone ```powershell cargo test -p registry cargo test -p registry --lib unit_tests +cargo test -p registry --lib unit_tests::logging cargo test -p registry --lib integration_tests::runtime cargo test -p registry -p terminal cargo test --workspace @@ -118,3 +176,7 @@ 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. + +Logging tests isolate global bridge/subscriber installation in child processes +and verify Registry's dual output and recovery messages. File retention, +reopen/append, filtering and backpressure tests live in the shared log crate. diff --git a/registry/src/config.rs b/registry/src/config.rs index e38cc85..9f80616 100644 --- a/registry/src/config.rs +++ b/registry/src/config.rs @@ -4,7 +4,7 @@ use std::time::Duration; use crate::RegistryError; -const KEYS: [&str; 7] = [ +const KEYS: [&str; 9] = [ "HOST", "PORT", "DATA_PATH", @@ -12,6 +12,8 @@ const KEYS: [&str; 7] = [ "HEALTH_TIMEOUT_SECS", "DATA_FILE_COUNT", "LOG_LEVEL", + "LOG_DIR", + "LOG_MAX_FILES", ]; #[derive(Clone, Debug)] @@ -23,6 +25,8 @@ pub struct Config { pub health_timeout: Duration, pub data_file_count: u64, pub log_level: String, + pub log_dir: PathBuf, + pub log_max_files: usize, } impl Config { @@ -97,6 +101,16 @@ impl Config { } let data_file_count = positive("DATA_FILE_COUNT", "10")?; let log_level = value("LOG_LEVEL", "info"); + crate::logging::parse_level(&log_level)?; + let log_dir = value("LOG_DIR", "logs/registry"); + if log_dir.is_empty() { + return Err(RegistryError::new( + "CONFIG_ERROR", + "LOG_DIR must not be empty", + )); + } + let log_max_files = usize::try_from(positive("LOG_MAX_FILES", "10")?) + .map_err(|_| RegistryError::new("CONFIG_ERROR", "LOG_MAX_FILES is too large"))?; Ok(Self { host, port, @@ -105,6 +119,8 @@ impl Config { health_timeout, data_file_count: data_file_count, log_level, + log_dir: log_dir.into(), + log_max_files, }) } } diff --git a/registry/src/error.rs b/registry/src/error.rs index 74edeab..cfc4d4d 100644 --- a/registry/src/error.rs +++ b/registry/src/error.rs @@ -2,7 +2,7 @@ use std::fmt; use buffa::MessageField; use buffa_types::google::protobuf::{Any, StringValue}; -use proto::proto::control::InvokeResponse; +use proto::control::InvokeResponse; #[derive(Debug)] pub struct RegistryError { diff --git a/registry/src/health.rs b/registry/src/health.rs index 7ee6533..c1366e6 100644 --- a/registry/src/health.rs +++ b/registry/src/health.rs @@ -1,53 +1,25 @@ -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 proto::control::TerminalInfo; +use proto::rpc::{ + client::RpcEndpoint, + health::{ServingStatus, check_health}, }; 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 { + let Ok(port) = u16::try_from(info.terminal_port) 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(), + let Ok(endpoint) = RpcEndpoint::from_host_port(&info.terminal_host, port) else { + return ServingStatus::NOT_SERVING.into(); + }; + match check_health(&endpoint, "", timeout).await { + Ok(response) => response.status, + Err(_) => ServingStatus::NOT_SERVING.into(), } } diff --git a/registry/src/lib.rs b/registry/src/lib.rs index 7bf488a..48e2ff7 100644 --- a/registry/src/lib.rs +++ b/registry/src/lib.rs @@ -1,6 +1,7 @@ pub mod config; pub mod error; mod health; +pub mod logging; mod rpc; pub mod runtime; pub mod service; diff --git a/registry/src/logging.rs b/registry/src/logging.rs new file mode 100644 index 0000000..5ee7389 --- /dev/null +++ b/registry/src/logging.rs @@ -0,0 +1,37 @@ +use flysim_log::{LoggingConfig, LoggingError, LoggingGuard}; + +use crate::{Config, RegistryError}; + +pub(crate) fn parse_level(value: &str) -> Result { + flysim_log::parse_level(value).map_err(map_error) +} + +pub fn init_bridge() -> Result<(), RegistryError> { + flysim_log::install_log_bridge().map_err(map_error) +} + +pub fn init(config: &Config) -> Result { + let logging = LoggingConfig { + level: parse_level(&config.log_level)?, + directory: config.log_dir.clone(), + file_prefix: "registry".into(), + max_files: config.log_max_files, + }; + let (subscriber, guard) = flysim_log::build_subscriber(&logging).map_err(map_error)?; + flysim_log::install_subscriber(subscriber).map_err(map_error)?; + Ok(guard) +} + +pub fn report_startup_error(error: &dyn std::fmt::Display) { + tracing::dispatcher::with_default(&flysim_log::stderr_subscriber(), || { + log::error!("registry startup failed: {error}"); + }); +} + +fn map_error(error: LoggingError) -> RegistryError { + let code = match error { + LoggingError::InvalidConfig(_) => "CONFIG_ERROR", + _ => "LOG_INIT_FAILED", + }; + RegistryError::new(code, error.to_string()) +} diff --git a/registry/src/main.rs b/registry/src/main.rs index e5f683d..f5b17fb 100644 --- a/registry/src/main.rs +++ b/registry/src/main.rs @@ -1,12 +1,47 @@ -use registry::{Config, RegistryService, runtime}; +use std::process::ExitCode; + +use registry::{Config, RegistryService, logging, runtime}; #[tokio::main] -async fn main() -> Result<(), Box> { - let config = Config::load()?; +async fn main() -> ExitCode { + if let Err(error) = logging::init_bridge() { + logging::report_startup_error(&error); + return ExitCode::FAILURE; + } + let config = match Config::load() { + Ok(config) => config, + Err(error) => { + logging::report_startup_error(&error); + return ExitCode::FAILURE; + } + }; + let guard = match logging::init(&config) { + Ok(guard) => guard, + Err(error) => { + logging::report_startup_error(&error); + return ExitCode::FAILURE; + } + }; + let result = run(config).await; + let exit = match result { + Ok(()) => { + log::info!("registry stopped"); + ExitCode::SUCCESS + } + Err(error) => { + log::error!("registry failed: {error}"); + ExitCode::FAILURE + } + }; + drop(guard); + exit +} + +async fn run(config: Config) -> Result<(), Box> { 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 {}", + log::info!( + "registry started listen_addr={} terminal_count={} data_path={}", listener.local_addr()?, service.subscribe().borrow().infos.len(), config.data_path.display() @@ -18,7 +53,7 @@ async fn main() -> Result<(), Box> { config.health_timeout, async { if let Err(error) = tokio::signal::ctrl_c().await { - eprintln!("failed to listen for shutdown signal: {error}"); + log::error!("failed to listen for shutdown signal: {error}"); } }, ) diff --git a/registry/src/rpc.rs b/registry/src/rpc.rs index 0f7e735..8583faf 100644 --- a/registry/src/rpc.rs +++ b/registry/src/rpc.rs @@ -1,12 +1,9 @@ use buffa_types::google::protobuf::{Empty, StringValue}; -use connectrpc::{ - ConnectError, RequestContext, Response, ServiceRequest, ServiceResult, ServiceStream, -}; -use futures_util::{Stream, stream}; -use proto::proto::control::{ +use connectrpc::{RequestContext, Response, ServiceRequest, ServiceResult, ServiceStream}; +use proto::control::{ Center, InvokeResponse, TerminalInfo, TerminalInfos, TerminalRegisterResponse, }; -use tokio::sync::watch; +use proto::rpc::stream::watch_stream; use crate::RegistryService; @@ -49,29 +46,6 @@ impl Center for RegistryService { _context: RequestContext, _request: ServiceRequest<'_, Empty>, ) -> ServiceResult> { - Response::stream_ok(snapshots(self.subscribe(), self.shutdown_receiver())) + Response::stream_ok(watch_stream(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 index 96f1d87..7c6a3a0 100644 --- a/registry/src/runtime.rs +++ b/registry/src/runtime.rs @@ -1,8 +1,9 @@ -use std::future::{Future, IntoFuture}; +use std::future::Future; use std::io; use std::sync::Arc; use std::time::Duration; +use proto::rpc::{Router, health::HealthService, server}; use tokio::net::TcpListener; use crate::{RegistryService, health}; @@ -25,15 +26,18 @@ pub async fn serve( "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 rpc = Router::new() + .add_service(Arc::new(service.clone())) + .add_service(Arc::new(HealthService::new( + service.health_reporter(), + service.shutdown_receiver(), + ))); 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(); + let server = server::serve(listener, rpc, async move { + let _ = shutdown.wait_for(|stopped| *stopped).await; + }); tokio::pin!(server); + service.set_ready().await.map_err(io::Error::other)?; let mut monitor = tokio::spawn(health::monitor( service.clone(), health_interval, diff --git a/registry/src/service.rs b/registry/src/service.rs index c0f1361..eccee43 100644 --- a/registry/src/service.rs +++ b/registry/src/service.rs @@ -3,8 +3,8 @@ 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 proto::control::{TerminalInfo, TerminalInfos, TerminalRuntimeInfo}; +use proto::rpc::health::{HealthReporter, ServingStatus}; use tokio::sync::{Mutex, Notify, watch}; use uuid::Uuid; @@ -23,6 +23,7 @@ struct Inner { data_path: PathBuf, snapshots: watch::Sender, shutdown: watch::Sender, + health: HealthReporter, probe_requested: Notify, } @@ -46,6 +47,13 @@ impl RegistryService { let revisions = snapshot.infos.keys().map(|id| (id.clone(), 0)).collect(); let (snapshots, _) = watch::channel(snapshot.clone()); let (shutdown, _) = watch::channel(false); + let health = HealthReporter::new(); + health + .set_statuses(&[ + ("", ServingStatus::NOT_SERVING), + ("control.Center", ServingStatus::NOT_SERVING), + ]) + .expect("valid initial health statuses"); Ok(Self { inner: Arc::new(Inner { directory: Mutex::new(Directory { @@ -56,6 +64,7 @@ impl RegistryService { data_path, snapshots, shutdown, + health, probe_requested: Notify::new(), }), }) @@ -71,9 +80,28 @@ impl RegistryService { pub async fn shutdown(&self) { let _directory = self.inner.directory.lock().await; + self.publish_readiness(ServingStatus::NOT_SERVING); self.inner.shutdown.send_replace(true); } + pub(crate) fn health_reporter(&self) -> &HealthReporter { + &self.inner.health + } + + pub(crate) async fn set_ready(&self) -> Result<(), RegistryError> { + let _directory = self.inner.directory.lock().await; + self.ensure_running()?; + self.publish_readiness(ServingStatus::SERVING); + Ok(()) + } + + fn publish_readiness(&self, status: ServingStatus) { + self.inner + .health + .set_statuses(&[("", status), ("control.Center", status)]) + .expect("readiness maps to valid health statuses"); + } + pub async fn register(&self, info: TerminalInfo) -> Result { let info = normalize_info(info)?; let service = self.clone(); diff --git a/registry/src/storage.rs b/registry/src/storage.rs index bd036ff..2abe5f5 100644 --- a/registry/src/storage.rs +++ b/registry/src/storage.rs @@ -3,8 +3,8 @@ 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 proto::control::TerminalInfos; +use proto::grpc::health::v1::health_check_response::ServingStatus; use crate::RegistryError; use crate::service::{normalize_info, terminal_id}; @@ -22,8 +22,9 @@ pub(crate) fn load(path: &Path) -> Result { Err(error) => { let backup = corrupt_path(path); std::fs::rename(path, &backup)?; - eprintln!( - "invalid registry snapshot ({error}); moved to {}", + log::warn!( + "invalid registry snapshot error={error} path={} backup_path={}", + path.display(), backup.display() ); Ok(TerminalInfos::default()) diff --git a/registry/tests/integration/runtime.rs b/registry/tests/integration/runtime.rs index a4a4cca..3ce3e94 100644 --- a/registry/tests/integration/runtime.rs +++ b/registry/tests/integration/runtime.rs @@ -5,14 +5,116 @@ 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 proto::control::{CenterClient, TerminalInfo}; +use 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 registry_health_is_independent_of_downstream_health() { + use proto::grpc::health::v1::HealthCheckRequest; + use proto::rpc::client::{RpcChannel, RpcClientOptions, RpcEndpoint}; + tokio::time::timeout(Duration::from_secs(5), async { + let directory = tempfile::tempdir().unwrap(); + let service = RegistryService::open(directory.path().join("terminals.bin")) + .await + .unwrap(); + assert_eq!( + service.health_reporter().status(""), + Some(ServingStatus::NOT_SERVING) + ); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = + RpcEndpoint::from_host_port("127.0.0.1", listener.local_addr().unwrap().port()) + .unwrap(); + let task = tokio::spawn(serve( + listener, + service.clone(), + Duration::from_millis(20), + Duration::from_millis(30), + std::future::pending(), + )); + let channel = RpcChannel::connect(&endpoint, RpcClientOptions::default()) + .await + .unwrap(); + let health = channel.health_client(); + for name in ["", "control.Center"] { + assert_eq!( + health + .check(HealthCheckRequest { + service: name.into(), + ..Default::default() + }) + .await + .unwrap() + .into_owned() + .status, + ServingStatus::SERVING + ); + } + let mut updates = health.watch(HealthCheckRequest::default()).await.unwrap(); + assert_eq!( + updates + .message() + .await + .unwrap() + .unwrap() + .to_owned_message() + .status, + ServingStatus::SERVING + ); + let unresponsive = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let response = channel + .center_client() + .register_terminal(TerminalInfo { + terminal_host: "127.0.0.1".into(), + terminal_port: unresponsive.local_addr().unwrap().port().into(), + terminal_mac: "unresponsive".into(), + ..Default::default() + }) + .await + .unwrap() + .into_owned(); + assert!(response.success); + let mut directory_updates = service.subscribe(); + directory_updates + .wait_for(|snapshot| { + snapshot.infos[&response.message].status == ServingStatus::NOT_SERVING + }) + .await + .unwrap(); + assert_eq!( + health + .check(HealthCheckRequest::default()) + .await + .unwrap() + .into_owned() + .status, + ServingStatus::SERVING + ); + service.shutdown().await; + for name in ["", "control.Center"] { + assert_eq!( + service.health_reporter().status(name), + Some(ServingStatus::NOT_SERVING) + ); + } + while let Some(message) = updates.message().await.unwrap() { + assert_eq!( + message.to_owned_message().status, + ServingStatus::NOT_SERVING + ); + } + task.await.unwrap().unwrap(); + assert!(service.set_ready().await.is_err()); + }) + .await + .unwrap(); +} + #[tokio::test] async fn center_rpc_register_update_subscribe_deregister_and_shutdown() { tokio::time::timeout(Duration::from_secs(10), async { diff --git a/registry/tests/unit/config.rs b/registry/tests/unit/config.rs index cf75dcd..2a2a267 100644 --- a/registry/tests/unit/config.rs +++ b/registry/tests/unit/config.rs @@ -10,14 +10,24 @@ fn defaults_file_and_environment_precedence() { 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(); + assert_eq!(config.log_level, "info"); + assert_eq!(config.log_dir, std::path::Path::new("logs/registry")); + assert_eq!(config.log_max_files, 10); + std::fs::write(&path, "PORT=1234\nHOST=localhost\nLOG_LEVEL=warn\nLOG_DIR=custom-logs\nLOG_MAX_FILES=4\nDATA_FILE_COUNT=7\n").unwrap(); let config = Config::from_file( &path, - HashMap::from([("REGISTRY_PORT".into(), "4321".into())]), + HashMap::from([ + ("PORT".into(), "4321".into()), + ("LOG_LEVEL".into(), "DEBUG".into()), + ]), ) .unwrap(); assert_eq!(config.port, 4321); assert_eq!(config.host, "localhost"); + assert_eq!(config.log_level, "DEBUG"); + assert_eq!(config.log_dir, std::path::Path::new("custom-logs")); + assert_eq!(config.log_max_files, 4); + assert_eq!(config.data_file_count, 7); } #[test] @@ -25,15 +35,24 @@ 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", ""), + ("PORT", "0"), + ("PORT", "65536"), + ("HEALTH_INTERVAL_SECS", "0"), + ("HEALTH_TIMEOUT_SECS", "abc"), + ("HOST", " "), + ("DATA_PATH", ""), + ("LOG_LEVEL", ""), + ("LOG_LEVEL", "verbose"), + ("LOG_DIR", " "), + ("LOG_MAX_FILES", "0"), + ("LOG_MAX_FILES", "-1"), + ("LOG_MAX_FILES", "18446744073709551616"), ] { assert!(Config::from_file(&path, HashMap::from([(key.into(), value.into())])).is_err()); } - std::fs::write(&path, "REGISTRY_PORT='unterminated").unwrap(); + let config = + Config::from_file(&path, HashMap::from([("LOG_LEVEL".into(), "off".into())])).unwrap(); + assert_eq!(config.log_level, "off"); + std::fs::write(&path, "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 index 53aaaf4..a1b43d0 100644 --- a/registry/tests/unit/health.rs +++ b/registry/tests/unit/health.rs @@ -5,14 +5,14 @@ use connectrpc::{ ConnectError, RequestContext, Response, ServiceRequest, ServiceResult, ServiceStream, }; use futures_util::stream; -use proto::proto::control::TerminalInfo; -use proto::proto::grpc::health::v1::{ +use proto::control::TerminalInfo; +use 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}; +use crate::health::{check, monitor}; struct FakeHealth(watch::Receiver); @@ -39,7 +39,7 @@ impl Health for FakeHealth { } async fn wait_status( - receiver: &mut watch::Receiver, + receiver: &mut watch::Receiver, id: &str, status: ServingStatus, ) { @@ -127,15 +127,22 @@ async fn timeout_covers_http2_connection_setup() { 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() - }) +#[tokio::test] +async fn readiness_cannot_override_shutdown() { + let directory = tempfile::tempdir().unwrap(); + let service = RegistryService::open(directory.path().join("terminals.bin")) + .await .unwrap(); - assert_eq!(uri.port_u16(), Some(1234)); + assert_eq!( + service.health_reporter().status(""), + Some(ServingStatus::NOT_SERVING) + ); + let _ = tokio::join!(service.shutdown(), service.set_ready()); + assert!(service.set_ready().await.is_err()); + for name in ["", "control.Center"] { + assert_eq!( + service.health_reporter().status(name), + Some(ServingStatus::NOT_SERVING) + ); } } diff --git a/registry/tests/unit/logging.rs b/registry/tests/unit/logging.rs new file mode 100644 index 0000000..e551405 --- /dev/null +++ b/registry/tests/unit/logging.rs @@ -0,0 +1,70 @@ +use std::collections::HashMap; +use std::process::Command; + +use crate::{Config, logging}; + +#[test] +fn bridge_outputs_once_filters_and_flushes() { + if let Some(directory) = std::env::var_os("REGISTRY_LOG_TEST_CHILD") { + let directory = std::path::PathBuf::from(directory); + let config = Config::from_file( + &directory.join("absent.env"), + HashMap::from([("LOG_DIR".into(), directory.to_string_lossy().into_owned())]), + ) + .unwrap(); + logging::init_bridge().unwrap(); + let guard = logging::init(&config).unwrap(); + log::info!(target: "registry::log_test", "bridge-visible terminal_id=test-terminal"); + log::debug!("bridge-hidden"); + tracing::warn!(target: "registry::log_test", terminal_id = "test-terminal", "structured-visible"); + let snapshot = directory.join("snapshot.bin"); + std::fs::write(&snapshot, [0xff]).unwrap(); + crate::storage::load(&snapshot).unwrap(); + log::error!("last-record-before-flush"); + drop(guard); + return; + } + let directory = tempfile::tempdir().unwrap(); + let output = Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "unit_tests::logging::bridge_outputs_once_filters_and_flushes", + "--nocapture", + ]) + .env("REGISTRY_LOG_TEST_CHILD", directory.path()) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let console = String::from_utf8(output.stderr).unwrap(); + let logs = std::fs::read_dir(directory.path()) + .unwrap() + .map(|entry| entry.unwrap().path()) + .filter(|path| path.extension().is_some_and(|extension| extension == "log")) + .collect::>(); + assert_eq!(logs.len(), 1); + let name = logs[0].file_name().unwrap().to_str().unwrap(); + assert!(name.starts_with("registry.")); + let date = &name["registry.".len()..name.len() - ".log".len()]; + assert_eq!(date.len(), 10); + assert_eq!(&date[4..5], "-"); + assert_eq!(&date[7..8], "-"); + let file = std::fs::read_to_string(&logs[0]).unwrap(); + for text in [&console, &file] { + for message in [ + "bridge-visible", + "structured-visible", + "invalid registry snapshot", + "last-record-before-flush", + ] { + assert_eq!(text.matches(message).count(), 1, "{text}"); + } + assert!(!text.contains("bridge-hidden")); + assert!(text.contains("registry::log_test")); + assert!(text.contains("test-terminal")); + assert!(!text.contains('\u{1b}')); + } +} diff --git a/registry/tests/unit/mod.rs b/registry/tests/unit/mod.rs index b9bfeca..a89a519 100644 --- a/registry/tests/unit/mod.rs +++ b/registry/tests/unit/mod.rs @@ -1,5 +1,6 @@ mod config; mod health; +mod logging; mod rpc; mod service; mod storage; diff --git a/registry/tests/unit/rpc.rs b/registry/tests/unit/rpc.rs index 3839fd1..510997e 100644 --- a/registry/tests/unit/rpc.rs +++ b/registry/tests/unit/rpc.rs @@ -1,8 +1,8 @@ use futures_util::StreamExt; -use proto::proto::control::TerminalInfo; +use proto::control::TerminalInfo; use crate::RegistryService; -use crate::rpc::snapshots; +use proto::rpc::stream::watch_stream as snapshots; #[tokio::test] async fn subscribers_receive_initial_and_changed_snapshots_then_close() { diff --git a/registry/tests/unit/service.rs b/registry/tests/unit/service.rs index ef0585d..03928e1 100644 --- a/registry/tests/unit/service.rs +++ b/registry/tests/unit/service.rs @@ -1,5 +1,5 @@ -use proto::proto::control::TerminalInfo; -use proto::proto::grpc::health::v1::health_check_response::ServingStatus; +use proto::control::TerminalInfo; +use proto::grpc::health::v1::health_check_response::ServingStatus; use crate::RegistryService; use crate::service::normalize_info; diff --git a/registry/tests/unit/storage.rs b/registry/tests/unit/storage.rs index e75bfaf..11b5f1a 100644 --- a/registry/tests/unit/storage.rs +++ b/registry/tests/unit/storage.rs @@ -1,5 +1,5 @@ use buffa::Message; -use proto::proto::control::TerminalInfos; +use proto::control::TerminalInfos; use crate::storage::{decode, load, save}; diff --git a/terminal/Cargo.toml b/terminal/Cargo.toml index b2a34fc..285f85d 100644 --- a/terminal/Cargo.toml +++ b/terminal/Cargo.toml @@ -12,9 +12,16 @@ proto.workspace = true connectrpc.workspace = true buffa.workspace = true buffa-types.workspace = true +tokio.workspace = true +log.workspace = true +tracing.workspace = true +flysim-log.workspace = true + +[dev-dependencies] +tempfile.workspace = true +tracing-subscriber.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 index 454e815..e99c356 100644 --- a/terminal/README.md +++ b/terminal/README.md @@ -30,7 +30,8 @@ The C header declares functions and callbacks, not C Protobuf message structs. ## Host Integration -1. Call `terminal_service_create` to obtain an opaque handle. +1. Call `terminal_service_create` to obtain an opaque handle. To enable built-in + logs, call `terminal_logging_init` once before starting any terminal. 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. @@ -39,8 +40,9 @@ The C header declares functions and callbacks, not C Protobuf message structs. 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`. +6. Call `terminal_service_stop` and inspect any error. After all terminals and + callbacks have stopped, call `terminal_logging_shutdown` if built-in logs were + enabled, then destroy the remaining 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, @@ -60,8 +62,8 @@ a handle while another thread may still use it. 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]`. +The shared `RpcEndpoint` builds the center URI from host and port. IPv6 literals +can be supplied raw (`::1`) or bracketed (`[::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 @@ -71,6 +73,79 @@ 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. +## Logging + +The backend is provided by [flysim-log](../log/README.md). Terminal retains +the module-wide FFI state, error mapping and explicit guard ownership; extracting +the backend does not change any C ABI signature or DLL-global restrictions. + +Terminal records low-frequency lifecycle events with `log` macros: listener and +registration success, registration/deregistration failures and retries, shutdown +timeouts, and local stop. It does not log command payloads or high-frequency +status pushes. The same events reach stderr and daily rotating files through +`log -> tracing-log -> tracing-subscriber`; native tracing events also work. +Calling create/start/stop never installs or shuts down global logging implicitly. + +For a C/C++ host, use the generated declarations in [terminal.h](terminal.h): + +```c +void *handle = terminal_service_create(); +const char *level = "info"; +const char *directory = "logs/terminal"; +int32_t result = terminal_logging_init( + handle, + (const uint8_t *)level, strlen(level), + (const uint8_t *)directory, strlen(directory), + 10 +); +``` + +Include `terminal.h` and `` for this snippet. Check `result` against +`TERMINAL_OK` and retrieve details through `terminal_service_last_error`. +The handle supplies error storage only; logging is module-wide, not owned by +that terminal instance. UTF-8 input buffers are borrowed only for the call. + +The level accepts `off/error/warn/info/debug/trace` case-insensitively; the log +directory must be nonempty and the maximum file count positive. Configuration +is passed explicitly, not read from `.env` or `RUST_LOG`. Files are named +`terminal.YYYY-MM-DD.log`, with UTC daily rotation and at most the specified +number of matching files (the example uses 10). Retention may remove old matching +files during initialization/rotation; it is not an exact number of days. Use a +dedicated directory per host process and do not store unrelated `terminal*.log` +files there. Relative paths resolve against the host's working directory. + +Both outputs include UTC time, level and target; files disable ANSI colors. +stderr is synchronous. File output runs on a worker with an 8192-entry queue; +a full queue blocks the logging thread instead of dropping records. Slow +storage or consoles can delay the host and RPC threads. Worker-guard release +drains buffered records during normal shutdown, but cannot guarantee delivery +after a crash, forced termination, disk failure, or a stalled writer. + +After stopping every terminal and in-flight callback, call +`terminal_logging_shutdown(handle)` on a normal host thread. Repeated shutdown +is harmless, and shutdown before initialization is a no-op. Keep a handle alive +for reporting shutdown errors. Do not close logging from inside a callback or +while another thread is initializing/shutting it down. + +Initialization is once per module's logging instance. An existing logger or +subscriber is not replaced: initialization returns `TERMINAL_ERROR_INVALID_STATE`. +Invalid parameters return `TERMINAL_ERROR_INVALID_ARGUMENT`, and file/worker +initialization errors return `TERMINAL_ERROR_INTERNAL`. Ordinary parameter or I/O +failures may be corrected and retried. Installed global logger/subscriber state +cannot be uninstalled. Installation of the two globals is not atomic: serialize +this call with all host logging setup; a concurrent subscriber installation can +leave the bridge installed even though initialization fails. Such a failure is +reported and no new writer thread is retained. + +Shutdown closes only the owned file worker, not the global logger/subscriber; +stderr may still receive late records. Do not expect file output afterward or +attempt to initialize again. Keep the library loaded until host process exit; +DLL hot unloading/reloading is not supported after global logging installation. +Rust static linking can share a host's logger/subscriber, while a separately +loaded cdylib may have independent globals. When the host already owns logging +in the same Rust instance, omit these initialization/shutdown calls. A terminal +can still run without built-in logging initialized. + ## Runtime Lifecycle [RunningServer](src/runtime.rs) owns one multithreaded Tokio runtime, the Axum @@ -117,9 +192,12 @@ 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. +and 500 ms waits before retries. The shared RPC channel explicitly limits connection +establishment to three seconds, separately from each RPC's three-second deadline. +These are per-attempt budgets, not a three-second total for start/stop. The +transport already had default establishment bounds; the project now sets its +own explicit value. A new center connection is created for each attempt. No +short default deadline is imposed on status/Health subscriptions. There is no background re-registration or center heartbeat after startup. The [Registry](../registry/README.md) persists registrations and probes Terminal's @@ -152,6 +230,10 @@ 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. +[proto::rpc](../proto/README.md) supplies client factories, server hosting, +snapshot streams and Health protocol behavior. Terminal still owns the Tokio +runtime, registration retries, lifecycle mapping and server shutdown timeout. + ### Commands `Execute` requires a ready service, a registered callback and a valid simulation @@ -258,6 +340,11 @@ For Health, empty service names and `control.Terminal` are known. `Check` report Streams terminate at shutdown. Health describes readiness, not simulation state, and does not actively test the host callback or simulation engine. +The shared HealthReporter is the only health-state store. Terminal updates empty +name and `control.Terminal` together; each start constructs a new HealthService +bound to that run's shutdown signal. The common service supports later registration +of an unknown watched name, though Terminal currently registers only these two names. + 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 @@ -271,21 +358,38 @@ appropriately secured transport boundary. | [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. +Health unit tests. [tests/unit/health.rs](tests/unit/health.rs) verifies lifecycle +mapping and restart isolation; common protocol semantics are tested in proto. + +[src/logging.rs](src/logging.rs) delegates backend construction to flysim-log and +owns the explicit FFI logging lifecycle. Common filtering/retention tests are in +the shared log crate; [tests/integration/logging.rs](tests/integration/logging.rs) +uses isolated child processes for global state and real Terminal runtime logs. + +On Windows, [tests/integration/logging_smoke.ps1](tests/integration/logging_smoke.ps1) +loads the actual DLL through a .NET host and verifies its exports, error codes, +one-time initialization, and flushed daily log file. Run it in a fresh PowerShell +7 process because installed module-wide logging cannot be initialized again: + +```powershell +cargo build -p terminal +pwsh -NoProfile -File terminal/tests/integration/logging_smoke.ps1 +``` + +The script keeps the DLL loaded until the host exits and removes only its own +temporary log directory. It does not start a terminal or contact a center. ```powershell cargo test -p terminal cargo test -p terminal --lib unit_tests::health cargo test -p terminal --lib integration_tests::runtime +cargo test -p terminal logging cargo test -p registry --lib integration_tests::runtime ``` diff --git a/terminal/src/callback.rs b/terminal/src/callback.rs index c05f6e5..37b63c1 100644 --- a/terminal/src/callback.rs +++ b/terminal/src/callback.rs @@ -1,7 +1,7 @@ use std::ffi::c_void; use buffa::Message; -use proto::proto::control::{Command, InvokeResponse, TerminalEvent}; +use proto::control::{Command, InvokeResponse, TerminalEvent}; use crate::error::TerminalError; diff --git a/terminal/src/error.rs b/terminal/src/error.rs index 75d820a..7a63e2a 100644 --- a/terminal/src/error.rs +++ b/terminal/src/error.rs @@ -1,6 +1,6 @@ use buffa::MessageField; use buffa_types::google::protobuf::{Any, StringValue}; -use proto::proto::control::{InvokeResponse, TerminalEventHandle}; +use proto::control::{InvokeResponse, TerminalEventHandle}; #[derive(Debug, Clone)] pub(crate) struct TerminalError { diff --git a/terminal/src/ffi.rs b/terminal/src/ffi.rs index ee1fa23..af0c3c6 100644 --- a/terminal/src/ffi.rs +++ b/terminal/src/ffi.rs @@ -4,7 +4,7 @@ use std::ptr; use std::sync::Mutex; use buffa::Message; -use proto::proto::control::{ +use proto::control::{ InvokeResponse, TerminalEventHandle, TerminalEventInfo, TerminalInfo, TerminalStatus, }; @@ -55,6 +55,37 @@ pub extern "C" fn terminal_service_create() -> *mut c_void { Box::into_raw(Box::new(ServiceHandle::new())).cast::() } +/// Initializes module-wide console and daily rolling file logging once, before starting terminals. +/// `handle` is used only for error reporting. Does not replace an existing logger/subscriber. +/// # Safety +/// `handle` must be live; both non-null input pointers must reference their declared readable +/// UTF-8 byte lengths. Serialize logging initialization with other process logging setup. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn terminal_logging_init( + handle: *mut c_void, + log_level: *const u8, + log_level_len: usize, + log_dir: *const u8, + log_dir_len: usize, + max_log_files: u32, +) -> i32 { + ffi_call(handle, |_| { + let level = unsafe { input_str(log_level, log_level_len)? }; + let directory = unsafe { input_str(log_dir, log_dir_len)? }; + crate::logging::init(level, directory, max_log_files) + }) +} + +/// Flushes and closes the module-owned log worker. Repeated shutdown is harmless. +/// Does not uninstall global logging or permit reinitialization after shutdown. +/// # Safety +/// `handle` must be live. Stop all terminals and callbacks first, serialize logging lifecycle +/// calls, and keep the library loaded until process exit. Do not call from a callback. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn terminal_logging_shutdown(handle: *mut c_void) -> i32 { + ffi_call(handle, |_| crate::logging::shutdown()) +} + /// # Safety /// `handle` must be a live pointer returned by `terminal_service_create` and must not be used /// after this function succeeds. diff --git a/terminal/src/health.rs b/terminal/src/health.rs deleted file mode 100644 index cf3b1ee..0000000 --- a/terminal/src/health.rs +++ /dev/null @@ -1,67 +0,0 @@ -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 0e704ad..d7fa0f3 100644 --- a/terminal/src/lib.rs +++ b/terminal/src/lib.rs @@ -1,6 +1,6 @@ mod callback; mod error; -mod health; +mod logging; mod rpc; mod runtime; diff --git a/terminal/src/logging.rs b/terminal/src/logging.rs new file mode 100644 index 0000000..7eb01e7 --- /dev/null +++ b/terminal/src/logging.rs @@ -0,0 +1,81 @@ +use std::sync::Mutex; + +use flysim_log::{LoggingConfig, LoggingError, LoggingGuard}; + +use crate::error::TerminalError; + +enum LoggingState { + Uninitialized, + Active(LoggingGuard), + Closed, +} + +static LOGGING: Mutex = Mutex::new(LoggingState::Uninitialized); + +pub(crate) fn init(level: &str, directory: &str, max_files: u32) -> Result<(), TerminalError> { + let mut state = LOGGING + .lock() + .map_err(|_| TerminalError::new("INTERNAL", "logging state lock is poisoned"))?; + if !matches!(*state, LoggingState::Uninitialized) { + return Err(TerminalError::new( + "INVALID_STATE", + "logging can only be initialized once", + )); + } + if tracing::dispatcher::get_default(|subscriber| { + !subscriber.is::() + }) { + return Err(TerminalError::new( + "INVALID_STATE", + "a tracing subscriber is already installed", + )); + } + let max_files = usize::try_from(max_files) + .map_err(|_| TerminalError::new("INVALID_ARGUMENT", "log file count is too large"))?; + let config = LoggingConfig { + level: flysim_log::parse_level(level).map_err(map_error)?, + directory: directory.into(), + file_prefix: "terminal".into(), + max_files, + }; + let (subscriber, guard) = flysim_log::build_subscriber(&config).map_err(map_error)?; + flysim_log::install_log_bridge().map_err(map_error)?; + if let Err(error) = flysim_log::install_subscriber(subscriber) { + *state = LoggingState::Closed; + return Err(TerminalError::new( + "INVALID_STATE", + format!("subscriber installation failed after log bridge installation: {error}"), + )); + } + *state = LoggingState::Active(guard); + drop(state); + log::info!("terminal logging initialized directory={directory} max_files={max_files}"); + Ok(()) +} + +pub(crate) fn shutdown() -> Result<(), TerminalError> { + let guard = { + let mut state = LOGGING + .lock() + .map_err(|_| TerminalError::new("INTERNAL", "logging state lock is poisoned"))?; + if !matches!(*state, LoggingState::Active(_)) { + return Ok(()); + } + match std::mem::replace(&mut *state, LoggingState::Closed) { + LoggingState::Active(guard) => guard, + _ => unreachable!(), + } + }; + log::info!("terminal logging shutdown"); + drop(guard); + Ok(()) +} + +fn map_error(error: LoggingError) -> TerminalError { + let code = match error { + LoggingError::InvalidConfig(_) => "INVALID_ARGUMENT", + LoggingError::Appender(_) => "INTERNAL", + _ => "INVALID_STATE", + }; + TerminalError::new(code, error.to_string()) +} diff --git a/terminal/src/rpc.rs b/terminal/src/rpc.rs index 16816bf..cf068d3 100644 --- a/terminal/src/rpc.rs +++ b/terminal/src/rpc.rs @@ -1,13 +1,10 @@ use buffa_types::google::protobuf::Empty; -use connectrpc::{ - ConnectError, RequestContext, Response, ServiceRequest, ServiceResult, ServiceStream, -}; -use futures_util::{Stream, stream}; -use proto::proto::control::{ +use connectrpc::{RequestContext, Response, ServiceRequest, ServiceResult, ServiceStream}; +use proto::control::{ Command, InvokeResponse, Terminal, TerminalCancelEvent, TerminalEvent, TerminalMetaStatus, TerminalStatus, }; -use tokio::sync::watch; +use proto::rpc::stream::watch_stream; use crate::terminal::Service; @@ -59,42 +56,3 @@ impl Terminal for Service { )) } } - -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 index 2efe8b2..ca35321 100644 --- a/terminal/src/runtime.rs +++ b/terminal/src/runtime.rs @@ -1,16 +1,18 @@ 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 proto::control::TerminalInfo; +use proto::rpc::{ + Router, + client::{CallOptions, RpcChannel, RpcClientOptions, RpcEndpoint}, + health::HealthService, + server, +}; 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; @@ -40,6 +42,7 @@ impl RunningServer { } let info = service.registration_info()?; let runtime = Runtime::new().map_err(|error| { + log::error!("terminal runtime creation failed error={error}"); TerminalError::new("START_FAILED", format!("failed to create runtime: {error}")) })?; service.reset_shutdown()?; @@ -56,6 +59,7 @@ impl RunningServer { { Ok(listener) => listener, Err(error) => { + log::error!("terminal bind failed host={host} port={port} error={error}"); service.set_configured(); return Err(TerminalError::new( "START_FAILED", @@ -77,25 +81,34 @@ impl RunningServer { service.set_configured(); return Err(error); } + log::info!( + "terminal listening host={host} port={bound_port} center_host={center_host} center_port={center_port}" + ); - let rpc = connectrpc::Router::new() + let rpc = 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()); + .add_service(Arc::new(HealthService::new( + service.health_reporter(), + service.shutdown_receiver(), + ))); let mut shutdown = service.shutdown_receiver(); let server_task = runtime.spawn(async move { - axum::serve(listener, app) - .with_graceful_shutdown(async move { + log::debug!("terminal server task started port={bound_port}"); + let result = server::serve(listener, rpc, async move { + if *shutdown.borrow() { + return; + } + while shutdown.changed().await.is_ok() { if *shutdown.borrow() { return; } - while shutdown.changed().await.is_ok() { - if *shutdown.borrow() { - return; - } - } - }) - .await + } + }) + .await; + if let Err(error) = &result { + log::error!("terminal server task failed port={bound_port} error={error}"); + } + result }); let register_result = runtime.block_on(register_terminal( @@ -106,6 +119,10 @@ impl RunningServer { let terminal_id = match register_result { Ok(terminal_id) => terminal_id, Err(error) => { + log::error!( + "terminal registration failed center_host={center_host} center_port={center_port} error={}", + error.display_message() + ); service.signal_shutdown(); runtime.block_on(async { let _ = tokio::time::timeout(SHUTDOWN_TIMEOUT, server_task).await; @@ -114,7 +131,8 @@ impl RunningServer { return Err(error); } }; - service.set_ready(terminal_id)?; + service.set_ready(terminal_id.clone())?; + log::info!("terminal registered terminal_id={terminal_id} port={bound_port}"); Ok(Self { runtime, @@ -132,6 +150,10 @@ impl RunningServer { pub(crate) fn stop(mut self, service: &Service) -> Result<(), TerminalError> { service.set_stopping()?; let terminal_id = service.terminal_id()?; + log::info!( + "terminal stopping terminal_id={terminal_id} port={}", + self.bound_port + ); let deregister_result = self.runtime.block_on(deregister_terminal( &self.center_host, self.center_port, @@ -144,6 +166,11 @@ impl RunningServer { .runtime .block_on(async { tokio::time::timeout(SHUTDOWN_TIMEOUT, &mut task).await }); if completed.is_err() { + log::warn!( + "terminal server shutdown timed out port={} timeout_secs={}", + self.bound_port, + SHUTDOWN_TIMEOUT.as_secs() + ); task.abort(); self.runtime.block_on(async { let _ = task.await; @@ -151,6 +178,13 @@ impl RunningServer { } } service.set_stopped(); + if let Err(error) = &deregister_result { + log::warn!( + "terminal deregistration failed after retries error={}", + error.display_message() + ); + } + log::info!("terminal stopped port={}", self.bound_port); deregister_result } } @@ -160,17 +194,12 @@ async fn register_terminal( center_port: u16, info: TerminalInfo, ) -> Result { - let uri = center_uri(center_host, center_port)?; + let endpoint = center_endpoint(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 RpcChannel::connect(&endpoint, center_options()).await { + Ok(channel) => { + let client = channel.center_client(); match client .register_terminal_with_options( info.clone(), @@ -194,6 +223,10 @@ async fn register_terminal( } Err(error) => last_error = error.to_string(), } + log::warn!( + "center request failed operation=register attempt={} center_host={center_host} center_port={center_port} error={last_error}", + attempt + 1 + ); if attempt + 1 < CENTER_ATTEMPTS { tokio::time::sleep(CENTER_RETRY_DELAY * (attempt as u32 + 1)).await; } @@ -209,17 +242,12 @@ async fn deregister_terminal( if terminal_id.is_empty() { return Ok(()); } - let uri = center_uri(center_host, center_port)?; + let endpoint = center_endpoint(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 RpcChannel::connect(&endpoint, center_options()).await { + Ok(channel) => { + let client = channel.center_client(); let request = StringValue { value: terminal_id.clone(), ..Default::default() @@ -243,6 +271,10 @@ async fn deregister_terminal( } Err(error) => last_error = error.to_string(), } + log::warn!( + "center request failed operation=deregister attempt={} center_host={center_host} center_port={center_port} terminal_id={terminal_id} error={last_error}", + attempt + 1 + ); if attempt + 1 < CENTER_ATTEMPTS { tokio::time::sleep(CENTER_RETRY_DELAY * (attempt as u32 + 1)).await; } @@ -250,13 +282,19 @@ async fn deregister_terminal( 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}"), - ) - }) +fn center_endpoint(center_host: &str, center_port: u16) -> Result { + RpcEndpoint::from_host_port(center_host, center_port).map_err(|error| { + TerminalError::new( + "INVALID_ARGUMENT", + format!("invalid center address: {error}"), + ) + }) +} + +fn center_options() -> RpcClientOptions { + RpcClientOptions { + connect_timeout: CENTER_RPC_TIMEOUT, + request_timeout: None, + buffer_capacity: 1024, + } } diff --git a/terminal/src/terminal.rs b/terminal/src/terminal.rs index 4331e92..0c8e7ab 100644 --- a/terminal/src/terminal.rs +++ b/terminal/src/terminal.rs @@ -2,11 +2,11 @@ use std::collections::HashMap; use std::sync::{Arc, Mutex, MutexGuard}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; -use proto::proto::control::{ +use proto::control::{ Command, InvokeResponse, TerminalCancelEvent, TerminalEvent, TerminalEventHandle, TerminalEventInfo, TerminalInfo, TerminalMetaStatus, TerminalStatus, }; -use proto::proto::grpc::health::v1::{HealthCheckResponse, health_check_response::ServingStatus}; +use proto::rpc::health::{HealthReporter, ServingStatus}; use tokio::sync::watch; use crate::callback::{CommandCallback, EventCallback}; @@ -67,7 +67,7 @@ struct Inner { callback_gate: Arc>, status: watch::Sender, meta_status: watch::Sender, - health: watch::Sender, + health: HealthReporter, shutdown: Mutex>, } @@ -91,10 +91,13 @@ impl Service { 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() - }); + let health = HealthReporter::new(); + health + .set_statuses(&[ + ("", ServingStatus::NOT_SERVING), + ("control.Terminal", ServingStatus::NOT_SERVING), + ]) + .expect("valid initial health statuses"); Self { inner: Arc::new(Inner { context: Mutex::new(Context { @@ -342,8 +345,8 @@ impl Service { .subscribe() } - pub(crate) fn health_receiver(&self) -> watch::Receiver { - self.inner.health.subscribe() + pub(crate) fn health_reporter(&self) -> &HealthReporter { + &self.inner.health } fn publish_health(&self, state: ServiceState) { @@ -352,13 +355,10 @@ impl Service { } else { ServingStatus::NOT_SERVING }; - self.inner.health.send_if_modified(|response| { - if response.status == status { - return false; - } - response.status = status.into(); - true - }); + self.inner + .health + .set_statuses(&[("", status), ("control.Terminal", status)]) + .expect("lifecycle maps to valid health statuses"); } pub(crate) fn reset_shutdown(&self) -> Result<(), TerminalError> { diff --git a/terminal/terminal.h b/terminal/terminal.h index a7fba51..f15f9cd 100644 --- a/terminal/terminal.h +++ b/terminal/terminal.h @@ -40,6 +40,29 @@ typedef int32_t (*TerminalEventCallback)(void *user_data, void *terminal_service_create(void); +/** + * Initializes module-wide console and daily rolling file logging once, before starting terminals. + * `handle` is used only for error reporting. Does not replace an existing logger/subscriber. + * # Safety + * `handle` must be live; both non-null input pointers must reference their declared readable + * UTF-8 byte lengths. Serialize logging initialization with other process logging setup. + */ +int32_t terminal_logging_init(void *handle, + const uint8_t *log_level, + size_t log_level_len, + const uint8_t *log_dir, + size_t log_dir_len, + uint32_t max_log_files); + +/** + * Flushes and closes the module-owned log worker. Repeated shutdown is harmless. + * Does not uninstall global logging or permit reinitialization after shutdown. + * # Safety + * `handle` must be live. Stop all terminals and callbacks first, serialize logging lifecycle + * calls, and keep the library loaded until process exit. Do not call from a callback. + */ +int32_t terminal_logging_shutdown(void *handle); + /** * # Safety * `handle` must be a live pointer returned by `terminal_service_create` and must not be used diff --git a/terminal/tests/integration/logging.rs b/terminal/tests/integration/logging.rs new file mode 100644 index 0000000..a504139 --- /dev/null +++ b/terminal/tests/integration/logging.rs @@ -0,0 +1,193 @@ +use std::ffi::c_void; +use std::process::Command; +use std::ptr; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use crate::ffi::*; + +static EXTERNAL_LOG_COUNT: AtomicUsize = AtomicUsize::new(0); + +struct ExternalLogger; + +impl log::Log for ExternalLogger { + fn enabled(&self, _: &log::Metadata<'_>) -> bool { + true + } + fn log(&self, _: &log::Record<'_>) { + EXTERNAL_LOG_COUNT.fetch_add(1, Ordering::Relaxed); + } + fn flush(&self) {} +} + +fn initialize(handle: *mut c_void, level: &[u8], directory: &[u8], count: u32) -> i32 { + unsafe { + terminal_logging_init( + handle, + level.as_ptr(), + level.len(), + directory.as_ptr(), + directory.len(), + count, + ) + } +} + +fn last_error(handle: *mut c_void) -> String { + let mut length = 0; + assert_eq!( + unsafe { terminal_service_last_error(handle, ptr::null_mut(), &mut length) }, + TERMINAL_OK + ); + let mut bytes = vec![0; length]; + assert_eq!( + unsafe { terminal_service_last_error(handle, bytes.as_mut_ptr(), &mut length) }, + TERMINAL_OK + ); + String::from_utf8(bytes[..length - 1].to_vec()).unwrap() +} + +#[test] +fn explicit_logging_lifecycle_and_conflicts() { + if let Ok(scenario) = std::env::var("TERMINAL_LOG_TEST_SCENARIO") { + let directory = std::env::var("TERMINAL_LOG_TEST_DIRECTORY").unwrap(); + let handle = terminal_service_create(); + assert_eq!(unsafe { terminal_logging_shutdown(handle) }, TERMINAL_OK); + match scenario.as_str() { + "lifecycle" => { + for (level, path, count) in [ + (&b""[..], directory.as_bytes(), 10), + (&b"invalid"[..], directory.as_bytes(), 10), + (&[0xff][..], directory.as_bytes(), 10), + (&b"info"[..], &b""[..], 10), + (&b"info"[..], &[0xff][..], 10), + (&b"info"[..], directory.as_bytes(), 0), + ] { + assert_eq!( + initialize(handle, level, path, count), + TERMINAL_ERROR_INVALID_ARGUMENT + ); + assert!(last_error(handle).starts_with("INVALID_ARGUMENT:")); + } + assert_eq!( + unsafe { + terminal_logging_init( + handle, + ptr::null(), + 0, + directory.as_ptr(), + directory.len(), + 10, + ) + }, + TERMINAL_ERROR_INVALID_ARGUMENT + ); + let invalid_path = std::path::Path::new(&directory).join("ordinary-file"); + std::fs::write(&invalid_path, b"keep").unwrap(); + assert_eq!( + initialize( + handle, + b"info", + invalid_path.to_str().unwrap().as_bytes(), + 10 + ), + TERMINAL_ERROR_INTERNAL + ); + assert_eq!( + initialize(handle, b"debug", directory.as_bytes(), 10), + TERMINAL_OK + ); + assert_eq!( + initialize(handle, b"debug", directory.as_bytes(), 10), + TERMINAL_ERROR_INVALID_STATE + ); + log::info!(target: "terminal::log_test", "ffi-bridge-visible"); + log::trace!("ffi-bridge-hidden"); + tracing::info!(target: "terminal::log_test", terminal_id = "test-id", "ffi-structured-visible"); + super::runtime::exercise_runtime(); + assert_eq!(unsafe { terminal_logging_shutdown(handle) }, TERMINAL_OK); + assert_eq!(unsafe { terminal_logging_shutdown(handle) }, TERMINAL_OK); + assert_eq!( + initialize(handle, b"debug", directory.as_bytes(), 10), + TERMINAL_ERROR_INVALID_STATE + ); + } + "logger-conflict" => { + log::set_logger(&ExternalLogger).unwrap(); + log::set_max_level(log::LevelFilter::Trace); + assert_eq!( + initialize(handle, b"info", directory.as_bytes(), 10), + TERMINAL_ERROR_INVALID_STATE + ); + assert!(last_error(handle).contains("logger is already installed")); + log::info!("external-logger-kept"); + assert_eq!(EXTERNAL_LOG_COUNT.load(Ordering::Relaxed), 1); + assert_eq!(unsafe { terminal_logging_shutdown(handle) }, TERMINAL_OK); + log::info!("external-logger-still-kept"); + assert_eq!(EXTERNAL_LOG_COUNT.load(Ordering::Relaxed), 2); + } + "subscriber-conflict" => { + tracing::subscriber::set_global_default( + tracing_subscriber::fmt() + .with_writer(std::io::sink) + .finish(), + ) + .unwrap(); + assert_eq!( + initialize(handle, b"info", directory.as_bytes(), 10), + TERMINAL_ERROR_INVALID_STATE + ); + assert!(last_error(handle).contains("subscriber is already installed")); + log::set_logger(&ExternalLogger).unwrap(); + log::set_max_level(log::LevelFilter::Info); + assert_eq!(unsafe { terminal_logging_shutdown(handle) }, TERMINAL_OK); + } + _ => panic!("unexpected scenario"), + } + assert_eq!(unsafe { terminal_service_destroy(handle) }, TERMINAL_OK); + return; + } + for scenario in ["lifecycle", "logger-conflict", "subscriber-conflict"] { + let directory = tempfile::tempdir().unwrap(); + let output = Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "integration_tests::logging::explicit_logging_lifecycle_and_conflicts", + "--nocapture", + ]) + .env("TERMINAL_LOG_TEST_SCENARIO", scenario) + .env("TERMINAL_LOG_TEST_DIRECTORY", directory.path()) + .output() + .unwrap(); + assert!( + output.status.success(), + "scenario={scenario}\n{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + if scenario == "lifecycle" { + let console = String::from_utf8(output.stderr).unwrap(); + let files = std::fs::read_dir(directory.path()) + .unwrap() + .map(|entry| entry.unwrap().path()) + .filter(|path| path.extension().is_some_and(|extension| extension == "log")) + .collect::>(); + assert_eq!(files.len(), 1); + let text = std::fs::read_to_string(&files[0]).unwrap(); + for contents in [&console, &text] { + for message in [ + "ffi-bridge-visible", + "ffi-structured-visible", + "terminal registered", + "terminal server task started", + "terminal stopped", + "terminal logging shutdown", + ] { + assert_eq!(contents.matches(message).count(), 1, "{contents}"); + } + assert!(contents.contains("center-terminal-1")); + assert!(!contents.contains("ffi-bridge-hidden")); + assert!(!contents.contains('\u{1b}')); + } + } + } +} diff --git a/terminal/tests/integration/logging_smoke.ps1 b/terminal/tests/integration/logging_smoke.ps1 new file mode 100644 index 0000000..b349cb8 --- /dev/null +++ b/terminal/tests/integration/logging_smoke.ps1 @@ -0,0 +1,89 @@ +param( + [string] $LibraryPath = (Join-Path $PSScriptRoot '../../../target/debug/terminal.dll') +) + +$ErrorActionPreference = 'Stop' +$library = (Resolve-Path $LibraryPath).Path +$directory = Join-Path ([System.IO.Path]::GetTempPath()) ('terminal-logging-smoke-' + [guid]::NewGuid()) +[System.IO.Directory]::CreateDirectory($directory) | Out-Null + +Add-Type -TypeDefinition @' +using System; +using System.Runtime.InteropServices; +using System.Text; + +public static class TerminalLoggingSmokeHost +{ + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate IntPtr Create(); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate int HandleOperation(IntPtr handle); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate int Initialize(IntPtr handle, byte[] level, UIntPtr levelLength, + byte[] directory, UIntPtr directoryLength, uint maxFiles); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate int LastError(IntPtr handle, byte[] buffer, ref UIntPtr length); + + private static void Expect(int actual, int expected, string operation) + { + if (actual != expected) + throw new InvalidOperationException(operation + ": expected " + expected + ", got " + actual); + } + + public static void Run(string libraryPath, string directory) + { + IntPtr library = NativeLibrary.Load(libraryPath); + var create = Marshal.GetDelegateForFunctionPointer(NativeLibrary.GetExport(library, "terminal_service_create")); + var destroy = Marshal.GetDelegateForFunctionPointer(NativeLibrary.GetExport(library, "terminal_service_destroy")); + var initialize = Marshal.GetDelegateForFunctionPointer(NativeLibrary.GetExport(library, "terminal_logging_init")); + var shutdown = Marshal.GetDelegateForFunctionPointer(NativeLibrary.GetExport(library, "terminal_logging_shutdown")); + var lastError = Marshal.GetDelegateForFunctionPointer(NativeLibrary.GetExport(library, "terminal_service_last_error")); + byte[] path = Encoding.UTF8.GetBytes(directory); + byte[] level = Encoding.UTF8.GetBytes("info"); + byte[] invalid = Encoding.UTF8.GetBytes("invalid"); + IntPtr handle = create(); + if (handle == IntPtr.Zero) throw new InvalidOperationException("create returned null"); + try + { + Expect(shutdown(IntPtr.Zero), -1, "null handle"); + Expect(shutdown(handle), 0, "shutdown before init"); + Expect(initialize(handle, invalid, (UIntPtr)invalid.Length, path, (UIntPtr)path.Length, 10), -2, "invalid level"); + UIntPtr length = UIntPtr.Zero; + Expect(lastError(handle, null, ref length), 0, "last_error size"); + byte[] error = new byte[checked((int)length.ToUInt64())]; + Expect(lastError(handle, error, ref length), 0, "last_error text"); + if (!Encoding.UTF8.GetString(error).StartsWith("INVALID_ARGUMENT:")) + throw new InvalidOperationException("unexpected last_error"); + Expect(initialize(handle, level, (UIntPtr)level.Length, path, (UIntPtr)path.Length, 10), 0, "initialize"); + Expect(initialize(handle, level, (UIntPtr)level.Length, path, (UIntPtr)path.Length, 10), -3, "duplicate initialize"); + Expect(shutdown(handle), 0, "shutdown"); + Expect(shutdown(handle), 0, "repeat shutdown"); + Expect(initialize(handle, level, (UIntPtr)level.Length, path, (UIntPtr)path.Length, 10), -3, "initialize after shutdown"); + } + finally + { + Expect(shutdown(handle), 0, "final shutdown"); + Expect(destroy(handle), 0, "destroy"); + } + } +} +'@ + +try { + [TerminalLoggingSmokeHost]::Run($library, $directory) + $files = @(Get-ChildItem -LiteralPath $directory -Filter 'terminal.*.log' -File) + if ($files.Count -ne 1) { throw "Expected one daily log file, got $($files.Count)" } + $contents = [System.IO.File]::ReadAllText($files[0].FullName) + foreach ($message in @('terminal logging initialized', 'terminal logging shutdown')) { + if ([regex]::Matches($contents, [regex]::Escape($message)).Count -ne 1) { + throw "Expected exactly one '$message' record in the flushed log" + } + } + if ($contents.Contains([char]27)) { throw 'File output contains ANSI escape characters' } + Write-Output "PASS: DLL exports, error codes, one-time initialization and shutdown flush ($($files[0].Name))" +} finally { + Remove-Item -LiteralPath $directory -Recurse -Force +} \ No newline at end of file diff --git a/terminal/tests/integration/mod.rs b/terminal/tests/integration/mod.rs index 4a59515..55af2ca 100644 --- a/terminal/tests/integration/mod.rs +++ b/terminal/tests/integration/mod.rs @@ -1 +1,2 @@ +mod logging; mod runtime; diff --git a/terminal/tests/integration/runtime.rs b/terminal/tests/integration/runtime.rs index 9be4daa..967c49d 100644 --- a/terminal/tests/integration/runtime.rs +++ b/terminal/tests/integration/runtime.rs @@ -1,20 +1,18 @@ +use std::sync::atomic::{AtomicUsize, Ordering}; 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, + ConnectError, 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 proto::control::{ + Center, Command, InvokeResponse, TerminalInfo, TerminalInfos, TerminalRegisterResponse, }; +use proto::grpc::health::v1::{HealthCheckRequest, health_check_response::ServingStatus}; +use proto::rpc::client::{RpcChannel, RpcClientOptions, RpcEndpoint}; use tokio::runtime::Runtime; use tokio::sync::oneshot; @@ -27,6 +25,9 @@ const CENTER_ASSIGNED_ID: &str = "center-terminal-1"; struct FakeCenter { registered: Mutex>, deregistered_id: Mutex>, + failures: usize, + registrations: AtomicUsize, + deregistrations: AtomicUsize, } #[allow(refining_impl_trait)] @@ -38,7 +39,7 @@ impl Center for FakeCenter { ) -> ServiceResult { *self.registered.lock().unwrap() = Some(request.to_owned_message()); Response::ok(TerminalRegisterResponse { - success: true, + success: self.registrations.fetch_add(1, Ordering::Relaxed) >= self.failures, message: CENTER_ASSIGNED_ID.to_owned(), ..Default::default() }) @@ -51,7 +52,7 @@ impl Center for FakeCenter { ) -> ServiceResult { *self.deregistered_id.lock().unwrap() = Some(request.to_owned_message().value); Response::ok(InvokeResponse { - success: true, + success: self.deregistrations.fetch_add(1, Ordering::Relaxed) >= self.failures, ..Default::default() }) } @@ -67,7 +68,23 @@ impl Center for FakeCenter { #[test] fn start_registers_actual_port_and_stop_deregisters_same_id() { - let center = Arc::new(FakeCenter::default()); + exercise_runtime(); +} + +pub(super) fn exercise_runtime() { + exercise_runtime_with_failures(0); +} + +#[test] +fn registration_and_deregistration_retries_survive_transport_refactor() { + exercise_runtime_with_failures(2); +} + +fn exercise_runtime_with_failures(failures: usize) { + let center = Arc::new(FakeCenter { + failures, + ..Default::default() + }); let center_runtime = Runtime::new().unwrap(); let listener = center_runtime .block_on(tokio::net::TcpListener::bind(("127.0.0.1", 0))) @@ -107,18 +124,19 @@ fn start_registers_actual_port_and_stop_deregisters_same_id() { CENTER_ASSIGNED_ID ); - let terminal_uri: axum::http::Uri = format!("http://127.0.0.1:{}", server.bound_port()) - .parse() - .unwrap(); + let endpoint = RpcEndpoint::from_host_port("127.0.0.1", server.bound_port()).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()); + let channel = RpcChannel::connect( + &endpoint, + RpcClientOptions { + request_timeout: Some(Duration::from_secs(2)), + buffer_capacity: 32, + ..Default::default() + }, + ) + .await + .unwrap(); + let health = channel.health_client(); for name in ["", "control.Terminal"] { let response = health .check(HealthCheckRequest { @@ -168,7 +186,7 @@ fn start_registers_actual_port_and_stop_deregisters_same_id() { ServingStatus::SERVICE_UNKNOWN ); drop(watcher); - let client = TerminalClient::new(connection, config); + let client = channel.terminal_client(); let response = client .execute(Command { id: "not-registered".to_owned(), @@ -181,6 +199,8 @@ fn start_registers_actual_port_and_stop_deregisters_same_id() { }); server.stop(&service).unwrap(); + assert_eq!(center.registrations.load(Ordering::Relaxed), failures + 1); + assert_eq!(center.deregistrations.load(Ordering::Relaxed), failures + 1); assert_eq!( center.deregistered_id.lock().unwrap().as_deref(), Some(CENTER_ASSIGNED_ID) diff --git a/terminal/tests/unit/ffi.rs b/terminal/tests/unit/ffi.rs index 0687c2d..ab0dac0 100644 --- a/terminal/tests/unit/ffi.rs +++ b/terminal/tests/unit/ffi.rs @@ -1,79 +1,87 @@ -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); -} +use std::ptr; + +use buffa::Message; +use proto::control::TerminalInfo; + +use crate::ffi::*; + +#[test] +fn null_handles_are_rejected() { + assert_eq!( + unsafe { terminal_logging_init(ptr::null_mut(), ptr::null(), 0, ptr::null(), 0, 10) }, + TERMINAL_ERROR_NULL + ); + assert_eq!( + unsafe { terminal_logging_shutdown(ptr::null_mut()) }, + TERMINAL_ERROR_NULL + ); + 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 index 61b6fa7..94d0e0b 100644 --- a/terminal/tests/unit/health.rs +++ b/terminal/tests/unit/health.rs @@ -1,67 +1,125 @@ -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()); -} +use crate::terminal::Service; +use proto::control::TerminalInfo; +use proto::grpc::health::v1::HealthCheckRequest; +use proto::rpc::{ + Router, + client::{HealthRpcClient, RpcChannel, RpcClientOptions, RpcEndpoint}, + health::{HealthService, ServingStatus}, + server, +}; +use std::{sync::Arc, time::Duration}; + +fn assert_status(service: &Service, status: ServingStatus) { + for name in ["", "control.Terminal"] { + assert_eq!(service.health_reporter().status(name), Some(status)); + } +} + +#[test] +fn lifecycle_health_mapping() { + let service = Service::new_value(); + assert_status(&service, 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_status(&service, ServingStatus::NOT_SERVING); + service.set_ready("id".into()).unwrap(); + assert_status(&service, ServingStatus::SERVING); + service.set_stopping().unwrap(); + assert_status(&service, ServingStatus::NOT_SERVING); + service.set_stopped(); + service.set_starting().unwrap(); + service.set_configured(); + assert_status(&service, ServingStatus::NOT_SERVING); +} + +async fn serve_health( + service: &Service, +) -> ( + HealthRpcClient, + tokio::task::JoinHandle>, +) { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = + RpcEndpoint::from_host_port("127.0.0.1", listener.local_addr().unwrap().port()).unwrap(); + let mut shutdown = service.shutdown_receiver(); + let router = Router::new().add_service(Arc::new(HealthService::new( + service.health_reporter(), + shutdown.clone(), + ))); + let task = tokio::spawn(server::serve(listener, router, async move { + let _ = shutdown.wait_for(|stopped| *stopped).await; + })); + let channel = RpcChannel::connect(&endpoint, RpcClientOptions::default()) + .await + .unwrap(); + (channel.health_client(), task) +} + +#[tokio::test] +async fn restart_uses_new_shutdown_channel() { + tokio::time::timeout(Duration::from_secs(5), async { + let service = Service::new_value(); + service + .configure(TerminalInfo { + terminal_host: "127.0.0.1".into(), + terminal_mac: "test".into(), + ..Default::default() + }) + .unwrap(); + service.set_starting().unwrap(); + service.set_ready("first".into()).unwrap(); + let (client, task) = serve_health(&service).await; + let mut first = client.watch(HealthCheckRequest::default()).await.unwrap(); + assert_eq!( + first + .message() + .await + .unwrap() + .unwrap() + .to_owned_message() + .status, + ServingStatus::SERVING + ); + service.signal_shutdown(); + assert!(first.message().await.unwrap().is_none()); + task.await.unwrap().unwrap(); + service.set_stopped(); + service.reset_shutdown().unwrap(); + service.set_starting().unwrap(); + let (client, task) = serve_health(&service).await; + let mut second = client.watch(HealthCheckRequest::default()).await.unwrap(); + assert_eq!( + second + .message() + .await + .unwrap() + .unwrap() + .to_owned_message() + .status, + ServingStatus::NOT_SERVING + ); + service.set_ready("second".into()).unwrap(); + assert_eq!( + second + .message() + .await + .unwrap() + .unwrap() + .to_owned_message() + .status, + ServingStatus::SERVING + ); + assert!(first.message().await.unwrap().is_none()); + service.signal_shutdown(); + assert!(second.message().await.unwrap().is_none()); + task.await.unwrap().unwrap(); + }) + .await + .unwrap(); +} diff --git a/terminal/tests/unit/terminal.rs b/terminal/tests/unit/terminal.rs index e5821c0..f33a193 100644 --- a/terminal/tests/unit/terminal.rs +++ b/terminal/tests/unit/terminal.rs @@ -3,7 +3,7 @@ use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::Duration; use buffa::Message; -use proto::proto::control::{ +use proto::control::{ Command, InvokeResponse, TerminalCancelEvent, TerminalEvent, TerminalEventHandle, TerminalEventInfo, TerminalInfo, TerminalStatus, };