use core::ffi::{CStr, c_char};
use std::ops::RangeInclusive;
use std::path::{Path, PathBuf};
use libloading::Library;
use crate::constants::ErrorCode;
use crate::error::RepeError;
use crate::message::{Message, MessageView, create_error_response_for};
use crate::peer::CallContext;
use crate::server::HandlerErased;
use super::{REPE_PLUGIN_INTERFACE_VERSION, RepeBuffer, RepePluginData, RepeResult};
const MIN_SUPPORTED_INTERFACE_VERSION: u32 = 3;
const _: () = assert!(MIN_SUPPORTED_INTERFACE_VERSION <= REPE_PLUGIN_INTERFACE_VERSION);
pub fn supported_interface_versions() -> RangeInclusive<u32> {
MIN_SUPPORTED_INTERFACE_VERSION..=REPE_PLUGIN_INTERFACE_VERSION
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum HostError {
#[error("could not load plugin library {}: {source}", path.display())]
Load {
path: PathBuf,
#[source]
source: libloading::Error,
},
#[error("plugin library {} does not export `{symbol}`: {source}", path.display())]
MissingSymbol {
path: PathBuf,
symbol: &'static str,
#[source]
source: libloading::Error,
},
#[error(
"plugin library {} reports ABI version {reported}; this host supports {}..={}",
path.display(),
supported_interface_versions().start(),
supported_interface_versions().end()
)]
UnsupportedInterfaceVersion {
path: PathBuf,
reported: u32,
},
#[error("plugin library {} has unusable metadata: {reason}", path.display())]
Metadata {
path: PathBuf,
reason: String,
},
#[error("repe_plugin_init in {} failed with code {code}", path.display())]
InitFailed {
path: PathBuf,
code: i32,
},
#[error("repe_plugin_call returned a null data pointer with size {size}")]
NullResponse {
size: u64,
},
#[error("repe_plugin_call returned {size} bytes, more than this target can address")]
ResponseTooLarge {
size: u64,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum LoadOrigin {
Mapped,
AlreadyResident,
Unknown,
}
type InterfaceVersionFn = unsafe extern "C" fn() -> u32;
type InfoFn = unsafe extern "C" fn() -> *const RepePluginData;
type InitFn = unsafe extern "C" fn() -> i32;
type ShutdownFn = unsafe extern "C" fn();
type CallFn = unsafe extern "C" fn(*const c_char, u64) -> RepeBuffer;
struct PluginAbi {
interface_version: InterfaceVersionFn,
info: InfoFn,
init: Option<InitFn>,
shutdown: Option<ShutdownFn>,
call: CallFn,
}
pub struct Plugin {
path: PathBuf,
origin: LoadOrigin,
interface_version: u32,
name: String,
version: String,
root_path: String,
call: CallFn,
shutdown: Option<ShutdownFn>,
}
static EMPTY_REQUEST_ANCHOR: u8 = 0;
impl Plugin {
pub unsafe fn load(path: impl AsRef<Path>) -> Result<Self, HostError> {
let path = path.as_ref().to_path_buf();
let origin = probe_origin(&path);
let library = match unsafe { open(&path) } {
Ok(library) => library,
Err(source) => return Err(HostError::Load { path, source }),
};
let interface_version = required(&library, &path, "repe_plugin_interface_version");
let info = required(&library, &path, "repe_plugin_info");
let init = optional(&library, "repe_plugin_init");
let shutdown = optional(&library, "repe_plugin_shutdown");
let call = required(&library, &path, "repe_plugin_call");
std::mem::forget(library);
let abi = PluginAbi {
interface_version: interface_version?,
info: info?,
init,
shutdown,
call: call?,
};
unsafe { Self::from_abi(path, abi, origin) }
}
unsafe fn from_abi(
path: PathBuf,
abi: PluginAbi,
origin: LoadOrigin,
) -> Result<Self, HostError> {
let interface_version = unsafe { (abi.interface_version)() };
if !supported_interface_versions().contains(&interface_version) {
return Err(HostError::UnsupportedInterfaceVersion {
path,
reported: interface_version,
});
}
let info = unsafe { (abi.info)() };
if info.is_null() {
return Err(HostError::Metadata {
path,
reason: "repe_plugin_info returned NULL".to_string(),
});
}
let info = unsafe { *info };
let name = unsafe { string_field(info.name, "name", &path) }?;
let version = unsafe { string_field(info.version, "version", &path) }?;
let root_path = unsafe { string_field(info.root_path, "root_path", &path) }?;
if !root_path.is_empty() && !root_path.starts_with('/') {
return Err(HostError::Metadata {
path,
reason: format!(
"root_path {root_path:?} is not an absolute JSON Pointer prefix: it must start with `/`"
),
});
}
if root_path.len() > 1 && root_path.ends_with('/') {
return Err(HostError::Metadata {
path,
reason: format!(
"root_path {root_path:?} ends with `/`, which no request query it is matched against will"
),
});
}
if let Some(init) = abi.init {
let code = unsafe { init() };
if code != RepeResult::Ok as i32 && code != RepeResult::AlreadyInitialized as i32 {
return Err(HostError::InitFailed { path, code });
}
}
Ok(Self {
path,
origin,
interface_version,
name,
version,
root_path,
call: abi.call,
shutdown: abi.shutdown,
})
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn load_origin(&self) -> LoadOrigin {
self.origin
}
pub fn interface_version(&self) -> u32 {
self.interface_version
}
pub fn name(&self) -> &str {
&self.name
}
pub fn version(&self) -> &str {
&self.version
}
pub fn root_path(&self) -> &str {
&self.root_path
}
pub fn claims(&self, query: &str) -> bool {
match query.strip_prefix(self.root_path.as_str()) {
Some("") => true,
Some(rest) => rest.starts_with('/'),
None => false,
}
}
pub fn call(&self, request: &[u8]) -> Result<Option<Vec<u8>>, HostError> {
let mut response = Vec::new();
if self.call_into(request, &mut response)? {
Ok(Some(response))
} else {
Ok(None)
}
}
pub fn call_into(&self, request: &[u8], response: &mut Vec<u8>) -> Result<bool, HostError> {
response.clear();
let data = if request.is_empty() {
&raw const EMPTY_REQUEST_ANCHOR
} else {
request.as_ptr()
};
let buffer = unsafe { (self.call)(data.cast::<c_char>(), request.len() as u64) };
if buffer.size == 0 {
return Ok(false);
}
let size = match usize::try_from(buffer.size) {
Ok(size) if size <= isize::MAX as usize => size,
_ => return Err(HostError::ResponseTooLarge { size: buffer.size }),
};
if buffer.data.is_null() {
return Err(HostError::NullResponse { size: buffer.size });
}
response.extend_from_slice(unsafe {
std::slice::from_raw_parts(buffer.data.cast::<u8>(), size)
});
Ok(true)
}
pub fn shutdown(self) {
if let Some(shutdown) = self.shutdown {
unsafe { shutdown() };
}
}
}
impl HandlerErased for Plugin {
fn handle(&self, req: &Message) -> Result<Message, RepeError> {
if !self.claims(req.query_str().unwrap_or("")) {
return Ok(self.disclaim(req.header.id, &req.query));
}
let mut frame = Vec::with_capacity(req.serialized_len());
req.write_to(&mut frame)?;
Ok(self.forward(req.header, &req.query, &frame))
}
fn handle_view(&self, view: &MessageView, _ctx: &CallContext) -> Result<Message, RepeError> {
if !self.claims(std::str::from_utf8(view.query).unwrap_or("")) {
return Ok(self.disclaim(view.header.id, view.query));
}
let mut frame =
Vec::with_capacity(crate::constants::HEADER_SIZE + view.query.len() + view.body.len());
crate::io::write_message_streaming(
&mut frame,
view.header,
view.query,
view.body.len() as u64,
|w| std::io::Write::write_all(w, view.body),
)?;
Ok(self.forward(view.header, view.query, &frame))
}
}
impl Plugin {
fn disclaim(&self, id: u64, query: &[u8]) -> Message {
create_error_response_for(
id,
query,
ErrorCode::MethodNotFound,
format!("Method not found: {}", String::from_utf8_lossy(query)),
)
}
fn forward(&self, header: crate::header::Header, query: &[u8], frame: &[u8]) -> Message {
let error = |code, message| create_error_response_for(header.id, query, code, message);
let mut response = Vec::new();
match self.call_into(frame, &mut response) {
Ok(true) => match Message::from_slice(&response) {
Ok(message) => message,
Err(err) => error(
ErrorCode::InternalError,
format!(
"plugin `{}` answered with a frame that does not parse: {err}",
self.name
),
),
},
Ok(false) if header.notify == 1 => Message::builder().id(header.id).build(),
Ok(false) => error(
ErrorCode::InternalError,
format!(
"plugin `{}` returned no response to a request that expects one",
self.name
),
),
Err(err) => error(ErrorCode::InternalError, err.to_string()),
}
}
}
impl std::fmt::Debug for Plugin {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Plugin")
.field("path", &self.path)
.field("name", &self.name)
.field("version", &self.version)
.field("root_path", &self.root_path)
.field("interface_version", &self.interface_version)
.field("has_shutdown", &self.shutdown.is_some())
.finish()
}
}
unsafe fn open(path: &Path) -> Result<Library, libloading::Error> {
#[cfg(unix)]
unsafe {
use libloading::os::unix::{RTLD_LOCAL, RTLD_NOW};
libloading::os::unix::Library::open(Some(path), RTLD_NOW | RTLD_LOCAL).map(Library::from)
}
#[cfg(not(unix))]
unsafe {
Library::new(path)
}
}
#[cfg(all(
unix,
not(any(
target_os = "openbsd",
target_os = "haiku",
target_os = "aix",
target_os = "vxworks"
))
))]
fn probe_origin(path: &Path) -> LoadOrigin {
use libloading::os::unix::{Library, RTLD_LAZY, RTLD_LOCAL};
let resident =
unsafe { Library::open(Some(path), libc::RTLD_NOLOAD | RTLD_LAZY | RTLD_LOCAL) }.is_ok();
if resident {
LoadOrigin::AlreadyResident
} else {
LoadOrigin::Mapped
}
}
#[cfg(all(
unix,
any(
target_os = "openbsd",
target_os = "haiku",
target_os = "aix",
target_os = "vxworks"
)
))]
fn probe_origin(_path: &Path) -> LoadOrigin {
LoadOrigin::Unknown
}
#[cfg(not(unix))]
fn probe_origin(path: &Path) -> LoadOrigin {
if libloading::os::windows::Library::open_already_loaded(path).is_ok() {
LoadOrigin::AlreadyResident
} else {
LoadOrigin::Mapped
}
}
fn required<T: Copy>(library: &Library, path: &Path, symbol: &'static str) -> Result<T, HostError> {
match unsafe { library.get::<T>(symbol.as_bytes()) } {
Ok(symbol) => Ok(*symbol),
Err(source) => Err(HostError::MissingSymbol {
path: path.to_path_buf(),
symbol,
source,
}),
}
}
fn optional<T: Copy>(library: &Library, symbol: &'static str) -> Option<T> {
unsafe { library.get::<T>(symbol.as_bytes()) }
.ok()
.map(|symbol| *symbol)
}
unsafe fn string_field(
field: *const c_char,
name: &'static str,
path: &Path,
) -> Result<String, HostError> {
if field.is_null() {
return Err(HostError::Metadata {
path: path.to_path_buf(),
reason: format!("repe_plugin_data::{name} is NULL"),
});
}
let field = unsafe { CStr::from_ptr(field) };
field
.to_str()
.map(str::to_string)
.map_err(|_| HostError::Metadata {
path: path.to_path_buf(),
reason: format!("repe_plugin_data::{name} is not valid UTF-8"),
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::constants::{ErrorCode, QueryFormat};
use crate::message::Message;
use crate::plugin::PluginRuntime;
use crate::server::Router;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
mod good {
use super::*;
static RUNTIME: PluginRuntime = PluginRuntime::new(build);
fn build() -> Router {
Router::new().with_typed("/example/double", |v: i64| Ok(v * 2))
}
pub unsafe extern "C" fn interface_version() -> u32 {
REPE_PLUGIN_INTERFACE_VERSION
}
pub unsafe extern "C" fn info() -> *const RepePluginData {
static DATA: RepePluginData = RepePluginData {
name: c"example".as_ptr(),
version: c"1.0.0".as_ptr(),
root_path: c"/example".as_ptr(),
};
&raw const DATA
}
pub unsafe extern "C" fn init() -> i32 {
RUNTIME.init() as i32
}
pub unsafe extern "C" fn shutdown() {
RUNTIME.shutdown();
}
pub unsafe extern "C" fn call(request: *const c_char, size: u64) -> RepeBuffer {
unsafe { RUNTIME.call(request, size) }
}
}
fn abi() -> PluginAbi {
PluginAbi {
interface_version: good::interface_version,
info: good::info,
init: Some(good::init),
shutdown: Some(good::shutdown),
call: good::call,
}
}
fn load(abi: PluginAbi) -> Result<Plugin, HostError> {
unsafe { Plugin::from_abi(PathBuf::from("in-process"), abi, LoadOrigin::Mapped) }
}
fn request<T: structio::json::Write + ?Sized>(path: &str, body: &T, notify: bool) -> Vec<u8> {
Message::builder()
.id(7)
.notify(notify)
.query_str(path)
.query_format(QueryFormat::JsonPointer)
.body_json(body)
.build()
.to_vec()
}
#[test]
fn a_conforming_plugin_loads_and_serves() {
let plugin = load(abi()).expect("a conforming plugin loads");
assert_eq!(plugin.name(), "example");
assert_eq!(plugin.version(), "1.0.0");
assert_eq!(plugin.root_path(), "/example");
assert_eq!(plugin.interface_version(), REPE_PLUGIN_INTERFACE_VERSION);
let response = plugin
.call(&request("/example/double", &21i64, false))
.expect("the call crosses the ABI")
.expect("a non-notify request produces a response");
let response = Message::from_slice(&response).unwrap();
assert_eq!(response.error_code(), Some(ErrorCode::Ok));
assert_eq!(response.body, b"42");
}
#[test]
fn a_notify_produces_no_response() {
let plugin = load(abi()).expect("a conforming plugin loads");
let response = plugin
.call(&request("/example/double", &1i64, true))
.expect("the call crosses the ABI");
assert!(
response.is_none(),
"a zero-size buffer is `no response`, not an error"
);
}
#[test]
fn call_into_reuses_the_caller_s_buffer() {
let plugin = load(abi()).expect("a conforming plugin loads");
let mut buffer = Vec::new();
assert!(
plugin
.call_into(&request("/example/double", &2i64, false), &mut buffer)
.unwrap()
);
let after_first = buffer.capacity();
assert!(!buffer.is_empty());
assert!(
!plugin
.call_into(&request("/example/double", &2i64, true), &mut buffer)
.unwrap()
);
assert!(buffer.is_empty());
assert_eq!(buffer.capacity(), after_first, "the allocation is reused");
}
#[test]
fn an_empty_request_is_answered_rather_than_dereferenced() {
let plugin = load(abi()).expect("a conforming plugin loads");
let response = plugin
.call(&[])
.expect("the call crosses the ABI")
.expect("an empty request is answered, not dropped");
let response = Message::from_slice(&response).unwrap();
assert_ne!(response.error_code(), Some(ErrorCode::Ok));
}
#[test]
fn a_handler_error_is_forwarded_rather_than_reported_as_a_host_error() {
let plugin = load(abi()).expect("a conforming plugin loads");
let response = plugin
.call(&request("/example/absent", &None::<i64>, false))
.expect("an unknown method is not a host error")
.expect("it is answered rather than dropped");
let response = Message::from_slice(&response).unwrap();
assert_eq!(response.error_code(), Some(ErrorCode::MethodNotFound));
}
#[test]
fn an_unsupported_interface_version_is_refused_before_the_metadata_is_read() {
unsafe extern "C" fn from_the_future() -> u32 {
REPE_PLUGIN_INTERFACE_VERSION + 1
}
unsafe extern "C" fn unreadable_info() -> *const RepePluginData {
unreachable!("the metadata must not be read before the version is cleared")
}
let error = load(PluginAbi {
interface_version: from_the_future,
info: unreadable_info,
..abi()
})
.expect_err("a version this host does not speak is refused");
assert!(matches!(
error,
HostError::UnsupportedInterfaceVersion { reported, .. }
if reported == REPE_PLUGIN_INTERFACE_VERSION + 1
));
}
#[test]
fn an_empty_root_path_is_accepted_and_claims_everything() {
unsafe extern "C" fn top_level() -> *const RepePluginData {
static DATA: RepePluginData = RepePluginData {
name: c"example".as_ptr(),
version: c"1.0.0".as_ptr(),
root_path: c"".as_ptr(),
};
&raw const DATA
}
let plugin = load(PluginAbi {
info: top_level,
..abi()
})
.expect("an empty root is a plugin published at the top level");
assert_eq!(plugin.root_path(), "");
assert!(plugin.claims("/gain"));
assert!(plugin.claims("/anything/at/all"));
}
#[test]
fn claims_puts_the_separator_in_the_comparison() {
let plugin = load(abi()).expect("a conforming plugin loads");
assert_eq!(plugin.root_path(), "/example");
assert!(plugin.claims("/example"), "the object itself");
assert!(plugin.claims("/example/double"), "something under it");
assert!(!plugin.claims("/example_two/double"));
assert!(!plugin.claims("/examples"));
assert!(!plugin.claims("/other/double"));
assert!(!plugin.claims("example/double"), "not absolute");
}
#[test]
fn null_metadata_is_a_refusal() {
unsafe extern "C" fn no_info() -> *const RepePluginData {
std::ptr::null()
}
let error = load(PluginAbi {
info: no_info,
..abi()
})
.expect_err("`plugin.h` gives NULL the meaning `refuse to load`");
assert!(matches!(error, HostError::Metadata { .. }));
}
#[test]
fn a_null_metadata_field_is_a_refusal_rather_than_a_dereference() {
unsafe extern "C" fn null_name() -> *const RepePluginData {
static DATA: RepePluginData = RepePluginData {
name: std::ptr::null(),
version: c"1.0.0".as_ptr(),
root_path: c"/example".as_ptr(),
};
&raw const DATA
}
let error = load(PluginAbi {
info: null_name,
..abi()
})
.expect_err("a null field cannot be read");
assert!(matches!(error, HostError::Metadata { reason, .. } if reason.contains("name")));
}
#[test]
fn a_root_path_that_could_never_match_is_refused_at_load() {
unsafe extern "C" fn relative_root() -> *const RepePluginData {
static DATA: RepePluginData = RepePluginData {
name: c"example".as_ptr(),
version: c"1.0.0".as_ptr(),
root_path: c"example".as_ptr(),
};
&raw const DATA
}
unsafe extern "C" fn trailing_separator() -> *const RepePluginData {
static DATA: RepePluginData = RepePluginData {
name: c"example".as_ptr(),
version: c"1.0.0".as_ptr(),
root_path: c"/example/".as_ptr(),
};
&raw const DATA
}
for (info, why) in [
(relative_root as InfoFn, "relative"),
(trailing_separator as InfoFn, "trailing separator"),
] {
let error = load(PluginAbi { info, ..abi() })
.err()
.unwrap_or_else(|| panic!("a {why} root_path is refused"));
assert!(
matches!(error, HostError::Metadata { ref reason, .. } if reason.contains("root_path")),
"a {why} root_path reports what is wrong with it, got {error}"
);
}
}
#[test]
fn a_failed_initializer_stops_the_load() {
unsafe extern "C" fn refuses() -> i32 {
RepeResult::InitFailed as i32
}
let error = load(PluginAbi {
init: Some(refuses),
..abi()
})
.expect_err("a plugin that cannot initialize is not usable");
assert!(matches!(error, HostError::InitFailed { code, .. } if code == 1));
}
#[test]
fn an_already_initialized_plugin_is_not_a_failure() {
unsafe extern "C" fn already() -> i32 {
RepeResult::AlreadyInitialized as i32
}
load(PluginAbi {
init: Some(already),
..abi()
})
.expect("ALREADY_INITIALIZED is a plugin that is up");
}
#[test]
fn an_unrecognized_init_code_is_reported_rather_than_transmuted() {
unsafe extern "C" fn errno_ish() -> i32 {
13
}
let error = load(PluginAbi {
init: Some(errno_ish),
..abi()
})
.expect_err("an unknown result code is not success");
assert!(matches!(error, HostError::InitFailed { code, .. } if code == 13));
}
#[test]
fn a_plugin_with_no_lifecycle_hooks_loads_and_serves() {
let plugin = load(PluginAbi {
init: None,
shutdown: None,
..abi()
})
.expect("init and shutdown may be absent");
assert!(
plugin
.call(&request("/example/double", &3i64, false))
.unwrap()
.is_some()
);
plugin.shutdown();
}
#[test]
fn a_null_response_pointer_is_refused_rather_than_read() {
unsafe extern "C" fn lies(_: *const c_char, _: u64) -> RepeBuffer {
RepeBuffer {
data: std::ptr::null(),
size: 32,
}
}
let plugin = load(PluginAbi {
call: lies,
..abi()
})
.unwrap();
assert!(matches!(
plugin.call(&request("/example/double", &1i64, false)),
Err(HostError::NullResponse { size: 32 })
));
}
#[test]
fn a_zero_size_response_is_a_notify_even_with_a_null_pointer() {
unsafe extern "C" fn empty_and_null(_: *const c_char, _: u64) -> RepeBuffer {
RepeBuffer {
data: std::ptr::null(),
size: 0,
}
}
let plugin = load(PluginAbi {
call: empty_and_null,
..abi()
})
.unwrap();
assert!(
plugin
.call(&request("/example/double", &1i64, false))
.unwrap()
.is_none()
);
}
#[test]
fn an_unreadable_response_size_is_refused_rather_than_sliced() {
unsafe extern "C" fn too_big(_: *const c_char, _: u64) -> RepeBuffer {
RepeBuffer {
data: (&raw const EMPTY_REQUEST_ANCHOR).cast::<c_char>(),
size: u64::MAX,
}
}
let plugin = load(PluginAbi {
call: too_big,
..abi()
})
.unwrap();
assert!(matches!(
plugin.call(&request("/example/double", &1i64, false)),
Err(HostError::ResponseTooLarge { size: u64::MAX })
));
}
fn through_router(plugin: Plugin, request: &[u8]) -> Option<Message> {
let router = Router::new().with_fallback(Arc::new(plugin));
router
.call(request)
.map(|frame| Message::from_slice(&frame).expect("a REPE frame comes back"))
}
#[test]
fn a_mounted_plugin_serves_what_it_claims() {
let response = through_router(
load(abi()).unwrap(),
&request("/example/double", &21i64, false),
)
.expect("a non-notify request is answered");
assert_eq!(response.json_body::<i64>().unwrap(), 42);
assert_eq!(response.header.id, 7);
}
#[test]
fn a_mounted_plugin_declines_a_path_outside_its_root() {
let response = through_router(load(abi()).unwrap(), &request("/elsewhere", &1i64, false))
.expect("a declined path is still answered");
assert_eq!(response.error_code(), Some(ErrorCode::MethodNotFound));
assert!(
response
.error_message_utf8()
.is_some_and(|text| text.contains("/elsewhere"))
);
}
#[test]
fn a_mounted_plugin_forwards_a_notify_without_answering() {
static SEEN: AtomicUsize = AtomicUsize::new(0);
unsafe extern "C" fn counting(request: *const c_char, size: u64) -> RepeBuffer {
SEEN.fetch_add(1, Ordering::SeqCst);
unsafe { good::call(request, size) }
}
let plugin = load(PluginAbi {
call: counting,
..abi()
})
.unwrap();
let before = SEEN.load(Ordering::SeqCst);
assert!(through_router(plugin, &request("/example/double", &1i64, true),).is_none());
assert_eq!(
SEEN.load(Ordering::SeqCst),
before + 1,
"the notify reached the plugin rather than being dropped at the mount"
);
}
#[test]
fn a_plugin_that_answers_nothing_to_a_real_request_is_an_internal_error() {
unsafe extern "C" fn silent(_: *const c_char, _: u64) -> RepeBuffer {
RepeBuffer {
data: std::ptr::null(),
size: 0,
}
}
let plugin = load(PluginAbi {
call: silent,
..abi()
})
.unwrap();
let response = through_router(plugin, &request("/example/double", &1i64, false))
.expect("the caller is told rather than left waiting");
assert_eq!(response.error_code(), Some(ErrorCode::InternalError));
}
#[test]
fn a_plugin_answer_that_is_not_a_frame_is_an_internal_error() {
unsafe extern "C" fn garbage(_: *const c_char, _: u64) -> RepeBuffer {
static JUNK: &[u8] = b"not a repe frame";
RepeBuffer {
data: JUNK.as_ptr().cast::<c_char>(),
size: JUNK.len() as u64,
}
}
let plugin = load(PluginAbi {
call: garbage,
..abi()
})
.unwrap();
let response =
through_router(plugin, &request("/example/double", &1i64, false)).expect("answered");
assert_eq!(response.error_code(), Some(ErrorCode::InternalError));
}
#[test]
fn a_mounted_plugin_s_own_error_frame_is_forwarded_unchanged() {
let bodiless = Message::builder()
.id(7)
.query_str("/example/double")
.query_format(QueryFormat::JsonPointer)
.build()
.to_vec();
let response = through_router(load(abi()).unwrap(), &bodiless).expect("answered");
assert_eq!(response.error_code(), Some(ErrorCode::InvalidBody));
assert_eq!(response.header.id, 7);
}
#[test]
fn the_owning_and_borrowing_dispatch_paths_agree() {
let plugin = load(abi()).unwrap();
let frame = request("/example/double", &21i64, false);
let owned = Message::from_slice(&frame).unwrap();
let view = MessageView::from_slice(&frame).unwrap();
let by_message = plugin.handle(&owned).unwrap();
let by_view = plugin
.handle_view(&view, &CallContext::detached("/example/double"))
.unwrap();
assert_eq!(by_message.body, by_view.body);
assert_eq!(by_message.header.ec, by_view.header.ec);
assert_eq!(by_message.header.id, by_view.header.id);
}
#[test]
fn a_plugin_is_send_and_sync() {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<Plugin>();
}
}