diff --git a/aimdb-wasm-adapter/Cargo.toml b/aimdb-wasm-adapter/Cargo.toml index cebb1afc..29c85deb 100644 --- a/aimdb-wasm-adapter/Cargo.toml +++ b/aimdb-wasm-adapter/Cargo.toml @@ -41,6 +41,22 @@ aimdb-data-contracts = { version = "0.3.0", path = "../aimdb-data-contracts", de "alloc", "aimdb-core", ] } +# Serialization (no_std + alloc) +serde = { workspace = true } +serde_json = { workspace = true } + +# Async utilities (minimal, no_std compatible) +futures-util = { version = "0.3", default-features = false, features = [ + "alloc", + "sink", +] } + +# Bounded MPSC channel for join fan-in. +# Note: futures-channel mpsc requires "std" because its internal BiLock uses std::sync. +# The "alloc"-only path does not expose mpsc; "std" is the minimum required feature. +futures-channel = { version = "0.3", default-features = false, features = ["std", "sink"] } + +[target.'cfg(target_arch = "wasm32")'.dependencies] # WASM bindings wasm-bindgen = { version = "0.2", optional = true } wasm-bindgen-futures = { version = "0.4", optional = true } @@ -56,28 +72,14 @@ web-sys = { version = "0.3", optional = true, features = [ "Window", ] } -# Serialization (no_std + alloc) -serde = { workspace = true } -serde_json = { workspace = true } serde-wasm-bindgen = { version = "0.6", optional = true } -# Async utilities (minimal, no_std compatible) -futures-util = { version = "0.3", default-features = false, features = [ - "alloc", - "sink", -] } - -# Bounded MPSC channel for join fan-in. -# Note: futures-channel mpsc requires "std" because its internal BiLock uses std::sync. -# The "alloc"-only path does not expose mpsc; "std" is the minimum required feature. -futures-channel = { version = "0.3", default-features = false, features = ["std", "sink"] } - [lints.rust] unexpected_cfgs = { level = "warn", check-cfg = [ 'cfg(feature, values("std"))', ] } -[dev-dependencies] +[target.'cfg(target_arch = "wasm32")'.dev-dependencies] wasm-bindgen-test = "0.3" # Host-only: drives the async `aimdb-core` buffer contract suite via diff --git a/aimdb-wasm-adapter/README.md b/aimdb-wasm-adapter/README.md index cf6efeb1..f613fc53 100644 --- a/aimdb-wasm-adapter/README.md +++ b/aimdb-wasm-adapter/README.md @@ -130,14 +130,12 @@ Two rules follow from how the registry is keyed: ## Target support -With `wasm-runtime` (the default) enabled this crate builds for `wasm32-*` only: -the bridge holds `web_sys` closures across await points, so its futures are -`!Send` and rely on an `unsafe impl` sound only on single-threaded wasm. A host -build stops on one `compile_error!` saying so. For the portable buffer/runtime -unit tests, drop the feature: +The default `wasm-runtime` feature enables browser integration on `wasm32`. +Native builds include the portable buffer and runtime implementations. Run their +unit tests with: ```bash -cargo test -p aimdb-wasm-adapter --no-default-features --lib +cargo test -p aimdb-wasm-adapter --lib ``` ## Build diff --git a/aimdb-wasm-adapter/src/bindings.rs b/aimdb-wasm-adapter/src/bindings.rs index 32f89fa3..055f57be 100644 --- a/aimdb-wasm-adapter/src/bindings.rs +++ b/aimdb-wasm-adapter/src/bindings.rs @@ -636,7 +636,7 @@ where .map_err(|e| JsError::new(&format!("{e:?}")))?; let callback = callback.clone(); - let (cancel_token, cancel_handle) = crate::buffer::cancel_pair(); + let (cancel_token, cancel_handle) = crate::cancellation::cancel_pair(); wasm_bindgen_futures::spawn_local(async move { use core::task::Poll; diff --git a/aimdb-wasm-adapter/src/buffer.rs b/aimdb-wasm-adapter/src/buffer.rs index 9e1b8997..2dd86652 100644 --- a/aimdb-wasm-adapter/src/buffer.rs +++ b/aimdb-wasm-adapter/src/buffer.rs @@ -11,16 +11,19 @@ //! # Safety //! //! `WasmBuffer` and `WasmBufferReader` implement `Send + Sync` via -//! `unsafe impl` because `wasm32-unknown-unknown` is single-threaded. +//! `unsafe impl` on single-threaded wasm32. Native builds use synchronized +//! shared storage. extern crate alloc; use alloc::boxed::Box; use alloc::collections::VecDeque; -use alloc::rc::Rc; +#[cfg(target_arch = "wasm32")] +use alloc::rc::Rc as Shared; +#[cfg(not(target_arch = "wasm32"))] +use alloc::sync::Arc as Shared; use alloc::vec::Vec; -#[cfg(feature = "wasm-runtime")] -use core::cell::Cell; +#[cfg(target_arch = "wasm32")] use core::cell::RefCell; use core::task::{Context, Poll, Waker}; @@ -30,24 +33,44 @@ use aimdb_core::DbError; #[cfg(feature = "observability")] use aimdb_core::buffer::{BufferCounters, BufferMetrics, BufferMetricsSnapshot}; +#[cfg(target_arch = "wasm32")] +type BufferState = RefCell>; +#[cfg(not(target_arch = "wasm32"))] +type BufferState = std::sync::Mutex>; + +#[cfg(target_arch = "wasm32")] +fn lock_state( + state: &BufferState, +) -> impl core::ops::DerefMut> + '_ { + state.borrow_mut() +} + +#[cfg(not(target_arch = "wasm32"))] +fn lock_state( + state: &BufferState, +) -> impl core::ops::DerefMut> + '_ { + state.lock().expect("WASM buffer state lock poisoned") +} + // ============================================================================ // Buffer // ============================================================================ -/// Single-threaded buffer for the WASM runtime. +/// Buffer for the WASM runtime. /// -/// Wraps an `Rc>` inner enum that holds the actual buffer state. /// All three AimDB buffer types (SPMC Ring, SingleLatest, Mailbox) share /// this outer struct — the variant is determined by [`BufferCfg`] at /// construction time. pub struct WasmBuffer { - inner: Rc>>, + inner: Shared>, #[cfg(feature = "observability")] - metrics: Rc, + metrics: Shared, } // SAFETY: wasm32 is single-threaded — Rc> cannot be accessed concurrently +#[cfg(target_arch = "wasm32")] unsafe impl Send for WasmBuffer {} +#[cfg(target_arch = "wasm32")] unsafe impl Sync for WasmBuffer {} /// Internal buffer state — one variant per buffer type. @@ -113,9 +136,9 @@ impl Buffer for WasmBuffer { }; WasmBuffer { - inner: Rc::new(RefCell::new(inner)), + inner: Shared::new(BufferState::new(inner)), #[cfg(feature = "observability")] - metrics: Rc::new(BufferCounters::new(capacity)), + metrics: Shared::new(BufferCounters::new(capacity)), } } @@ -123,8 +146,8 @@ impl Buffer for WasmBuffer { #[cfg(feature = "observability")] self.metrics.increment_produced(); - let mut inner = self.inner.borrow_mut(); - match &mut *inner { + let mut inner = lock_state(&self.inner); + let wakers = match &mut *inner { WasmBufferInner::SpmcRing { ring, capacity, @@ -136,7 +159,7 @@ impl Buffer for WasmBuffer { } ring.push_back(value); *write_seq += 1; - wake_all(wakers); + wakers } WasmBufferInner::SingleLatest { value: slot, @@ -145,17 +168,22 @@ impl Buffer for WasmBuffer { } => { *slot = Some(value); *version += 1; - wake_all(wakers); + wakers } WasmBufferInner::Mailbox { slot, wakers } => { *slot = Some(value); - wake_all(wakers); + wakers } + }; + let wakers = core::mem::take(wakers); + drop(inner); + for waker in wakers { + waker.wake(); } } fn subscribe(&self) -> Self::Reader { - let inner = self.inner.borrow(); + let inner = lock_state(&self.inner); let state = match &*inner { WasmBufferInner::SpmcRing { write_seq, .. } => { // New readers start at the current write position (no backfill). @@ -179,10 +207,10 @@ impl Buffer for WasmBuffer { }; WasmBufferReader { - buffer: Rc::clone(&self.inner), + buffer: Shared::clone(&self.inner), state, #[cfg(feature = "observability")] - metrics: Rc::clone(&self.metrics), + metrics: Shared::clone(&self.metrics), } } } @@ -202,7 +230,7 @@ impl DynBuffer for WasmBuffer { } fn peek(&self) -> Option { - match &*self.inner.borrow() { + match &*lock_state(&self.inner) { // The single slot holds the current value non-destructively. WasmBufferInner::SingleLatest { value, .. } => value.clone(), // The pending slot, cloned without taking it (drained on recv). @@ -227,7 +255,7 @@ impl DynBuffer for WasmBuffer { #[cfg(feature = "observability")] impl BufferMetrics for WasmBuffer { fn metrics(&self) -> BufferMetricsSnapshot { - let current_occupancy = match &*self.inner.borrow() { + let current_occupancy = match &*lock_state(&self.inner) { WasmBufferInner::SpmcRing { ring, .. } => ring.len(), WasmBufferInner::SingleLatest { value, .. } => usize::from(value.is_some()), WasmBufferInner::Mailbox { slot, .. } => usize::from(slot.is_some()), @@ -246,19 +274,21 @@ impl BufferMetrics for WasmBuffer { // Reader // ============================================================================ -/// Single-threaded buffer reader for the WASM runtime. +/// Buffer reader for the WASM runtime. /// /// Created by [`WasmBuffer::subscribe()`]. Each reader maintains independent /// state (cursor position, last-seen version) and can advance at its own pace. pub struct WasmBufferReader { - buffer: Rc>>, + buffer: Shared>, state: ReaderState, #[cfg(feature = "observability")] - metrics: Rc, + metrics: Shared, } // SAFETY: wasm32 is single-threaded — no concurrent access possible +#[cfg(target_arch = "wasm32")] unsafe impl Send for WasmBufferReader {} +#[cfg(target_arch = "wasm32")] unsafe impl Sync for WasmBufferReader {} /// Per-reader tracking state. @@ -275,40 +305,52 @@ impl BufferReader for WasmBufferReader { /// Poll for the next value. /// /// On each poll: - /// 1. Try to read a value (non-blocking). + /// 1. Check for a value under the same guard used to register the waker. /// 2. If available, return `Poll::Ready(Ok(value))`. /// 3. If not, register the waker and return `Poll::Pending`. /// - /// The waker is woken when [`WasmBuffer::push()`](WasmBuffer) fires. This is - /// allocation-free — a per-message `Box::pin(WasmRecvFuture { .. })` existed - /// solely to satisfy the old async trait signature. + /// [`WasmBuffer::push()`](WasmBuffer) wakes registered readers after releasing + /// the buffer state. fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> { - // Try non-blocking read first - match self.try_recv() { - Ok(value) => Poll::Ready(Ok(value)), - Err(e @ DbError::BufferLagged { .. }) => Poll::Ready(Err(e)), - Err(DbError::BufferEmpty) => { - // Register waker so we get woken on next push - let mut inner = self.buffer.borrow_mut(); - let wakers = match &mut *inner { - WasmBufferInner::SpmcRing { wakers, .. } => wakers, - WasmBufferInner::SingleLatest { wakers, .. } => wakers, - WasmBufferInner::Mailbox { wakers, .. } => wakers, - }; - // Deduplicate: only add if no existing waker will wake the same task. - // Prevents unbounded growth when a single reader is polled repeatedly. - if !wakers.iter().any(|w| w.will_wake(cx.waker())) { - wakers.push(cx.waker().clone()); - } - Poll::Pending - } - Err(e) => Poll::Ready(Err(e)), + let mut inner = lock_state(&self.buffer); + let result = Self::read( + &mut inner, + &mut self.state, + #[cfg(feature = "observability")] + &self.metrics, + ); + if !matches!(result, Err(DbError::BufferEmpty)) { + return Poll::Ready(result); + } + + let wakers = match &mut *inner { + WasmBufferInner::SpmcRing { wakers, .. } + | WasmBufferInner::SingleLatest { wakers, .. } + | WasmBufferInner::Mailbox { wakers, .. } => wakers, + }; + if !wakers.iter().any(|waker| waker.will_wake(cx.waker())) { + wakers.push(cx.waker().clone()); } + Poll::Pending } fn try_recv(&mut self) -> Result { - let mut inner = self.buffer.borrow_mut(); - match (&mut *inner, &mut self.state) { + Self::read( + &mut lock_state(&self.buffer), + &mut self.state, + #[cfg(feature = "observability")] + &self.metrics, + ) + } +} + +impl WasmBufferReader { + fn read( + inner: &mut WasmBufferInner, + state: &mut ReaderState, + #[cfg(feature = "observability")] metrics: &BufferCounters, + ) -> Result { + match (inner, state) { ( WasmBufferInner::SpmcRing { ring, write_seq, .. @@ -327,7 +369,7 @@ impl BufferReader for WasmBufferReader { let lag_count = oldest_seq - *read_seq; *read_seq = oldest_seq; #[cfg(feature = "observability")] - self.metrics.add_dropped(lag_count); + metrics.add_dropped(lag_count); return Err(DbError::BufferLagged { lag_count, buffer_name: alloc::string::String::from("wasm ring"), @@ -338,7 +380,7 @@ impl BufferReader for WasmBufferReader { let value = ring[offset].clone(); *read_seq += 1; #[cfg(feature = "observability")] - self.metrics.increment_consumed(); + metrics.increment_consumed(); Ok(value) } ( @@ -352,7 +394,7 @@ impl BufferReader for WasmBufferReader { Some(v) => { *last_seen_version = *version; #[cfg(feature = "observability")] - self.metrics.increment_consumed(); + metrics.increment_consumed(); Ok(v.clone()) } // Unreachable given the invariants (value is `Some` iff @@ -365,7 +407,7 @@ impl BufferReader for WasmBufferReader { (WasmBufferInner::Mailbox { slot, .. }, ReaderState::Mailbox) => match slot.take() { Some(value) => { #[cfg(feature = "observability")] - self.metrics.increment_consumed(); + metrics.increment_consumed(); Ok(value) } None => Err(DbError::BufferEmpty), @@ -375,106 +417,12 @@ impl BufferReader for WasmBufferReader { } } -// ============================================================================ -// Helpers -// ============================================================================ - -/// Wake all registered wakers and clear the list. -fn wake_all(wakers: &mut Vec) { - for waker in wakers.drain(..) { - waker.wake(); - } -} - -// ============================================================================ -// Cancellation -// ============================================================================ - -/// Shared state between [`CancelToken`] and [`CancelHandle`]. -#[cfg(feature = "wasm-runtime")] -struct CancelInner { - cancelled: Cell, - waker: RefCell>, -} - -/// Token held by the subscription task (reader side). -/// -/// Polled in a `futures_util::future::select` alongside `reader.recv()`. -/// When [`CancelHandle::cancel()`] fires, the stored waker is woken and -/// `is_cancelled()` returns `true`, causing the select to resolve. -#[cfg(feature = "wasm-runtime")] -pub(crate) struct CancelToken { - inner: Rc, -} - -/// Handle held by the JS unsubscribe closure. -/// -/// Calling [`cancel()`](CancelHandle::cancel) sets the flag and wakes the -/// subscription task so it exits immediately — even if `recv()` is blocked. -#[cfg(feature = "wasm-runtime")] -pub(crate) struct CancelHandle { - inner: Rc, -} - -// SAFETY: wasm32 is single-threaded — no concurrent access possible -#[cfg(feature = "wasm-runtime")] -unsafe impl Send for CancelToken {} -#[cfg(feature = "wasm-runtime")] -unsafe impl Sync for CancelToken {} -#[cfg(feature = "wasm-runtime")] -unsafe impl Send for CancelHandle {} -#[cfg(feature = "wasm-runtime")] -unsafe impl Sync for CancelHandle {} - -/// Create a linked cancel token/handle pair. -#[cfg(feature = "wasm-runtime")] -pub(crate) fn cancel_pair() -> (CancelToken, CancelHandle) { - let inner = Rc::new(CancelInner { - cancelled: Cell::new(false), - waker: RefCell::new(None), - }); - ( - CancelToken { - inner: inner.clone(), - }, - CancelHandle { inner }, - ) -} - -#[cfg(feature = "wasm-runtime")] -impl CancelToken { - /// Returns `true` if [`CancelHandle::cancel()`] has been called. - pub(crate) fn is_cancelled(&self) -> bool { - self.inner.cancelled.get() - } - - /// Store the current task's waker so [`CancelHandle::cancel()`] can wake it. - pub(crate) fn register_waker(&self, waker: &Waker) { - *self.inner.waker.borrow_mut() = Some(waker.clone()); - } -} - -#[cfg(feature = "wasm-runtime")] -impl CancelHandle { - /// Signal cancellation and wake the subscription task. - /// - /// Idempotent — safe to call multiple times (React StrictMode). - pub(crate) fn cancel(&self) { - self.inner.cancelled.set(true); - if let Some(w) = self.inner.waker.borrow_mut().take() { - w.wake(); - } - } -} - // ============================================================================ // Tests // ============================================================================ // -// `WasmBuffer` is pure `core` + `alloc` (`Rc>`, no `wasm_bindgen` in -// this module), so these run under the host `cargo test` lane — no wasm-pack or -// headless browser needed. They are plain `#[test]` fns (not -// `#[wasm_bindgen_test]`); the browser lane covers the bindings/bridge layer. +// The native unit tests exercise buffer behavior. The browser integration +// tests cover asynchronous execution through the WASM runtime. #[cfg(test)] mod tests { use super::*; diff --git a/aimdb-wasm-adapter/src/cancellation.rs b/aimdb-wasm-adapter/src/cancellation.rs new file mode 100644 index 00000000..36504c00 --- /dev/null +++ b/aimdb-wasm-adapter/src/cancellation.rs @@ -0,0 +1,70 @@ +use alloc::rc::Rc; +use core::cell::{Cell, RefCell}; +use core::task::Waker; + +/// Shared state between [`CancelToken`] and [`CancelHandle`]. +struct CancelInner { + cancelled: Cell, + waker: RefCell>, +} + +/// Token held by the subscription task (reader side). +/// +/// Polled in a `futures_util::future::select` alongside `reader.recv()`. +/// When [`CancelHandle::cancel()`] fires, the stored waker is woken and +/// `is_cancelled()` returns `true`, causing the select to resolve. +pub(crate) struct CancelToken { + inner: Rc, +} + +/// Handle held by the JS unsubscribe closure. +/// +/// Calling [`cancel()`](CancelHandle::cancel) sets the flag and wakes the +/// subscription task so it exits immediately — even if `recv()` is blocked. +pub(crate) struct CancelHandle { + inner: Rc, +} + +// SAFETY: wasm32 is single-threaded — no concurrent access possible +unsafe impl Send for CancelToken {} +unsafe impl Sync for CancelToken {} +unsafe impl Send for CancelHandle {} +unsafe impl Sync for CancelHandle {} + +/// Create a linked cancel token/handle pair. +pub(crate) fn cancel_pair() -> (CancelToken, CancelHandle) { + let inner = Rc::new(CancelInner { + cancelled: Cell::new(false), + waker: RefCell::new(None), + }); + ( + CancelToken { + inner: inner.clone(), + }, + CancelHandle { inner }, + ) +} + +impl CancelToken { + /// Returns `true` if [`CancelHandle::cancel()`] has been called. + pub(crate) fn is_cancelled(&self) -> bool { + self.inner.cancelled.get() + } + + /// Store the current task's waker so [`CancelHandle::cancel()`] can wake it. + pub(crate) fn register_waker(&self, waker: &Waker) { + *self.inner.waker.borrow_mut() = Some(waker.clone()); + } +} + +impl CancelHandle { + /// Signal cancellation and wake the subscription task. + /// + /// Idempotent — safe to call multiple times (React StrictMode). + pub(crate) fn cancel(&self) { + self.inner.cancelled.set(true); + if let Some(w) = self.inner.waker.borrow_mut().take() { + w.wake(); + } + } +} diff --git a/aimdb-wasm-adapter/src/lib.rs b/aimdb-wasm-adapter/src/lib.rs index f4be2651..958b4550 100644 --- a/aimdb-wasm-adapter/src/lib.rs +++ b/aimdb-wasm-adapter/src/lib.rs @@ -18,47 +18,37 @@ //! //! # Buffer Implementation //! -//! Buffers use `Rc>` instead of atomics — zero-overhead for the -//! single-threaded browser environment. All three buffer types are supported: +//! Buffers use `Rc>` in the single-threaded browser environment +//! and `Arc>` in native builds. All three buffer types are supported: //! SPMC Ring, SingleLatest, and Mailbox. //! //! # Feature Flags //! -//! - `wasm-runtime` (default) — Enables WASM bindings (`wasm-bindgen`, -//! `js-sys`, `web-sys`). Disable for native-target unit tests. -//! -//! # Target Support -//! -//! With `wasm-runtime` on, this crate builds for `wasm32-*` only: the bridge -//! holds `web_sys` closures across await points, so its futures are `!Send` and -//! meet the engine's `Send` bounds only via an arch-gated `SendFuture`. Pass -//! `--target wasm32-unknown-unknown`, or `--no-default-features` for the -//! host-side buffer/runtime unit tests. +//! - `wasm-runtime` (default) — Enables browser bindings, the WebSocket +//! bridge, and browser-backed timing and logging on `wasm32`. +//! Native builds use the portable buffer and runtime implementations. #![no_std] -// A host build with `wasm-runtime` on otherwise fails deep in the bridge with a -// wall of `E0277`s about `!Send` futures. Say why once, here, instead. -#[cfg(all(feature = "wasm-runtime", not(target_arch = "wasm32")))] +#[cfg(all(target_arch = "wasm32", target_feature = "atomics"))] compile_error!( - "aimdb-wasm-adapter's `wasm-runtime` feature builds only for wasm32 targets \ - (its web-sys bridge futures are !Send). Pass \ - `--target wasm32-unknown-unknown`, or `--no-default-features` for the \ - host-side buffer/runtime tests." + "The WASM adapter requires single-threaded execution. Disable the atomics target feature." ); extern crate alloc; +#[cfg(not(target_arch = "wasm32"))] +extern crate std; pub mod buffer; pub mod runtime; pub mod time; -// The three JS-facing modules are additionally arch-gated: off wasm32 they are -// what produces the `!Send` wall, and leaving them out keeps the guard above as -// the only error a host build reports. #[cfg(all(feature = "wasm-runtime", target_arch = "wasm32"))] pub mod bindings; +#[cfg(all(feature = "wasm-runtime", target_arch = "wasm32"))] +mod cancellation; + #[cfg(all(feature = "wasm-runtime", target_arch = "wasm32"))] pub(crate) mod schema_registry; diff --git a/aimdb-wasm-adapter/src/time.rs b/aimdb-wasm-adapter/src/time.rs index 483bd406..82caa9c9 100644 --- a/aimdb-wasm-adapter/src/time.rs +++ b/aimdb-wasm-adapter/src/time.rs @@ -8,149 +8,12 @@ //! accessing `globalThis` via `js_sys::global()` instead of `web_sys::window()`. use crate::runtime::WasmAdapter; -#[cfg(feature = "wasm-runtime")] -use core::future::Future; -#[cfg(feature = "wasm-runtime")] -use core::pin::Pin; -#[cfg(feature = "wasm-runtime")] -use core::task::{Context, Poll}; - -/// A wrapper that implements `Send` for a future **on wasm32 only**, so a -/// JS-touching (`!Send`) future can satisfy the engine's `Send` bounds and box -/// into the `dyn Future + Send` transport shapes. -/// -/// # Safety -/// -/// The blanket `unsafe impl Send for SendFuture` is sound only where -/// execution is single-threaded, so it is gated on `target_arch = "wasm32"` -/// (matching the per-type `unsafe impl Send` gates in `ws_bridge` and -/// `buffer`). The gate is the guarantee, not the incidental fact that the -/// crate's JS bridge fails to compile off-wasm: on any other target -/// `SendFuture` remains a plain `Future` that is only `Send` when `F: Send`, -/// the correct default. The `compile_error!` guard below is the backstop for -/// the one unsound wasm configuration — `wasm32` *with* the `atomics` / -/// shared-memory proposal (multi-threaded) — failing the build rather than -/// silently producing UB. -#[cfg(feature = "wasm-runtime")] -pub(crate) struct SendFuture(pub(crate) F); - -// Guard: detect wasm32 + threads (atomics target feature). The shared-memory -// proposal makes wasm multi-threaded, which invalidates the Send blanket impl. -#[cfg(all(target_arch = "wasm32", target_feature = "atomics"))] -compile_error!( - "SendFuture's blanket `impl Send` is unsound with wasm threads enabled. \ - Disable the `atomics` target feature or provide a thread-safe implementation." -); - -// SAFETY: single-threaded wasm32 (without atomics) — the future is never -// actually sent between threads. Arch-gated so it can't satisfy a `Send` bound -// on a multi-threaded native target. -#[cfg(all(feature = "wasm-runtime", target_arch = "wasm32"))] -unsafe impl Send for SendFuture {} - -#[cfg(feature = "wasm-runtime")] -impl Future for SendFuture { - type Output = F::Output; - - fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { - // SAFETY: We only project to the inner field, preserving Pin guarantees. - let inner = unsafe { self.map_unchecked_mut(|s| &mut s.0) }; - inner.poll(cx) - } -} - -// ─── globalThis helpers (Window + Worker compatible) ────────────────────── - -/// Get `performance.now()` from `globalThis`. -/// -/// Works in Window, Worker, and ServiceWorker contexts. #[cfg(all(feature = "wasm-runtime", target_arch = "wasm32"))] -fn global_performance_now() -> f64 { - use wasm_bindgen::JsCast; - - let global = js_sys::global(); - let perf = js_sys::Reflect::get(&global, &"performance".into()) - .expect("globalThis.performance not available"); - let now = js_sys::Reflect::get(&perf, &"now".into()) - .expect("globalThis.performance.now not available"); - let now_fn: js_sys::Function = now.unchecked_into(); - now_fn - .call0(&perf) - .expect("performance.now() call failed") - .as_f64() - .expect("performance.now() did not return a number") -} - -/// Call `globalThis.setTimeout(callback, delay)`. -/// -/// Works in Window, Worker, and ServiceWorker contexts. -#[cfg(all(feature = "wasm-runtime", target_arch = "wasm32"))] -fn global_set_timeout(callback: &js_sys::Function, delay_ms: i32) { - use wasm_bindgen::JsCast; - - let global = js_sys::global(); - let set_timeout: js_sys::Function = js_sys::Reflect::get(&global, &"setTimeout".into()) - .expect("globalThis.setTimeout not available") - .unchecked_into(); - let _ = set_timeout.call2(&global, callback, &delay_ms.into()); -} - -// ─── Instance clock ─────────────────────────────────────────────────────── - -/// The instance clock (design 058 §3.2): the realm's `performance.now()`, -/// measured from `build()`. -struct WasmClock { - /// `performance.now()` at `build()`, in milliseconds. - #[cfg_attr( - not(all(feature = "wasm-runtime", target_arch = "wasm32")), - allow(dead_code) - )] - origin_ms: f64, -} - -impl WasmClock { - fn new() -> Self { - #[cfg(all(feature = "wasm-runtime", target_arch = "wasm32"))] - let origin_ms = global_performance_now(); - #[cfg(not(all(feature = "wasm-runtime", target_arch = "wasm32")))] - let origin_ms = 0.0; - Self { origin_ms } - } -} - -impl aimdb_core::InstanceClock for WasmClock { - fn now(&self) -> aimdb_core::Stamp { - #[cfg(all(feature = "wasm-runtime", target_arch = "wasm32"))] - { - aimdb_core::clock::stamp_from_millis_f64(global_performance_now() - self.origin_ms) - } - - #[cfg(not(all(feature = "wasm-runtime", target_arch = "wasm32")))] - { - // Fallback for native-target unit tests — clock pinned at 0 - aimdb_core::Stamp::from_nanos(0) - } - } - - fn unix_time(&self) -> Option<(u64, u32)> { - #[cfg(all(feature = "wasm-runtime", target_arch = "wasm32"))] - { - // `Date.now()` is wall-clock milliseconds since the Unix epoch. - let ms = js_sys::Date::now(); - if ms <= 0.0 { - return None; - } - let secs = (ms / 1000.0) as u64; - let sub_nanos = ((ms % 1000.0) * 1_000_000.0) as u32; - Some((secs, sub_nanos)) - } - - #[cfg(not(all(feature = "wasm-runtime", target_arch = "wasm32")))] - { - None - } - } -} +#[path = "time/browser.rs"] +pub(crate) mod platform; +#[cfg(not(all(feature = "wasm-runtime", target_arch = "wasm32")))] +#[path = "time/fallback.rs"] +mod platform; // ─── RuntimeOps (dyn-safe capability surface) ───────────────────────────── @@ -160,53 +23,15 @@ impl aimdb_core::RuntimeOps for WasmAdapter { } fn sleep(&self, d: core::time::Duration) -> aimdb_core::BoxFuture { - extern crate alloc; - let ms = d.as_secs_f64() * 1000.0; - - #[cfg(all(feature = "wasm-runtime", target_arch = "wasm32"))] - { - use futures_util::FutureExt; - // Convert setTimeout Promise to a Rust Future. - // setTimeout never rejects, so the Ok/Err result is safe to discard. - let fut = wasm_bindgen_futures::JsFuture::from(js_sys::Promise::new( - &mut |resolve, _reject| { - global_set_timeout(&resolve, ms as i32); - }, - )) - .map(|_result| ()); - // SAFETY: wasm32 without atomics is single-threaded — JsFuture - // (which contains Rc) cannot be accessed concurrently, so - // the required Send bound is vacuously satisfied. - alloc::boxed::Box::pin(SendFuture(fut)) - } - - #[cfg(not(all(feature = "wasm-runtime", target_arch = "wasm32")))] - { - let _ = ms; - alloc::boxed::Box::pin(core::future::ready(())) - } + platform::sleep(d) } fn log(&self, level: aimdb_core::LogLevel, msg: &str) { - #[cfg(feature = "wasm-runtime")] - { - use aimdb_core::LogLevel; - match level { - LogLevel::Debug => web_sys::console::debug_1(&msg.into()), - LogLevel::Info => web_sys::console::log_1(&msg.into()), - LogLevel::Warn => web_sys::console::warn_1(&msg.into()), - LogLevel::Error => web_sys::console::error_1(&msg.into()), - } - } - - #[cfg(not(feature = "wasm-runtime"))] - { - let _ = (level, msg); - } + platform::log(level, msg) } fn new_clock(&self) -> alloc::sync::Arc { - alloc::sync::Arc::new(WasmClock::new()) + alloc::sync::Arc::new(platform::WasmClock::new()) } } diff --git a/aimdb-wasm-adapter/src/time/browser.rs b/aimdb-wasm-adapter/src/time/browser.rs new file mode 100644 index 00000000..3602254c --- /dev/null +++ b/aimdb-wasm-adapter/src/time/browser.rs @@ -0,0 +1,123 @@ +use core::future::Future; +use core::pin::Pin; +use core::task::{Context, Poll}; + +/// A wrapper that implements `Send` for a future **on wasm32 only**, so a +/// JS-touching (`!Send`) future can satisfy the engine's `Send` bounds and box +/// into the `dyn Future + Send` transport shapes. +/// +/// # Safety +/// +/// The blanket `unsafe impl Send for SendFuture` is sound only where +/// execution is single-threaded. The wrapper is available only on wasm32, +/// and the crate root rejects targets that advertise atomics. +pub(crate) struct SendFuture(pub(crate) F); + +// SAFETY: single-threaded wasm32 (without atomics) — the future is never +// actually sent between threads. Arch-gated so it can't satisfy a `Send` bound +// on a multi-threaded native target. +unsafe impl Send for SendFuture {} + +impl Future for SendFuture { + type Output = F::Output; + + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + // SAFETY: We only project to the inner field, preserving Pin guarantees. + let inner = unsafe { self.map_unchecked_mut(|s| &mut s.0) }; + inner.poll(cx) + } +} + +// ─── globalThis helpers (Window + Worker compatible) ────────────────────── + +/// Get `performance.now()` from `globalThis`. +/// +/// Works in Window, Worker, and ServiceWorker contexts. +fn global_performance_now() -> f64 { + use wasm_bindgen::JsCast; + + let global = js_sys::global(); + let perf = js_sys::Reflect::get(&global, &"performance".into()) + .expect("globalThis.performance not available"); + let now = js_sys::Reflect::get(&perf, &"now".into()) + .expect("globalThis.performance.now not available"); + let now_fn: js_sys::Function = now.unchecked_into(); + now_fn + .call0(&perf) + .expect("performance.now() call failed") + .as_f64() + .expect("performance.now() did not return a number") +} + +/// Call `globalThis.setTimeout(callback, delay)`. +/// +/// Works in Window, Worker, and ServiceWorker contexts. +fn global_set_timeout(callback: &js_sys::Function, delay_ms: i32) { + use wasm_bindgen::JsCast; + + let global = js_sys::global(); + let set_timeout: js_sys::Function = js_sys::Reflect::get(&global, &"setTimeout".into()) + .expect("globalThis.setTimeout not available") + .unchecked_into(); + let _ = set_timeout.call2(&global, callback, &delay_ms.into()); +} + +// ─── Instance clock ─────────────────────────────────────────────────────── + +/// The instance clock (design 058 §3.2): the realm's `performance.now()`, +/// measured from `build()`. +pub(super) struct WasmClock { + /// `performance.now()` at `build()`, in milliseconds. + origin_ms: f64, +} + +impl WasmClock { + pub(super) fn new() -> Self { + let origin_ms = global_performance_now(); + Self { origin_ms } + } +} + +impl aimdb_core::InstanceClock for WasmClock { + fn now(&self) -> aimdb_core::Stamp { + aimdb_core::clock::stamp_from_millis_f64(global_performance_now() - self.origin_ms) + } + + fn unix_time(&self) -> Option<(u64, u32)> { + // `Date.now()` is wall-clock milliseconds since the Unix epoch. + let ms = js_sys::Date::now(); + if ms <= 0.0 { + return None; + } + let secs = (ms / 1000.0) as u64; + let sub_nanos = ((ms % 1000.0) * 1_000_000.0) as u32; + Some((secs, sub_nanos)) + } +} + +pub(super) fn sleep(d: core::time::Duration) -> aimdb_core::BoxFuture { + use futures_util::FutureExt; + + let ms = d.as_secs_f64() * 1000.0; + // Convert setTimeout Promise to a Rust Future. + // setTimeout never rejects, so the Ok/Err result is safe to discard. + let fut = + wasm_bindgen_futures::JsFuture::from(js_sys::Promise::new(&mut |resolve, _reject| { + global_set_timeout(&resolve, ms as i32); + })) + .map(|_result| ()); + // SAFETY: wasm32 without atomics is single-threaded — JsFuture + // (which contains Rc) cannot be accessed concurrently, so + // the required Send bound is vacuously satisfied. + alloc::boxed::Box::pin(SendFuture(fut)) +} + +pub(super) fn log(level: aimdb_core::LogLevel, msg: &str) { + use aimdb_core::LogLevel; + match level { + LogLevel::Debug => web_sys::console::debug_1(&msg.into()), + LogLevel::Info => web_sys::console::log_1(&msg.into()), + LogLevel::Warn => web_sys::console::warn_1(&msg.into()), + LogLevel::Error => web_sys::console::error_1(&msg.into()), + } +} diff --git a/aimdb-wasm-adapter/src/time/fallback.rs b/aimdb-wasm-adapter/src/time/fallback.rs new file mode 100644 index 00000000..05b635f2 --- /dev/null +++ b/aimdb-wasm-adapter/src/time/fallback.rs @@ -0,0 +1,22 @@ +pub(super) struct WasmClock; + +impl WasmClock { + pub(super) fn new() -> Self { + Self + } +} + +impl aimdb_core::InstanceClock for WasmClock { + fn now(&self) -> aimdb_core::Stamp { + aimdb_core::Stamp::from_nanos(0) + } + fn unix_time(&self) -> Option<(u64, u32)> { + None + } +} + +pub(super) fn sleep(_: core::time::Duration) -> aimdb_core::BoxFuture { + alloc::boxed::Box::pin(core::future::ready(())) +} + +pub(super) fn log(_: aimdb_core::LogLevel, _: &str) {} diff --git a/aimdb-wasm-adapter/src/ws_bridge.rs b/aimdb-wasm-adapter/src/ws_bridge.rs index ecac85a5..5f284b6d 100644 --- a/aimdb-wasm-adapter/src/ws_bridge.rs +++ b/aimdb-wasm-adapter/src/ws_bridge.rs @@ -36,7 +36,7 @@ use aimdb_core::{ }; use crate::schema_registry::SchemaRegistry; -use crate::time::SendFuture; +use crate::time::platform::SendFuture; use crate::WasmAdapter; // ─── Connection status ──────────────────────────────────────────────────── diff --git a/aimdb-wasm-adapter/tests/transform_join_integration_tests.rs b/aimdb-wasm-adapter/tests/transform_join_integration_tests.rs index 3de6538d..4c8ee47a 100644 --- a/aimdb-wasm-adapter/tests/transform_join_integration_tests.rs +++ b/aimdb-wasm-adapter/tests/transform_join_integration_tests.rs @@ -5,6 +5,8 @@ //! //! Run with: wasm-pack test --headless --chrome (or --firefox) +#![cfg(all(feature = "wasm-runtime", target_arch = "wasm32"))] + use std::sync::Arc; use aimdb_core::buffer::BufferCfg;