1#![doc = include_str!("../README.md")]
2#![warn(missing_docs)]
3#![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#[derive(Debug, thiserror::Error)]
26pub enum Error {
27 #[error("not started by a Weirdnet extension host: {0}")]
29 NotHosted(String),
30 #[error("connecting to the host: {0}")]
32 Transport(#[from] tonic::transport::Error),
33 #[error("handshake: {0}")]
35 Handshake(#[from] Status),
36 #[error(transparent)]
38 Io(#[from] std::io::Error),
39}
40
41#[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
52pub type Client = HostClient<InterceptedService<Channel, Session>>;
54
55#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct Capability {
58 pub name: String,
60 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#[derive(Debug, Clone, PartialEq, Eq)]
70pub enum Event {
71 App {
73 kind: String,
75 payload: Vec<u8>,
77 },
78 Grants(Vec<Capability>),
80 Stop {
82 reason: String,
84 grace_ms: u32,
86 },
87}
88
89#[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 let s = unsafe { std::os::unix::net::UnixStream::from_raw_fd(fd) };
111 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 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 pub fn id(&self) -> &str {
170 &self.id
171 }
172
173 pub fn host(&self) -> &str {
175 &self.host
176 }
177
178 pub fn api_version(&self) -> u32 {
180 self.api_version
181 }
182
183 pub fn granted(&self) -> Vec<Capability> {
185 self.granted.lock().unwrap().clone()
186 }
187
188 pub fn has(&self, name: &str) -> bool {
190 self.granted.lock().unwrap().iter().any(|c| c.name == name)
191 }
192
193 pub fn client(&self) -> Client {
195 self.client.clone()
196 }
197
198 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 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 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 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}