Skip to main content

vs_engine_webkit/
runtime.rs

1//! Engine thread + channel bridge.
2//!
3//! WebKit on either platform must be driven from the thread that owns
4//! its run loop (`GMainLoop` on Linux, `CFRunLoop` on macOS). The
5//! daemon's Tokio workers can not call WebKit directly. [`EngineRuntime`]
6//! owns a dedicated OS thread, lets the platform construct the engine
7//! on that thread, and dispatches every call from the daemon over an
8//! `mpsc` channel.
9//!
10//! Every wrapper method on [`EngineRuntime`] (e.g. [`EngineRuntime::open`])
11//! is synchronous and blocks until the engine thread replies. The
12//! daemon wraps these in `tokio::task::spawn_blocking` to keep them
13//! off Tokio's worker threads.
14
15#![allow(clippy::result_unit_err, clippy::must_use_candidate)]
16
17use std::path::PathBuf;
18use std::sync::mpsc;
19use std::thread::{self, JoinHandle};
20use std::time::Duration;
21
22use vs_protocol::{Ref, Tree};
23
24use crate::engine::{
25    ActTarget, Action, AuthBlob, CaptureScope, DataStore, Download, DownloadEntry, DownloadSource,
26    Engine, EngineCapabilities, EngineError, EngineResult, LayoutBox, PageHandle, Viewport,
27    WaitCondition,
28};
29
30/// One unit of work for the engine thread.
31type Job = Box<dyn FnOnce(&mut dyn Engine) + Send>;
32
33/// Extract a human-readable message from a `catch_unwind` payload.
34fn panic_message(payload: &(dyn std::any::Any + Send)) -> String {
35    let detail = payload
36        .downcast_ref::<&str>()
37        .map(|s| (*s).to_string())
38        .or_else(|| payload.downcast_ref::<String>().cloned())
39        .unwrap_or_else(|| "unknown panic".to_string());
40    format!("engine panicked: {detail}")
41}
42
43/// Owns the engine thread and exposes a synchronous facade.
44///
45/// Drop semantics: dropping the runtime closes the command channel,
46/// which causes the engine thread to exit its loop and drop the
47/// engine. The destructor joins the thread.
48/// Called after a job is queued, to nudge a host loop that is asleep.
49///
50/// An `mpsc` send is invisible to a platform run loop, so a
51/// [`MainThreadDispatcher`] host cannot block waiting for work — it has
52/// to wake periodically and poll, trading idle CPU against how long a
53/// queued job sits. With a waker installed the host can sleep properly
54/// and be woken the moment a job lands, which removes both costs.
55///
56/// Must be safe to call from any thread.
57pub type Waker = Box<dyn Fn() + Send + Sync>;
58
59pub struct EngineRuntime {
60    sender: Option<mpsc::Sender<Job>>,
61    handle: Option<JoinHandle<()>>,
62    waker: Option<Waker>,
63}
64
65impl std::fmt::Debug for EngineRuntime {
66    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
67        f.debug_struct("EngineRuntime")
68            .field("running", &self.sender.is_some())
69            .finish_non_exhaustive()
70    }
71}
72
73impl EngineRuntime {
74    /// Spawn the engine thread and construct the engine *on that thread*
75    /// via `make`. This is the only correct construction point: the
76    /// platform run loop must be initialized on the same thread that
77    /// later drives WebKit.
78    ///
79    /// Returns once the engine thread has signaled it is ready.
80    pub fn spawn<F>(make: F) -> EngineResult<Self>
81    where
82        F: FnOnce() -> EngineResult<Box<dyn Engine>> + Send + 'static,
83    {
84        let (tx, rx) = mpsc::channel::<Job>();
85        let (ready_tx, ready_rx) = mpsc::sync_channel::<EngineResult<()>>(1);
86
87        let handle = thread::Builder::new()
88            .name("vibesurfer-engine".into())
89            .spawn(move || {
90                let mut engine = match make() {
91                    Ok(e) => {
92                        let _ = ready_tx.send(Ok(()));
93                        e
94                    }
95                    Err(e) => {
96                        let _ = ready_tx.send(Err(e));
97                        return;
98                    }
99                };
100
101                while let Ok(job) = rx.recv() {
102                    job(engine.as_mut());
103                }
104                // Channel closed: drop the engine on this thread and exit.
105                drop(engine);
106            })
107            .map_err(|e| EngineError::Other(format!("spawn engine thread: {e}")))?;
108
109        match ready_rx.recv() {
110            Ok(Ok(())) => {}
111            Ok(Err(e)) => {
112                let _ = handle.join();
113                return Err(e);
114            }
115            Err(_) => {
116                let _ = handle.join();
117                return Err(EngineError::Crashed);
118            }
119        }
120
121        Ok(Self {
122            sender: Some(tx),
123            handle: Some(handle),
124            // The spawned-thread runtime blocks on `rx.recv()`, so it is
125            // already woken by the send itself.
126            waker: None,
127        })
128    }
129
130    /// Construct a runtime whose engine runs on the *caller'\''s* thread.
131    /// No internal thread is spawned. The returned [`MainThreadDispatcher`]
132    /// drives the engine: call [`MainThreadDispatcher::tick`] in the
133    /// caller'\''s loop to drain one queued job, or [`MainThreadDispatcher::run_until`]
134    /// to block until a stop flag fires.
135    ///
136    /// Use this when the engine is bound to a specific OS thread (e.g.
137    /// the macOS Cocoa main thread, where `WKWebView` must run).
138    pub fn dispatcher(engine: Box<dyn Engine>) -> (Self, MainThreadDispatcher) {
139        let (tx, rx) = mpsc::channel::<Job>();
140        let runtime = Self {
141            sender: Some(tx),
142            handle: None,
143            waker: None,
144        };
145        let dispatcher = MainThreadDispatcher { engine, rx };
146        (runtime, dispatcher)
147    }
148
149    /// Install the [`Waker`] the host loop is woken by.
150    ///
151    /// Call before the runtime is shared. Without one the host must
152    /// poll; with one it can sleep until there is actually work.
153    #[must_use]
154    pub fn with_waker(mut self, waker: Waker) -> Self {
155        self.waker = Some(waker);
156        self
157    }
158
159    /// Cleanly shut down: close the channel and join the thread.
160    /// Idempotent — calling shutdown twice is a no-op.
161    pub fn shutdown(&mut self) {
162        drop(self.sender.take());
163        if let Some(handle) = self.handle.take() {
164            let _ = handle.join();
165        }
166    }
167
168    fn dispatch<R, F>(&self, f: F) -> EngineResult<R>
169    where
170        F: FnOnce(&mut dyn Engine) -> EngineResult<R> + Send + 'static,
171        R: Send + 'static,
172    {
173        let sender = self.sender.as_ref().ok_or(EngineError::Closed)?;
174        let (reply_tx, reply_rx) = mpsc::sync_channel::<EngineResult<R>>(1);
175        let job: Job = Box::new(move |engine| {
176            // Isolate a panicking engine op: on macOS the job runs on
177            // the Cocoa main thread inside an Obj-C run-loop frame, so an
178            // unwinding panic is undefined behavior that can take the
179            // whole daemon down ("could not connect to the server" on the
180            // next request). Catch it here and hand back a clean, message-
181            // bearing error instead — far better than the bare
182            // `ENGINE_CRASH` (empty-args) the dropped reply channel would
183            // otherwise produce.
184            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(engine)))
185                .unwrap_or_else(|payload| Err(EngineError::Other(panic_message(&payload))));
186            let _ = reply_tx.send(result);
187        });
188        sender.send(job).map_err(|_| EngineError::Closed)?;
189        // Wake the host loop *after* the job is queued, so it cannot
190        // wake, find nothing, and go back to sleep past this job.
191        if let Some(waker) = &self.waker {
192            waker();
193        }
194        reply_rx.recv().map_err(|_| EngineError::Crashed)?
195    }
196
197    // -----------------------------------------------------------------
198    // Synchronous facade for every Engine method.
199    // -----------------------------------------------------------------
200
201    pub fn open(&self, url: &str, store: &DataStore) -> EngineResult<PageHandle> {
202        let url = url.to_string();
203        let store = store.clone();
204        self.dispatch(move |e| e.open(&url, &store))
205    }
206
207    pub fn drop_store(&self, key: &str) -> EngineResult<()> {
208        let key = key.to_string();
209        self.dispatch(move |e| e.drop_store(&key))
210    }
211
212    pub fn navigate(&self, page: PageHandle, url: &str) -> EngineResult<()> {
213        let url = url.to_string();
214        self.dispatch(move |e| e.navigate(page, &url))
215    }
216
217    pub fn load_html(&self, page: PageHandle, url: &str, html: &str) -> EngineResult<()> {
218        let url = url.to_string();
219        let html = html.to_string();
220        self.dispatch(move |e| e.load_html(page, &url, &html))
221    }
222
223    pub fn close(&self, page: PageHandle) -> EngineResult<()> {
224        self.dispatch(move |e| e.close(page))
225    }
226
227    pub fn enable_webauthn(&self, page: PageHandle) -> EngineResult<()> {
228        self.dispatch(move |e| e.enable_webauthn(page))
229    }
230
231    pub fn add_init_script(&self, page: PageHandle, source: &str) -> EngineResult<()> {
232        let source = source.to_string();
233        self.dispatch(move |e| e.add_init_script(page, &source))
234    }
235
236    pub fn snapshot(&self, page: PageHandle) -> EngineResult<Tree> {
237        self.dispatch(move |e| e.snapshot(page))
238    }
239
240    /// Snapshot the tree and read the console buffer in a single
241    /// main-thread hop. `vs_view` needs both (the tree, plus the
242    /// console entries behind its `? console_error` warning); folding
243    /// the cheap native console read into the snapshot dispatch avoids
244    /// a second round trip on every view. The console read is a buffer
245    /// borrow, so it adds no measurable cost.
246    pub fn snapshot_with_console(
247        &self,
248        page: PageHandle,
249    ) -> EngineResult<(Tree, Vec<crate::inspector::ConsoleEntry>)> {
250        self.dispatch(move |e| {
251            let tree = e.snapshot(page)?;
252            let console = e.console_entries(page)?;
253            Ok((tree, console))
254        })
255    }
256
257    pub fn act(
258        &self,
259        page: PageHandle,
260        target: ActTarget,
261        action: Action,
262        mode: crate::engine::InputMode,
263    ) -> EngineResult<()> {
264        self.dispatch(move |e| e.act(page, target, action, mode))
265    }
266
267    /// Perform an action and snapshot the resulting tree in a single
268    /// main-thread hop. `vs_act` always snapshots right after acting, so
269    /// folding the two into one dispatch removes a full engine round
270    /// trip (~10ms) from every action. The backend's `act` already
271    /// settles input + flushes rAF before returning, so the snapshot
272    /// sees the post-action DOM exactly as the two-call form did.
273    pub fn act_and_snapshot(
274        &self,
275        page: PageHandle,
276        target: ActTarget,
277        action: Action,
278        mode: crate::engine::InputMode,
279    ) -> EngineResult<Tree> {
280        self.dispatch(move |e| {
281            e.act(page, target, action, mode)?;
282            e.snapshot(page)
283        })
284    }
285
286    pub fn wait(
287        &self,
288        page: PageHandle,
289        cond: WaitCondition,
290        budget: Duration,
291    ) -> EngineResult<()> {
292        self.dispatch(move |e| e.wait(page, cond, budget))
293    }
294
295    pub fn capture(&self, page: PageHandle, scope: CaptureScope) -> EngineResult<PathBuf> {
296        self.dispatch(move |e| e.capture(page, scope))
297    }
298
299    pub fn capture_live(&self, page: PageHandle, max_width: u32) -> EngineResult<PathBuf> {
300        self.dispatch(move |e| e.capture_live(page, max_width))
301    }
302
303    pub fn record_begin(
304        &self,
305        page: PageHandle,
306        tx: std::sync::mpsc::Sender<crate::engine::RecFrame>,
307        fps: u32,
308        max_width: u32,
309    ) -> EngineResult<()> {
310        self.dispatch(move |e| e.record_begin(page, tx, fps, max_width))
311    }
312
313    pub fn record_end(&self, page: PageHandle) -> EngineResult<()> {
314        self.dispatch(move |e| e.record_end(page))
315    }
316
317    pub fn layout(&self, page: PageHandle, refs: Vec<Ref>) -> EngineResult<Vec<LayoutBox>> {
318        self.dispatch(move |e| e.layout(page, &refs))
319    }
320
321    pub fn download(
322        &self,
323        page: PageHandle,
324        source: DownloadSource,
325        budget: Duration,
326    ) -> EngineResult<Download> {
327        self.dispatch(move |e| e.download(page, source, budget))
328    }
329
330    pub fn download_list(&self, page: PageHandle) -> EngineResult<Vec<DownloadEntry>> {
331        self.dispatch(move |e| e.download_list(page))
332    }
333
334    pub fn set_viewport(&self, page: PageHandle, viewport: Viewport) -> EngineResult<()> {
335        self.dispatch(move |e| e.set_viewport(page, viewport))
336    }
337
338    pub fn save_auth(&self, page: PageHandle) -> EngineResult<AuthBlob> {
339        self.dispatch(move |e| e.save_auth(page))
340    }
341
342    pub fn load_auth(&self, page: PageHandle, blob: AuthBlob) -> EngineResult<()> {
343        self.dispatch(move |e| e.load_auth(page, &blob))
344    }
345
346    pub fn console_entries(
347        &self,
348        page: PageHandle,
349    ) -> EngineResult<Vec<crate::inspector::ConsoleEntry>> {
350        self.dispatch(move |e| e.console_entries(page))
351    }
352
353    pub fn network_entries(
354        &self,
355        page: PageHandle,
356    ) -> EngineResult<Vec<crate::inspector::NetworkEntry>> {
357        self.dispatch(move |e| e.network_entries(page))
358    }
359
360    pub fn request_detail(
361        &self,
362        page: PageHandle,
363        seq: u64,
364    ) -> EngineResult<Option<crate::inspector::RequestDetail>> {
365        self.dispatch(move |e| e.request_detail(page, seq))
366    }
367
368    pub fn eval_js(
369        &self,
370        page: PageHandle,
371        expr: &str,
372    ) -> EngineResult<crate::inspector::EvalResult> {
373        let expr = expr.to_string();
374        self.dispatch(move |e| e.eval_js(page, &expr))
375    }
376
377    pub fn eval_js_in_frame(
378        &self,
379        page: PageHandle,
380        frame: &str,
381        expr: &str,
382    ) -> EngineResult<crate::inspector::EvalResult> {
383        let (frame, expr) = (frame.to_string(), expr.to_string());
384        self.dispatch(move |e| e.eval_js_in_frame(page, &frame, &expr))
385    }
386
387    pub fn storage(
388        &self,
389        page: PageHandle,
390        scope: crate::inspector::StorageScope,
391    ) -> EngineResult<Vec<crate::inspector::StorageEntry>> {
392        self.dispatch(move |e| e.storage(page, scope))
393    }
394
395    pub fn cookie_events(
396        &self,
397        page: PageHandle,
398    ) -> EngineResult<Vec<crate::inspector::CookieEvent>> {
399        self.dispatch(move |e| e.cookie_events(page))
400    }
401
402    pub fn type_text(
403        &self,
404        page: PageHandle,
405        text: &str,
406        mode: crate::engine::InputMode,
407    ) -> EngineResult<()> {
408        let text = text.to_string();
409        self.dispatch(move |e| e.type_text(page, &text, mode))
410    }
411
412    pub fn cursor_op(
413        &self,
414        page: PageHandle,
415        op: crate::engine::CursorOp,
416        mode: crate::engine::InputMode,
417    ) -> EngineResult<()> {
418        self.dispatch(move |e| e.cursor_op(page, op, mode))
419    }
420
421    pub fn scripts(&self, page: PageHandle) -> EngineResult<Vec<crate::inspector::ScriptEntry>> {
422        self.dispatch(move |e| e.scripts(page))
423    }
424
425    pub fn script_source(
426        &self,
427        page: PageHandle,
428        seq: u64,
429    ) -> EngineResult<Option<crate::inspector::ScriptSource>> {
430        self.dispatch(move |e| e.script_source(page, seq))
431    }
432
433    pub fn dom(
434        &self,
435        page: PageHandle,
436        r: vs_protocol::Ref,
437        extra_props: Vec<String>,
438    ) -> EngineResult<Option<crate::inspector::DomDetail>> {
439        self.dispatch(move |e| e.dom(page, r, &extra_props))
440    }
441
442    pub fn performance(
443        &self,
444        page: PageHandle,
445    ) -> EngineResult<crate::inspector::PerformanceMetrics> {
446        self.dispatch(move |e| e.performance(page))
447    }
448
449    pub fn main_response(
450        &self,
451        page: PageHandle,
452    ) -> EngineResult<Option<crate::inspector::MainResponse>> {
453        self.dispatch(move |e| e.main_response(page))
454    }
455
456    pub fn capabilities(&self) -> EngineResult<EngineCapabilities> {
457        self.dispatch(|e| Ok(e.capabilities()))
458    }
459
460    pub fn set_popups(&self, page: PageHandle, on: bool) -> EngineResult<()> {
461        self.dispatch(move |e| e.set_popups(page, on))
462    }
463
464    pub fn popup_feed(&self) -> EngineResult<Option<std::sync::Arc<crate::engine::PopupFeed>>> {
465        self.dispatch(|e| Ok(e.popup_feed()))
466    }
467}
468
469impl Drop for EngineRuntime {
470    fn drop(&mut self) {
471        self.shutdown();
472    }
473}
474
475/// Drives an engine that lives on the caller'\''s thread (typically the
476/// OS main thread on macOS, since `WKWebView` is pinned there). The
477/// driver owns the engine and a receiver for jobs sent by the runtime
478/// handle that the daemon holds.
479pub struct MainThreadDispatcher {
480    engine: Box<dyn Engine>,
481    rx: mpsc::Receiver<Job>,
482}
483
484impl MainThreadDispatcher {
485    /// Drain one job if available. Returns `Ok(true)` if a job was
486    /// executed, `Ok(false)` if the queue is currently empty,
487    /// `Err(())` if the channel is closed (the runtime was dropped —
488    /// the dispatcher should exit its loop).
489    pub fn tick(&mut self) -> Result<bool, ()> {
490        match self.rx.try_recv() {
491            Ok(job) => {
492                job(self.engine.as_mut());
493                Ok(true)
494            }
495            Err(mpsc::TryRecvError::Empty) => Ok(false),
496            Err(mpsc::TryRecvError::Disconnected) => Err(()),
497        }
498    }
499
500    /// Block until a job arrives or the channel is closed; execute one
501    /// job. Returns `Ok(true)` after running, `Err(())` on closed.
502    pub fn tick_blocking(&mut self) -> Result<bool, ()> {
503        match self.rx.recv() {
504            Ok(job) => {
505                job(self.engine.as_mut());
506                Ok(true)
507            }
508            Err(_) => Err(()),
509        }
510    }
511}
512
513#[cfg(test)]
514mod tests {
515    use std::path::PathBuf;
516    use std::time::Duration;
517
518    use vs_protocol::{Node, Ref, Role, Tree};
519
520    use super::*;
521    use crate::engine::{
522        ActTarget, Action, AuthBlob, CaptureScope, EngineCapabilities, LayoutBox, Viewport,
523        WaitCondition,
524    };
525
526    /// Minimal in-process `Engine` impl used only to exercise the
527    /// runtime's spawn / dispatch / shutdown plumbing. Lives in the
528    /// same `cfg(test)` block as the tests so it can never be reached
529    /// from production code.
530    #[derive(Default)]
531    struct TestEngine {
532        next_handle: u64,
533        last_url: String,
534    }
535
536    impl Engine for TestEngine {
537        fn open(&mut self, url: &str, _store: &DataStore) -> EngineResult<PageHandle> {
538            self.next_handle += 1;
539            self.last_url = url.to_string();
540            Ok(PageHandle(self.next_handle))
541        }
542        fn navigate(&mut self, _page: PageHandle, url: &str) -> EngineResult<()> {
543            self.last_url = url.to_string();
544            Ok(())
545        }
546        fn enable_webauthn(&mut self, _page: PageHandle) -> EngineResult<()> {
547            Ok(())
548        }
549        fn add_init_script(&mut self, _page: PageHandle, _source: &str) -> EngineResult<()> {
550            Ok(())
551        }
552        fn close(&mut self, _page: PageHandle) -> EngineResult<()> {
553            Ok(())
554        }
555        fn snapshot(&mut self, _page: PageHandle) -> EngineResult<Tree> {
556            Ok(Tree::from_root(Node::leaf(
557                Ref(1),
558                Role::Doc,
559                &self.last_url,
560            )))
561        }
562        fn act(
563            &mut self,
564            _: PageHandle,
565            _: ActTarget,
566            _: Action,
567            _: crate::engine::InputMode,
568        ) -> EngineResult<()> {
569            Ok(())
570        }
571        fn wait(&mut self, _: PageHandle, _: WaitCondition, _: Duration) -> EngineResult<()> {
572            Ok(())
573        }
574        fn capture(&mut self, _: PageHandle, _: CaptureScope) -> EngineResult<PathBuf> {
575            Ok(PathBuf::from("/tmp/test.png"))
576        }
577        fn layout(&mut self, _: PageHandle, refs: &[Ref]) -> EngineResult<Vec<LayoutBox>> {
578            Ok(refs
579                .iter()
580                .map(|r| LayoutBox {
581                    r: *r,
582                    x: 0.0,
583                    y: 0.0,
584                    width: 1.0,
585                    height: 1.0,
586                    visible: true,
587                    z_index: 0,
588                })
589                .collect())
590        }
591        fn set_viewport(&mut self, _: PageHandle, _: Viewport) -> EngineResult<()> {
592            Ok(())
593        }
594        fn save_auth(&mut self, _: PageHandle) -> EngineResult<AuthBlob> {
595            Ok(AuthBlob {
596                bytes: self.last_url.as_bytes().to_vec(),
597            })
598        }
599        fn load_auth(&mut self, _: PageHandle, _: &AuthBlob) -> EngineResult<()> {
600            Ok(())
601        }
602        fn capabilities(&self) -> EngineCapabilities {
603            EngineCapabilities {
604                renders: false,
605                honors_viewport: false,
606                measures_layout: false,
607                persists_auth: false,
608                inspector_console: false,
609                inspector_network: false,
610                inspector_cookie_events: false,
611                name: "test",
612                version: "runtime-tests",
613            }
614        }
615    }
616
617    fn spawn_test_runtime() -> EngineRuntime {
618        EngineRuntime::spawn(|| Ok(Box::new(TestEngine::default()) as Box<dyn Engine>))
619            .expect("spawn")
620    }
621
622    #[test]
623    fn spawn_and_shutdown_cleanly() {
624        let mut rt = spawn_test_runtime();
625        rt.shutdown();
626        rt.shutdown();
627    }
628
629    #[test]
630    fn dispatch_blocks_until_reply() {
631        let rt = spawn_test_runtime();
632        let caps = rt.capabilities().unwrap();
633        assert_eq!(caps.name, "test");
634    }
635
636    #[test]
637    fn engine_construction_failure_reported() {
638        let err =
639            EngineRuntime::spawn(|| Err::<Box<dyn Engine>, _>(EngineError::Other("nope".into())))
640                .unwrap_err();
641        assert!(matches!(err, EngineError::Other(_)));
642    }
643
644    #[test]
645    fn calls_after_drop_error_with_closed() {
646        let mut rt = spawn_test_runtime();
647        rt.shutdown();
648        let err = rt.capabilities().unwrap_err();
649        assert!(matches!(err, EngineError::Closed));
650    }
651
652    /// Cover the round-trip path that used to live in
653    /// `tests/runtime_round_trip.rs`. The Engine impl is intentionally
654    /// trivial — this test verifies the dispatch channel, not engine
655    /// behavior.
656    #[test]
657    fn full_primitive_sequence_via_runtime() {
658        let rt = spawn_test_runtime();
659        let page = rt
660            .open("https://example.com/login", &DataStore::Shared)
661            .unwrap();
662        rt.wait(page, WaitCondition::Stable, Duration::from_millis(0))
663            .unwrap();
664        let tree = rt.snapshot(page).unwrap();
665        assert!(tree.roots[0].label.contains("https://example.com/login"));
666        rt.act(
667            page,
668            ActTarget::Ref(Ref(3)),
669            Action::Fill { value: "x".into() },
670            crate::engine::InputMode::Careful,
671        )
672        .unwrap();
673        let auth = rt.save_auth(page).unwrap();
674        rt.load_auth(page, auth).unwrap();
675        rt.close(page).unwrap();
676        rt.close(page).unwrap();
677    }
678
679    #[test]
680    fn dispatch_serializes_calls() {
681        let rt = spawn_test_runtime();
682        let mut handles = Vec::new();
683        for i in 0..32 {
684            handles.push(
685                rt.open(&format!("https://example.com/{i}"), &DataStore::Shared)
686                    .unwrap(),
687            );
688        }
689        let mut sorted = handles.clone();
690        sorted.sort();
691        sorted.dedup();
692        assert_eq!(sorted.len(), handles.len());
693    }
694}