- 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.
23 KiB
Terminal
An embeddable simulation terminal library. A host application supplies simulation logic through C callbacks; Rust owns the RPC server, center registration, lifecycle, event scheduling, and subscription snapshots.
This crate builds a Rust library and a cdylib, not a standalone executable.
There is no cargo run -p terminal entry point or automatic .env loading.
Configuration and lifecycle are controlled by the host through terminal.h.
Build
Run from the workspace root with a Rust toolchain supporting edition 2024 and the native linker for your target platform:
cargo build -p terminal
cargo build -p terminal --release
build.rs uses cbindgen and cbindgen.toml to regenerate
terminal.h. Do not edit the generated header manually. The shared
proto crate generates the Rust RPC/message types during the build.
Default shared-library outputs are target/debug/terminal.dll on Windows,
target/debug/libterminal.so on Linux, and target/debug/libterminal.dylib on
macOS. Release builds use target/release. The host must provide a compatible
Protobuf implementation for the messages in the control protocols.
The C header declares functions and callbacks, not C Protobuf message structs.
Host Integration
- Call
terminal_service_createto obtain an opaque handle. To enable built-in logs, callterminal_logging_initonce before starting any terminal. - Serialize
control.TerminalInfoand callterminal_service_configure. - Register command callbacks and event definitions/callbacks. Keep callback code and user data alive for every possible invocation.
- Call
terminal_service_startwith the center host, center port, and a writableuint16_toutput for the actual terminal port. A successful return means both the listener and center registration are ready. - Push simulation snapshots with
terminal_service_push_status; report event completion withterminal_service_complete_eventwhen host work finishes. - Call
terminal_service_stopand inspect any error. After all terminals and callbacks have stopped, callterminal_logging_shutdownif built-in logs were enabled, then destroy the remaining handle withterminal_service_destroy.
All functions are synchronous at the ABI boundary. In particular, start and stop perform blocking network work. Invoke them from a normal host/control thread, not from a Tokio async task or a terminal callback: they create, block on, and drop an owned Tokio runtime. Serialize lifecycle operations and do not destroy a handle while another thread may still use it.
Configuration
| Field or argument | Behavior |
|---|---|
TerminalInfo.terminal_host |
Nonempty host used for both binding and center registration. |
TerminalInfo.terminal_port |
0..=65535; zero lets the OS choose a port. |
TerminalInfo.terminal_mac |
Nonempty identity sent to the center for idempotent registration. |
TerminalInfo.meta_info |
Host-provided capability description; keep it consistent with callbacks. |
center_host, center_port |
Supplied separately to start; host must be nonempty and port nonzero. |
Use an address that the center and control clients can reach. There is no separate
bind/advertised address, NAT discovery, or automatic conversion of wildcard hosts.
The 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
means a later restart reuses that stored port; configure port zero again while
stopped to request another OS-assigned port.
Command callback registration does not populate meta_info.supported_type or
its command descriptions automatically. The host must supply matching metadata.
Logging
The backend is provided by flysim-log. 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:
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 <string.h> 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 owns one multithreaded Tokio runtime, the Axum
server task, the center address, and the bound port per running terminal.
Service is cloneable shared state backed by Arc, mutexes and
Tokio watch channels; it outlives an individual start/stop cycle.
sequenceDiagram
participant Host
participant Runtime as RunningServer
participant Service
participant Center
Host->>Service: configure TerminalInfo and callbacks
Host->>Runtime: start(center, bound_port)
Runtime->>Service: new shutdown channel; Starting
Runtime->>Runtime: bind TCP listener; record actual port
Runtime->>Runtime: serve Terminal and Health on one port
Runtime->>Center: RegisterTerminal(actual TerminalInfo)
Center-->>Runtime: success + terminal_id
Runtime->>Service: Ready; publish metadata and SERVING
Runtime-->>Host: success + bound_port
Host->>Runtime: stop()
Runtime->>Service: Stopping; NOT_SERVING
Runtime->>Center: DeregisterTerminal(terminal_id)
Runtime->>Service: signal shutdown
Runtime->>Runtime: wait for server; abort task on timeout
Runtime->>Service: Stopped; clear ID and active events
Runtime-->>Host: deregistration result
Startup And Registration
The normal lifecycle is Created -> Configured -> Starting -> Ready -> Stopping -> Stopped. Start accepts Configured or Stopped; configure rejects changes
while starting, ready, or stopping.
The server starts listening before registration so it can already answer Health
requests. Until registration succeeds, command/event execution is not ready and
Health reports NOT_SERVING. Registration succeeds only when the center returns
success=true with a nonempty ID. The ID is then exposed in TerminalMetaStatus.
Bind or registration failure returns an error and restores Configured; after a
registration failure the server is signaled to close.
Center communication uses ConnectRPC's gRPC protocol over plaintext HTTP/2. Registration and deregistration each make at most three attempts, with 250 ms and 500 ms waits before retries. 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 persists registrations and probes Terminal's Health service; a different center that loses its directory needs an external recovery policy or a host-managed terminal restart.
Shutdown And Restart
Stop first switches to Stopping, then attempts deregistration. Even when that
RPC fails, stop signals local shutdown, waits up to five seconds for the Axum
server task, aborts that task if necessary, and sets Stopped. The deregistration
error is still returned to the host; a failure does not mean the listener was
left intentionally running.
Subscriptions observe shutdown and close. Event waits observe cancellation or
shutdown. Already-running spawn_blocking callbacks cannot be forcibly stopped;
dropping the Tokio runtime can wait for them. Consequently the five-second
server-task timeout is not a hard bound on total stop latency. Callbacks must
return promptly and cooperate with the host's own cancellation policy.
Destroy rejects a handle that still owns a running server; it does not implicitly stop the terminal. Stop clears the registered ID and active-event table, but retains configuration, callback registrations, event definitions and the latest status snapshot. Reconfiguration resets the simulation state; a new handle gives a fully fresh service. Lifecycle errors and ordinary RPC failures are distinct.
RPC And Host Work
Terminal and standard Health RPCs share a single ConnectRPC router and Axum listener. rpc.rs adapts generated RPC traits to the domain service; callback.rs bridges messages to the host ABI.
proto::rpc 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
state transition. The callback runs via spawn_blocking, under a per-terminal
mutex shared by command and event callbacks. This serializes callback invocation,
but it does not impose FIFO ordering or provide a transaction over concurrent
RPC validation, callbacks and state updates. Control clients should sequence
lifecycle-sensitive commands.
Only a successful callback response applies a built-in simulation transition:
| Command | Accepted simulation states | Result on success |
|---|---|---|
init |
Any | Initialized; reset event instance counter and active table. |
reset |
Any except Uninitialized |
Initialized. |
start |
Initialized, Stopped |
Running. |
stop |
Initialized, Running, Suspended |
Stopped. |
suspend |
Running |
Suspended. |
resume |
Suspended |
Running. |
| Other registered command | Any | No built-in simulation-state change. |
Simulation state is separate from service readiness: the stop command does not
shut down networking or deregister the terminal. The protocol expects the six
basic commands above; the library does not create their callbacks or validate
the entire advertised command set at startup. Parameter validation and command
timestamp ordering are the host/controller's responsibility.
Events
PublishEvent requires a ready service, an initialized simulation and a registered
event definition. It returns an InvokeResponse whose Any contains a
TerminalEventHandle { event_id, instance_id }. This acknowledges scheduling,
not successful completion of the simulation work.
After trigger_delay_ms, the host event callback receives the event and instance
ID. Its successful response only accepts that trigger. The host must also report
completion through terminal_service_complete_event, passing the encoded handle
and an encoded InvokeResponse. This applies to both one-shot and repeated events.
No completion timeout is imposed by the library.
A successful completion ends a one-shot event. For a repeated event, the next
trigger waits repeat_period_ms after completion; this is not a fixed wall-clock
schedule. Callback failure, completion failure, cancellation, unregistration or
shutdown ends the instance. CancelEvent matches both ID fields and fails for a
missing instance. Successful publish/cancel responses carry the handle in Any.
Cancellation does not forcibly interrupt a callback already executing. Keep its
user data valid until in-flight work has returned, even after unregistering an
event. Instance IDs are local to the service and reset by successful init; do
not reuse handles across reinitialization. The protocol's reserved emergency
event-type rule is a host-side contract, not currently enforced at registration.
Callback ABI And Errors
- Requests and responses crossing the ABI are serialized Protobuf bytes, not JSON or Rust-owned structs. String arguments are UTF-8 pointer/length pairs.
- Request pointers and the response sink/context are valid only during that callback. Do not retain them or submit a response asynchronously through the sink.
- Submit exactly one encoded
InvokeResponseto the sink before returning. The sink copies the bytes immediately. Return zero from the callback for bridge success; useInvokeResponse.successfor the business result. - Missing, duplicate or undecodable sink responses, and nonzero callback return codes, become business failures. C++ exceptions must not cross the ABI.
- Callbacks execute on blocking worker threads, not the host UI thread. The host must safely synchronize callback state with its other threads and avoid blocking a callback while waiting for another callback from the same terminal.
Ordinary Terminal RPC business failures use InvokeResponse.success=false, with
an error string of the form CODE: message packed as google.protobuf.StringValue
inside Any. Transport failures and unknown Health service names use RPC errors.
TERMINAL_OK(0): success.TERMINAL_ERROR_NULL(-1): null handle, or null length pointer for last-error retrieval.TERMINAL_ERROR_INVALID_ARGUMENT(-2): invalid argument, including null input bytes or bound-port output.TERMINAL_ERROR_INVALID_STATE(-3): operation invalid for the lifecycle state.TERMINAL_ERROR_DECODE(-4): input Protobuf cannot be decoded.TERMINAL_ERROR_INTERNAL(-5): other failures, including start/registration failures.TERMINAL_ERROR_BUFFER_TOO_SMALL(-6): error-text buffer is too small.
For error details, call terminal_service_last_error with a null buffer to obtain
the required length, allocate that many bytes, then call again. The length includes
the trailing NUL. Error text is handle-wide, not thread-local, and successful
operations generally clear it. Catching Rust panics does not make invalid or freed
host pointers safe; all pointer/lifetime preconditions in the header still apply.
Subscriptions And Health
SubscribeStatus immediately returns the latest TerminalStatus, then follows
host pushes. Rust assigns sequence and Unix-millisecond timestamp, overriding
the host's values; it preserves current_param. Pushes require Ready.
The protocol specifies a maximum 100 Hz, but the current implementation has no
rate limiter: the host must enforce that limit.
SubscribeMetaStatus immediately returns the current terminal ID, registered event
definitions and active instance map, then sends changed snapshots. These fields
are derived by Rust rather than pushed independently by the host. Watch channels
retain only the latest value: slow subscribers may skip intermediate states.
Neither subscription is a durable event log.
For Health, empty service names and control.Terminal are known. Check reports
SERVING only in lifecycle Ready; all other lifecycle states are NOT_SERVING.
Watch sends an initial value and later changes. An unknown name returns
NotFound from Check and a persistent SERVICE_UNKNOWN stream from Watch.
Streams terminate at shutdown. Health describes readiness, not simulation state,
and does not actively test the host callback or simulation engine.
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 appropriately secured transport boundary.
Source And Tests
| File | Responsibility |
|---|---|
| src/ffi.rs | Opaque handle, C ABI, byte decoding and last-error storage. |
| src/runtime.rs | Tokio runtime, TCP binding, RPC hosting, center registration and stop. |
| src/terminal.rs | Lifecycle, simulation state, callbacks, event instances and snapshots. |
| src/rpc.rs | Terminal RPC adapters and shutdown-aware watch streams. |
| src/callback.rs | Host callback invocation and response sink validation. |
| 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 through #[cfg(test)]
and #[path]. tests/unit/mod.rs declares the FFI, terminal and
Health unit tests. tests/unit/health.rs verifies lifecycle
mapping and restart isolation; common protocol semantics are tested in proto.
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 uses isolated child processes for global state and real Terminal runtime logs.
On Windows, 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:
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.
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
Terminal's runtime integration test runs inside the library test target, not a
standalone --test integration target. It verifies the actual registered port,
center-assigned ID, same-port Terminal/Health RPCs and deregistration. Registry's
integration tests additionally run a real Terminal through the C ABI while the
registry restarts. Unit tests cover FFI errors, state/metadata updates, explicit
event completion, Health transitions and stream shutdown.