| 1 | //! Plumbing shared by g1t services that run on Workers. |
| 2 | //! |
| 3 | //! Services talk to each other over service bindings with a small JSON |
| 4 | //! protocol: `POST /rpc/<method>` with the method's arguments as the body, |
| 5 | //! answered with the method's return value. |
| 6 | |
| 7 | use serde::Serialize; |
| 8 | use serde::de::DeserializeOwned; |
| 9 | use worker::{Date, Fetcher, Headers, Method, Request, RequestInit, Response, Result}; |
| 10 | |
| 11 | /// The current time in milliseconds since the epoch. |
| 12 | pub fn now_ms() -> u64 { |
| 13 | Date::now().as_millis() |
| 14 | } |
| 15 | |
| 16 | /// The method name of an RPC request, or `None` if it is not one. |
| 17 | pub fn rpc_method(request: &Request) -> Option<String> { |
| 18 | if request.method() != Method::Post { |
| 19 | return None; |
| 20 | } |
| 21 | request |
| 22 | .path() |
| 23 | .strip_prefix("/rpc/") |
| 24 | .map(|method| method.to_owned()) |
| 25 | } |
| 26 | |
| 27 | /// Deserializes a method's arguments. |
| 28 | pub fn args<A: DeserializeOwned>(body: serde_json::Value) -> Result<A> { |
| 29 | serde_json::from_value(body) |
| 30 | .map_err(|error| worker::Error::RustError(format!("bad arguments: {error}"))) |
| 31 | } |
| 32 | |
| 33 | /// Serializes a method's return value as the response body. |
| 34 | pub fn reply<R: Serialize>(value: &R) -> Result<Response> { |
| 35 | Response::from_json(value) |
| 36 | } |
| 37 | |
| 38 | /// Calls `method` on another service through its binding. |
| 39 | pub async fn call<A: Serialize, R: DeserializeOwned>( |
| 40 | service: &Fetcher, |
| 41 | method: &str, |
| 42 | arguments: &A, |
| 43 | ) -> Result<R> { |
| 44 | let headers = Headers::new(); |
| 45 | headers.set("content-type", "application/json")?; |
| 46 | let mut init = RequestInit::new(); |
| 47 | init.with_method(Method::Post) |
| 48 | .with_headers(headers) |
| 49 | .with_body(Some(serde_json::to_string(arguments)?.into())); |
| 50 | // The hostname is ignored; a service binding always reaches its service. |
| 51 | let request = Request::new_with_init(&format!("https://service/rpc/{method}"), &init)?; |
| 52 | let mut response = service.fetch_request(request).await?; |
| 53 | if response.status_code() != 200 { |
| 54 | return Err(worker::Error::RustError(format!( |
| 55 | "{method} failed with status {}: {}", |
| 56 | response.status_code(), |
| 57 | response.text().await.unwrap_or_default() |
| 58 | ))); |
| 59 | } |
| 60 | response.json().await |
| 61 | } |
| 62 | |
| 63 | pub mod wire; |
| 64 | |
| 65 | /// Helpers for bindings that workers-rs has no typed wrapper for, such as |
| 66 | /// Artifacts and Email Sending. Values cross the boundary as JSON. |
| 67 | pub mod js { |
| 68 | use std::fmt; |
| 69 | |
| 70 | use serde::Serialize; |
| 71 | use serde::de::DeserializeOwned; |
| 72 | use worker::js_sys::{Array, Function, JSON, Promise, Reflect}; |
| 73 | use worker::wasm_bindgen::{JsCast, JsValue}; |
| 74 | use worker::wasm_bindgen_futures::JsFuture; |
| 75 | use worker::{Env, Error, Result}; |
| 76 | |
| 77 | /// An exception thrown by JavaScript, with its `code` if it had one. |
| 78 | #[derive(Debug)] |
| 79 | pub struct Thrown { |
| 80 | pub code: Option<String>, |
| 81 | pub message: String, |
| 82 | } |
| 83 | |
| 84 | impl Thrown { |
| 85 | fn from_value(value: JsValue) -> Self { |
| 86 | let property = |name: &str| { |
| 87 | Reflect::get(&value, &name.into()) |
| 88 | .ok() |
| 89 | .and_then(|property| property.as_string()) |
| 90 | }; |
| 91 | Thrown { |
| 92 | code: property("code"), |
| 93 | message: property("message").unwrap_or_else(|| format!("{value:?}")), |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | pub fn is(&self, code: &str) -> bool { |
| 98 | self.code.as_deref() == Some(code) |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | impl fmt::Display for Thrown { |
| 103 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 104 | match &self.code { |
| 105 | Some(code) => write!(f, "{code}: {}", self.message), |
| 106 | None => f.write_str(&self.message), |
| 107 | } |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | impl From<Thrown> for Error { |
| 112 | fn from(thrown: Thrown) -> Self { |
| 113 | Error::RustError(thrown.to_string()) |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | /// The binding called `name`, as a raw JavaScript value. |
| 118 | pub fn binding(env: &Env, name: &str) -> Result<JsValue> { |
| 119 | let value = Reflect::get(env.as_ref(), &name.into()).map_err(Thrown::from_value)?; |
| 120 | if value.is_undefined() { |
| 121 | return Err(Error::RustError(format!( |
| 122 | "binding {name} is not configured" |
| 123 | ))); |
| 124 | } |
| 125 | Ok(value) |
| 126 | } |
| 127 | |
| 128 | /// Reads a property of a JavaScript object. |
| 129 | pub fn get(target: &JsValue, name: &str) -> JsValue { |
| 130 | Reflect::get(target, &name.into()).unwrap_or(JsValue::UNDEFINED) |
| 131 | } |
| 132 | |
| 133 | /// Sets a property on an object. |
| 134 | pub fn set(target: &JsValue, name: &str, value: &JsValue) { |
| 135 | let _ = Reflect::set(target, &name.into(), value); |
| 136 | } |
| 137 | |
| 138 | pub fn to_js<T: Serialize>(value: &T) -> Result<JsValue> { |
| 139 | Ok(JSON::parse(&serde_json::to_string(value)?).map_err(Thrown::from_value)?) |
| 140 | } |
| 141 | |
| 142 | pub fn from_js<T: DeserializeOwned>(value: &JsValue) -> Result<T> { |
| 143 | let text = if value.is_undefined() { |
| 144 | None |
| 145 | } else { |
| 146 | JSON::stringify(value) |
| 147 | .map_err(Thrown::from_value)? |
| 148 | .as_string() |
| 149 | }; |
| 150 | let text = text.as_deref().unwrap_or("null"); |
| 151 | serde_json::from_str(text).map_err(|error| { |
| 152 | // Say what arrived; a bare serde error is useless in a log. |
| 153 | let seen: String = text.chars().take(300).collect(); |
| 154 | Error::RustError(format!( |
| 155 | "unexpected value from JavaScript ({error}): {seen}" |
| 156 | )) |
| 157 | }) |
| 158 | } |
| 159 | |
| 160 | /// Calls `target[method](...args)` and awaits the result if it is a |
| 161 | /// thenable. `method` may be a name or a symbol. |
| 162 | pub async fn call_key( |
| 163 | target: &JsValue, |
| 164 | method: &JsValue, |
| 165 | args: &[JsValue], |
| 166 | ) -> std::result::Result<JsValue, Thrown> { |
| 167 | let function: Function = Reflect::get(target, method) |
| 168 | .map_err(Thrown::from_value)? |
| 169 | .dyn_into() |
| 170 | .map_err(|_| Thrown { |
| 171 | code: None, |
| 172 | message: format!("{method:?} is not a function"), |
| 173 | })?; |
| 174 | let arguments: Array = args.iter().collect(); |
| 175 | // An RPC stub treats every property access as a remote method, so |
| 176 | // `function.apply(...)` would be sent over the wire as a call to |
| 177 | // "apply". Reflect.apply invokes the function without touching it. |
| 178 | let returned = Reflect::apply(&function, target, &arguments).map_err(Thrown::from_value)?; |
| 179 | // Worker RPC returns its own thenable rather than a Promise, so |
| 180 | // resolve whatever came back instead of testing its type. |
| 181 | JsFuture::from(Promise::resolve(&returned)) |
| 182 | .await |
| 183 | .map_err(Thrown::from_value) |
| 184 | } |
| 185 | |
| 186 | /// Calls `target.method(...args)`; see [`call_key`]. |
| 187 | pub async fn call( |
| 188 | target: &JsValue, |
| 189 | method: &str, |
| 190 | args: &[JsValue], |
| 191 | ) -> std::result::Result<JsValue, Thrown> { |
| 192 | call_key(target, &method.into(), args).await |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | /// Moving a service's rows when a workspace is renamed. |
| 197 | pub mod rename { |
| 198 | use std::collections::HashMap; |
| 199 | |
| 200 | use g1t_contracts::events::{Event, WorkspaceRenamed}; |
| 201 | use g1t_contracts::identity::UsernamesArgs; |
| 202 | use worker::wasm_bindgen::JsValue; |
| 203 | use worker::{D1Database, Env, Result}; |
| 204 | |
| 205 | /// Handles `workspace.renamed` with `statements`, and says whether |
| 206 | /// `event` was one. Each statement uses `?1` for the workspace's current |
| 207 | /// slug (asked of identity by id, so renames delivered twice or out of |
| 208 | /// order converge) and `?2` for a slug its rows may still be under; the |
| 209 | /// statements run in one batch per such slug. A statement that matches |
| 210 | /// nothing changes nothing, so running them again is harmless. |
| 211 | pub async fn on_event(env: &Env, db: &D1Database, event: &Event, statements: &[&str]) -> Result<bool> { |
| 212 | if event.kind != "workspace.renamed" { |
| 213 | return Ok(false); |
| 214 | } |
| 215 | let Ok(renamed) = serde_json::from_value::<WorkspaceRenamed>(event.data.clone()) else { |
| 216 | worker::console_error!("workspace.renamed {} could not be read", event.id); |
| 217 | return Ok(true); |
| 218 | }; |
| 219 | let names: HashMap<String, String> = crate::call( |
| 220 | &env.service("IDENTITY")?, |
| 221 | "usernames", |
| 222 | &UsernamesArgs { |
| 223 | ids: vec![renamed.workspace_id.clone()], |
| 224 | }, |
| 225 | ) |
| 226 | .await?; |
| 227 | let current = names |
| 228 | .get(&renamed.workspace_id) |
| 229 | .cloned() |
| 230 | .unwrap_or_else(|| renamed.to.clone()); |
| 231 | for stale in renamed.stale_slugs(¤t) { |
| 232 | let values: [JsValue; 2] = [current.as_str().into(), stale.as_str().into()]; |
| 233 | let mut batch = Vec::with_capacity(statements.len()); |
| 234 | for sql in statements { |
| 235 | batch.push(db.prepare(*sql).bind(&values[..parameters(sql)])?); |
| 236 | } |
| 237 | db.batch(batch).await?; |
| 238 | } |
| 239 | Ok(true) |
| 240 | } |
| 241 | |
| 242 | /// How many values a statement takes: its highest `?N`. |
| 243 | pub fn parameters(sql: &str) -> usize { |
| 244 | sql.split('?') |
| 245 | .skip(1) |
| 246 | .filter_map(|rest| { |
| 247 | let digits: String = rest.chars().take_while(char::is_ascii_digit).collect(); |
| 248 | digits.parse().ok() |
| 249 | }) |
| 250 | .max() |
| 251 | .unwrap_or(0) |
| 252 | } |
| 253 | |
| 254 | #[cfg(test)] |
| 255 | mod tests { |
| 256 | use super::parameters; |
| 257 | |
| 258 | #[test] |
| 259 | fn counts_numbered_parameters() { |
| 260 | assert_eq!(parameters("UPDATE t SET a = ?1 WHERE a = ?2"), 2); |
| 261 | assert_eq!(parameters("DELETE FROM t WHERE a = ?2"), 2); |
| 262 | assert_eq!(parameters("UPDATE t SET a = ?1"), 1); |
| 263 | assert_eq!(parameters("DELETE FROM t"), 0); |
| 264 | } |
| 265 | } |
| 266 | } |