Share owned host API state between HTTP hooks and native pages

This commit is contained in:
2026-11-07 00:23:57 +00:00
parent 45d099c3e4
commit c91ecbf7a4
14 changed files with 261 additions and 133 deletions
+5 -18
View File
@@ -6,7 +6,7 @@ use std::sync::Arc;
use wasmtime_wasi_http::{Error, RequestOptions};
use wasmtime_wasi_http::{WasiBody, WasiHttpHooks};
type Io = Box<dyn Future<Output = Result<(), Error>> + Send>;
pub type Router = fn(&Caller, Request<Bytes>) -> Response<Bytes>;
pub type Router = Arc<crate::api::Api>;
pub(super) struct Hooks {
pub caller: Caller,
pub cred: Arc<Cred>,
@@ -14,21 +14,6 @@ pub(super) struct Hooks {
pub policy: Arc<super::net::NetPolicy>,
pub router: Router,
}
pub fn whoami(caller: &Caller, request: Request<Bytes>) -> Response<Bytes> {
let (status, body) = if request.uri().path() == "/whoami" {
(200, serde_json::to_vec(caller).unwrap())
} else {
(
404,
serde_json::to_vec(&serde_json::json!({"error":"unknown host API route"})).unwrap(),
)
};
Response::builder()
.status(status)
.header("content-type", "application/json")
.body(Bytes::from(body))
.unwrap()
}
fn response(response: Response<Bytes>) -> (Response<WasiBody>, Io) {
(
response.map(|b| Full::new(b).map_err(|n| match n {}).boxed_unsync()),
@@ -51,7 +36,7 @@ impl WasiHttpHooks for Hooks {
let cred = self.cred.clone();
let script = self.script.clone();
let policy = self.policy.clone();
let router = self.router;
let router = self.router.clone();
Box::new(async move {
let (parts, mut body) = request.into_parts();
if parts
@@ -60,7 +45,9 @@ impl WasiHttpHooks for Hooks {
.is_some_and(|h| h.eq_ignore_ascii_case("host.sausage"))
{
let bytes = body.collect().await?.to_bytes();
return Ok(response(router(&caller, Request::from_parts(parts, bytes))));
return Ok(response(
crate::api::handle(&router, caller, Request::from_parts(parts, bytes)).await,
));
}
if !matches!(parts.uri.scheme_str(), Some("http" | "https")) {
while let Some(frame) = body.frame().await {