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.
This commit is contained in:
2026-09-20 10:55:38 +08:00
parent 3bef0e4ef2
commit 7f331565c7
90 changed files with 7807 additions and 14 deletions
+16 -1
View File
@@ -2,4 +2,19 @@
name = "terminal"
version.workspace = true
edition.workspace = true
author.workspace = true
authors.workspace = true
[lib]
crate-type = ["lib", "cdylib"]
[dependencies]
proto.workspace = true
connectrpc.workspace = true
buffa.workspace = true
buffa-types.workspace = true
axum.workspace = true
futures-util.workspace = true
tokio.workspace = true
[build-dependencies]
cbindgen.workspace = true
+297
View File
@@ -0,0 +1,297 @@
# Terminal
An embeddable simulation terminal library. A host application supplies simulation
logic through C callbacks; Rust owns the RPC server, center registration,
lifecycle, event scheduling, and subscription snapshots.
This crate builds a Rust library and a `cdylib`, not a standalone executable.
There is no `cargo run -p terminal` entry point or automatic `.env` loading.
Configuration and lifecycle are controlled by the host through [terminal.h](terminal.h).
## Build
Run from the workspace root with a Rust toolchain supporting edition 2024 and
the native linker for your target platform:
```powershell
cargo build -p terminal
cargo build -p terminal --release
```
[build.rs](build.rs) uses cbindgen and [cbindgen.toml](cbindgen.toml) to regenerate
[terminal.h](terminal.h). Do not edit the generated header manually. The shared
`proto` crate generates the Rust RPC/message types during the build.
Default shared-library outputs are `target/debug/terminal.dll` on Windows,
`target/debug/libterminal.so` on Linux, and `target/debug/libterminal.dylib` on
macOS. Release builds use `target/release`. The host must provide a compatible
Protobuf implementation for the messages in [the control protocols](../proto/control).
The C header declares functions and callbacks, not C Protobuf message structs.
## Host Integration
1. Call `terminal_service_create` to obtain an opaque handle.
2. Serialize `control.TerminalInfo` and call `terminal_service_configure`.
3. Register command callbacks and event definitions/callbacks. Keep callback code
and user data alive for every possible invocation.
4. Call `terminal_service_start` with the center host, center port, and a writable
`uint16_t` output for the actual terminal port. A successful return means both
the listener and center registration are ready.
5. Push simulation snapshots with `terminal_service_push_status`; report event
completion with `terminal_service_complete_event` when host work finishes.
6. Call `terminal_service_stop`, inspect any error, then destroy the stopped
handle with `terminal_service_destroy`.
All functions are synchronous at the ABI boundary. In particular, start and stop
perform blocking network work. Invoke them from a normal host/control thread,
not from a Tokio async task or a terminal callback: they create, block on, and
drop an owned Tokio runtime. Serialize lifecycle operations and do not destroy
a handle while another thread may still use it.
### Configuration
| Field or argument | Behavior |
| ---------------------------- | ------------------------------------------------------------------------ |
| `TerminalInfo.terminal_host` | Nonempty host used for both binding and center registration. |
| `TerminalInfo.terminal_port` | `0..=65535`; zero lets the OS choose a port. |
| `TerminalInfo.terminal_mac` | Nonempty identity sent to the center for idempotent registration. |
| `TerminalInfo.meta_info` | Host-provided capability description; keep it consistent with callbacks. |
| `center_host`, `center_port` | Supplied separately to start; host must be nonempty and port nonzero. |
Use an address that the center and control clients can reach. There is no separate
bind/advertised address, NAT discovery, or automatic conversion of wildcard hosts.
The center URI is built as `http://<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.
+17
View File
@@ -0,0 +1,17 @@
fn main() {
let crate_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
let output_file = std::path::PathBuf::from(&crate_dir).join("terminal.h");
let config_file = std::path::PathBuf::from(&crate_dir).join("cbindgen.toml");
println!("cargo:rerun-if-changed=cbindgen.toml");
println!("cargo:rerun-if-changed=src");
let config = cbindgen::Config::from_file(config_file).expect("Unable to read cbindgen config");
cbindgen::Builder::new()
.with_crate(crate_dir)
.with_config(config)
.generate()
.expect("Unable to generate bindings")
.write_to_file(output_file);
}
+8
View File
@@ -0,0 +1,8 @@
language = "C"
include_guard = "FLYSIM_TERMINAL_H"
pragma_once = true
usize_is_size_t = true
documentation = true
[parse]
parse_deps = false
+184
View File
@@ -0,0 +1,184 @@
use std::ffi::c_void;
use buffa::Message;
use proto::proto::control::{Command, InvokeResponse, TerminalEvent};
use crate::error::TerminalError;
pub type TerminalResponseSink =
unsafe extern "C" fn(context: *mut c_void, response: *const u8, response_len: usize) -> i32;
pub type TerminalCommandCallback = Option<
unsafe extern "C" fn(
user_data: *mut c_void,
command: *const u8,
command_len: usize,
sink: TerminalResponseSink,
sink_context: *mut c_void,
) -> i32,
>;
pub type TerminalEventCallback = Option<
unsafe extern "C" fn(
user_data: *mut c_void,
event: *const u8,
event_len: usize,
instance_id: u64,
sink: TerminalResponseSink,
sink_context: *mut c_void,
) -> i32,
>;
#[derive(Clone, Copy)]
pub(crate) struct CommandCallback {
callback: TerminalCommandCallback,
user_data: usize,
}
#[derive(Clone, Copy)]
pub(crate) struct EventCallback {
callback: TerminalEventCallback,
user_data: usize,
}
impl CommandCallback {
pub(crate) fn new(
callback: TerminalCommandCallback,
user_data: *mut c_void,
) -> Result<Self, TerminalError> {
if callback.is_none() {
return Err(TerminalError::new(
"INVALID_ARGUMENT",
"command callback must not be null",
));
}
Ok(Self {
callback,
user_data: user_data as usize,
})
}
pub(crate) fn invoke(self, command: &Command) -> Result<InvokeResponse, TerminalError> {
let request = command.try_encode_to_vec().map_err(|error| {
TerminalError::new(
"ENCODE_FAILED",
format!("failed to encode command: {error}"),
)
})?;
let callback = self.callback.expect("callback validated at registration");
invoke_with_sink(|sink, sink_context| unsafe {
callback(
self.user_data as *mut c_void,
request.as_ptr(),
request.len(),
sink,
sink_context,
)
})
}
}
impl EventCallback {
pub(crate) fn new(
callback: TerminalEventCallback,
user_data: *mut c_void,
) -> Result<Self, TerminalError> {
if callback.is_none() {
return Err(TerminalError::new(
"INVALID_ARGUMENT",
"event callback must not be null",
));
}
Ok(Self {
callback,
user_data: user_data as usize,
})
}
pub(crate) fn invoke(
self,
event: &TerminalEvent,
instance_id: u64,
) -> Result<InvokeResponse, TerminalError> {
let request = event.try_encode_to_vec().map_err(|error| {
TerminalError::new("ENCODE_FAILED", format!("failed to encode event: {error}"))
})?;
let callback = self.callback.expect("callback validated at registration");
invoke_with_sink(|sink, sink_context| unsafe {
callback(
self.user_data as *mut c_void,
request.as_ptr(),
request.len(),
instance_id,
sink,
sink_context,
)
})
}
}
struct SinkState {
response: Option<Vec<u8>>,
duplicate: bool,
}
unsafe extern "C" fn response_sink(
context: *mut c_void,
response: *const u8,
response_len: usize,
) -> i32 {
if context.is_null() || (response.is_null() && response_len != 0) {
return -1;
}
let state = unsafe { &mut *(context as *mut SinkState) };
if state.response.is_some() {
state.duplicate = true;
return -2;
}
let bytes = if response_len == 0 {
Vec::new()
} else {
unsafe { std::slice::from_raw_parts(response, response_len) }.to_vec()
};
state.response = Some(bytes);
0
}
fn invoke_with_sink(
invoke: impl FnOnce(TerminalResponseSink, *mut c_void) -> i32,
) -> Result<InvokeResponse, TerminalError> {
let mut state = SinkState {
response: None,
duplicate: false,
};
let status = invoke(
response_sink,
(&mut state as *mut SinkState).cast::<c_void>(),
);
if status != 0 {
return Err(TerminalError::new(
"CALLBACK_FAILED",
format!("host callback returned status {status}"),
));
}
if state.duplicate {
return Err(TerminalError::new(
"INVALID_CALLBACK_RESPONSE",
"host callback submitted more than one response",
));
}
let response = state.response.ok_or_else(|| {
TerminalError::new(
"INVALID_CALLBACK_RESPONSE",
"host callback did not submit a response",
)
})?;
InvokeResponse::decode_from_slice(&response).map_err(|error| {
TerminalError::new(
"INVALID_CALLBACK_RESPONSE",
format!("failed to decode callback response: {error}"),
)
})
}
+43
View File
@@ -0,0 +1,43 @@
use buffa::MessageField;
use buffa_types::google::protobuf::{Any, StringValue};
use proto::proto::control::{InvokeResponse, TerminalEventHandle};
#[derive(Debug, Clone)]
pub(crate) struct TerminalError {
pub(crate) code: &'static str,
pub(crate) message: String,
}
impl TerminalError {
pub(crate) fn new(code: &'static str, message: impl Into<String>) -> Self {
Self {
code,
message: message.into(),
}
}
pub(crate) fn into_response(self) -> InvokeResponse {
let error = StringValue {
value: format!("{}: {}", self.code, self.message),
..Default::default()
};
InvokeResponse {
success: false,
message: MessageField::some(Any::pack(&error, StringValue::TYPE_URL)),
..Default::default()
}
}
pub(crate) fn display_message(&self) -> String {
format!("{}: {}", self.code, self.message)
}
}
pub(crate) fn success_handle(handle: &TerminalEventHandle) -> InvokeResponse {
InvokeResponse {
success: true,
message: MessageField::some(Any::pack(handle, TerminalEventHandle::TYPE_URL)),
..Default::default()
}
}
+361
View File
@@ -0,0 +1,361 @@
use std::ffi::c_void;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::ptr;
use std::sync::Mutex;
use buffa::Message;
use proto::proto::control::{
InvokeResponse, TerminalEventHandle, TerminalEventInfo, TerminalInfo, TerminalStatus,
};
use crate::callback::{CommandCallback, EventCallback};
use crate::error::TerminalError;
use crate::runtime::RunningServer;
use crate::terminal::Service;
use crate::{TerminalCommandCallback, TerminalEventCallback};
pub const TERMINAL_OK: i32 = 0;
pub const TERMINAL_ERROR_NULL: i32 = -1;
pub const TERMINAL_ERROR_INVALID_ARGUMENT: i32 = -2;
pub const TERMINAL_ERROR_INVALID_STATE: i32 = -3;
pub const TERMINAL_ERROR_DECODE: i32 = -4;
pub const TERMINAL_ERROR_INTERNAL: i32 = -5;
pub const TERMINAL_ERROR_BUFFER_TOO_SMALL: i32 = -6;
struct ServiceHandle {
service: Service,
running: Mutex<Option<RunningServer>>,
last_error: Mutex<String>,
}
impl ServiceHandle {
fn new() -> Self {
Self {
service: Service::new_value(),
running: Mutex::new(None),
last_error: Mutex::new(String::new()),
}
}
fn set_error(&self, error: &TerminalError) {
if let Ok(mut message) = self.last_error.lock() {
*message = error.display_message();
}
}
fn clear_error(&self) {
if let Ok(mut message) = self.last_error.lock() {
message.clear();
}
}
}
#[unsafe(no_mangle)]
pub extern "C" fn terminal_service_create() -> *mut c_void {
Box::into_raw(Box::new(ServiceHandle::new())).cast::<c_void>()
}
/// # Safety
/// `handle` must be a live pointer returned by `terminal_service_create` and must not be used
/// after this function succeeds.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn terminal_service_destroy(handle: *mut c_void) -> i32 {
if handle.is_null() {
return TERMINAL_ERROR_NULL;
}
catch_unwind(AssertUnwindSafe(|| {
let handle_ref = unsafe { &*handle.cast::<ServiceHandle>() };
let running = match handle_ref.running.lock() {
Ok(running) => running,
Err(_) => return TERMINAL_ERROR_INTERNAL,
};
if running.is_some() {
let error =
TerminalError::new("INVALID_STATE", "terminal must be stopped before destroy");
handle_ref.set_error(&error);
return TERMINAL_ERROR_INVALID_STATE;
}
drop(running);
unsafe {
drop(Box::from_raw(handle.cast::<ServiceHandle>()));
}
TERMINAL_OK
}))
.unwrap_or(TERMINAL_ERROR_INTERNAL)
}
/// # Safety
/// `handle` must be live, and `terminal_info` must reference `terminal_info_len` readable bytes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn terminal_service_configure(
handle: *mut c_void,
terminal_info: *const u8,
terminal_info_len: usize,
) -> i32 {
ffi_call(handle, |handle| {
let bytes = unsafe { input_bytes(terminal_info, terminal_info_len)? };
let info = TerminalInfo::decode_from_slice(bytes).map_err(|error| {
TerminalError::new(
"DECODE_FAILED",
format!("failed to decode TerminalInfo: {error}"),
)
})?;
handle.service.configure(info)
})
}
/// # Safety
/// `handle` must be live; `command_id` must reference `command_id_len` readable UTF-8 bytes.
/// The callback and `user_data` must remain valid until the service is destroyed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn terminal_service_register_command(
handle: *mut c_void,
command_id: *const u8,
command_id_len: usize,
callback: TerminalCommandCallback,
user_data: *mut c_void,
) -> i32 {
ffi_call(handle, |handle| {
let command_id = unsafe { input_str(command_id, command_id_len)? };
handle.service.register_command(
command_id.to_owned(),
CommandCallback::new(callback, user_data)?,
)
})
}
/// # Safety
/// `handle` must be live; `event_info` must reference `event_info_len` readable bytes. The
/// callback and `user_data` must remain valid until the event is unregistered or service destroyed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn terminal_service_register_event(
handle: *mut c_void,
event_info: *const u8,
event_info_len: usize,
callback: TerminalEventCallback,
user_data: *mut c_void,
) -> i32 {
ffi_call(handle, |handle| {
let bytes = unsafe { input_bytes(event_info, event_info_len)? };
let info = TerminalEventInfo::decode_from_slice(bytes).map_err(|error| {
TerminalError::new(
"DECODE_FAILED",
format!("failed to decode TerminalEventInfo: {error}"),
)
})?;
handle
.service
.register_event(info, EventCallback::new(callback, user_data)?)
})
}
/// # Safety
/// `handle` must be live, and `event_id` must reference `event_id_len` readable UTF-8 bytes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn terminal_service_unregister_event(
handle: *mut c_void,
event_id: *const u8,
event_id_len: usize,
) -> i32 {
ffi_call(handle, |handle| {
let event_id = unsafe { input_str(event_id, event_id_len)? };
handle.service.unregister_event(event_id)
})
}
/// # Safety
/// `handle` must be live, and `status` must reference `status_len` readable bytes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn terminal_service_push_status(
handle: *mut c_void,
status: *const u8,
status_len: usize,
) -> i32 {
ffi_call(handle, |handle| {
let bytes = unsafe { input_bytes(status, status_len)? };
let status = TerminalStatus::decode_from_slice(bytes).map_err(|error| {
TerminalError::new(
"DECODE_FAILED",
format!("failed to decode TerminalStatus: {error}"),
)
})?;
handle.service.push_status(status)
})
}
/// # Safety
/// `handle` must be live. Both protobuf pointers must reference their declared readable lengths.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn terminal_service_complete_event(
handle: *mut c_void,
event_handle: *const u8,
event_handle_len: usize,
response: *const u8,
response_len: usize,
) -> i32 {
ffi_call(handle, |handle| {
let event_handle = TerminalEventHandle::decode_from_slice(unsafe {
input_bytes(event_handle, event_handle_len)?
})
.map_err(|error| {
TerminalError::new(
"DECODE_FAILED",
format!("failed to decode TerminalEventHandle: {error}"),
)
})?;
let response =
InvokeResponse::decode_from_slice(unsafe { input_bytes(response, response_len)? })
.map_err(|error| {
TerminalError::new(
"DECODE_FAILED",
format!("failed to decode InvokeResponse: {error}"),
)
})?;
handle.service.complete_event(&event_handle, &response)
})
}
/// # Safety
/// `handle` must be live; `center_host` must reference `center_host_len` readable UTF-8 bytes;
/// `bound_port` must be writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn terminal_service_start(
handle: *mut c_void,
center_host: *const u8,
center_host_len: usize,
center_port: u16,
bound_port: *mut u16,
) -> i32 {
ffi_call(handle, |handle| {
if bound_port.is_null() {
return Err(TerminalError::new(
"INVALID_ARGUMENT",
"bound port output must not be null",
));
}
let center_host = unsafe { input_str(center_host, center_host_len)? }.to_owned();
let mut running = handle.running.lock().map_err(internal_lock_error)?;
if running.is_some() {
return Err(TerminalError::new(
"INVALID_STATE",
"terminal is already running",
));
}
let server = RunningServer::start(&handle.service, center_host, center_port)?;
unsafe {
*bound_port = server.bound_port();
}
*running = Some(server);
Ok(())
})
}
/// # Safety
/// `handle` must be a live pointer returned by `terminal_service_create`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn terminal_service_stop(handle: *mut c_void) -> i32 {
ffi_call(handle, |handle| {
let server = handle
.running
.lock()
.map_err(internal_lock_error)?
.take()
.ok_or_else(|| TerminalError::new("INVALID_STATE", "terminal is not running"))?;
server.stop(&handle.service)
})
}
/// # Safety
/// `handle` must be live and `buffer_len` writable. A non-null `buffer` must reference at least
/// the input value of `*buffer_len` writable bytes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn terminal_service_last_error(
handle: *mut c_void,
buffer: *mut u8,
buffer_len: *mut usize,
) -> i32 {
if handle.is_null() || buffer_len.is_null() {
return TERMINAL_ERROR_NULL;
}
let result = catch_unwind(AssertUnwindSafe(|| {
let handle = unsafe { &*handle.cast::<ServiceHandle>() };
let message = handle
.last_error
.lock()
.map_err(|_| TERMINAL_ERROR_INTERNAL)?;
let required = message.len().saturating_add(1);
let available = unsafe { *buffer_len };
unsafe {
*buffer_len = required;
}
if buffer.is_null() {
return Ok(TERMINAL_OK);
}
if available < required {
return Ok(TERMINAL_ERROR_BUFFER_TOO_SMALL);
}
unsafe {
ptr::copy_nonoverlapping(message.as_ptr(), buffer, message.len());
*buffer.add(message.len()) = 0;
}
Ok(TERMINAL_OK)
}));
match result {
Ok(Ok(code)) => code,
Ok(Err(code)) => code,
Err(_) => TERMINAL_ERROR_INTERNAL,
}
}
fn ffi_call(
handle: *mut c_void,
operation: impl FnOnce(&ServiceHandle) -> Result<(), TerminalError>,
) -> i32 {
if handle.is_null() {
return TERMINAL_ERROR_NULL;
}
let result = catch_unwind(AssertUnwindSafe(|| {
let handle = unsafe { &*handle.cast::<ServiceHandle>() };
match operation(handle) {
Ok(()) => {
handle.clear_error();
TERMINAL_OK
}
Err(error) => {
let code = error_code(&error);
handle.set_error(&error);
code
}
}
}));
result.unwrap_or(TERMINAL_ERROR_INTERNAL)
}
fn error_code(error: &TerminalError) -> i32 {
match error.code {
"INVALID_ARGUMENT" => TERMINAL_ERROR_INVALID_ARGUMENT,
"INVALID_STATE" => TERMINAL_ERROR_INVALID_STATE,
"DECODE_FAILED" => TERMINAL_ERROR_DECODE,
_ => TERMINAL_ERROR_INTERNAL,
}
}
fn internal_lock_error<T>(_: std::sync::PoisonError<T>) -> TerminalError {
TerminalError::new("INTERNAL", "terminal lock is poisoned")
}
unsafe fn input_bytes<'a>(input: *const u8, len: usize) -> Result<&'a [u8], TerminalError> {
if input.is_null() {
return Err(TerminalError::new(
"INVALID_ARGUMENT",
"input pointer must not be null",
));
}
Ok(unsafe { std::slice::from_raw_parts(input, len) })
}
unsafe fn input_str<'a>(input: *const u8, len: usize) -> Result<&'a str, TerminalError> {
std::str::from_utf8(unsafe { input_bytes(input, len)? }).map_err(|error| {
TerminalError::new("INVALID_ARGUMENT", format!("input is not UTF-8: {error}"))
})
}
+67
View File
@@ -0,0 +1,67 @@
use connectrpc::{
ConnectError, ErrorCode, RequestContext, Response, ServiceRequest, ServiceResult, ServiceStream,
};
use futures_util::{StreamExt, stream};
use proto::proto::grpc::health::v1::{
Health, HealthCheckRequest, HealthCheckResponse, health_check_response::ServingStatus,
};
use crate::{rpc::watch_stream, terminal::Service};
pub(crate) struct TerminalHealth(pub(crate) Service);
fn known_service(name: &str) -> bool {
name.is_empty() || name == "control.Terminal"
}
impl TerminalHealth {
pub(crate) fn responses(
&self,
name: &str,
) -> futures_util::stream::BoxStream<'static, Result<HealthCheckResponse, ConnectError>> {
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<HealthCheckResponse> {
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<ServiceStream<HealthCheckResponse>> {
Response::stream_ok(self.responses(&request.to_owned_message().service))
}
}
+19
View File
@@ -0,0 +1,19 @@
mod callback;
mod error;
mod health;
mod rpc;
mod runtime;
pub use callback::{TerminalCommandCallback, TerminalEventCallback, TerminalResponseSink};
pub mod terminal;
pub mod ffi;
#[cfg(test)]
#[path = "../tests/unit/mod.rs"]
mod unit_tests;
#[cfg(test)]
#[path = "../tests/integration/mod.rs"]
mod integration_tests;
+100
View File
@@ -0,0 +1,100 @@
use buffa_types::google::protobuf::Empty;
use connectrpc::{
ConnectError, RequestContext, Response, ServiceRequest, ServiceResult, ServiceStream,
};
use futures_util::{Stream, stream};
use proto::proto::control::{
Command, InvokeResponse, Terminal, TerminalCancelEvent, TerminalEvent, TerminalMetaStatus,
TerminalStatus,
};
use tokio::sync::watch;
use crate::terminal::Service;
#[allow(refining_impl_trait)]
impl Terminal for Service {
async fn execute(
&self,
_context: RequestContext,
request: ServiceRequest<'_, Command>,
) -> ServiceResult<InvokeResponse> {
Response::ok(self.execute_command(request.to_owned_message()).await)
}
async fn publish_event(
&self,
_context: RequestContext,
request: ServiceRequest<'_, TerminalEvent>,
) -> ServiceResult<InvokeResponse> {
Response::ok(self.publish_event(request.to_owned_message()).await)
}
async fn cancel_event(
&self,
_context: RequestContext,
request: ServiceRequest<'_, TerminalCancelEvent>,
) -> ServiceResult<InvokeResponse> {
Response::ok(self.cancel_event(request.to_owned_message()))
}
async fn subscribe_status(
&self,
_context: RequestContext,
_request: ServiceRequest<'_, Empty>,
) -> ServiceResult<ServiceStream<TerminalStatus>> {
Response::stream_ok(watch_stream(
self.status_receiver(),
self.shutdown_receiver(),
))
}
async fn subscribe_meta_status(
&self,
_context: RequestContext,
_request: ServiceRequest<'_, Empty>,
) -> ServiceResult<ServiceStream<TerminalMetaStatus>> {
Response::stream_ok(watch_stream(
self.meta_status_receiver(),
self.shutdown_receiver(),
))
}
}
pub(crate) fn watch_stream<T>(
receiver: watch::Receiver<T>,
shutdown: watch::Receiver<bool>,
) -> impl Stream<Item = Result<T, ConnectError>> + 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)));
}
}
}
},
)
}
+262
View File
@@ -0,0 +1,262 @@
use std::sync::Arc;
use std::time::Duration;
use axum::Router;
use buffa_types::google::protobuf::StringValue;
use connectrpc::Protocol;
use connectrpc::client::{CallOptions, ClientConfig, Http2Connection};
use proto::proto::control::{CenterClient, TerminalInfo};
use tokio::runtime::Runtime;
use tokio::task::JoinHandle;
use crate::error::TerminalError;
use crate::health::TerminalHealth;
use crate::terminal::Service;
const CENTER_ATTEMPTS: usize = 3;
const CENTER_RPC_TIMEOUT: Duration = Duration::from_secs(3);
const CENTER_RETRY_DELAY: Duration = Duration::from_millis(250);
const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
pub(crate) struct RunningServer {
runtime: Runtime,
server_task: Option<JoinHandle<Result<(), std::io::Error>>>,
center_host: String,
center_port: u16,
bound_port: u16,
}
impl RunningServer {
pub(crate) fn start(
service: &Service,
center_host: String,
center_port: u16,
) -> Result<Self, TerminalError> {
if center_host.is_empty() || center_port == 0 {
return Err(TerminalError::new(
"INVALID_ARGUMENT",
"center host and port must be valid",
));
}
let info = service.registration_info()?;
let runtime = Runtime::new().map_err(|error| {
TerminalError::new("START_FAILED", format!("failed to create runtime: {error}"))
})?;
service.reset_shutdown()?;
service.set_starting()?;
let host = info.terminal_host.clone();
let port = u16::try_from(info.terminal_port).map_err(|_| {
TerminalError::new(
"INVALID_ARGUMENT",
"terminal port is outside the valid range",
)
})?;
let listener = match runtime.block_on(tokio::net::TcpListener::bind((host.as_str(), port)))
{
Ok(listener) => listener,
Err(error) => {
service.set_configured();
return Err(TerminalError::new(
"START_FAILED",
format!("failed to bind terminal listener: {error}"),
));
}
};
let bound_port = match listener.local_addr() {
Ok(address) => address.port(),
Err(error) => {
service.set_configured();
return Err(TerminalError::new(
"START_FAILED",
format!("failed to read bound address: {error}"),
));
}
};
if let Err(error) = service.set_bound_port(bound_port) {
service.set_configured();
return Err(error);
}
let rpc = connectrpc::Router::new()
.add_service(Arc::new(service.clone()))
.add_service(Arc::new(TerminalHealth(service.clone())));
let app = Router::new().fallback_service(rpc.into_axum_service());
let mut shutdown = service.shutdown_receiver();
let server_task = runtime.spawn(async move {
axum::serve(listener, app)
.with_graceful_shutdown(async move {
if *shutdown.borrow() {
return;
}
while shutdown.changed().await.is_ok() {
if *shutdown.borrow() {
return;
}
}
})
.await
});
let register_result = runtime.block_on(register_terminal(
&center_host,
center_port,
service.registration_info()?,
));
let terminal_id = match register_result {
Ok(terminal_id) => terminal_id,
Err(error) => {
service.signal_shutdown();
runtime.block_on(async {
let _ = tokio::time::timeout(SHUTDOWN_TIMEOUT, server_task).await;
});
service.set_configured();
return Err(error);
}
};
service.set_ready(terminal_id)?;
Ok(Self {
runtime,
server_task: Some(server_task),
center_host,
center_port,
bound_port,
})
}
pub(crate) fn bound_port(&self) -> u16 {
self.bound_port
}
pub(crate) fn stop(mut self, service: &Service) -> Result<(), TerminalError> {
service.set_stopping()?;
let terminal_id = service.terminal_id()?;
let deregister_result = self.runtime.block_on(deregister_terminal(
&self.center_host,
self.center_port,
terminal_id,
));
service.signal_shutdown();
if let Some(mut task) = self.server_task.take() {
let completed = self
.runtime
.block_on(async { tokio::time::timeout(SHUTDOWN_TIMEOUT, &mut task).await });
if completed.is_err() {
task.abort();
self.runtime.block_on(async {
let _ = task.await;
});
}
}
service.set_stopped();
deregister_result
}
}
async fn register_terminal(
center_host: &str,
center_port: u16,
info: TerminalInfo,
) -> Result<String, TerminalError> {
let uri = center_uri(center_host, center_port)?;
let mut last_error = String::new();
for attempt in 0..CENTER_ATTEMPTS {
match Http2Connection::connect_plaintext(uri.clone()).await {
Ok(connection) => {
let client = CenterClient::new(
connection.shared(1024),
ClientConfig::new(uri.clone())
.with_protocol(Protocol::Grpc)
.with_default_timeout(CENTER_RPC_TIMEOUT),
);
match client
.register_terminal_with_options(
info.clone(),
CallOptions::default().with_timeout(CENTER_RPC_TIMEOUT),
)
.await
{
Ok(response) => {
let response = response.into_owned();
if response.success && !response.message.is_empty() {
return Ok(response.message);
}
last_error = if response.message.is_empty() {
"center rejected registration".to_owned()
} else {
response.message
};
}
Err(error) => last_error = error.to_string(),
}
}
Err(error) => last_error = error.to_string(),
}
if attempt + 1 < CENTER_ATTEMPTS {
tokio::time::sleep(CENTER_RETRY_DELAY * (attempt as u32 + 1)).await;
}
}
Err(TerminalError::new("REGISTER_FAILED", last_error))
}
async fn deregister_terminal(
center_host: &str,
center_port: u16,
terminal_id: String,
) -> Result<(), TerminalError> {
if terminal_id.is_empty() {
return Ok(());
}
let uri = center_uri(center_host, center_port)?;
let mut last_error = String::new();
for attempt in 0..CENTER_ATTEMPTS {
match Http2Connection::connect_plaintext(uri.clone()).await {
Ok(connection) => {
let client = CenterClient::new(
connection.shared(1024),
ClientConfig::new(uri.clone())
.with_protocol(Protocol::Grpc)
.with_default_timeout(CENTER_RPC_TIMEOUT),
);
let request = StringValue {
value: terminal_id.clone(),
..Default::default()
};
match client
.deregister_terminal_with_options(
request,
CallOptions::default().with_timeout(CENTER_RPC_TIMEOUT),
)
.await
{
Ok(response) => {
let response = response.into_owned();
if response.success {
return Ok(());
}
last_error = "center rejected deregistration".to_owned();
}
Err(error) => last_error = error.to_string(),
}
}
Err(error) => last_error = error.to_string(),
}
if attempt + 1 < CENTER_ATTEMPTS {
tokio::time::sleep(CENTER_RETRY_DELAY * (attempt as u32 + 1)).await;
}
}
Err(TerminalError::new("DEREGISTER_FAILED", last_error))
}
fn center_uri(center_host: &str, center_port: u16) -> Result<axum::http::Uri, TerminalError> {
format!("http://{center_host}:{center_port}")
.parse()
.map_err(|error| {
TerminalError::new(
"INVALID_ARGUMENT",
format!("invalid center address: {error}"),
)
})
}
+803
View File
@@ -0,0 +1,803 @@
use std::collections::HashMap;
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use proto::proto::control::{
Command, InvokeResponse, TerminalCancelEvent, TerminalEvent, TerminalEventHandle,
TerminalEventInfo, TerminalInfo, TerminalMetaStatus, TerminalStatus,
};
use proto::proto::grpc::health::v1::{HealthCheckResponse, health_check_response::ServingStatus};
use tokio::sync::watch;
use crate::callback::{CommandCallback, EventCallback};
use crate::error::{TerminalError, success_handle};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ServiceState {
Created,
Configured,
Starting,
Ready,
Stopping,
Stopped,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SimulationState {
Uninitialized,
Initialized,
Running,
Suspended,
Stopped,
}
#[derive(Clone)]
struct EventDefinition {
info: TerminalEventInfo,
callback: EventCallback,
}
struct ActiveEvent {
event_id: String,
awaiting_completion: bool,
signal: watch::Sender<EventSignal>,
}
#[derive(Clone)]
enum EventSignal {
Pending,
Complete(InvokeResponse),
Cancelled,
}
struct Context {
service_state: ServiceState,
simulation_state: SimulationState,
terminal_info: Option<TerminalInfo>,
terminal_id: String,
commands: HashMap<String, CommandCallback>,
event_definitions: HashMap<String, EventDefinition>,
active_events: HashMap<u64, ActiveEvent>,
next_instance_id: u64,
status_sequence: u64,
}
struct Inner {
context: Mutex<Context>,
callback_gate: Arc<Mutex<()>>,
status: watch::Sender<TerminalStatus>,
meta_status: watch::Sender<TerminalMetaStatus>,
health: watch::Sender<HealthCheckResponse>,
shutdown: Mutex<watch::Sender<bool>>,
}
#[derive(Clone)]
pub struct Service {
inner: Arc<Inner>,
}
impl Default for Service {
fn default() -> Self {
Self::new_value()
}
}
impl Service {
pub fn new() -> Box<Self> {
Box::new(Self::new_value())
}
pub(crate) fn new_value() -> Self {
let (status, _) = watch::channel(TerminalStatus::default());
let (meta_status, _) = watch::channel(TerminalMetaStatus::default());
let (shutdown, _) = watch::channel(false);
let (health, _) = watch::channel(HealthCheckResponse {
status: ServingStatus::NOT_SERVING.into(),
..Default::default()
});
Self {
inner: Arc::new(Inner {
context: Mutex::new(Context {
service_state: ServiceState::Created,
simulation_state: SimulationState::Uninitialized,
terminal_info: None,
terminal_id: String::new(),
commands: HashMap::new(),
event_definitions: HashMap::new(),
active_events: HashMap::new(),
next_instance_id: 1,
status_sequence: 0,
}),
callback_gate: Arc::new(Mutex::new(())),
status,
meta_status,
health,
shutdown: Mutex::new(shutdown),
}),
}
}
pub fn closed(&self) -> bool {
self.state()
.map(|state| {
!matches!(
state,
ServiceState::Starting | ServiceState::Ready | ServiceState::Stopping
)
})
.unwrap_or(false)
}
pub(crate) fn configure(&self, terminal_info: TerminalInfo) -> Result<(), TerminalError> {
validate_terminal_info(&terminal_info)?;
let mut context = self.lock_context()?;
if matches!(
context.service_state,
ServiceState::Starting | ServiceState::Ready | ServiceState::Stopping
) {
return Err(TerminalError::new(
"INVALID_STATE",
"terminal cannot be configured while running",
));
}
context.terminal_info = Some(terminal_info);
context.terminal_id.clear();
context.simulation_state = SimulationState::Uninitialized;
context.service_state = ServiceState::Configured;
self.publish_health(context.service_state);
drop(context);
self.publish_meta_status();
Ok(())
}
pub(crate) fn register_command(
&self,
command_id: String,
callback: CommandCallback,
) -> Result<(), TerminalError> {
if command_id.is_empty() {
return Err(TerminalError::new(
"INVALID_ARGUMENT",
"command id must not be empty",
));
}
self.lock_context()?.commands.insert(command_id, callback);
Ok(())
}
pub(crate) fn register_event(
&self,
info: TerminalEventInfo,
callback: EventCallback,
) -> Result<(), TerminalError> {
if info.event_id.is_empty() {
return Err(TerminalError::new(
"INVALID_ARGUMENT",
"event id must not be empty",
));
}
self.lock_context()?
.event_definitions
.insert(info.event_id.clone(), EventDefinition { info, callback });
self.publish_meta_status();
Ok(())
}
pub(crate) fn unregister_event(&self, event_id: &str) -> Result<(), TerminalError> {
let cancelled = {
let mut context = self.lock_context()?;
context.event_definitions.remove(event_id);
let instance_ids = context
.active_events
.iter()
.filter_map(|(instance_id, active)| {
(active.event_id == event_id).then_some(*instance_id)
})
.collect::<Vec<_>>();
instance_ids
.into_iter()
.filter_map(|instance_id| context.active_events.remove(&instance_id))
.map(|active| active.signal)
.collect::<Vec<_>>()
};
for signal in cancelled {
let _ = signal.send(EventSignal::Cancelled);
}
self.publish_meta_status();
Ok(())
}
pub(crate) fn push_status(&self, mut status: TerminalStatus) -> Result<(), TerminalError> {
let sequence = {
let mut context = self.lock_context()?;
if context.service_state != ServiceState::Ready {
return Err(TerminalError::new("INVALID_STATE", "terminal is not ready"));
}
context.status_sequence = context.status_sequence.saturating_add(1);
context.status_sequence
};
status.sequence = sequence;
status.timestamp = unix_timestamp_millis();
self.inner.status.send_replace(status);
Ok(())
}
pub(crate) async fn execute_command(&self, command: Command) -> InvokeResponse {
let callback = match self.prepare_command(&command) {
Ok(callback) => callback,
Err(error) => return error.into_response(),
};
let command_id = command.id.clone();
let gate = Arc::clone(&self.inner.callback_gate);
let response = tokio::task::spawn_blocking(move || {
let _guard = gate
.lock()
.map_err(|_| TerminalError::new("INTERNAL", "callback lock is poisoned"))?;
callback.invoke(&command)
})
.await
.map_err(|error| TerminalError::new("CALLBACK_FAILED", error.to_string()))
.and_then(|response| response);
match response {
Ok(response) => {
if response.success
&& let Err(error) = self.apply_command_transition(&command_id)
{
return error.into_response();
}
response
}
Err(error) => error.into_response(),
}
}
pub(crate) async fn publish_event(&self, event: TerminalEvent) -> InvokeResponse {
let (handle, callback, signal) = match self.create_event_instance(&event) {
Ok(value) => value,
Err(error) => return error.into_response(),
};
self.publish_meta_status();
self.spawn_event_task(event, handle.clone(), callback, signal);
success_handle(&handle)
}
pub(crate) fn cancel_event(&self, request: TerminalCancelEvent) -> InvokeResponse {
let handle = TerminalEventHandle {
event_id: request.event_id,
instance_id: request.instance_id,
..Default::default()
};
let removed = {
let mut context = match self.lock_context() {
Ok(context) => context,
Err(error) => return error.into_response(),
};
match context.active_events.get(&handle.instance_id) {
Some(active) if active.event_id == handle.event_id => {
context.active_events.remove(&handle.instance_id)
}
Some(_) => {
return TerminalError::new(
"INVALID_ARGUMENT",
"event id does not match the active instance",
)
.into_response();
}
None => None,
}
};
let Some(active) = removed else {
return TerminalError::new("NOT_FOUND", "event instance was not found").into_response();
};
let _ = active.signal.send(EventSignal::Cancelled);
self.publish_meta_status();
success_handle(&handle)
}
pub(crate) fn complete_event(
&self,
handle: &TerminalEventHandle,
response: &InvokeResponse,
) -> Result<(), TerminalError> {
let signal = {
let mut context = self.lock_context()?;
let active = context
.active_events
.get_mut(&handle.instance_id)
.ok_or_else(|| TerminalError::new("NOT_FOUND", "event instance was not found"))?;
if active.event_id != handle.event_id {
return Err(TerminalError::new(
"INVALID_ARGUMENT",
"event id does not match the active instance",
));
}
if !active.awaiting_completion {
return Err(TerminalError::new(
"INVALID_STATE",
"event instance is not awaiting completion",
));
}
active.awaiting_completion = false;
active.signal.clone()
};
signal
.send(EventSignal::Complete(response.clone()))
.map_err(|_| TerminalError::new("NOT_FOUND", "event task has already stopped"))
}
pub(crate) fn status_receiver(&self) -> watch::Receiver<TerminalStatus> {
self.inner.status.subscribe()
}
pub(crate) fn meta_status_receiver(&self) -> watch::Receiver<TerminalMetaStatus> {
self.inner.meta_status.subscribe()
}
pub(crate) fn shutdown_receiver(&self) -> watch::Receiver<bool> {
self.inner
.shutdown
.lock()
.expect("shutdown lock poisoned")
.subscribe()
}
pub(crate) fn health_receiver(&self) -> watch::Receiver<HealthCheckResponse> {
self.inner.health.subscribe()
}
fn publish_health(&self, state: ServiceState) {
let status = if state == ServiceState::Ready {
ServingStatus::SERVING
} else {
ServingStatus::NOT_SERVING
};
self.inner.health.send_if_modified(|response| {
if response.status == status {
return false;
}
response.status = status.into();
true
});
}
pub(crate) fn reset_shutdown(&self) -> Result<(), TerminalError> {
let (sender, _) = watch::channel(false);
*self
.inner
.shutdown
.lock()
.map_err(|_| TerminalError::new("INTERNAL", "shutdown lock is poisoned"))? = sender;
Ok(())
}
pub(crate) fn signal_shutdown(&self) {
if let Ok(sender) = self.inner.shutdown.lock() {
sender.send_replace(true);
}
}
pub(crate) fn set_starting(&self) -> Result<(), TerminalError> {
let mut context = self.lock_context()?;
if !matches!(
context.service_state,
ServiceState::Configured | ServiceState::Stopped
) {
return Err(TerminalError::new(
"INVALID_STATE",
"terminal must be configured before starting",
));
}
context.service_state = ServiceState::Starting;
self.publish_health(context.service_state);
Ok(())
}
pub(crate) fn set_ready(&self, terminal_id: String) -> Result<(), TerminalError> {
if terminal_id.is_empty() {
return Err(TerminalError::new(
"REGISTER_FAILED",
"center returned an empty terminal id",
));
}
let mut context = self.lock_context()?;
context.terminal_id = terminal_id;
context.service_state = ServiceState::Ready;
self.publish_health(context.service_state);
drop(context);
self.publish_meta_status();
Ok(())
}
pub(crate) fn set_configured(&self) {
if let Ok(mut context) = self.inner.context.lock() {
context.terminal_id.clear();
context.service_state = ServiceState::Configured;
self.publish_health(context.service_state);
}
self.publish_meta_status();
}
pub(crate) fn set_stopping(&self) -> Result<(), TerminalError> {
let mut context = self.lock_context()?;
if context.service_state != ServiceState::Ready {
return Err(TerminalError::new(
"INVALID_STATE",
"terminal is not running",
));
}
context.service_state = ServiceState::Stopping;
self.publish_health(context.service_state);
Ok(())
}
pub(crate) fn set_stopped(&self) {
if let Ok(mut context) = self.inner.context.lock() {
context.terminal_id.clear();
context.service_state = ServiceState::Stopped;
self.publish_health(context.service_state);
context.simulation_state = SimulationState::Stopped;
context.active_events.clear();
}
self.publish_meta_status();
}
pub(crate) fn registration_info(&self) -> Result<TerminalInfo, TerminalError> {
self.lock_context()?
.terminal_info
.clone()
.ok_or_else(|| TerminalError::new("INVALID_STATE", "terminal is not configured"))
}
pub(crate) fn set_bound_port(&self, port: u16) -> Result<(), TerminalError> {
let mut context = self.lock_context()?;
let info = context
.terminal_info
.as_mut()
.ok_or_else(|| TerminalError::new("INVALID_STATE", "terminal is not configured"))?;
info.terminal_port = u32::from(port);
Ok(())
}
pub(crate) fn terminal_id(&self) -> Result<String, TerminalError> {
Ok(self.lock_context()?.terminal_id.clone())
}
fn state(&self) -> Result<ServiceState, TerminalError> {
Ok(self.lock_context()?.service_state)
}
fn lock_context(&self) -> Result<MutexGuard<'_, Context>, TerminalError> {
self.inner
.context
.lock()
.map_err(|_| TerminalError::new("INTERNAL", "terminal state lock is poisoned"))
}
fn prepare_command(&self, command: &Command) -> Result<CommandCallback, TerminalError> {
if command.id.is_empty() {
return Err(TerminalError::new(
"INVALID_ARGUMENT",
"command id must not be empty",
));
}
let context = self.lock_context()?;
if context.service_state != ServiceState::Ready {
return Err(TerminalError::new("INVALID_STATE", "terminal is not ready"));
}
validate_command_transition(context.simulation_state, &command.id)?;
context.commands.get(&command.id).copied().ok_or_else(|| {
TerminalError::new(
"NOT_FOUND",
format!("command '{}' is not registered", command.id),
)
})
}
fn apply_command_transition(&self, command_id: &str) -> Result<(), TerminalError> {
let mut context = self.lock_context()?;
match command_id {
"init" => {
context.simulation_state = SimulationState::Initialized;
context.next_instance_id = 1;
context.active_events.clear();
}
"reset" => context.simulation_state = SimulationState::Initialized,
"start" | "resume" => context.simulation_state = SimulationState::Running,
"stop" => context.simulation_state = SimulationState::Stopped,
"suspend" => context.simulation_state = SimulationState::Suspended,
_ => {}
}
drop(context);
if command_id == "init" {
self.publish_meta_status();
}
Ok(())
}
fn create_event_instance(
&self,
event: &TerminalEvent,
) -> Result<
(
TerminalEventHandle,
EventCallback,
watch::Receiver<EventSignal>,
),
TerminalError,
> {
if event.event_id.is_empty() {
return Err(TerminalError::new(
"INVALID_ARGUMENT",
"event id must not be empty",
));
}
let mut context = self.lock_context()?;
if context.service_state != ServiceState::Ready {
return Err(TerminalError::new("INVALID_STATE", "terminal is not ready"));
}
if context.simulation_state == SimulationState::Uninitialized {
return Err(TerminalError::new(
"INVALID_STATE",
"simulation must be initialized before publishing events",
));
}
let callback = context
.event_definitions
.get(&event.event_id)
.map(|definition| definition.callback)
.ok_or_else(|| {
TerminalError::new(
"NOT_FOUND",
format!("event '{}' is not registered", event.event_id),
)
})?;
let instance_id = context.next_instance_id;
context.next_instance_id = context
.next_instance_id
.checked_add(1)
.ok_or_else(|| TerminalError::new("RESOURCE_EXHAUSTED", "event id space exhausted"))?;
let (signal, receiver) = watch::channel(EventSignal::Pending);
context.active_events.insert(
instance_id,
ActiveEvent {
event_id: event.event_id.clone(),
awaiting_completion: false,
signal,
},
);
Ok((
TerminalEventHandle {
event_id: event.event_id.clone(),
instance_id,
..Default::default()
},
callback,
receiver,
))
}
fn spawn_event_task(
&self,
event: TerminalEvent,
handle: TerminalEventHandle,
callback: EventCallback,
mut signal: watch::Receiver<EventSignal>,
) {
let service = self.clone();
let mut shutdown = self.shutdown_receiver();
tokio::spawn(async move {
if wait_for_event(
Duration::from_millis(event.trigger_delay_ms),
&mut signal,
&mut shutdown,
)
.await
.is_none()
{
service.remove_active_event(handle.instance_id);
return;
}
loop {
if service
.set_event_awaiting(handle.instance_id, true)
.is_err()
{
return;
}
let callback_event = event.clone();
let gate = Arc::clone(&service.inner.callback_gate);
let callback_response = tokio::task::spawn_blocking(move || {
let _guard = gate
.lock()
.map_err(|_| TerminalError::new("INTERNAL", "callback lock is poisoned"))?;
callback.invoke(&callback_event, handle.instance_id)
})
.await;
if !matches!(callback_response, Ok(Ok(response)) if response.success) {
service.remove_active_event(handle.instance_id);
return;
}
let completion = wait_for_completion(&mut signal, &mut shutdown).await;
let Some(response) = completion else {
service.remove_active_event(handle.instance_id);
return;
};
if !response.success || event.repeat_period_ms == 0 {
service.remove_active_event(handle.instance_id);
return;
}
if wait_for_event(
Duration::from_millis(event.repeat_period_ms),
&mut signal,
&mut shutdown,
)
.await
.is_none()
{
service.remove_active_event(handle.instance_id);
return;
}
}
});
}
fn set_event_awaiting(&self, instance_id: u64, awaiting: bool) -> Result<(), TerminalError> {
let mut context = self.lock_context()?;
let active = context
.active_events
.get_mut(&instance_id)
.ok_or_else(|| TerminalError::new("NOT_FOUND", "event instance was not found"))?;
active.awaiting_completion = awaiting;
if awaiting {
active.signal.send_replace(EventSignal::Pending);
}
Ok(())
}
fn remove_active_event(&self, instance_id: u64) {
let removed = self
.inner
.context
.lock()
.map(|mut context| context.active_events.remove(&instance_id).is_some())
.unwrap_or(false);
if removed {
self.publish_meta_status();
}
}
fn publish_meta_status(&self) {
let snapshot = match self.inner.context.lock() {
Ok(context) => {
let mut publishable_events = context
.event_definitions
.values()
.map(|definition| definition.info.clone())
.collect::<Vec<_>>();
publishable_events.sort_by(|left, right| left.event_id.cmp(&right.event_id));
TerminalMetaStatus {
terminal_id: context.terminal_id.clone(),
publishable_events,
triggered_events: context
.active_events
.iter()
.map(|(instance_id, active)| (*instance_id, active.event_id.clone()))
.collect(),
..Default::default()
}
}
Err(_) => return,
};
if *self.inner.meta_status.borrow() != snapshot {
self.inner.meta_status.send_replace(snapshot);
}
}
}
fn validate_terminal_info(info: &TerminalInfo) -> Result<(), TerminalError> {
if info.terminal_host.is_empty() {
return Err(TerminalError::new(
"INVALID_ARGUMENT",
"terminal host must not be empty",
));
}
if info.terminal_port > u16::MAX as u32 {
return Err(TerminalError::new(
"INVALID_ARGUMENT",
"terminal port is outside the valid range",
));
}
if info.terminal_mac.is_empty() {
return Err(TerminalError::new(
"INVALID_ARGUMENT",
"terminal mac must not be empty",
));
}
Ok(())
}
fn validate_command_transition(
state: SimulationState,
command_id: &str,
) -> Result<(), TerminalError> {
let allowed = match command_id {
"init" => true,
"reset" => state != SimulationState::Uninitialized,
"start" => matches!(
state,
SimulationState::Initialized | SimulationState::Stopped
),
"stop" => matches!(
state,
SimulationState::Initialized | SimulationState::Running | SimulationState::Suspended
),
"suspend" => state == SimulationState::Running,
"resume" => state == SimulationState::Suspended,
_ => true,
};
if allowed {
Ok(())
} else {
Err(TerminalError::new(
"INVALID_STATE",
format!("command '{command_id}' is not valid in state {state:?}"),
))
}
}
fn unix_timestamp_millis() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|duration| duration.as_millis().min(i64::MAX as u128) as i64)
.unwrap_or_default()
}
async fn wait_for_completion(
signal: &mut watch::Receiver<EventSignal>,
shutdown: &mut watch::Receiver<bool>,
) -> Option<InvokeResponse> {
loop {
match signal.borrow_and_update().clone() {
EventSignal::Complete(response) => return Some(response),
EventSignal::Cancelled => return None,
EventSignal::Pending => {}
}
tokio::select! {
changed = signal.changed() => {
if changed.is_err() {
return None;
}
}
changed = shutdown.changed() => {
if changed.is_err() || *shutdown.borrow() {
return None;
}
}
}
}
}
async fn wait_for_event(
duration: Duration,
signal: &mut watch::Receiver<EventSignal>,
shutdown: &mut watch::Receiver<bool>,
) -> Option<()> {
tokio::select! {
_ = tokio::time::sleep(duration) => Some(()),
changed = signal.changed() => {
match changed {
Ok(()) if !matches!(*signal.borrow(), EventSignal::Cancelled) => Some(()),
_ => None,
}
}
changed = shutdown.changed() => {
match changed {
Ok(()) if !*shutdown.borrow() => Some(()),
_ => None,
}
}
}
}
+128
View File
@@ -0,0 +1,128 @@
#ifndef FLYSIM_TERMINAL_H
#define FLYSIM_TERMINAL_H
#pragma once
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#define TERMINAL_OK 0
#define TERMINAL_ERROR_NULL -1
#define TERMINAL_ERROR_INVALID_ARGUMENT -2
#define TERMINAL_ERROR_INVALID_STATE -3
#define TERMINAL_ERROR_DECODE -4
#define TERMINAL_ERROR_INTERNAL -5
#define TERMINAL_ERROR_BUFFER_TOO_SMALL -6
typedef int32_t (*TerminalResponseSink)(void *context, const uint8_t *response, size_t response_len);
typedef int32_t (*TerminalCommandCallback)(void *user_data,
const uint8_t *command,
size_t command_len,
TerminalResponseSink sink,
void *sink_context);
typedef int32_t (*TerminalEventCallback)(void *user_data,
const uint8_t *event,
size_t event_len,
uint64_t instance_id,
TerminalResponseSink sink,
void *sink_context);
void *terminal_service_create(void);
/**
* # Safety
* `handle` must be a live pointer returned by `terminal_service_create` and must not be used
* after this function succeeds.
*/
int32_t terminal_service_destroy(void *handle);
/**
* # Safety
* `handle` must be live, and `terminal_info` must reference `terminal_info_len` readable bytes.
*/
int32_t terminal_service_configure(void *handle,
const uint8_t *terminal_info,
size_t terminal_info_len);
/**
* # Safety
* `handle` must be live; `command_id` must reference `command_id_len` readable UTF-8 bytes.
* The callback and `user_data` must remain valid until the service is destroyed.
*/
int32_t terminal_service_register_command(void *handle,
const uint8_t *command_id,
size_t command_id_len,
TerminalCommandCallback callback,
void *user_data);
/**
* # Safety
* `handle` must be live; `event_info` must reference `event_info_len` readable bytes. The
* callback and `user_data` must remain valid until the event is unregistered or service destroyed.
*/
int32_t terminal_service_register_event(void *handle,
const uint8_t *event_info,
size_t event_info_len,
TerminalEventCallback callback,
void *user_data);
/**
* # Safety
* `handle` must be live, and `event_id` must reference `event_id_len` readable UTF-8 bytes.
*/
int32_t terminal_service_unregister_event(void *handle,
const uint8_t *event_id,
size_t event_id_len);
/**
* # Safety
* `handle` must be live, and `status` must reference `status_len` readable bytes.
*/
int32_t terminal_service_push_status(void *handle, const uint8_t *status, size_t status_len);
/**
* # Safety
* `handle` must be live. Both protobuf pointers must reference their declared readable lengths.
*/
int32_t terminal_service_complete_event(void *handle,
const uint8_t *event_handle,
size_t event_handle_len,
const uint8_t *response,
size_t response_len);
/**
* # Safety
* `handle` must be live; `center_host` must reference `center_host_len` readable UTF-8 bytes;
* `bound_port` must be writable.
*/
int32_t terminal_service_start(void *handle,
const uint8_t *center_host,
size_t center_host_len,
uint16_t center_port,
uint16_t *bound_port);
/**
* # Safety
* `handle` must be a live pointer returned by `terminal_service_create`.
*/
int32_t terminal_service_stop(void *handle);
/**
* # Safety
* `handle` must be live and `buffer_len` writable. A non-null `buffer` must reference at least
* the input value of `*buffer_len` writable bytes.
*/
int32_t terminal_service_last_error(void *handle, uint8_t *buffer, size_t *buffer_len);
#endif /* FLYSIM_TERMINAL_H */
+1
View File
@@ -0,0 +1 @@
mod runtime;
+191
View File
@@ -0,0 +1,191 @@
use std::sync::{Arc, Mutex, mpsc};
use std::time::Duration;
use axum::Router;
use buffa_types::google::protobuf::{Empty, StringValue};
use connectrpc::client::{ClientConfig, Http2Connection};
use connectrpc::{
ConnectError, Protocol, RequestContext, Response, ServiceRequest, ServiceResult, ServiceStream,
};
use futures_util::stream;
use proto::proto::control::{
Center, Command, InvokeResponse, TerminalClient, TerminalInfo, TerminalInfos,
TerminalRegisterResponse,
};
use proto::proto::grpc::health::v1::{
HealthCheckRequest, HealthClient, health_check_response::ServingStatus,
};
use tokio::runtime::Runtime;
use tokio::sync::oneshot;
use crate::runtime::RunningServer;
use crate::terminal::Service;
const CENTER_ASSIGNED_ID: &str = "center-terminal-1";
#[derive(Default)]
struct FakeCenter {
registered: Mutex<Option<TerminalInfo>>,
deregistered_id: Mutex<Option<String>>,
}
#[allow(refining_impl_trait)]
impl Center for FakeCenter {
async fn register_terminal(
&self,
_context: RequestContext,
request: ServiceRequest<'_, TerminalInfo>,
) -> ServiceResult<TerminalRegisterResponse> {
*self.registered.lock().unwrap() = Some(request.to_owned_message());
Response::ok(TerminalRegisterResponse {
success: true,
message: CENTER_ASSIGNED_ID.to_owned(),
..Default::default()
})
}
async fn deregister_terminal(
&self,
_context: RequestContext,
request: ServiceRequest<'_, StringValue>,
) -> ServiceResult<InvokeResponse> {
*self.deregistered_id.lock().unwrap() = Some(request.to_owned_message().value);
Response::ok(InvokeResponse {
success: true,
..Default::default()
})
}
async fn subscribe_terminal(
&self,
_context: RequestContext,
_request: ServiceRequest<'_, Empty>,
) -> ServiceResult<ServiceStream<TerminalInfos>> {
Response::stream_ok(stream::empty::<Result<TerminalInfos, ConnectError>>())
}
}
#[test]
fn start_registers_actual_port_and_stop_deregisters_same_id() {
let center = Arc::new(FakeCenter::default());
let center_runtime = Runtime::new().unwrap();
let listener = center_runtime
.block_on(tokio::net::TcpListener::bind(("127.0.0.1", 0)))
.unwrap();
let center_port = listener.local_addr().unwrap().port();
let rpc = connectrpc::Router::new().add_service(Arc::clone(&center));
let app = Router::new().fallback_service(rpc.into_axum_service());
let (shutdown_tx, shutdown_rx) = oneshot::channel();
let (started_tx, started_rx) = mpsc::sync_channel(1);
let center_task = center_runtime.spawn(async move {
started_tx.send(()).unwrap();
axum::serve(listener, app)
.with_graceful_shutdown(async move {
let _ = shutdown_rx.await;
})
.await
});
started_rx.recv_timeout(Duration::from_secs(1)).unwrap();
let service = Service::new_value();
service
.configure(TerminalInfo {
terminal_host: "127.0.0.1".to_owned(),
terminal_port: 0,
terminal_mac: "00:11:22:33:44:55".to_owned(),
..Default::default()
})
.unwrap();
let server = RunningServer::start(&service, "127.0.0.1".to_owned(), center_port).unwrap();
let registered = center.registered.lock().unwrap().clone().unwrap();
assert_ne!(registered.terminal_port, 0);
assert_eq!(registered.terminal_port, u32::from(server.bound_port()));
assert_eq!(
service.meta_status_receiver().borrow().terminal_id,
CENTER_ASSIGNED_ID
);
let terminal_uri: axum::http::Uri = format!("http://127.0.0.1:{}", server.bound_port())
.parse()
.unwrap();
center_runtime.block_on(async {
let connection = Http2Connection::connect_plaintext(terminal_uri.clone())
.await
.unwrap();
let connection = connection.shared(32);
let config = ClientConfig::new(terminal_uri)
.with_protocol(Protocol::Grpc)
.with_default_timeout(Duration::from_secs(2));
let health = HealthClient::new(connection.clone(), config.clone());
for name in ["", "control.Terminal"] {
let response = health
.check(HealthCheckRequest {
service: name.into(),
..Default::default()
})
.await
.unwrap()
.into_owned();
assert_eq!(response.status, ServingStatus::SERVING);
}
let error = health
.check(HealthCheckRequest {
service: "missing".into(),
..Default::default()
})
.await
.unwrap_err();
assert_eq!(error.code, connectrpc::ErrorCode::NotFound);
let mut watcher = health.watch(HealthCheckRequest::default()).await.unwrap();
assert_eq!(
watcher
.message()
.await
.unwrap()
.unwrap()
.to_owned_message()
.status,
ServingStatus::SERVING
);
drop(watcher);
let mut watcher = health
.watch(HealthCheckRequest {
service: "missing".into(),
..Default::default()
})
.await
.unwrap();
assert_eq!(
watcher
.message()
.await
.unwrap()
.unwrap()
.to_owned_message()
.status,
ServingStatus::SERVICE_UNKNOWN
);
drop(watcher);
let client = TerminalClient::new(connection, config);
let response = client
.execute(Command {
id: "not-registered".to_owned(),
..Default::default()
})
.await
.unwrap()
.into_owned();
assert!(!response.success);
});
server.stop(&service).unwrap();
assert_eq!(
center.deregistered_id.lock().unwrap().as_deref(),
Some(CENTER_ASSIGNED_ID)
);
shutdown_tx.send(()).unwrap();
center_runtime.block_on(center_task).unwrap().unwrap();
}
+79
View File
@@ -0,0 +1,79 @@
use std::ptr;
use buffa::Message;
use proto::proto::control::TerminalInfo;
use crate::ffi::*;
#[test]
fn null_handles_are_rejected() {
assert_eq!(
unsafe { terminal_service_configure(ptr::null_mut(), ptr::null(), 0) },
TERMINAL_ERROR_NULL
);
assert_eq!(
unsafe { terminal_service_destroy(ptr::null_mut()) },
TERMINAL_ERROR_NULL
);
}
#[test]
fn invalid_protobuf_is_reported_through_last_error() {
let handle = terminal_service_create();
let invalid = [0xff_u8, 0xff];
assert_eq!(
unsafe { terminal_service_configure(handle, invalid.as_ptr(), invalid.len()) },
TERMINAL_ERROR_DECODE
);
let mut required = 0;
assert_eq!(
unsafe { terminal_service_last_error(handle, ptr::null_mut(), &mut required) },
TERMINAL_OK
);
assert!(required > 1);
let mut buffer = vec![0_u8; required];
assert_eq!(
unsafe { terminal_service_last_error(handle, buffer.as_mut_ptr(), &mut required) },
TERMINAL_OK
);
let message = std::str::from_utf8(&buffer[..required - 1]).unwrap();
assert!(message.starts_with("DECODE_FAILED:"));
assert_eq!(unsafe { terminal_service_destroy(handle) }, TERMINAL_OK);
}
#[test]
fn configured_service_can_be_destroyed() {
let handle = terminal_service_create();
let info = TerminalInfo {
terminal_host: "127.0.0.1".to_owned(),
terminal_port: 0,
terminal_mac: "00:11:22:33:44:55".to_owned(),
..Default::default()
}
.encode_to_vec();
assert_eq!(
unsafe { terminal_service_configure(handle, info.as_ptr(), info.len()) },
TERMINAL_OK
);
assert_eq!(unsafe { terminal_service_destroy(handle) }, TERMINAL_OK);
}
#[test]
fn null_callback_is_rejected() {
let handle = terminal_service_create();
let command_id = b"init";
assert_eq!(
unsafe {
terminal_service_register_command(
handle,
command_id.as_ptr(),
command_id.len(),
None,
ptr::null_mut(),
)
},
TERMINAL_ERROR_INVALID_ARGUMENT
);
assert_eq!(unsafe { terminal_service_destroy(handle) }, TERMINAL_OK);
}
+67
View File
@@ -0,0 +1,67 @@
use futures_util::StreamExt;
use proto::proto::control::TerminalInfo;
use proto::proto::grpc::health::v1::health_check_response::ServingStatus;
use crate::health::TerminalHealth;
use crate::terminal::Service;
#[tokio::test]
async fn lifecycle_health_stream_and_shutdown() {
let service = Service::new_value();
let health = TerminalHealth(service.clone());
let mut responses = health.responses("");
assert_eq!(
responses.next().await.unwrap().unwrap().status,
ServingStatus::NOT_SERVING
);
service
.configure(TerminalInfo {
terminal_host: "127.0.0.1".into(),
terminal_mac: "test".into(),
..Default::default()
})
.unwrap();
service.set_starting().unwrap();
assert_eq!(
service.health_receiver().borrow().status,
ServingStatus::NOT_SERVING
);
service.set_ready("id".into()).unwrap();
assert_eq!(
responses.next().await.unwrap().unwrap().status,
ServingStatus::SERVING
);
service.set_stopping().unwrap();
assert_eq!(
responses.next().await.unwrap().unwrap().status,
ServingStatus::NOT_SERVING
);
service.set_stopped();
service.set_starting().unwrap();
service.set_configured();
assert_eq!(
service.health_receiver().borrow().status,
ServingStatus::NOT_SERVING
);
service.signal_shutdown();
assert!(responses.next().await.is_none());
assert!(health.responses("").next().await.is_none());
}
#[tokio::test]
async fn unknown_watch_stays_open_until_shutdown() {
let service = Service::new_value();
let health = TerminalHealth(service.clone());
let mut responses = health.responses("missing");
assert_eq!(
responses.next().await.unwrap().unwrap().status,
ServingStatus::SERVICE_UNKNOWN
);
assert!(
tokio::time::timeout(std::time::Duration::from_millis(20), responses.next())
.await
.is_err()
);
service.signal_shutdown();
assert!(responses.next().await.is_none());
}
+3
View File
@@ -0,0 +1,3 @@
mod ffi;
mod health;
mod terminal;
+228
View File
@@ -0,0 +1,228 @@
use std::ffi::c_void;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use buffa::Message;
use proto::proto::control::{
Command, InvokeResponse, TerminalCancelEvent, TerminalEvent, TerminalEventHandle,
TerminalEventInfo, TerminalInfo, TerminalStatus,
};
use crate::callback::{CommandCallback, EventCallback, TerminalResponseSink};
use crate::terminal::Service;
unsafe extern "C" fn successful_command(
_user_data: *mut c_void,
_command: *const u8,
_command_len: usize,
sink: TerminalResponseSink,
sink_context: *mut c_void,
) -> i32 {
send_response(sink, sink_context, true)
}
unsafe extern "C" fn counted_event(
user_data: *mut c_void,
_event: *const u8,
_event_len: usize,
_instance_id: u64,
sink: TerminalResponseSink,
sink_context: *mut c_void,
) -> i32 {
unsafe { &*(user_data as *const AtomicUsize) }.fetch_add(1, Ordering::SeqCst);
send_response(sink, sink_context, true)
}
fn send_response(sink: TerminalResponseSink, sink_context: *mut c_void, success: bool) -> i32 {
let response = InvokeResponse {
success,
..Default::default()
}
.encode_to_vec();
unsafe { sink(sink_context, response.as_ptr(), response.len()) }
}
fn ready_service() -> Service {
let service = Service::new_value();
service
.configure(TerminalInfo {
terminal_host: "127.0.0.1".to_owned(),
terminal_port: 0,
terminal_mac: "00:11:22:33:44:55".to_owned(),
..Default::default()
})
.unwrap();
service.set_starting().unwrap();
service.set_ready("terminal-1".to_owned()).unwrap();
service
}
async fn initialize(service: &Service) {
service
.register_command(
"init".to_owned(),
CommandCallback::new(Some(successful_command), std::ptr::null_mut()).unwrap(),
)
.unwrap();
let response = service
.execute_command(Command {
id: "init".to_owned(),
..Default::default()
})
.await;
assert!(response.success);
}
#[test]
fn status_sequence_and_timestamp_are_managed_by_rust() {
let service = ready_service();
let receiver = service.status_receiver();
service
.push_status(TerminalStatus {
sequence: 999,
timestamp: -1,
..Default::default()
})
.unwrap();
let first = receiver.borrow().clone();
assert_eq!(first.sequence, 1);
assert!(first.timestamp > 0);
service.push_status(TerminalStatus::default()).unwrap();
assert_eq!(receiver.borrow().sequence, 2);
}
#[tokio::test]
async fn meta_status_is_derived_from_rust_owned_state() {
let service = ready_service();
initialize(&service).await;
let counter = AtomicUsize::new(0);
service
.register_event(
TerminalEventInfo {
event_id: "engine-fire".to_owned(),
..Default::default()
},
EventCallback::new(
Some(counted_event),
(&counter as *const AtomicUsize).cast_mut().cast::<c_void>(),
)
.unwrap(),
)
.unwrap();
let receiver = service.meta_status_receiver();
assert_eq!(receiver.borrow().terminal_id, "terminal-1");
assert_eq!(receiver.borrow().publishable_events.len(), 1);
let response = service
.publish_event(TerminalEvent {
event_id: "engine-fire".to_owned(),
trigger_delay_ms: 10_000,
..Default::default()
})
.await;
let handle = response
.message
.as_option()
.unwrap()
.unpack_if::<TerminalEventHandle>(TerminalEventHandle::TYPE_URL)
.unwrap()
.unwrap();
assert_eq!(
receiver.borrow().triggered_events.get(&handle.instance_id),
Some(&handle.event_id)
);
let cancelled = service.cancel_event(TerminalCancelEvent {
event_id: handle.event_id,
instance_id: handle.instance_id,
..Default::default()
});
assert!(cancelled.success);
assert!(receiver.borrow().triggered_events.is_empty());
}
#[tokio::test]
async fn repeating_event_waits_for_explicit_completion() {
let service = ready_service();
initialize(&service).await;
let counter = AtomicUsize::new(0);
service
.register_event(
TerminalEventInfo {
event_id: "repeat".to_owned(),
..Default::default()
},
EventCallback::new(
Some(counted_event),
(&counter as *const AtomicUsize).cast_mut().cast::<c_void>(),
)
.unwrap(),
)
.unwrap();
let response = service
.publish_event(TerminalEvent {
event_id: "repeat".to_owned(),
trigger_delay_ms: 10,
repeat_period_ms: 10,
..Default::default()
})
.await;
let handle = response
.message
.as_option()
.unwrap()
.unpack_if::<TerminalEventHandle>(TerminalEventHandle::TYPE_URL)
.unwrap()
.unwrap();
wait_for_count(&counter, 1).await;
tokio::time::sleep(Duration::from_millis(30)).await;
assert_eq!(counter.load(Ordering::SeqCst), 1);
service
.complete_event(
&handle,
&InvokeResponse {
success: true,
..Default::default()
},
)
.unwrap();
wait_for_count(&counter, 2).await;
service
.complete_event(
&handle,
&InvokeResponse {
success: false,
..Default::default()
},
)
.unwrap();
tokio::time::timeout(Duration::from_secs(1), async {
while service
.meta_status_receiver()
.borrow()
.triggered_events
.contains_key(&handle.instance_id)
{
tokio::task::yield_now().await;
}
})
.await
.unwrap();
}
async fn wait_for_count(counter: &AtomicUsize, expected: usize) {
tokio::time::timeout(Duration::from_secs(1), async {
while counter.load(Ordering::SeqCst) < expected {
tokio::task::yield_now().await;
}
})
.await
.unwrap();
}