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, Engine, EngineCapabilities, EngineError,
26    EngineResult, LayoutBox, PageHandle, Viewport, WaitCondition,
27};
28
29/// One unit of work for the engine thread.
30type Job = Box<dyn FnOnce(&mut dyn Engine) + Send>;
31
32/// Extract a human-readable message from a `catch_unwind` payload.
33fn panic_message(payload: &(dyn std::any::Any + Send)) -> String {
34    let detail = payload
35        .downcast_ref::<&str>()
36        .map(|s| (*s).to_string())
37        .or_else(|| payload.downcast_ref::<String>().cloned())
38        .unwrap_or_else(|| "unknown panic".to_string());
39    format!("engine panicked: {detail}")
40}
41
42/// Owns the engine thread and exposes a synchronous facade.
43///
44/// Drop semantics: dropping the runtime closes the command channel,
45/// which causes the engine thread to exit its loop and drop the
46/// engine. The destructor joins the thread.
47pub struct EngineRuntime {
48    sender: Option<mpsc::Sender<Job>>,
49    handle: Option<JoinHandle<()>>,
50}
51
52impl std::fmt::Debug for EngineRuntime {
53    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54        f.debug_struct("EngineRuntime")
55            .field("running", &self.sender.is_some())
56            .finish_non_exhaustive()
57    }
58}
59
60impl EngineRuntime {
61    /// Spawn the engine thread and construct the engine *on that thread*
62    /// via `make`. This is the only correct construction point: the
63    /// platform run loop must be initialized on the same thread that
64    /// later drives WebKit.
65    ///
66    /// Returns once the engine thread has signaled it is ready.
67    pub fn spawn<F>(make: F) -> EngineResult<Self>
68    where
69        F: FnOnce() -> EngineResult<Box<dyn Engine>> + Send + 'static,
70    {
71        let (tx, rx) = mpsc::channel::<Job>();
72        let (ready_tx, ready_rx) = mpsc::sync_channel::<EngineResult<()>>(1);
73
74        let handle = thread::Builder::new()
75            .name("vibesurfer-engine".into())
76            .spawn(move || {
77                let mut engine = match make() {
78                    Ok(e) => {
79                        let _ = ready_tx.send(Ok(()));
80                        e
81                    }
82                    Err(e) => {
83                        let _ = ready_tx.send(Err(e));
84                        return;
85                    }
86                };
87
88                while let Ok(job) = rx.recv() {
89                    job(engine.as_mut());
90                }
91                // Channel closed: drop the engine on this thread and exit.
92                drop(engine);
93            })
94            .map_err(|e| EngineError::Other(format!("spawn engine thread: {e}")))?;
95
96        match ready_rx.recv() {
97            Ok(Ok(())) => {}
98            Ok(Err(e)) => {
99                let _ = handle.join();
100                return Err(e);
101            }
102            Err(_) => {
103                let _ = handle.join();
104                return Err(EngineError::Crashed);
105            }
106        }
107
108        Ok(Self {
109            sender: Some(tx),
110            handle: Some(handle),
111        })
112    }
113
114    /// Construct a runtime whose engine runs on the *caller'\''s* thread.
115    /// No internal thread is spawned. The returned [`MainThreadDispatcher`]
116    /// drives the engine: call [`MainThreadDispatcher::tick`] in the
117    /// caller'\''s loop to drain one queued job, or [`MainThreadDispatcher::run_until`]
118    /// to block until a stop flag fires.
119    ///
120    /// Use this when the engine is bound to a specific OS thread (e.g.
121    /// the macOS Cocoa main thread, where `WKWebView` must run).
122    pub fn dispatcher(engine: Box<dyn Engine>) -> (Self, MainThreadDispatcher) {
123        let (tx, rx) = mpsc::channel::<Job>();
124        let runtime = Self {
125            sender: Some(tx),
126            handle: None,
127        };
128        let dispatcher = MainThreadDispatcher { engine, rx };
129        (runtime, dispatcher)
130    }
131
132    /// Cleanly shut down: close the channel and join the thread.
133    /// Idempotent — calling shutdown twice is a no-op.
134    pub fn shutdown(&mut self) {
135        drop(self.sender.take());
136        if let Some(handle) = self.handle.take() {
137            let _ = handle.join();
138        }
139    }
140
141    fn dispatch<R, F>(&self, f: F) -> EngineResult<R>
142    where
143        F: FnOnce(&mut dyn Engine) -> EngineResult<R> + Send + 'static,
144        R: Send + 'static,
145    {
146        let sender = self.sender.as_ref().ok_or(EngineError::Closed)?;
147        let (reply_tx, reply_rx) = mpsc::sync_channel::<EngineResult<R>>(1);
148        let job: Job = Box::new(move |engine| {
149            // Isolate a panicking engine op: on macOS the job runs on
150            // the Cocoa main thread inside an Obj-C run-loop frame, so an
151            // unwinding panic is undefined behavior that can take the
152            // whole daemon down ("could not connect to the server" on the
153            // next request). Catch it here and hand back a clean, message-
154            // bearing error instead — far better than the bare
155            // `ENGINE_CRASH` (empty-args) the dropped reply channel would
156            // otherwise produce.
157            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(engine)))
158                .unwrap_or_else(|payload| Err(EngineError::Other(panic_message(&payload))));
159            let _ = reply_tx.send(result);
160        });
161        sender.send(job).map_err(|_| EngineError::Closed)?;
162        reply_rx.recv().map_err(|_| EngineError::Crashed)?
163    }
164
165    // -----------------------------------------------------------------
166    // Synchronous facade for every Engine method.
167    // -----------------------------------------------------------------
168
169    pub fn open(&self, url: &str) -> EngineResult<PageHandle> {
170        let url = url.to_string();
171        self.dispatch(move |e| e.open(&url))
172    }
173
174    pub fn close(&self, page: PageHandle) -> EngineResult<()> {
175        self.dispatch(move |e| e.close(page))
176    }
177
178    pub fn snapshot(&self, page: PageHandle) -> EngineResult<Tree> {
179        self.dispatch(move |e| e.snapshot(page))
180    }
181
182    pub fn act(&self, page: PageHandle, target: ActTarget, action: Action) -> EngineResult<()> {
183        self.dispatch(move |e| e.act(page, target, action))
184    }
185
186    pub fn wait(
187        &self,
188        page: PageHandle,
189        cond: WaitCondition,
190        budget: Duration,
191    ) -> EngineResult<()> {
192        self.dispatch(move |e| e.wait(page, cond, budget))
193    }
194
195    pub fn capture(&self, page: PageHandle, scope: CaptureScope) -> EngineResult<PathBuf> {
196        self.dispatch(move |e| e.capture(page, scope))
197    }
198
199    pub fn layout(&self, page: PageHandle, refs: Vec<Ref>) -> EngineResult<Vec<LayoutBox>> {
200        self.dispatch(move |e| e.layout(page, &refs))
201    }
202
203    pub fn set_viewport(&self, page: PageHandle, viewport: Viewport) -> EngineResult<()> {
204        self.dispatch(move |e| e.set_viewport(page, viewport))
205    }
206
207    pub fn save_auth(&self, page: PageHandle) -> EngineResult<AuthBlob> {
208        self.dispatch(move |e| e.save_auth(page))
209    }
210
211    pub fn load_auth(&self, page: PageHandle, blob: AuthBlob) -> EngineResult<()> {
212        self.dispatch(move |e| e.load_auth(page, &blob))
213    }
214
215    pub fn console_entries(
216        &self,
217        page: PageHandle,
218    ) -> EngineResult<Vec<crate::inspector::ConsoleEntry>> {
219        self.dispatch(move |e| e.console_entries(page))
220    }
221
222    pub fn network_entries(
223        &self,
224        page: PageHandle,
225    ) -> EngineResult<Vec<crate::inspector::NetworkEntry>> {
226        self.dispatch(move |e| e.network_entries(page))
227    }
228
229    pub fn request_detail(
230        &self,
231        page: PageHandle,
232        seq: u64,
233    ) -> EngineResult<Option<crate::inspector::RequestDetail>> {
234        self.dispatch(move |e| e.request_detail(page, seq))
235    }
236
237    pub fn eval_js(
238        &self,
239        page: PageHandle,
240        expr: &str,
241    ) -> EngineResult<crate::inspector::EvalResult> {
242        let expr = expr.to_string();
243        self.dispatch(move |e| e.eval_js(page, &expr))
244    }
245
246    pub fn storage(
247        &self,
248        page: PageHandle,
249        scope: crate::inspector::StorageScope,
250    ) -> EngineResult<Vec<crate::inspector::StorageEntry>> {
251        self.dispatch(move |e| e.storage(page, scope))
252    }
253
254    pub fn cookie_events(
255        &self,
256        page: PageHandle,
257    ) -> EngineResult<Vec<crate::inspector::CookieEvent>> {
258        self.dispatch(move |e| e.cookie_events(page))
259    }
260
261    pub fn cursor_op(
262        &self,
263        page: PageHandle,
264        op: crate::engine::CursorOp,
265        mode: crate::engine::InputMode,
266    ) -> EngineResult<()> {
267        self.dispatch(move |e| e.cursor_op(page, op, mode))
268    }
269
270    pub fn scripts(&self, page: PageHandle) -> EngineResult<Vec<crate::inspector::ScriptEntry>> {
271        self.dispatch(move |e| e.scripts(page))
272    }
273
274    pub fn script_source(
275        &self,
276        page: PageHandle,
277        seq: u64,
278    ) -> EngineResult<Option<crate::inspector::ScriptSource>> {
279        self.dispatch(move |e| e.script_source(page, seq))
280    }
281
282    pub fn dom(
283        &self,
284        page: PageHandle,
285        r: vs_protocol::Ref,
286        extra_props: Vec<String>,
287    ) -> EngineResult<Option<crate::inspector::DomDetail>> {
288        self.dispatch(move |e| e.dom(page, r, &extra_props))
289    }
290
291    pub fn performance(
292        &self,
293        page: PageHandle,
294    ) -> EngineResult<crate::inspector::PerformanceMetrics> {
295        self.dispatch(move |e| e.performance(page))
296    }
297
298    pub fn capabilities(&self) -> EngineResult<EngineCapabilities> {
299        self.dispatch(|e| Ok(e.capabilities()))
300    }
301}
302
303impl Drop for EngineRuntime {
304    fn drop(&mut self) {
305        self.shutdown();
306    }
307}
308
309/// Drives an engine that lives on the caller'\''s thread (typically the
310/// OS main thread on macOS, since `WKWebView` is pinned there). The
311/// driver owns the engine and a receiver for jobs sent by the runtime
312/// handle that the daemon holds.
313pub struct MainThreadDispatcher {
314    engine: Box<dyn Engine>,
315    rx: mpsc::Receiver<Job>,
316}
317
318impl MainThreadDispatcher {
319    /// Drain one job if available. Returns `Ok(true)` if a job was
320    /// executed, `Ok(false)` if the queue is currently empty,
321    /// `Err(())` if the channel is closed (the runtime was dropped —
322    /// the dispatcher should exit its loop).
323    pub fn tick(&mut self) -> Result<bool, ()> {
324        match self.rx.try_recv() {
325            Ok(job) => {
326                job(self.engine.as_mut());
327                Ok(true)
328            }
329            Err(mpsc::TryRecvError::Empty) => Ok(false),
330            Err(mpsc::TryRecvError::Disconnected) => Err(()),
331        }
332    }
333
334    /// Block until a job arrives or the channel is closed; execute one
335    /// job. Returns `Ok(true)` after running, `Err(())` on closed.
336    pub fn tick_blocking(&mut self) -> Result<bool, ()> {
337        match self.rx.recv() {
338            Ok(job) => {
339                job(self.engine.as_mut());
340                Ok(true)
341            }
342            Err(_) => Err(()),
343        }
344    }
345}
346
347#[cfg(test)]
348mod tests {
349    use std::path::PathBuf;
350    use std::time::Duration;
351
352    use vs_protocol::{Node, Ref, Role, Tree};
353
354    use super::*;
355    use crate::engine::{
356        ActTarget, Action, AuthBlob, CaptureScope, EngineCapabilities, LayoutBox, Viewport,
357        WaitCondition,
358    };
359
360    /// Minimal in-process `Engine` impl used only to exercise the
361    /// runtime's spawn / dispatch / shutdown plumbing. Lives in the
362    /// same `cfg(test)` block as the tests so it can never be reached
363    /// from production code.
364    #[derive(Default)]
365    struct TestEngine {
366        next_handle: u64,
367        last_url: String,
368    }
369
370    impl Engine for TestEngine {
371        fn open(&mut self, url: &str) -> EngineResult<PageHandle> {
372            self.next_handle += 1;
373            self.last_url = url.to_string();
374            Ok(PageHandle(self.next_handle))
375        }
376        fn close(&mut self, _page: PageHandle) -> EngineResult<()> {
377            Ok(())
378        }
379        fn snapshot(&mut self, _page: PageHandle) -> EngineResult<Tree> {
380            Ok(Tree::from_root(Node::leaf(
381                Ref(1),
382                Role::Doc,
383                &self.last_url,
384            )))
385        }
386        fn act(&mut self, _: PageHandle, _: ActTarget, _: Action) -> EngineResult<()> {
387            Ok(())
388        }
389        fn wait(&mut self, _: PageHandle, _: WaitCondition, _: Duration) -> EngineResult<()> {
390            Ok(())
391        }
392        fn capture(&mut self, _: PageHandle, _: CaptureScope) -> EngineResult<PathBuf> {
393            Ok(PathBuf::from("/tmp/test.png"))
394        }
395        fn layout(&mut self, _: PageHandle, refs: &[Ref]) -> EngineResult<Vec<LayoutBox>> {
396            Ok(refs
397                .iter()
398                .map(|r| LayoutBox {
399                    r: *r,
400                    x: 0.0,
401                    y: 0.0,
402                    width: 1.0,
403                    height: 1.0,
404                    visible: true,
405                    z_index: 0,
406                })
407                .collect())
408        }
409        fn set_viewport(&mut self, _: PageHandle, _: Viewport) -> EngineResult<()> {
410            Ok(())
411        }
412        fn save_auth(&mut self, _: PageHandle) -> EngineResult<AuthBlob> {
413            Ok(AuthBlob {
414                bytes: self.last_url.as_bytes().to_vec(),
415            })
416        }
417        fn load_auth(&mut self, _: PageHandle, _: &AuthBlob) -> EngineResult<()> {
418            Ok(())
419        }
420        fn capabilities(&self) -> EngineCapabilities {
421            EngineCapabilities {
422                renders: false,
423                honors_viewport: false,
424                measures_layout: false,
425                persists_auth: false,
426                inspector_console: false,
427                inspector_network: false,
428                inspector_cookie_events: false,
429                name: "test",
430                version: "runtime-tests",
431            }
432        }
433    }
434
435    fn spawn_test_runtime() -> EngineRuntime {
436        EngineRuntime::spawn(|| Ok(Box::new(TestEngine::default()) as Box<dyn Engine>))
437            .expect("spawn")
438    }
439
440    #[test]
441    fn spawn_and_shutdown_cleanly() {
442        let mut rt = spawn_test_runtime();
443        rt.shutdown();
444        rt.shutdown();
445    }
446
447    #[test]
448    fn dispatch_blocks_until_reply() {
449        let rt = spawn_test_runtime();
450        let caps = rt.capabilities().unwrap();
451        assert_eq!(caps.name, "test");
452    }
453
454    #[test]
455    fn engine_construction_failure_reported() {
456        let err =
457            EngineRuntime::spawn(|| Err::<Box<dyn Engine>, _>(EngineError::Other("nope".into())))
458                .unwrap_err();
459        assert!(matches!(err, EngineError::Other(_)));
460    }
461
462    #[test]
463    fn calls_after_drop_error_with_closed() {
464        let mut rt = spawn_test_runtime();
465        rt.shutdown();
466        let err = rt.capabilities().unwrap_err();
467        assert!(matches!(err, EngineError::Closed));
468    }
469
470    /// Cover the round-trip path that used to live in
471    /// `tests/runtime_round_trip.rs`. The Engine impl is intentionally
472    /// trivial — this test verifies the dispatch channel, not engine
473    /// behavior.
474    #[test]
475    fn full_primitive_sequence_via_runtime() {
476        let rt = spawn_test_runtime();
477        let page = rt.open("https://example.com/login").unwrap();
478        rt.wait(page, WaitCondition::Stable, Duration::from_millis(0))
479            .unwrap();
480        let tree = rt.snapshot(page).unwrap();
481        assert!(tree.roots[0].label.contains("https://example.com/login"));
482        rt.act(
483            page,
484            ActTarget::Ref(Ref(3)),
485            Action::Fill { value: "x".into() },
486        )
487        .unwrap();
488        let auth = rt.save_auth(page).unwrap();
489        rt.load_auth(page, auth).unwrap();
490        rt.close(page).unwrap();
491        rt.close(page).unwrap();
492    }
493
494    #[test]
495    fn dispatch_serializes_calls() {
496        let rt = spawn_test_runtime();
497        let mut handles = Vec::new();
498        for i in 0..32 {
499            handles.push(rt.open(&format!("https://example.com/{i}")).unwrap());
500        }
501        let mut sorted = handles.clone();
502        sorted.sort();
503        sorted.dedup();
504        assert_eq!(sorted.len(), handles.len());
505    }
506}