Files
FlySimOperationSystem/registry
lain bbb67a68ab feat(rpc): implement health check service and error handling
- Added `RpcError` enum for comprehensive error handling in RPC operations.
- Introduced `HealthReporter` and `HealthService` for managing service health statuses.
- Implemented health check and watch functionality in the health service.
- Created integration tests for health check service, covering various scenarios.
- Added unit tests for client options validation and stream functionality.
- Established logging infrastructure for terminal and registry components.
- Implemented logging lifecycle management and conflict resolution in tests.
2026-10-09 15:57:35 +08:00
..

Registry

The registry implements the control.Center service over plaintext HTTP/2 gRPC using ConnectRPC and Axum. It stores the active terminal directory and checks each terminal through grpc.health.v1.Health/Check on its registered port.

Run

Run from the workspace root:

Copy-Item .env.example .env
cargo run -p registry

The .env file is optional and is read from the current working directory. Process environment variables override file values. Relative data paths are also resolved against the current working directory. Invalid configuration stops startup. The actual .env and default data directory are git-ignored.

  • 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. 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 nonempty MAC. Metadata is stored as provided; it is not interpreted here.
  • MAC identity is trim().to_ascii_lowercase(). Separator characters are not rewritten. Logical identifiers are accepted as well as physical MAC addresses.
  • IDs are UUID v5 values in namespace 9a55cb17-4014-5712-8c2a-64d47c9b613a, using the normalized MAC's UTF-8 bytes. Do not change this namespace or normalization: the same identity retains its ID across restarts and explicit deregistration.
  • Identical registration retries return the existing ID without writing or publishing. Changed information retains the ID, resets health to UNKNOWN, and requests a new check. Deregistering an absent ID succeeds without publishing.
  • Business failures use success=false. Registration errors are strings; deregistration errors are google.protobuf.StringValue packed into Any.
  • Subscribers immediately receive the full current directory, including an empty directory. Later messages are complete replacement snapshots, not deltas. Slow readers may skip intermediate snapshots and receive the latest state.
  • Directory mutations serialize, persist first, then publish. Once accepted, a mutation completes even if its requesting client disconnects, so a retry can safely discover the committed outcome.

Storage And Recovery

The data file contains a Protobuf TerminalInfos message. Health is always written and restored as UNKNOWN; runtime health changes do not write to disk. Missing snapshots start an empty directory. Undecodable or semantically invalid snapshots are renamed to terminals.bin.corrupt-<timestamp>-<suffix> and reported 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 no separate backup recovery state. A process crash leaves either the previous or committed snapshot. Uncommitted .registry-snapshot-* files are ignored and can be removed while the registry is stopped. This is not a guarantee against filesystem damage or sudden power loss; keep operational backups separately.

Only one registry process may own a data path. Shared storage, replication, configuration hot reload, authentication, and TLS are not implemented. Deploy on a trusted network or behind an appropriately secured proxy; registration authorizes outbound health connections to the supplied host and port.

Health

Registry exposes grpc.health.v1.Health on the same port as control.Center, using proto's shared Health service. 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. 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 stream from Watch. Health describes service readiness, not simulation state.

Verify

All test implementations and test-only helpers live under tests/:

Like Terminal, src/lib.rs loads both test groups through #[cfg(test)] and #[path]. Production modules do not declare individual test modules. Tests use explicit crate imports and narrowly scoped pub(crate) functions, without adding public library APIs or exposing the directory's private state. The cancellation test uses a current-thread runtime to drop a polled caller before its spawned transaction is scheduled, without accessing internal locks.

Both test groups run in the library test target; there is no standalone --test integration target. Each test module is loaded exactly once.

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

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.