#![forbid(unsafe_code)]
mod convert;
mod reexports;
pub use convert::serde_to_tcb;
pub use reexports::*;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use async_trait::async_trait;
pub trait NativeService: Send + Sync {
fn execute(&self, args: &JsonValue) -> IoResult;
fn execute_async<'a>(
&'a self,
args: &'a JsonValue,
) -> Pin<Box<dyn Future<Output = IoResult> + Send + 'a>> {
Box::pin(async move { self.execute(args) })
}
}
pub struct NativeServiceDef {
pub name: &'static str,
pub sensitive: bool,
pub description: &'static str,
pub parameters: Option<&'static str>,
pub make: fn() -> Arc<dyn NativeService>,
}
pub struct NativeServiceRouter {
instances: Vec<(&'static str, Arc<dyn NativeService>)>,
fallback: Arc<dyn IoHandler>,
}
impl NativeServiceRouter {
pub fn new(defs: &'static [NativeServiceDef], fallback: Arc<dyn IoHandler>) -> Self {
Self {
instances: defs.iter().map(|d| (d.name, (d.make)())).collect(),
fallback,
}
}
pub fn with_enabled(
defs: &'static [NativeServiceDef],
fallback: Arc<dyn IoHandler>,
enabled: &[&str],
) -> Result<Self, String> {
if enabled.is_empty() {
return Err(
"plugin enable set is empty - to disable all native services set enabled=false \
directly (do not mount this router); to enable, list at least one service in \
plugin_manifest.services"
.to_string(),
);
}
let mut seen: Vec<&str> = Vec::new();
for name in enabled {
let known = defs.iter().any(|d| d.name == *name);
if !known {
return Err(format!(
"plugin_manifest references an unregistered native service '{name}' - valid \
service names: [{}]. Troubleshooting: (1) check the service_name spelling \
against this list (not the governance-side catalog); (2) to add a native \
service, append an entry to the NATIVE_SERVICES declaration table and then \
enable it in the manifest",
defs.iter().map(|d| d.name).collect::<Vec<_>>().join(", ")
));
}
if seen.contains(name) {
return Err(format!(
"plugin_manifest service '{name}' is declared more than once - deduplicate \
and retry (no silent dedup)"
));
}
seen.push(name);
}
Ok(Self {
instances: defs
.iter()
.filter(|d| seen.contains(&d.name))
.map(|d| (d.name, (d.make)()))
.collect(),
fallback,
})
}
pub fn enabled_service_names(&self) -> Vec<&'static str> {
self.instances.iter().map(|(n, _)| *n).collect()
}
pub fn native_service_names(defs: &'static [NativeServiceDef]) -> Vec<&'static str> {
defs.iter().map(|d| d.name).collect()
}
fn split_params(params: &JsonValue) -> (Option<String>, JsonValue) {
let service_name = params
.get("service_name")
.and_then(|v| v.as_str())
.or_else(|| params.get("name").and_then(|v| v.as_str()))
.map(|s| s.to_string());
let args = params
.get("args")
.cloned()
.unwrap_or_else(JsonValue::empty_object);
(service_name, args)
}
}
#[async_trait]
impl IoHandler for NativeServiceRouter {
async fn execute(&self, params: &JsonValue) -> IoResult {
let (service_name, args) = Self::split_params(params);
let name = service_name.as_deref().unwrap_or("");
match self.instances.iter().find(|(n, _)| *n == name) {
Some((_, svc)) => svc.execute_async(&args).await,
_ => self.fallback.execute(params).await,
}
}
}
pub fn mount_router(
defs: &'static [NativeServiceDef],
fallback: Arc<dyn IoHandler>,
enabled: Option<&[&str]>,
) -> Result<Arc<dyn IoHandler>, String> {
match enabled {
None => Ok(Arc::new(NativeServiceRouter::new(defs, fallback))),
Some(names) => Ok(Arc::new(NativeServiceRouter::with_enabled(
defs, fallback, names,
)?)),
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
struct Echo;
impl NativeService for Echo {
fn execute(&self, args: &JsonValue) -> IoResult {
Ok(JsonValue::object_from_pairs(&[
("svc", JsonValue::string("echo")),
("got", args.get("k").cloned().unwrap_or(JsonValue::Null)),
]))
}
}
struct Other;
impl NativeService for Other {
fn execute(&self, _args: &JsonValue) -> IoResult {
Ok(JsonValue::object_from_pairs(&[(
"svc",
JsonValue::string("other"),
)]))
}
}
static DEFS: &[NativeServiceDef] = &[
NativeServiceDef {
name: "kit_echo",
sensitive: false,
description: "echo stub",
parameters: None,
make: || Arc::new(Echo),
},
NativeServiceDef {
name: "kit_other",
sensitive: false,
description: "other stub",
parameters: None,
make: || Arc::new(Other),
},
];
struct ErrHandler;
#[async_trait]
impl IoHandler for ErrHandler {
async fn execute(&self, _params: &JsonValue) -> IoResult {
Err("fallback-called".to_string())
}
}
fn params_of(service_name: &str, args: JsonValue) -> JsonValue {
JsonValue::object_from_pairs(&[
("service_name", JsonValue::string(service_name)),
("args", args),
])
}
#[tokio::test]
async fn test_router_fallback_on_unknown_service() {
let router = NativeServiceRouter::new(DEFS, Arc::new(ErrHandler));
let p = params_of("unknown_svc", JsonValue::object_from_pairs(&[]));
assert_eq!(router.execute(&p).await.unwrap_err(), "fallback-called");
}
#[tokio::test]
async fn test_args_passed_through_and_name_alias() {
let router = NativeServiceRouter::new(DEFS, Arc::new(ErrHandler));
let p = JsonValue::object_from_pairs(&[
("name", JsonValue::string("kit_echo")),
(
"args",
JsonValue::object_from_pairs(&[("k", JsonValue::Integer(7))]),
),
]);
let r = router.execute(&p).await.unwrap();
assert_eq!(r.get("svc").and_then(|v| v.as_str()), Some("echo"));
assert_eq!(r.get("got").and_then(|v| v.as_i64()), Some(7));
}
#[tokio::test]
async fn test_router_dispatches_through_async_extension_point() {
struct AsyncOnly;
impl NativeService for AsyncOnly {
fn execute(&self, _args: &JsonValue) -> IoResult {
Ok(JsonValue::object_from_pairs(&[(
"path",
JsonValue::string("sync"),
)]))
}
fn execute_async<'a>(
&'a self,
_args: &'a JsonValue,
) -> Pin<Box<dyn Future<Output = IoResult> + Send + 'a>> {
Box::pin(async move {
Ok(JsonValue::object_from_pairs(&[(
"path",
JsonValue::string("async"),
)]))
})
}
}
static DEFS2: &[NativeServiceDef] = &[NativeServiceDef {
name: "kit_async_only",
sensitive: false,
description: "async extension point stub",
parameters: None,
make: || Arc::new(AsyncOnly),
}];
let router = NativeServiceRouter::new(DEFS2, Arc::new(ErrHandler));
let p = params_of("kit_async_only", JsonValue::object_from_pairs(&[]));
let r = router.execute(&p).await.unwrap();
assert_eq!(
r.get("path").and_then(|v| v.as_str()),
Some("async"),
"the router must go through execute_async (otherwise egress services have no \
regular path)"
);
}
#[test]
fn test_def_table_invariants() {
let mut names: Vec<&str> = DEFS.iter().map(|d| d.name).collect();
let total = names.len();
names.sort_unstable();
names.dedup();
assert_eq!(
names.len(),
total,
"declaration table service names must be unique"
);
for d in DEFS {
let _ = (d.make)();
}
}
#[tokio::test]
async fn test_all_defs_route_natively() {
let router = NativeServiceRouter::new(DEFS, Arc::new(ErrHandler));
for d in DEFS {
let p = params_of(d.name, JsonValue::object_from_pairs(&[]));
if let Err(e) = router.execute(&p).await {
assert_ne!(
e, "fallback-called",
"service {} fell through to the HTTP fallback",
d.name
);
}
}
}
#[tokio::test]
async fn test_with_enabled_subset_filter_deterministic() {
let router =
NativeServiceRouter::with_enabled(DEFS, Arc::new(ErrHandler), &["kit_echo"]).unwrap();
assert_eq!(router.enabled_service_names(), vec!["kit_echo"]);
let p = params_of("kit_echo", JsonValue::object_from_pairs(&[]));
let r = router.execute(&p).await.unwrap();
assert_eq!(r.get("svc").and_then(|v| v.as_str()), Some("echo"));
let p = params_of("kit_other", JsonValue::object_from_pairs(&[]));
assert_eq!(router.execute(&p).await.unwrap_err(), "fallback-called");
}
#[test]
fn test_with_enabled_rejects_unknown_duplicate_and_empty() {
fn expect_err(r: Result<NativeServiceRouter, String>) -> String {
match r {
Ok(_) => panic!("construction must fail"),
Err(e) => e,
}
}
let err = expect_err(NativeServiceRouter::with_enabled(
DEFS,
Arc::new(ErrHandler),
&["kit_echo", "no_such_svc"],
));
assert!(err.contains("no_such_svc"), "{err}");
assert!(
err.contains("kit_echo") && err.contains("NATIVE_SERVICES"),
"{err}"
);
let err = expect_err(NativeServiceRouter::with_enabled(
DEFS,
Arc::new(ErrHandler),
&["kit_echo", "kit_echo"],
));
assert!(err.contains("more than once"), "{err}");
let err = expect_err(NativeServiceRouter::with_enabled(
DEFS,
Arc::new(ErrHandler),
&[],
));
assert!(err.contains("enabled=false"), "{err}");
}
#[tokio::test]
async fn test_mount_router_all_and_subset() {
let all = mount_router(DEFS, Arc::new(ErrHandler), None).unwrap();
let p = params_of("kit_other", JsonValue::object_from_pairs(&[]));
assert_eq!(
all.execute(&p)
.await
.unwrap()
.get("svc")
.and_then(|v| v.as_str()),
Some("other")
);
let subset = mount_router(DEFS, Arc::new(ErrHandler), Some(&["kit_echo"])).unwrap();
assert_eq!(
subset.execute(&p).await.unwrap_err(),
"fallback-called",
"services outside a Some(subset) must fall back, not silently become full enable"
);
}
}