use bytes::Bytes;
use serde_json::Value;
use super::{HostBridge, InvocationScope};
use crate::fetch::BodySender;
use crate::{
Body, ChannelEnd, ChannelService, Error, FetchPolicy, HostServices, Limits, Result,
SocketPolicy, SocketService, WebSocketAccept, WebSocketService, channel_fn, socket_fn,
websocket_fn,
};
pub struct BridgeHarness {
bridge: HostBridge,
scope: Option<InvocationScope>,
}
impl BridgeHarness {
pub fn new(services: HostServices) -> Self {
Self {
bridge: HostBridge::new(services),
scope: None,
}
}
pub fn begin(&mut self, limits: Limits) -> Result<()> {
self.scope = None;
self.scope = Some(self.bridge.begin(limits)?);
Ok(())
}
pub fn end(&mut self) {
self.scope = None;
}
pub fn has_pending(&self) -> bool {
self.scope
.as_ref()
.is_some_and(InvocationScope::has_pending)
}
pub fn dispatch(&self, operation: &str, input: &str) -> Value {
let reply = self.bridge.dispatch(operation.into(), input.into());
serde_json::from_str(&reply).expect("replies are JSON")
}
pub fn put_guest_bytes(&self, bytes: &[u8]) -> Result<u64> {
self.bridge.put_guest_bytes(bytes)
}
pub fn take_guest_bytes(&self, handle: f64) -> Result<Bytes> {
self.bridge.take_guest_bytes(handle)
}
pub fn open_body(&self, body: Body, limit: Option<usize>) -> Result<u64> {
self.bridge.open_body(body, limit, "request body bytes")
}
pub fn open_fed_body(&self, capacity: usize, limit: Option<usize>) -> Result<(BodyFeed, u64)> {
let (sender, body) = Body::channel(Bytes::new(), capacity.max(1));
let id = self.open_body(body, limit)?;
Ok((BodyFeed(sender), id))
}
}
impl BridgeHarness {
pub fn open_connection(&self) -> Result<(ChannelFeed, u64)> {
self.bridge.allow_upgrade()?;
let reply = self.dispatch("websocket.upgrade", "null");
let Some(id) = reply["value"].as_u64() else {
return Err(Error::InvalidRequest(reply.to_string()));
};
Ok((ChannelFeed(self.bridge.take_upgrade(id)?), id))
}
}
pub fn harness_channel_service(
accept: bool,
) -> (impl ChannelService, std::sync::mpsc::Receiver<ChannelFeed>) {
let (feeds, received) = std::sync::mpsc::channel();
let service = channel_fn(move |request| {
let result = if accept {
let _ = feeds.send(ChannelFeed(request.end));
Ok(())
} else {
Err(Error::PermissionDenied)
};
async move { result }
});
(service, received)
}
pub fn harness_socket_service() -> (SocketService, std::sync::mpsc::Receiver<ChannelFeed>) {
let (feeds, received) = std::sync::mpsc::channel();
let transport = socket_fn(move |request| {
let _ = feeds.send(ChannelFeed(request.end));
async { Ok(()) }
});
let policy = SocketPolicy::deny_all()
.allow_ports("open.test", 1..=100)
.expect("a valid rule");
(SocketService::new(transport, policy), received)
}
pub fn harness_websocket_service() -> (WebSocketService, std::sync::mpsc::Receiver<ChannelFeed>) {
let (feeds, received) = std::sync::mpsc::channel();
let transport = websocket_fn(move |request| {
let _ = feeds.send(ChannelFeed(request.end));
async {
Ok(WebSocketAccept {
protocol: "chat".into(),
extensions: String::new(),
})
}
});
let policy = FetchPolicy::deny_all()
.allow_origin("https://open.test")
.expect("a valid origin");
(WebSocketService::new(transport, policy), received)
}
pub struct ChannelFeed(ChannelEnd);
impl ChannelFeed {
pub fn is_released(&self) -> bool {
self.0.peer_gone()
}
}
pub struct BodyFeed(BodySender);
impl BodyFeed {
pub fn send(&self, chunk: &[u8], last: bool) -> bool {
self.0
.try_send(Ok((Bytes::copy_from_slice(chunk), last)))
.is_ok()
}
pub fn is_released(&self) -> bool {
self.0.is_closed()
}
}