Files
FlySimOperationSystem/terminal/README.md
T
lain 7f331565c7 Add terminal service implementation and integration tests
- Introduced terminal.h header file defining the terminal service API.
- Implemented integration tests for terminal service registration and health checks.
- Added unit tests for FFI layer, health checks, and terminal service functionality.
- Created a mock center for testing terminal registration and deregistration.
- Ensured proper error handling and response validation in tests.
2026-09-20 10:55:38 +08:00

298 lines
17 KiB
Markdown

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