use std::process::ExitCode;
use repe::constants::{ErrorCode, QueryFormat};
use repe::message::{Message, MessageView};
use repe::plugin::host::{HostError, LoadOrigin, Plugin};
use repe::server::Router;
struct Checks {
failures: u32,
}
impl Checks {
fn check(&mut self, ok: bool, what: &str) {
println!(" {} {what}", if ok { "ok " } else { "FAIL" });
if !ok {
self.failures += 1;
}
}
}
fn read(query: &str, id: u64) -> Vec<u8> {
Message::builder()
.id(id)
.query_str(query)
.query_format(QueryFormat::JsonPointer)
.build()
.to_vec()
}
fn write<T: serde::Serialize>(query: &str, id: u64, value: &T) -> Vec<u8> {
Message::builder()
.id(id)
.query_str(query)
.query_format(QueryFormat::JsonPointer)
.body_json(value)
.expect("the values in this example serialize")
.build()
.to_vec()
}
fn notify(query: &str, id: u64) -> Vec<u8> {
Message::builder()
.id(id)
.notify(true)
.query_str(query)
.query_format(QueryFormat::JsonPointer)
.build()
.to_vec()
}
fn run(path: &str) -> Result<u32, HostError> {
let plugin = unsafe { Plugin::load(path) }?;
let mut checks = Checks { failures: 0 };
let root = plugin.root_path().to_string();
println!("metadata");
println!(
" name='{}' version='{}' root='{}' abi={} origin={:?}",
plugin.name(),
plugin.version(),
root,
plugin.interface_version(),
plugin.load_origin()
);
checks.check(root.starts_with('/'), "root_path is an absolute prefix");
checks.check(!plugin.name().is_empty(), "the plugin reports a name");
println!("routing");
{
let frame = read(&format!("{root}/gain"), 1);
let query = MessageView::from_slice(&frame)
.expect("a frame this process just built parses")
.query_str()
.expect("the query is UTF-8")
.to_string();
checks.check(
plugin.claims(&query),
"the request query matches the plugin's claimed root",
);
checks.check(
!plugin.claims(&format!("{root}_other/gain")),
"a plugin whose root shares a prefix with this one is not claimed",
);
}
println!("field read");
{
let response = plugin
.call(&read(&format!("{root}/gain"), 1))?
.expect("a non-notify read produces a response");
let message = Message::from_slice(&response).expect("the response is a REPE frame");
checks.check(
message.json_body::<f64>().is_ok_and(|gain| gain == 1.0),
"read /gain returns the constructed value",
);
checks.check(message.header.id == 1, "the response echoes the request id");
}
println!("field write");
{
let acknowledged = plugin.call(&write(&format!("{root}/channel"), 2, &6u32))?;
checks.check(acknowledged.is_some(), "a write is acknowledged");
let response = plugin
.call(&read(&format!("{root}/channel"), 3))?
.expect("a non-notify read produces a response");
let message = Message::from_slice(&response).expect("the response is a REPE frame");
checks.check(
message.json_body::<u32>().is_ok_and(|channel| channel == 6),
"the read observes what the write left behind",
);
}
println!("method call");
{
let response = plugin
.call(&write(&format!("{root}/calibrate"), 4, &8.0f64))?
.expect("a non-notify call produces a response");
let message = Message::from_slice(&response).expect("the response is a REPE frame");
checks.check(
message.json_body::<f64>().is_ok_and(|gain| gain == 4.0),
"the method returns its computed result",
);
}
println!("zero-argument method");
{
let response = plugin
.call(&read(&format!("{root}/identify"), 5))?
.expect("a non-notify call produces a response");
let message = Message::from_slice(&response).expect("the response is a REPE frame");
checks.check(
message
.json_body::<String>()
.is_ok_and(|identity| identity.starts_with("instrument fw")),
"the method result decodes as a string",
);
}
println!("notify");
{
let response = plugin.call(¬ify(&format!("{root}/reset"), 6))?;
checks.check(
response.is_none(),
"a notify answers with size 0, which the host reads as `send nothing`",
);
}
println!("unknown method");
{
let response = plugin
.call(&read(&format!("{root}/absent"), 7))?
.expect("an unknown method is answered, not dropped");
let message = Message::from_slice(&response).expect("the response is a REPE frame");
checks.check(
message.error_code() == Some(ErrorCode::MethodNotFound),
"an unknown method is method_not_found, not a dropped frame",
);
}
println!("malformed frame");
{
let response = plugin
.call(b"not a repe frame at all")?
.expect("a malformed frame is answered, not silently dropped");
let message = Message::from_slice(&response).expect("the answer is still a REPE frame");
checks.check(
message.is_error(),
"a malformed frame is answered with an error",
);
checks.check(
message.header.id == 0,
"the id is 0, because it could not be read",
);
}
println!("mounted on a router");
{
let mounted = unsafe { Plugin::load(path) }?;
checks.check(
mounted.load_origin() == LoadOrigin::AlreadyResident,
"a second load of one path reports itself as already resident",
);
let router = Router::new()
.with_json("/host/ping", |_| Ok(serde_json::json!("pong")))
.with_fallback_blocking(std::sync::Arc::new(mounted));
let frame = router
.call(&write("/host/ping", 8, &serde_json::Value::Null))
.expect("the host route answers");
let message = Message::from_slice(&frame).expect("the response is a REPE frame");
checks.check(
message
.json_body::<String>()
.is_ok_and(|pong| pong == "pong"),
"a route the host owns is not shadowed by the fallback",
);
let frame = router
.call(&read(&format!("{root}/channel"), 9))
.expect("the plugin answers through the router");
let message = Message::from_slice(&frame).expect("the response is a REPE frame");
checks.check(
message.json_body::<u32>().is_ok_and(|channel| channel == 6),
"a request under the plugin's root reaches the plugin",
);
checks.check(message.header.id == 9, "the mounted response keeps the id");
let frame = router
.call(&read("/not/claimed/by/anyone", 10))
.expect("a declined path is answered rather than dropped");
let message = Message::from_slice(&frame).expect("the response is a REPE frame");
checks.check(
message.error_code() == Some(ErrorCode::MethodNotFound),
"a path outside the plugin's root is method_not_found",
);
router.call(&write(&format!("{root}/calibrate"), 11, &8.0f64));
checks.check(
router.call(¬ify(&format!("{root}/reset"), 12)).is_none(),
"notify semantics carry through the mount",
);
let frame = router
.call(&read(&format!("{root}/gain"), 13))
.expect("answered");
let message = Message::from_slice(&frame).expect("the response is a REPE frame");
checks.check(
message.json_body::<f64>().is_ok_and(|gain| gain == 1.0),
"the notify reached the plugin and reset its gain",
);
}
println!("shutdown");
{
plugin.shutdown();
}
Ok(checks.failures)
}
fn main() -> ExitCode {
let Some(path) = std::env::args().nth(1) else {
eprintln!("usage: plugin_host <path-to-plugin-library>");
return ExitCode::from(2);
};
match run(&path) {
Ok(0) => {
println!("\nplugin host: PASS");
ExitCode::SUCCESS
}
Ok(failures) => {
println!("\nplugin host: FAIL ({failures} check(s))");
ExitCode::FAILURE
}
Err(error) => {
eprintln!("plugin host: {error}");
ExitCode::from(2)
}
}
}