| 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | |
| 3 | //! Host async runtime for the JS thread, using structured concurrency. Ops |
| 4 | //! never spawn detached: they ENQUEUE a future, and `js::run_loop` owns a |
| 5 | //! per-request tokio `JoinSet` (the "region") that spawns, drives, and — on |
| 6 | //! every exit path — aborts whatever is still pending. |
| 7 | //! Orphan tasks, leaked bookkeeping, and panic-hangs are impossible by |
| 8 | //! construction, not patched. The region is the one asupersync idea we take: |
| 9 | //! a task cannot outlive the scope that owns it. |
| 10 | use std::cell::RefCell; |
| 11 | use std::future::Future; |
| 12 | use std::pin::Pin; |
| 13 | use std::sync::atomic::{AtomicU64, Ordering}; |
| 14 | use std::sync::OnceLock; |
| 15 | |
| 16 | static NEXT_ID: AtomicU64 = AtomicU64::new(1); |
| 17 | static HOST_RT: OnceLock<tokio::runtime::Handle> = OnceLock::new(); |
| 18 | |
| 19 | /// What an async op resolves its JS promise with: a string, or raw bytes |
| 20 | /// (delivered as a `Uint8Array` — the structured-clone RPC payloads). |
| 21 | pub enum OpOut { |
| 22 | Str(String), |
| 23 | Bytes(Vec<u8>), |
| 24 | } |
| 25 | impl From<String> for OpOut { |
| 26 | fn from(value: String) -> Self { |
| 27 | Self::Str(value) |
| 28 | } |
| 29 | } |
| 30 | impl From<Vec<u8>> for OpOut { |
| 31 | fn from(value: Vec<u8>) -> Self { |
| 32 | Self::Bytes(value) |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | pub type OpFuture = Pin<Box<dyn Future<Output = Result<OpOut, String>> + Send>>; |
| 37 | |
| 38 | thread_local! { |
| 39 | // Per-JS-thread current-thread runtime: the Worker and each cell run on |
| 40 | // their own thread, so each needs its own runtime — a shared current-thread |
| 41 | // runtime cannot be driven by two threads at once. Held as `Rc` so a serve |
| 42 | // loop can `block_on` on a clone without keeping the RefCell borrowed (which |
| 43 | // would deadlock op spawns that clone the handle mid-drive). |
| 44 | static RT: RefCell<Option<std::rc::Rc<tokio::runtime::Runtime>>> = |
| 45 | const { RefCell::new(None) }; |
| 46 | // Ops push (id, future); run_loop drains and spawns them into its region. |
| 47 | static SPAWNS: RefCell<Vec<(u64, OpFuture)>> = const { RefCell::new(Vec::new()) }; |
| 48 | } |
| 49 | |
| 50 | pub fn init() { |
| 51 | RT.with(|r| { |
| 52 | if r.borrow().is_none() { |
| 53 | *r.borrow_mut() = Some(std::rc::Rc::new( |
| 54 | tokio::runtime::Builder::new_current_thread() |
| 55 | .enable_all() |
| 56 | .build() |
| 57 | .unwrap(), |
| 58 | )); |
| 59 | } |
| 60 | }); |
| 61 | } |
| 62 | |
| 63 | /// The thread's runtime (an `Rc` clone), for a serve loop that drives both hyper |
| 64 | /// and this thread's JS ops on one runtime. `block_on` on the returned clone |
| 65 | /// leaves the thread-local RefCell free for `handle()`/op spawns. |
| 66 | pub fn runtime() -> std::rc::Rc<tokio::runtime::Runtime> { |
| 67 | RT.with(|r| r.borrow().as_ref().unwrap().clone()) |
| 68 | } |
| 69 | |
| 70 | /// Install celld's shared Tokio runtime for host I/O. Futures remain owned by |
| 71 | /// each request's JoinSet, but polling network work on the shared runtime lets |
| 72 | /// a reqwest response body move into Axum and continue streaming after the JS |
| 73 | /// handler has returned. |
| 74 | pub fn set_host_handle(handle: tokio::runtime::Handle) { |
| 75 | let _ = HOST_RT.set(handle); |
| 76 | } |
| 77 | |
| 78 | pub fn handle() -> tokio::runtime::Handle { |
| 79 | RT.with(|r| r.borrow().as_ref().unwrap().handle().clone()) |
| 80 | } |
| 81 | pub fn op_handle() -> tokio::runtime::Handle { |
| 82 | HOST_RT.get().cloned().unwrap_or_else(handle) |
| 83 | } |
| 84 | pub fn block_on<F: Future>(f: F) -> F::Output { |
| 85 | let rt = runtime(); |
| 86 | rt.block_on(f) |
| 87 | } |
| 88 | |
| 89 | /// Register an async op's future; returns its promise id. NOT spawned here — the |
| 90 | /// region in `run_loop` owns spawning, so a task is never detached. |
| 91 | pub fn enqueue<T: Into<OpOut>>( |
| 92 | fut: impl Future<Output = Result<T, String>> + Send + 'static, |
| 93 | ) -> u64 { |
| 94 | let id = NEXT_ID.fetch_add(1, Ordering::Relaxed); |
| 95 | let fut: OpFuture = Box::pin(async move { fut.await.map(Into::into) }); |
| 96 | SPAWNS.with(|s| s.borrow_mut().push((id, fut))); |
| 97 | id |
| 98 | } |
| 99 | |
| 100 | pub fn drain_spawns() -> Vec<(u64, OpFuture)> { |
| 101 | SPAWNS.with(|s| s.borrow_mut().drain(..).collect()) |
| 102 | } |