Skip to main content

weirdnet_ext_sdk/
lib.rs

1#![doc = include_str!("../README.md")]
2#![warn(missing_docs)]
3// Native extensions run on Unix only for now; the rest still builds elsewhere.
4#![cfg_attr(not(unix), allow(unused))]
5
6use std::collections::HashMap;
7use std::sync::{Arc, Mutex};
8use tonic::metadata::{Ascii, MetadataValue};
9use tonic::service::Interceptor;
10use tonic::service::interceptor::InterceptedService;
11use tonic::transport::Channel;
12#[cfg(unix)]
13use tonic::transport::Endpoint;
14use weirdnet_ext_proto::v1::{self, host_client::HostClient};
15#[cfg(unix)]
16use weirdnet_ext_proto::{API_VERSION, ENV_FD};
17use weirdnet_ext_proto::{ENV_ID, ENV_TOKEN, SESSION_HEADER};
18
19pub use tonic::Status;
20pub use weirdnet_ext_proto as proto;
21pub use weirdnet_ext_proto::v1::health_report::State;
22pub use weirdnet_ext_proto::v1::log_record::Level;
23
24/// Errors from connecting.
25#[derive(Debug, thiserror::Error)]
26pub enum Error {
27    /// Not started by a Weirdnet host (an environment variable is missing or bad).
28    #[error("not started by a Weirdnet extension host: {0}")]
29    NotHosted(String),
30    /// The connection failed.
31    #[error("connecting to the host: {0}")]
32    Transport(#[from] tonic::transport::Error),
33    /// The host refused the handshake.
34    #[error("handshake: {0}")]
35    Handshake(#[from] Status),
36    /// An I/O error.
37    #[error(transparent)]
38    Io(#[from] std::io::Error),
39}
40
41/// Adds the session header to every call.
42#[derive(Clone)]
43pub struct Session(MetadataValue<Ascii>);
44
45impl Interceptor for Session {
46    fn call(&mut self, mut r: tonic::Request<()>) -> Result<tonic::Request<()>, Status> {
47        r.metadata_mut().insert(SESSION_HEADER, self.0.clone());
48        Ok(r)
49    }
50}
51
52/// The client type, for calls this crate has no helper for.
53pub type Client = HostClient<InterceptedService<Channel, Session>>;
54
55/// A capability the user granted.
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct Capability {
58    /// Its name.
59    pub name: String,
60    /// The patterns it is limited to (empty: unrestricted).
61    pub patterns: Vec<String>,
62}
63
64fn caps(v: Vec<v1::Capability>) -> Vec<Capability> {
65    v.into_iter().map(|c| Capability { name: c.name, patterns: c.patterns }).collect()
66}
67
68/// What an extension gets from its host.
69#[derive(Debug, Clone, PartialEq, Eq)]
70pub enum Event {
71    /// An app event (such as `morph.ext.v1.PageLoaded`), prost-encoded.
72    App {
73        /// The fully qualified message name.
74        kind: String,
75        /// The encoded message.
76        payload: Vec<u8>,
77    },
78    /// The grants changed.
79    Grants(Vec<Capability>),
80    /// Stop now (the process is killed after `grace_ms`).
81    Stop {
82        /// Why.
83        reason: String,
84        /// How long until the kill.
85        grace_ms: u32,
86    },
87}
88
89/// A connected extension.
90#[derive(Clone)]
91pub struct Extension {
92    client: Client,
93    id: String,
94    host: String,
95    api_version: u32,
96    granted: Arc<Mutex<Vec<Capability>>>,
97}
98
99#[cfg(unix)]
100fn take_stream() -> Result<tokio::net::UnixStream, Error> {
101    use std::os::fd::FromRawFd;
102    let fd: i32 = std::env::var(ENV_FD)
103        .map_err(|_| Error::NotHosted(format!("{ENV_FD} is not set")))?
104        .parse()
105        .map_err(|_| Error::NotHosted(format!("{ENV_FD} is not a number")))?;
106    if fd < 3 {
107        return Err(Error::NotHosted(format!("{ENV_FD} is not a socket")));
108    }
109    // SAFETY: the host passed this descriptor for us alone; it is taken once (see `connect`).
110    let s = unsafe { std::os::unix::net::UnixStream::from_raw_fd(fd) };
111    // Not inherited by anything this process starts.
112    // SAFETY: fcntl on a descriptor we own.
113    unsafe {
114        let flags = libc::fcntl(fd, libc::F_GETFD);
115        libc::fcntl(fd, libc::F_SETFD, flags | libc::FD_CLOEXEC);
116    }
117    s.set_nonblocking(true)?;
118    Ok(tokio::net::UnixStream::from_std(s)?)
119}
120
121static TAKEN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
122
123impl Extension {
124    /// Connects to the host that started this process and does the handshake. Call once;
125    /// `version` is the extension's version from its manifest.
126    pub async fn connect(version: &str) -> Result<Self, Error> {
127        let id = std::env::var(ENV_ID).map_err(|_| Error::NotHosted(format!("{ENV_ID} is not set")))?;
128        let token = std::env::var(ENV_TOKEN).map_err(|_| Error::NotHosted(format!("{ENV_TOKEN} is not set")))?;
129        if TAKEN.swap(true, std::sync::atomic::Ordering::SeqCst) {
130            return Err(Error::NotHosted("already connected".into()));
131        }
132        #[cfg(unix)]
133        let stream = take_stream()?;
134        #[cfg(not(unix))]
135        {
136            let _ = (version, token);
137            return Err(Error::NotHosted("native extensions don't run on this OS yet".into()));
138        }
139        #[cfg(unix)]
140        {
141            let slot = Arc::new(Mutex::new(Some(stream)));
142            let channel = Endpoint::from_static("http://weirdnet-ext.host")
143                .connect_with_connector(tower::service_fn(move |_| {
144                    let s = slot.lock().unwrap().take();
145                    async move {
146                        s.map(hyper_util::rt::TokioIo::new)
147                            .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotConnected, "the host connection is closed"))
148                    }
149                }))
150                .await?;
151            let mut raw = HostClient::new(channel.clone());
152            let r = raw
153                .handshake(v1::HandshakeRequest {
154                    token,
155                    extension_id: id.clone(),
156                    version: version.into(),
157                    api_version: API_VERSION,
158                    sdk: concat!("weirdnet-ext-sdk ", env!("CARGO_PKG_VERSION")).into(),
159                })
160                .await?
161                .into_inner();
162            let session = MetadataValue::try_from(r.session.as_str()).map_err(|_| Error::NotHosted("bad session".into()))?;
163            let client = HostClient::with_interceptor(channel, Session(session));
164            Ok(Self { client, id, host: r.host, api_version: r.api_version, granted: Arc::new(Mutex::new(caps(r.granted))) })
165        }
166    }
167
168    /// This extension's id.
169    pub fn id(&self) -> &str {
170        &self.id
171    }
172
173    /// The host app ("morph 0.5.0").
174    pub fn host(&self) -> &str {
175        &self.host
176    }
177
178    /// The API version in use.
179    pub fn api_version(&self) -> u32 {
180        self.api_version
181    }
182
183    /// What is granted now.
184    pub fn granted(&self) -> Vec<Capability> {
185        self.granted.lock().unwrap().clone()
186    }
187
188    /// True if `name` is granted (for some target).
189    pub fn has(&self, name: &str) -> bool {
190        self.granted.lock().unwrap().iter().any(|c| c.name == name)
191    }
192
193    /// The raw client.
194    pub fn client(&self) -> Client {
195        self.client.clone()
196    }
197
198    /// Calls an app service method with a prost-encoded request.
199    pub async fn call(&self, service: &str, method: &str, payload: Vec<u8>) -> Result<Vec<u8>, Status> {
200        let r = self.client.clone().call(v1::CallRequest { service: service.into(), method: method.into(), payload }).await?;
201        Ok(r.into_inner().payload)
202    }
203
204    /// Logs a line through the host.
205    pub async fn log(&self, level: Level, message: impl Into<String>, fields: &[(&str, &str)]) -> Result<(), Status> {
206        let fields: HashMap<String, String> = fields.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
207        self.client.clone().log(v1::LogRecord { level: level as i32, message: message.into(), fields }).await?;
208        Ok(())
209    }
210
211    /// Reports health.
212    pub async fn health(&self, state: State, detail: impl Into<String>) -> Result<(), Status> {
213        self.client.clone().health(v1::HealthReport { state: state as i32, detail: detail.into(), ping: 0 }).await?;
214        Ok(())
215    }
216
217    /// Runs the event loop: answers pings, keeps the grants current, and gives app events to
218    /// `on_event`; returns on Stop (or when the host goes away). Reports `READY` first.
219    pub async fn run<F, Fut>(&self, mut on_event: F) -> Result<Option<String>, Status>
220    where
221        F: FnMut(Event) -> Fut,
222        Fut: std::future::Future<Output = ()>,
223    {
224        let mut s = self.client.clone().events(v1::EventsRequest {}).await?.into_inner();
225        self.health(State::Ready, "").await?;
226        use v1::event::Kind;
227        while let Some(e) = s.message().await? {
228            match e.kind {
229                Some(Kind::Ping(p)) => {
230                    self.client.clone().health(v1::HealthReport { state: State::Ready as i32, detail: String::new(), ping: p.seq }).await?;
231                }
232                Some(Kind::Grants(g)) => {
233                    let c = caps(g.granted);
234                    *self.granted.lock().unwrap() = c.clone();
235                    on_event(Event::Grants(c)).await;
236                }
237                Some(Kind::App(a)) => on_event(Event::App { kind: a.kind, payload: a.payload }).await,
238                Some(Kind::Stop(st)) => {
239                    on_event(Event::Stop { reason: st.reason.clone(), grace_ms: st.grace_ms }).await;
240                    return Ok(Some(st.reason));
241                }
242                None => {}
243            }
244        }
245        Ok(None)
246    }
247}