sdk: readable clients (no Empty wrapper, no unused error module), documented examples with tests
This commit is contained in:
@@ -1,4 +1,6 @@
|
||||
//! Serve files from `/state/www` and expose a control endpoint at `/self/control`.
|
||||
//! Start this process detached or as a service so it outlives its caller.
|
||||
//! Clients read `/proc/<pid>/control`. A fresh core call cannot inspect this process's counters.
|
||||
use sausage_plugin::{Ctx, Result, background, listen, pid, rpc, schema, state_dir};
|
||||
use std::{cell::Cell, rc::Rc};
|
||||
use wstd::{
|
||||
@@ -6,6 +8,7 @@ use wstd::{
|
||||
iter::AsyncIterator,
|
||||
net::TcpListener,
|
||||
};
|
||||
/// The HTTP plugin starts a server and returns its process ID.
|
||||
struct Www;
|
||||
/// The server configuration.
|
||||
#[schema]
|
||||
@@ -24,7 +27,9 @@ impl Www {
|
||||
Ok(pid())
|
||||
}
|
||||
}
|
||||
/// Shared process-local state for the HTTP task and its endpoint.
|
||||
struct Control {
|
||||
/// The number of answered requests.
|
||||
hits: Cell<u64>,
|
||||
}
|
||||
#[rpc]
|
||||
@@ -39,6 +44,7 @@ impl Control {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
/// Answer HTTP requests with files and count all responses, including missing files.
|
||||
async fn serve(tcp: TcpListener, control: Rc<Control>) {
|
||||
let mut incoming = tcp.incoming();
|
||||
while let Some(Ok(mut stream)) = incoming.next().await {
|
||||
@@ -70,6 +76,22 @@ async fn serve(tcp: TcpListener, control: Rc<Control>) {
|
||||
let _ = stream.flush().await;
|
||||
}
|
||||
}
|
||||
/// Start the SDK transport for the HTTP plugin.
|
||||
fn main() {
|
||||
sausage_plugin::run(Www)
|
||||
}
|
||||
/// Tests check local counters and the service entry point.
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
/// Control reports its shared counter without a core round trip.
|
||||
#[test]
|
||||
fn stats_reads_counter() {
|
||||
assert_eq!(Control { hits: Cell::new(3) }.stats().unwrap(), 3);
|
||||
}
|
||||
/// The listener binds an ephemeral port and publishes its control endpoint.
|
||||
#[sausage_plugin::test]
|
||||
async fn starts_on_available_port() {
|
||||
assert_eq!(Www.start(StartParams { port: 0 }).await.unwrap(), pid());
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user