#![cfg(all(feature = "plugin-host", not(target_arch = "wasm32")))]
use std::path::{Path, PathBuf};
use std::process::Command;
use repe::constants::{ErrorCode, QueryFormat};
use repe::message::Message;
use repe::plugin::host::{HostError, LoadOrigin, Plugin};
use repe::server::Router;
use std::sync::Arc;
fn plugin_library() -> PathBuf {
let output = Command::new(env!("CARGO"))
.current_dir(env!("CARGO_MANIFEST_DIR"))
.args([
"build",
"--features",
"plugin",
"--example",
"repe_plugin",
"--message-format=json-render-diagnostics",
])
.output()
.expect("cargo is on PATH inside a cargo test");
assert!(
output.status.success(),
"building the plugin example failed:\n{}",
String::from_utf8_lossy(&output.stderr)
);
let library = String::from_utf8(output.stdout)
.expect("cargo's JSON output is UTF-8")
.lines()
.filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
.filter(|message| message["reason"] == "compiler-artifact")
.filter(|message| message["target"]["name"] == "repe_plugin")
.filter_map(|message| {
message["filenames"]
.as_array()?
.iter()
.filter_map(|name| name.as_str())
.find(|name| name.ends_with(std::env::consts::DLL_SUFFIX))
.map(PathBuf::from)
})
.next_back()
.expect("the plugin example reports a shared library among its artifacts");
assert!(
library.is_file(),
"cargo reported an artifact that is not there: {}",
library.display()
);
library
}
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)
.unwrap()
.build()
.to_vec()
}
fn parse(response: &[u8]) -> Message {
Message::from_slice(response).expect("the plugin answers with a REPE frame")
}
#[test]
fn a_real_shared_library_loads_and_serves() {
let path = plugin_library();
let plugin = unsafe { Plugin::load(&path) }.expect("the example is a conforming plugin");
assert_eq!(
plugin.load_origin(),
LoadOrigin::Mapped,
"nothing in this binary links the plugin, so this load mapped it"
);
assert_eq!(plugin.root_path(), "/instrument");
assert_eq!(plugin.interface_version(), 3);
assert_eq!(plugin.name(), env!("CARGO_PKG_NAME"));
assert_eq!(plugin.version(), env!("CARGO_PKG_VERSION"));
assert_eq!(plugin.path(), path);
let response = plugin
.call(&read("/instrument/gain", 1))
.expect("the call crosses the ABI")
.expect("a non-notify read produces a response");
let message = parse(&response);
assert_eq!(message.error_code(), Some(ErrorCode::Ok));
assert_eq!(message.json_body::<f64>().unwrap(), 1.0);
assert_eq!(message.header.id, 1, "the response echoes the request id");
assert_eq!(message.query_utf8(), "/instrument/gain");
assert!(
plugin
.call(&write("/instrument/channel", 2, &6u32))
.unwrap()
.is_some(),
"a write is acknowledged"
);
let response = plugin
.call(&read("/instrument/channel", 3))
.unwrap()
.unwrap();
assert_eq!(parse(&response).json_body::<u32>().unwrap(), 6);
let response = plugin
.call(&write("/instrument/calibrate", 4, &8.0f64))
.unwrap()
.unwrap();
assert_eq!(parse(&response).json_body::<f64>().unwrap(), 4.0);
let response = plugin
.call(&write("/instrument/calibrate", 5, &-1.0f64))
.unwrap()
.expect("a failing handler still answers");
let message = parse(&response);
assert!(message.is_error());
assert!(
message
.error_message_utf8()
.is_some_and(|text| text.contains("instrument fault")),
"the error frame carries the handler's own message"
);
let response = plugin
.call(&read("/instrument/samples", 6))
.unwrap()
.unwrap();
let message = parse(&response);
assert_eq!(message.decode_typed_slice::<f64>().unwrap().len(), 8);
let notify = Message::builder()
.id(7)
.notify(true)
.query_str("/instrument/reset")
.query_format(QueryFormat::JsonPointer)
.build()
.to_vec();
assert!(
plugin.call(¬ify).unwrap().is_none(),
"a notify answers with size 0, which is `send nothing` rather than an error"
);
let response = plugin
.call(&read("/instrument/absent", 8))
.unwrap()
.unwrap();
assert_eq!(
parse(&response).error_code(),
Some(ErrorCode::MethodNotFound)
);
let response = plugin
.call(b"not a repe frame at all")
.unwrap()
.expect("a malformed frame is answered, not dropped");
let message = parse(&response);
assert!(message.is_error());
assert_eq!(message.header.id, 0, "the id could not be read");
let second = unsafe { Plugin::load(&path) }.expect("a second load is not a failure");
assert_eq!(
second.load_origin(),
LoadOrigin::AlreadyResident,
"the second load reached the resident copy; a host that reports it as a \
successful reload is reporting a no-op"
);
let response = second
.call(&read("/instrument/channel", 9))
.unwrap()
.unwrap();
assert_eq!(
parse(&response).json_body::<u32>().unwrap(),
6,
"both handles drive one instance, so the state is shared"
);
{
let mounted = unsafe { Plugin::load(&path) }.expect("already resident");
assert_eq!(mounted.load_origin(), LoadOrigin::AlreadyResident);
let router = Router::new()
.with_json("/local", |_| Ok(serde_json::json!("served by the host")))
.with_fallback(Arc::new(mounted));
let message = parse(
&router
.call(&write("/local", 11, &serde_json::Value::Null))
.unwrap(),
);
assert_eq!(message.json_body::<String>().unwrap(), "served by the host");
let message = parse(&router.call(&read("/instrument/channel", 12)).unwrap());
assert_eq!(message.json_body::<u32>().unwrap(), 6);
assert_eq!(message.header.id, 12);
assert_eq!(message.query_utf8(), "/instrument/channel");
let message = parse(&router.call(&read("/instrument/samples", 13)).unwrap());
assert_eq!(message.decode_typed_slice::<f64>().unwrap().len(), 8);
let message = parse(&router.call(&read("/elsewhere", 14)).unwrap());
assert_eq!(message.error_code(), Some(ErrorCode::MethodNotFound));
let frame = router
.call(&read("/instrument/absent", 141))
.expect("answered");
let message = Message::from_slice(&frame).unwrap();
assert_eq!(message.error_code(), Some(ErrorCode::MethodNotFound));
let text = message.error_message_utf8().unwrap();
assert!(
!text.starts_with("Method not found:"),
"the plugin's own frame was replaced by the host's: {text:?}"
);
router
.call(&write("/instrument/calibrate", 15, &8.0f64))
.expect("answered");
let notify = Message::builder()
.id(16)
.notify(true)
.query_str("/instrument/reset")
.query_format(QueryFormat::JsonPointer)
.build()
.to_vec();
assert!(router.call(¬ify).is_none());
let frame = router
.call(&read("/instrument/gain", 17))
.expect("answered");
assert_eq!(
Message::from_slice(&frame)
.unwrap()
.json_body::<f64>()
.unwrap(),
1.0,
"the notify reached the plugin and reset its gain"
);
}
plugin.shutdown();
let response = second
.call(&read("/instrument/gain", 10))
.unwrap()
.expect("a call after shutdown is answered, not dropped");
assert!(parse(&response).is_error());
let error = unsafe { Plugin::load(&path) }
.expect_err("a shut-down plugin cannot be brought back by reloading it");
assert!(
matches!(error, HostError::InitFailed { code, .. } if code == 1),
"the refusal comes from the plugin's own initializer, got {error}"
);
}
#[test]
fn a_copy_at_a_new_path_is_a_fresh_load() {
let original = plugin_library();
let copy = original.with_file_name(format!(
"repe_plugin_fresh_path_copy{}",
std::env::consts::DLL_SUFFIX
));
std::fs::copy(&original, ©).expect("the target directory is writable");
let plugin = unsafe { Plugin::load(©) }.expect("the copy is the same conforming plugin");
assert_eq!(
plugin.load_origin(),
LoadOrigin::Mapped,
"a path the loader has never seen is a fresh load, whatever is resident \
under another name"
);
assert_eq!(plugin.root_path(), "/instrument");
let again = unsafe { Plugin::load(©) }.expect("a second load is not a failure");
assert_eq!(again.load_origin(), LoadOrigin::AlreadyResident);
}
#[test]
fn a_file_that_is_not_a_library_is_refused_by_the_loader() {
let not_a_library = Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml");
let error =
unsafe { Plugin::load(¬_a_library) }.expect_err("the dynamic loader refuses a manifest");
assert!(
matches!(error, HostError::Load { ref path, .. } if path == ¬_a_library),
"the error names the path that failed, got {error}"
);
}