fetchlet/host/channel/service.rs
1use std::future::Future;
2use std::pin::Pin;
3use std::sync::Arc;
4
5use serde_json::Value;
6
7use super::ChannelEnd;
8use crate::{Context, Result};
9
10/// The future of an open: Ok once the channel is open, or the error that
11/// refuses it.
12pub type ChannelFuture = Pin<Box<dyn Future<Output = Result<()>> + Send + 'static>>;
13
14/// A channel JavaScript asked a [`ChannelService`] to open, with
15/// `env.NAME.connect(options)`.
16#[non_exhaustive]
17pub struct ChannelRequest {
18 /// The options JavaScript passed, as JSON; null when it passed none.
19 /// They come from the application: check them as any guest input.
20 pub options: Value,
21 /// The invocation's trusted [`Context`], if its caller attached one.
22 pub context: Option<Context>,
23 /// Rust's end of the channel. JavaScript's end belongs to the invocation
24 /// that opened it and closes when that invocation ends.
25 pub end: ChannelEnd,
26}
27
28/// Opens the channels of one `env` binding for JavaScript.
29///
30/// `open` returns a future that settles the open: Ok opens the channel for
31/// JavaScript, an error refuses it. A service that accepts usually spawns a
32/// task that drives `request.end`, then resolves. The future is polled in
33/// the host pump of the invocation, within the host runtime when the App has
34/// one; it must not call the same App again. Dropping it, as the end of the
35/// invocation does, must cancel the open.
36///
37/// Services are trusted host code: they receive the invocation's
38/// [`Context`], and nothing authorizes the options for them.
39pub trait ChannelService: Send + Sync + 'static {
40 fn open(&self, request: ChannelRequest) -> ChannelFuture;
41}
42
43/// Share one service between bindings or Apps.
44impl<T: ChannelService + ?Sized> ChannelService for Arc<T> {
45 fn open(&self, request: ChannelRequest) -> ChannelFuture {
46 (**self).open(request)
47 }
48}
49
50struct FunctionService<F>(F);
51
52impl<F, Fut> ChannelService for FunctionService<F>
53where
54 F: Fn(ChannelRequest) -> Fut + Send + Sync + 'static,
55 Fut: Future<Output = Result<()>> + Send + 'static,
56{
57 fn open(&self, request: ChannelRequest) -> ChannelFuture {
58 Box::pin((self.0)(request))
59 }
60}
61
62/// Adapt an async Rust function to a channel service.
63pub fn channel_fn<F, Fut>(function: F) -> impl ChannelService
64where
65 F: Fn(ChannelRequest) -> Fut + Send + Sync + 'static,
66 Fut: Future<Output = Result<()>> + Send + 'static,
67{
68 FunctionService(function)
69}