use std::collections::BTreeMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};
use std::task::Poll;
use bytes::Bytes;
use serde::Deserialize;
use serde_json::{Value, json};
use super::body_source::{BodyRead, BodySource};
use super::channels::{GuestClose, GuestMessage, GuestPause, GuestWrite};
use super::clock::Clock;
use super::functions::{self, CallMessage, PendingCalls, Resources};
use super::handles::{Handles, Resource};
use super::upload::{UploadWrite, Uploads};
use crate::config::check_limit;
use crate::execution::WakeSignal;
use crate::host::{GuestEnd, Method, Redirect, TransportFuture, pair};
use crate::reentry;
use crate::wire::{BodyTransfer, BridgeBytes, ByteStore, WireBytes, WireRequest, WireResponse};
use crate::{
Body, ChannelEnd, ChannelRequest, CloseFrame, ConsoleLevel, Context, Error, FunctionRequest,
HostServices, Limits, Response, Result, SecureTransport, SocketAddress,
};
struct PendingFetch {
future: TransportFuture,
}
struct PendingRead {
id: u64,
whole: Option<Whole>,
}
#[derive(Clone, Copy)]
pub(super) enum Whole {
Bytes,
Text,
}
struct InvocationState {
generation: u64,
next_ticket: u64,
started_fetches: usize,
opened_channels: usize,
function_calls: usize,
limits: Limits,
pending_fetches: BTreeMap<String, PendingFetch>,
pending_calls: PendingCalls,
bytes: ByteStore,
handles: Handles,
pending_reads: BTreeMap<String, PendingRead>,
uploads: Uploads,
background_registered: usize,
background_pending: usize,
context: Option<Context>,
disconnect: Option<Disconnect>,
#[cfg(fetchlet_web)]
web: fetchlet_web::WebState,
upgrade: Upgrade,
}
enum Upgrade {
Unavailable,
Available,
Accepted {
id: u64,
end: Option<ChannelEnd>,
},
}
#[derive(Clone)]
pub(crate) struct Disconnect {
gone: Arc<AtomicBool>,
wake: WakeSignal,
}
impl Disconnect {
#[cfg_attr(
not(any(feature = "boa", feature = "quickjs", feature = "v8")),
allow(dead_code)
)]
pub fn signal(&self) {
self.gone.store(true, Ordering::Release);
self.wake.notify();
}
fn is_signalled(&self) -> bool {
self.gone.load(Ordering::Acquire)
}
}
impl InvocationState {
fn next_ticket(&mut self) -> Result<String> {
self.next_ticket = self
.next_ticket
.checked_add(1)
.ok_or(Error::LimitExceeded("host operation tickets"))?;
Ok(format!("{}:{}", self.generation, self.next_ticket))
}
fn bridge_bytes(&mut self) -> InvocationBytes<'_> {
InvocationBytes {
bytes: &mut self.bytes,
handles: &mut self.handles,
}
}
}
struct InvocationBytes<'a> {
bytes: &'a mut ByteStore,
handles: &'a mut Handles,
}
impl BridgeBytes for InvocationBytes<'_> {
fn send(&mut self, bytes: Bytes) -> Result<WireBytes> {
self.bytes.put(bytes).map(WireBytes::Handle)
}
fn receive(&mut self, bytes: WireBytes) -> Result<Bytes> {
match bytes {
WireBytes::Handle(handle) => self.bytes.take(handle),
WireBytes::Inline(bytes) => Ok(bytes.into()),
}
}
fn stream(
&mut self,
body: Body,
limit: Option<usize>,
resource: &'static str,
) -> Result<BodyTransfer> {
if body.is_buffered() {
return Ok(BodyTransfer::Collect(body));
}
check_limit(limit, body.declared_len(), resource)?;
self.handles
.insert(Resource::Body(BodySource::new(body, limit, resource)))
.map(BodyTransfer::Stream)
}
}
#[derive(Default)]
struct BridgeState {
generation: u64,
invocation: Option<InvocationState>,
handles: Handles,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct FetchStartRequest {
request: WireRequest,
#[serde(default)]
redirect: Redirect,
service: Option<String>,
#[serde(default)]
upload: bool,
}
struct Completion {
id: String,
result: Value,
}
impl Completion {
fn into_value(self) -> Value {
json!({ "id": self.id, "result": self.result })
}
}
#[derive(Clone)]
pub(crate) struct HostBridge {
services: HostServices,
state: Arc<Mutex<BridgeState>>,
limits: Limits,
wake: WakeSignal,
clock: Clock,
key: u64,
runtime: Option<tokio::runtime::Handle>,
}
impl Default for HostBridge {
fn default() -> Self {
Self::new(HostServices::default())
}
}
impl HostBridge {
pub fn new(services: HostServices) -> Self {
Self::with_limits(services, Limits::default())
}
pub fn with_limits(services: HostServices, limits: Limits) -> Self {
Self {
services,
state: Arc::new(Mutex::new(BridgeState::default())),
limits,
wake: WakeSignal::default(),
clock: Clock::default(),
key: reentry::new_key(),
runtime: None,
}
}
#[cfg_attr(
not(any(feature = "boa", feature = "quickjs", feature = "v8")),
allow(dead_code)
)]
pub fn with_key(mut self, key: u64) -> Self {
self.key = key;
self
}
#[cfg_attr(
not(any(feature = "boa", feature = "quickjs", feature = "v8")),
allow(dead_code)
)]
pub fn with_runtime(mut self, runtime: tokio::runtime::Handle) -> Self {
self.runtime = Some(runtime);
self
}
#[cfg_attr(
not(any(feature = "boa", feature = "quickjs", feature = "v8")),
allow(dead_code)
)]
pub fn wake_signal(&self) -> WakeSignal {
self.wake.clone()
}
#[cfg_attr(
not(any(feature = "boa", feature = "quickjs", feature = "v8")),
allow(dead_code)
)]
pub fn disconnect(&self) -> Disconnect {
Disconnect {
gone: Arc::default(),
wake: self.wake.clone(),
}
}
#[cfg_attr(
not(any(feature = "boa", feature = "quickjs", feature = "v8")),
allow(dead_code)
)]
pub fn watch_disconnect(&self, disconnect: Disconnect) -> Result<()> {
let mut state = self.lock_state()?;
let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
invocation.disconnect = Some(disconnect);
Ok(())
}
#[cfg_attr(
not(any(feature = "boa", feature = "quickjs", feature = "v8")),
allow(dead_code)
)]
pub fn allow_upgrade(&self) -> Result<()> {
let mut state = self.lock_state()?;
let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
if matches!(invocation.upgrade, Upgrade::Unavailable) {
invocation.upgrade = Upgrade::Available;
}
Ok(())
}
#[cfg_attr(
not(any(feature = "boa", feature = "quickjs", feature = "v8")),
allow(dead_code)
)]
pub fn lend_channel(&self, end: GuestEnd) -> Result<u64> {
let mut state = self.lock_state()?;
let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
let id = invocation
.handles
.open_requested(end, Box::pin(async { Ok(()) }))?;
self.wake.notify();
Ok(id)
}
#[cfg_attr(
not(any(feature = "boa", feature = "quickjs", feature = "v8")),
allow(dead_code)
)]
pub fn put_bytes(&self, bytes: Bytes) -> Result<u64> {
let mut state = self.lock_state()?;
let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
invocation.bytes.put(bytes)
}
#[cfg_attr(
not(any(feature = "boa", feature = "quickjs", feature = "v8")),
allow(dead_code)
)]
pub fn take_upgrade(&self, id: u64) -> Result<ChannelEnd> {
let mut state = self.lock_state()?;
let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
match &mut invocation.upgrade {
Upgrade::Accepted { id: accepted, end } if *accepted == id => end
.take()
.ok_or_else(|| Error::InvalidRequest("upgrade already returned".into())),
_ => Err(Error::InvalidRequest("unknown upgrade".into())),
}
}
#[cfg_attr(
not(any(feature = "boa", feature = "quickjs", feature = "v8")),
allow(dead_code)
)]
pub fn close_channels(&self, frame: &CloseFrame) {
if let Ok(mut state) = self.lock_state()
&& let Some(invocation) = state.invocation.as_mut()
{
invocation.handles.force_channels(frame);
}
self.wake.notify();
}
fn effective_limits(&self) -> Result<Limits> {
let state = self.lock_state()?;
Ok(state
.invocation
.as_ref()
.map(|invocation| invocation.limits.clone())
.unwrap_or_else(|| self.limits.clone()))
}
#[cfg(any(feature = "fuzzing", test))]
pub fn begin(&self, limits: Limits) -> Result<InvocationScope> {
self.begin_with_context(limits, None)
}
pub fn begin_with_context(
&self,
limits: Limits,
context: Option<Context>,
) -> Result<InvocationScope> {
let mut state = self.lock_state()?;
if state.invocation.is_some() {
return Err(Error::InstanceUnavailable);
}
state.generation = state
.generation
.checked_add(1)
.ok_or(Error::LimitExceeded("invocation IDs"))?;
let generation = state.generation;
let handles = std::mem::take(&mut state.handles);
state.invocation = Some(InvocationState {
generation,
next_ticket: 0,
started_fetches: 0,
opened_channels: 0,
function_calls: 0,
limits,
pending_fetches: BTreeMap::new(),
pending_calls: PendingCalls::default(),
bytes: ByteStore::default(),
handles,
pending_reads: BTreeMap::new(),
uploads: Uploads::default(),
background_registered: 0,
background_pending: 0,
context,
disconnect: None,
#[cfg(fetchlet_web)]
web: fetchlet_web::WebState::default(),
upgrade: Upgrade::Unavailable,
});
Ok(InvocationScope {
bridge: self.clone(),
generation,
})
}
pub fn dispatch(&self, operation: String, input: String) -> String {
let reply = encode_reply(self.dispatch_operation(&operation, &input)).to_string();
#[cfg(feature = "operation-counts")]
crate::diagnostics::record(&operation, input.len(), reply.len());
reply
}
pub fn put_guest_bytes(&self, bytes: &[u8]) -> Result<u64> {
#[cfg(feature = "operation-counts")]
crate::diagnostics::record("bytes.put", bytes.len(), 0);
let mut state = self.lock_state()?;
let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
check_limit(
invocation.limits.bridge_message_bytes,
bytes.len(),
"bridge message bytes",
)?;
invocation.bytes.put_guest(Bytes::copy_from_slice(bytes))
}
#[cfg(fetchlet_process)]
pub fn put_guest_bytes_at(&self, handle: u64, bytes: Bytes) -> Result<()> {
#[cfg(feature = "operation-counts")]
crate::diagnostics::record("bytes.put", bytes.len(), 0);
let mut state = self.lock_state()?;
let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
check_limit(
invocation.limits.bridge_message_bytes,
bytes.len(),
"bridge message bytes",
)?;
invocation.bytes.put_guest_at(handle, bytes)
}
#[cfg(fetchlet_process)]
pub fn is_disconnected(&self) -> bool {
matches!(self.invocation_disconnected(), Ok(Value::Bool(true)))
}
pub fn take_guest_bytes(&self, handle: f64) -> Result<Bytes> {
if !((1.0..=9_007_199_254_740_991.0).contains(&handle) && handle.fract() == 0.0) {
return Err(Error::InvalidRequest("invalid byte handle".into()));
}
let bytes = self.take_bytes(handle as u64);
#[cfg(feature = "operation-counts")]
if let Ok(bytes) = &bytes {
crate::diagnostics::record("bytes.take", 0, bytes.len());
}
bytes
}
pub fn take_bytes(&self, handle: u64) -> Result<Bytes> {
let mut state = self.lock_state()?;
let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
invocation.bytes.take(handle)
}
#[cfg(any(test, feature = "fuzzing"))]
pub fn open_body(
&self,
body: Body,
limit: Option<usize>,
resource: &'static str,
) -> Result<u64> {
let mut state = self.lock_state()?;
let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
invocation
.handles
.insert(Resource::Body(BodySource::new(body, limit, resource)))
}
fn with_bridge_bytes<T>(
&self,
operation: impl FnOnce(&mut InvocationBytes<'_>) -> Result<T>,
) -> Result<T> {
let mut state = self.lock_state()?;
let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
operation(&mut invocation.bridge_bytes())
}
fn lock_state(&self) -> Result<MutexGuard<'_, BridgeState>> {
self.state.lock().map_err(|_| Error::InstanceUnavailable)
}
pub(super) fn dispatch_operation(&self, operation: &str, input: &str) -> Result<Value> {
let limits = self.effective_limits()?;
check_limit(
limits.bridge_message_bytes,
input.len(),
"bridge message bytes",
)?;
#[cfg(fetchlet_web)]
if let Some(result) = self.web_operation(operation, input) {
return result;
}
match operation {
"background.register" => self.register_background(),
"background.settle" => self.settle_background(),
"bindings" => Ok(self.bindings()),
"body.cancel" => self.cancel_body(input),
"body.read" => self.read_body(input, None),
"body.readAll" => self.read_body(input, Some(Whole::Bytes)),
"body.readText" => self.read_body(input, Some(Whole::Text)),
"channel.buffered" => self.channel_buffered(input),
"channel.close" => self.close_channel(input),
"channel.open" => self.open_channel(input),
"channel.pause" => self.pause_channel(input),
"channel.send" => self.send_channel(input),
"channel.write" => self.write_channel(input),
"clock" => Ok(self.clock.read()),
"console.write" => self.write_console(input),
"fetch.cancel" => self.cancel_fetch(input),
"fetch.limits" => self.fetch_limits(),
"fetch.start" => self.start_fetch(input),
"fetch.upload" => self.write_upload(input),
"function.call" => self.call_function(input, false),
"function.start" => self.call_function(input, true),
"host.poll" => self.poll_host(),
"invocation.disconnected" => self.invocation_disconnected(),
"socket.end" => self.end_socket(input),
"socket.open" => self.open_socket(input),
"socket.startTls" => self.start_socket_tls(input),
"websocket.open" => self.open_websocket(input),
"websocket.upgrade" => self.upgrade_websocket(),
_ => Err(Error::PermissionDenied),
}
}
#[cfg(fetchlet_web)]
fn web_operation(&self, operation: &str, input: &str) -> Option<Result<Value>> {
let mut state = match self.lock_state() {
Ok(state) => state,
Err(error) => return Some(Err(error)),
};
match state.invocation.as_mut() {
Some(invocation) => {
let limits = invocation.limits.web();
fetchlet_web::dispatch(
operation,
input,
&limits,
Some(fetchlet_web::Invocation {
state: &mut invocation.web,
bytes: &mut WebBytes(&mut invocation.bytes),
}),
)
}
None => {
fetchlet_web::dispatch::<WebBytes<'_>>(operation, input, &self.limits.web(), None)
}
}
}
fn bindings(&self) -> Value {
let service_names: Vec<_> = self.services.services.keys().collect();
let channel_names: Vec<_> = self.services.channels.keys().collect();
let functions: serde_json::Map<String, Value> = self
.services
.functions
.iter()
.map(|(name, functions)| (name.clone(), functions.describe()))
.collect();
json!({
"env": self.services.env,
"processEnv": self.services.process_env,
"services": service_names,
"channels": channel_names,
"functions": functions,
"console": self.services.console.is_some(),
})
}
fn write_console(&self, input: &str) -> Result<Value> {
#[derive(Deserialize)]
struct Message<'a> {
level: &'a str,
#[serde(borrow)]
message: std::borrow::Cow<'a, str>,
}
let sink = self
.services
.console
.as_ref()
.ok_or(Error::PermissionDenied)?;
let message: Message<'_> = serde_json::from_str(input)
.map_err(|_| Error::InvalidRequest("invalid console message".into()))?;
let level = ConsoleLevel::parse(message.level)
.ok_or_else(|| Error::InvalidRequest("unknown console level".into()))?;
sink.write(level, &message.message);
Ok(Value::Null)
}
fn fetch_limits(&self) -> Result<Value> {
let state = self.lock_state()?;
let invocation = state.invocation.as_ref().ok_or(Error::InvocationClosed)?;
Ok(fetch_limits_reply(&invocation.limits))
}
fn invocation_disconnected(&self) -> Result<Value> {
let state = self.lock_state()?;
Ok(Value::Bool(state.invocation.as_ref().is_some_and(
|invocation| {
invocation
.disconnect
.as_ref()
.is_some_and(Disconnect::is_signalled)
},
)))
}
pub(super) fn start_fetch(&self, input: &str) -> Result<Value> {
let mut state = self.lock_state()?;
let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
let started = invocation
.started_fetches
.checked_add(1)
.ok_or(Error::LimitExceeded("subrequest counter"))?;
check_limit(invocation.limits.subrequests, started, "subrequests")?;
invocation.started_fetches = started;
let start: FetchStartRequest = serde_json::from_str(input)
.map_err(|_| Error::InvalidRequest("invalid fetch message".into()))?;
let service = match start.service {
Some(name) => self.services.services.get(&name),
None => self.services.outbound.as_ref(),
}
.cloned()
.ok_or(Error::PermissionDenied)?;
let mut request = start
.request
.into_http(&invocation.limits, &mut invocation.bytes)?;
if let Some(context) = &invocation.context {
request.extensions_mut().insert(context.clone());
}
let upload = if start.upload {
if matches!(*request.method(), http::Method::GET | http::Method::HEAD) {
return Err(Error::InvalidRequest("GET/HEAD request has a body".into()));
}
let ticket = invocation.next_ticket()?;
*request.body_mut() = invocation.uploads.open(ticket.clone(), self.wake.clone());
Some(ticket)
} else {
None
};
let limits = invocation.limits.clone();
let future =
Box::pin(async move { service.execute(request, start.redirect, limits).await });
let ticket = invocation.next_ticket()?;
invocation
.pending_fetches
.insert(ticket.clone(), PendingFetch { future });
Ok(json!({ "ticket": ticket, "upload": upload }))
}
fn write_upload(&self, input: &str) -> Result<Value> {
let write: UploadWrite = serde_json::from_str(input)
.map_err(|_| Error::InvalidRequest("invalid upload write".into()))?;
let mut state = self.lock_state()?;
let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
let chunk = write
.chunk
.map(|handle| invocation.bytes.take(handle))
.transpose()?;
let chunks = invocation.limits.request_body_chunks;
invocation.uploads.write(write, chunk, chunks)
}
fn call_function(&self, input: &str, start: bool) -> Result<Value> {
let (method, request, result_bytes) = {
let mut state = self.lock_state()?;
let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
let called = invocation
.function_calls
.checked_add(1)
.ok_or(Error::LimitExceeded("function call counter"))?;
check_limit(invocation.limits.function_calls, called, "function calls")?;
invocation.function_calls = called;
let message: CallMessage = serde_json::from_str(input)
.map_err(|_| Error::InvalidRequest("invalid function call".into()))?;
let (args, bytes) =
functions::arguments(message.args, message.bytes, &mut invocation.bytes)?;
let method = self
.services
.functions
.get(&message.binding)
.and_then(|functions| functions.get(&message.method))
.cloned()
.ok_or(Error::PermissionDenied)?;
let request = FunctionRequest::new(
message.method,
args,
bytes,
invocation.context.clone(),
invocation.limits.clone(),
);
(method, request, invocation.limits.bridge_message_bytes)
};
let running = reentry::enter(self.key);
let runtime = self.runtime.as_ref().map(tokio::runtime::Handle::enter);
match (method, start) {
(Method::Sync(method), false) => {
let result = functions::run_sync(|| method(request));
drop(runtime);
drop(running);
let mut state = self.lock_state()?;
let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
let mut resources = Resources {
bytes: &mut invocation.bytes,
handles: &mut invocation.handles,
};
let outcome = functions::outcome(result, result_bytes, &mut resources);
self.wake.notify();
Ok(outcome)
}
(Method::Async(method), true) => {
let future = functions::start_async(|| method(request));
drop(runtime);
drop(running);
let mut state = self.lock_state()?;
let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
let ticket = invocation.next_ticket()?;
invocation.pending_calls.insert(ticket.clone(), future);
self.wake.notify();
Ok(Value::String(ticket))
}
_ => Err(Error::InvalidRequest("wrong kind of function call".into())),
}
}
pub(super) fn poll_host(&self) -> Result<Value> {
let mut state = self.lock_state()?;
let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
let waker = self.wake.waker();
let mut context = std::task::Context::from_waker(&waker);
let mut completed = Vec::new();
let _polling = reentry::enter(self.key);
let _runtime = self.runtime.as_ref().map(tokio::runtime::Handle::enter);
let InvocationState {
pending_fetches,
pending_calls,
limits,
bytes,
handles,
pending_reads,
uploads: invocation_uploads,
..
} = invocation;
let mut bridge_bytes = InvocationBytes { bytes, handles };
for (ticket, pending) in pending_fetches.iter_mut() {
let Poll::Ready(response) = pending.future.as_mut().poll(&mut context) else {
continue;
};
let result =
response.and_then(|response| encode_response(response, limits, &mut bridge_bytes));
completed.push(Completion {
id: ticket.clone(),
result: encode_reply(result),
});
}
for completion in &completed {
pending_fetches.remove(&completion.id);
}
let mut finished_calls = Vec::new();
pending_calls.poll(
&mut context,
limits.bridge_message_bytes,
&mut Resources {
bytes: &mut *bridge_bytes.bytes,
handles: &mut *bridge_bytes.handles,
},
&mut finished_calls,
);
completed.extend(
finished_calls
.into_iter()
.map(|(id, result)| Completion { id, result }),
);
let InvocationBytes { bytes, handles } = bridge_bytes;
pending_reads.retain(|ticket, read| {
let id = read.id;
let result = match handles.body_mut(id) {
Some(source) if let Some(whole) = read.whole => {
match source.poll_read_all(&mut context) {
Poll::Pending => return true,
Poll::Ready(Ok(body)) => match whole {
Whole::Bytes => bytes
.put(body)
.map(|handle| json!({ "chunk": handle, "done": true })),
Whole::Text => Ok(json!({ "text": utf8_decode(&body), "done": true })),
},
Poll::Ready(Err(error)) => Err(error),
}
}
Some(source) => match source.poll_read(&mut context) {
Poll::Pending => return true,
Poll::Ready(Ok(BodyRead::Chunk(chunk))) => bytes
.put(chunk)
.map(|handle| json!({ "chunk": handle, "done": false })),
Poll::Ready(Ok(BodyRead::Done)) => Ok(json!({ "chunk": null, "done": true })),
Poll::Ready(Err(error)) => Err(error),
},
None => Err(Error::InvocationClosed),
};
if !matches!(result, Ok(ref value) if value["done"] == false) {
handles.release_body(id);
}
completed.push(Completion {
id: ticket.clone(),
result: encode_reply(result),
});
false
});
let mut events: Vec<Value> = completed.into_iter().map(Completion::into_value).collect();
invocation_uploads.poll(&mut events);
if handles.has_channels() {
handles.poll_channels(&mut context, bytes, &mut events)?;
}
Ok(Value::Array(events))
}
pub(super) fn cancel_fetch(&self, input: &str) -> Result<Value> {
let ticket: String = serde_json::from_str(input)
.map_err(|_| Error::InvalidRequest("invalid fetch ticket".into()))?;
let mut state = self.lock_state()?;
let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
if invocation.pending_fetches.remove(&ticket).is_none() {
return Err(Error::InvocationClosed);
}
Ok(Value::Null)
}
fn upgrade_websocket(&self) -> Result<Value> {
let mut state = self.lock_state()?;
let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
match invocation.upgrade {
Upgrade::Available => {}
Upgrade::Accepted { .. } => {
return Err(Error::InvalidRequest(
"the request is already upgraded".into(),
));
}
Upgrade::Unavailable => return Err(Error::PermissionDenied),
}
let (end, guest) = pair(&invocation.limits);
let id = invocation
.handles
.open_connection(guest, &invocation.limits)?;
invocation.upgrade = Upgrade::Accepted { id, end: Some(end) };
Ok(Value::from(id))
}
fn open_channel(&self, input: &str) -> Result<Value> {
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Open {
service: String,
#[serde(default)]
options: Value,
}
let mut state = self.lock_state()?;
let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
let opened = invocation
.opened_channels
.checked_add(1)
.ok_or(Error::LimitExceeded("channel counter"))?;
check_limit(invocation.limits.open_channels, opened, "open channels")?;
invocation.opened_channels = opened;
let open: Open = serde_json::from_str(input)
.map_err(|_| Error::InvalidRequest("invalid channel open".into()))?;
let service = self
.services
.channels
.get(&open.service)
.ok_or(Error::PermissionDenied)?;
let (end, guest) = pair(&invocation.limits);
let request = ChannelRequest {
options: open.options,
context: invocation.context.clone(),
end,
};
let opening = {
let _opening = reentry::enter(self.key);
let _runtime = self.runtime.as_ref().map(tokio::runtime::Handle::enter);
service.open(request)
};
let id = invocation.handles.open_requested(guest, opening)?;
self.wake.notify();
Ok(Value::from(id))
}
fn open_socket(&self, input: &str) -> Result<Value> {
#[derive(Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
struct Open {
hostname: String,
port: u16,
secure_transport: SecureTransportInput,
}
#[derive(Deserialize)]
#[serde(rename_all = "lowercase")]
enum SecureTransportInput {
Off,
On,
Starttls,
}
let mut state = self.lock_state()?;
let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
let opened = invocation
.opened_channels
.checked_add(1)
.ok_or(Error::LimitExceeded("channel counter"))?;
check_limit(invocation.limits.open_channels, opened, "open channels")?;
invocation.opened_channels = opened;
let open: Open = serde_json::from_str(input)
.map_err(|_| Error::InvalidRequest("invalid socket open".into()))?;
let service = self
.services
.sockets
.as_ref()
.ok_or(Error::PermissionDenied)?;
let address = SocketAddress::new(&open.hostname, open.port)?;
let secure = match open.secure_transport {
SecureTransportInput::Off => SecureTransport::Off,
SecureTransportInput::On => SecureTransport::On,
SecureTransportInput::Starttls => SecureTransport::StartTls,
};
let (end, guest) = pair(&invocation.limits);
let opening = {
let _opening = reentry::enter(self.key);
let _runtime = self.runtime.as_ref().map(tokio::runtime::Handle::enter);
service.open(address, secure, invocation.context.clone(), end)?
};
let id =
invocation
.handles
.open_socket(guest, opening, secure == SecureTransport::StartTls)?;
self.wake.notify();
Ok(Value::from(id))
}
fn open_websocket(&self, input: &str) -> Result<Value> {
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Open {
url: String,
protocols: Vec<String>,
}
let mut state = self.lock_state()?;
let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
let opened = invocation
.opened_channels
.checked_add(1)
.ok_or(Error::LimitExceeded("channel counter"))?;
check_limit(invocation.limits.open_channels, opened, "open channels")?;
invocation.opened_channels = opened;
let open: Open = serde_json::from_str(input)
.map_err(|_| Error::InvalidRequest("invalid WebSocket open".into()))?;
let service = self
.services
.websockets
.as_ref()
.ok_or(Error::PermissionDenied)?;
let (end, guest) = pair(&invocation.limits);
let handshake = {
let _opening = reentry::enter(self.key);
let _runtime = self.runtime.as_ref().map(tokio::runtime::Handle::enter);
service.open(&open.url, open.protocols, invocation.context.clone(), end)?
};
let id = invocation.handles.open_websocket(guest, handshake)?;
self.wake.notify();
Ok(Value::from(id))
}
fn end_socket(&self, input: &str) -> Result<Value> {
let id: u64 = serde_json::from_str(input)
.map_err(|_| Error::InvalidRequest("invalid socket id".into()))?;
let mut state = self.lock_state()?;
let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
invocation.handles.end_socket(id)
}
fn start_socket_tls(&self, input: &str) -> Result<Value> {
let id: u64 = serde_json::from_str(input)
.map_err(|_| Error::InvalidRequest("invalid socket id".into()))?;
let mut state = self.lock_state()?;
let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
invocation.handles.start_socket_tls(id)
}
fn write_channel(&self, input: &str) -> Result<Value> {
let write: GuestWrite = serde_json::from_str(input)
.map_err(|_| Error::InvalidRequest("invalid channel write".into()))?;
let mut state = self.lock_state()?;
let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
let result = invocation
.handles
.write_channel(write, &mut invocation.bytes);
self.wake.notify();
result
}
fn pause_channel(&self, input: &str) -> Result<Value> {
let pause: GuestPause = serde_json::from_str(input)
.map_err(|_| Error::InvalidRequest("invalid channel pause".into()))?;
let mut state = self.lock_state()?;
let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
let result = invocation.handles.pause_channel(pause);
self.wake.notify();
result
}
fn send_channel(&self, input: &str) -> Result<Value> {
let message: GuestMessage = serde_json::from_str(input)
.map_err(|_| Error::InvalidRequest("invalid channel message".into()))?;
let mut state = self.lock_state()?;
let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
let result = invocation
.handles
.send_channel(message, &mut invocation.bytes);
self.wake.notify();
result
}
fn close_channel(&self, input: &str) -> Result<Value> {
let close: GuestClose = serde_json::from_str(input)
.map_err(|_| Error::InvalidRequest("invalid channel close".into()))?;
let mut state = self.lock_state()?;
let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
invocation.handles.close_channel(close)
}
fn channel_buffered(&self, input: &str) -> Result<Value> {
let id: u64 = serde_json::from_str(input)
.map_err(|_| Error::InvalidRequest("invalid channel id".into()))?;
let mut state = self.lock_state()?;
let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
invocation.handles.channel_buffered(id)
}
pub(super) fn register_background(&self) -> Result<Value> {
let mut state = self.lock_state()?;
let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
let registered = invocation
.background_registered
.checked_add(1)
.ok_or(Error::LimitExceeded("background tasks"))?;
check_limit(
invocation.limits.background_tasks,
registered,
"background tasks",
)?;
invocation.background_registered = registered;
invocation.background_pending += 1;
Ok(Value::Null)
}
pub(super) fn settle_background(&self) -> Result<Value> {
let mut state = self.lock_state()?;
let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
invocation.background_pending = invocation.background_pending.saturating_sub(1);
Ok(Value::Null)
}
pub(super) fn read_body(&self, input: &str, whole: Option<Whole>) -> Result<Value> {
let id: u64 = serde_json::from_str(input)
.map_err(|_| Error::InvalidRequest("invalid body id".into()))?;
let mut state = self.lock_state()?;
let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
if invocation.handles.body_mut(id).is_none() {
return Err(Error::InvalidRequest("unknown body".into()));
}
if invocation
.pending_reads
.values()
.any(|reading| reading.id == id)
{
return Err(Error::InvalidRequest("body is already being read".into()));
}
let ticket = invocation.next_ticket()?;
invocation
.pending_reads
.insert(ticket.clone(), PendingRead { id, whole });
Ok(Value::String(ticket))
}
pub(super) fn cancel_body(&self, input: &str) -> Result<Value> {
let id: u64 = serde_json::from_str(input)
.map_err(|_| Error::InvalidRequest("invalid body id".into()))?;
let mut state = self.lock_state()?;
let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
invocation.handles.release_body(id);
invocation
.pending_reads
.retain(|_, reading| reading.id != id);
Ok(Value::Null)
}
}
pub(crate) struct InvocationScope {
bridge: HostBridge,
generation: u64,
}
impl InvocationScope {
#[cfg_attr(
not(any(feature = "boa", feature = "quickjs", feature = "v8")),
allow(dead_code)
)]
pub fn has_background(&self) -> bool {
let Ok(state) = self.bridge.lock_state() else {
return false;
};
state.invocation.as_ref().is_some_and(|invocation| {
invocation.generation == self.generation && invocation.background_pending > 0
})
}
pub fn has_pending(&self) -> bool {
let Ok(state) = self.bridge.lock_state() else {
return true;
};
state.invocation.as_ref().is_some_and(|invocation| {
invocation.generation == self.generation
&& (!invocation.pending_fetches.is_empty() || !invocation.pending_calls.is_empty())
})
}
}
impl Drop for InvocationScope {
fn drop(&mut self) {
let mut state = self
.bridge
.state
.lock()
.unwrap_or_else(|error| error.into_inner());
let owns_invocation = state
.invocation
.as_ref()
.is_some_and(|invocation| invocation.generation == self.generation);
if owns_invocation && let Some(mut invocation) = state.invocation.take() {
let mut handles = std::mem::take(&mut invocation.handles);
handles.release_all();
state.handles = handles;
}
}
}
fn utf8_decode(bytes: &[u8]) -> std::borrow::Cow<'_, str> {
String::from_utf8_lossy(bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(bytes))
}
fn encode_response(
response: Response,
limits: &Limits,
bytes: &mut impl BridgeBytes,
) -> Result<Value> {
let response = WireResponse::from_http(response, limits, bytes)?;
serde_json::to_value(response).map_err(|_| Error::Transport("invalid response encoding".into()))
}
pub(crate) fn fetch_limits_reply(limits: &Limits) -> Value {
json!({
"requestBodyBytes": limits.request_body_bytes.map(|value| value.to_string()),
"requestBodyChunks": limits.request_body_chunks.map(|value| value.to_string()),
})
}
pub(crate) fn encode_reply(result: Result<Value>) -> Value {
match result {
Ok(value) => json!({
"ok": true,
"value": value,
}),
Err(error) => json!({
"ok": false,
"error": {
"code": error.code(),
"message": error.guest_message(),
},
}),
}
}
#[cfg(fetchlet_web)]
struct WebBytes<'a>(&'a mut ByteStore);
#[cfg(fetchlet_web)]
impl fetchlet_web::ByteHandles for WebBytes<'_> {
type Error = Error;
fn put(&mut self, bytes: Bytes) -> Result<u64> {
self.0.put(bytes)
}
fn take(&mut self, handle: u64) -> Result<Bytes> {
self.0.take(handle)
}
}
impl BridgeBytes for HostBridge {
fn send(&mut self, bytes: Bytes) -> Result<WireBytes> {
self.with_bridge_bytes(|bridge_bytes| bridge_bytes.send(bytes))
}
fn receive(&mut self, bytes: WireBytes) -> Result<Bytes> {
self.with_bridge_bytes(|bridge_bytes| bridge_bytes.receive(bytes))
}
fn stream(
&mut self,
body: Body,
limit: Option<usize>,
resource: &'static str,
) -> Result<BodyTransfer> {
self.with_bridge_bytes(|bridge_bytes| bridge_bytes.stream(body, limit, resource))
}
}