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 =
158                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(engine)))
159                    .unwrap_or_else(|payload| Err(EngineError::Other(panic_message(&payload))));
160            let _ = reply_tx.send(result);
161        });
162        sender.send(job).map_err(|_| EngineError::Closed)?;
163        reply_rx.recv().map_err(|_| EngineError::Crashed)?
164    }
165
166    // -----------------------------------------------------------------
167    // Synchronous facade for every Engine method.
168    // -----------------------------------------------------------------
169
170    pub fn open(&self, url: &str) -> EngineResult<PageHandle> {
171        let url = url.to_string();
172        self.dispatch(move |e| e.open(&url))
173    }
174
175    pub fn close(&self, page: PageHandle) -> EngineResult<()> {
176        self.dispatch(move |e| e.close(page))
177    }
178
179    pub fn snapshot(&self, page: PageHandle) -> EngineResult<Tree> {
180        self.dispatch(move |e| e.snapshot(page))
181    }
182
183    pub fn act(&self, page: PageHandle, target: ActTarget, action: Action) -> EngineResult<()> {
184        self.dispatch(move |e| e.act(page, target, action))
185    }
186
187    pub fn wait(
188        &self,
189        page: PageHandle,
190        cond: WaitCondition,
191        budget: Duration,
192    ) -> EngineResult<()> {
193        self.dispatch(move |e| e.wait(page, cond, budget))
194    }
195
196    pub fn capture(&self, page: PageHandle, scope: CaptureScope) -> EngineResult<PathBuf> {
197        self.dispatch(move |e| e.capture(page, scope))
198    }
199
200    pub fn layout(&self, page: PageHandle, refs: Vec<Ref>) -> EngineResult<Vec<LayoutBox>> {
201        self.dispatch(move |e| e.layout(page, &refs))
202    }
203
204    pub fn set_viewport(&self, page: PageHandle, viewport: Viewport) -> EngineResult<()> {
205        self.dispatch(move |e| e.set_viewport(page, viewport))
206    }
207
208    pub fn save_auth(&self, page: PageHandle) -> EngineResult<AuthBlob> {
209        self.dispatch(move |e| e.save_auth(page))
210    }
211
212    pub fn load_auth(&self, page: PageHandle, blob: AuthBlob) -> EngineResult<()> {
213        self.dispatch(move |e| e.load_auth(page, &blob))
214    }
215
216    pub fn console_entries(
217        &self,
218        page: PageHandle,
219    ) -> EngineResult<Vec<crate::inspector::ConsoleEntry>> {
220        self.dispatch(move |e| e.console_entries(page))
221    }
222
223    pub fn network_entries(
224        &self,
225        page: PageHandle,
226    ) -> EngineResult<Vec<crate::inspector::NetworkEntry>> {
227        self.dispatch(move |e| e.network_entries(page))
228    }
229
230    pub fn request_detail(
231        &self,
232        page: PageHandle,
233        seq: u64,
234    ) -> EngineResult<Option<crate::inspector::RequestDetail>> {
235        self.dispatch(move |e| e.request_detail(page, seq))
236    }
237
238    pub fn eval_js(
239        &self,
240        page: PageHandle,
241        expr: &str,
242    ) -> EngineResult<crate::inspector::EvalResult> {
243        let expr = expr.to_string();
244        self.dispatch(move |e| e.eval_js(page, &expr))
245    }
246
247    pub fn storage(
248        &self,
249        page: PageHandle,
250        scope: crate::inspector::StorageScope,
251    ) -> EngineResult<Vec<crate::inspector::StorageEntry>> {
252        self.dispatch(move |e| e.storage(page, scope))
253    }
254
255    pub fn cookie_events(
256        &self,
257        page: PageHandle,
258    ) -> EngineResult<Vec<crate::inspector::CookieEvent>> {
259        self.dispatch(move |e| e.cookie_events(page))
260    }
261
262    pub fn cursor_op(
263        &self,
264        page: PageHandle,
265        op: crate::engine::CursorOp,
266        mode: crate::engine::InputMode,
267    ) -> EngineResult<()> {
268        self.dispatch(move |e| e.cursor_op(page, op, mode))
269    }
270
271    pub fn scripts(&self, page: PageHandle) -> EngineResult<Vec<crate::inspector::ScriptEntry>> {
272        self.dispatch(move |e| e.scripts(page))
273    }
274
275    pub fn script_source(
276        &self,
277        page: PageHandle,
278        seq: u64,
279    ) -> EngineResult<Option<crate::inspector::ScriptSource>> {
280        self.dispatch(move |e| e.script_source(page, seq))
281    }
282
283    pub fn dom(
284        &self,
285        page: PageHandle,
286        r: vs_protocol::Ref,
287        extra_props: Vec<String>,
288    ) -> EngineResult<Option<crate::inspector::DomDetail>> {
289        self.dispatch(move |e| e.dom(page, r, &extra_props))
290    }
291
292    pub fn performance(
293        &self,
294        page: PageHandle,
295    ) -> EngineResult<crate::inspector::PerformanceMetrics> {
296        self.dispatch(move |e| e.performance(page))
297    }
298
299    pub fn capabilities(&self) -> EngineResult<EngineCapabilities> {
300        self.dispatch(|e| Ok(e.capabilities()))
301    }
302}
303
304impl Drop for EngineRuntime {
305    fn drop(&mut self) {
306        self.shutdown();
307    }
308}
309
310/// Drives an engine that lives on the caller'\''s thread (typically the
311/// OS main thread on macOS, since `WKWebView` is pinned there). The
312/// driver owns the engine and a receiver for jobs sent by the runtime
313/// handle that the daemon holds.
314pub struct MainThreadDispatcher {
315    engine: Box<dyn Engine>,
316    rx: mpsc::Receiver<Job>,
317}
318
319impl MainThreadDispatcher {
320    /// Drain one job if available. Returns `Ok(true)` if a job was
321    /// executed, `Ok(false)` if the queue is currently empty,
322    /// `Err(())` if the channel is closed (the runtime was dropped —
323    /// the dispatcher should exit its loop).
324    pub fn tick(&mut self) -> Result<bool, ()> {
325        match self.rx.try_recv() {
326            Ok(job) => {
327                job(self.engine.as_mut());
328                Ok(true)
329            }
330            Err(mpsc::TryRecvError::Empty) => Ok(false),
331            Err(mpsc::TryRecvError::Disconnected) => Err(()),
332        }
333    }
334
335    /// Block until a job arrives or the channel is closed; execute one
336    /// job. Returns `Ok(true)` after running, `Err(())` on closed.
337    pub fn tick_blocking(&mut self) -> Result<bool, ()> {
338        match self.rx.recv() {
339            Ok(job) => {
340                job(self.engine.as_mut());
341                Ok(true)
342            }
343            Err(_) => Err(()),
344        }
345    }
346}
347
348#[cfg(test)]
349mod tests {
350    use std::path::PathBuf;
351    use std::time::Duration;
352
353    use vs_protocol::{Node, Ref, Role, Tree};
354
355    use super::*;
356    use crate::engine::{
357        ActTarget, Action, AuthBlob, CaptureScope, EngineCapabilities, LayoutBox, Viewport,
358        WaitCondition,
359    };
360
361    /// Minimal in-process `Engine` impl used only to exercise the
362    /// runtime's spawn / dispatch / shutdown plumbing. Lives in the
363    /// same `cfg(test)` block as the tests so it can never be reached
364    /// from production code.
365    #[derive(Default)]
366    struct TestEngine {
367        next_handle: u64,
368        last_url: String,
369    }
370
371    impl Engine for TestEngine {
372        fn open(&mut self, url: &str) -> EngineResult<PageHandle> {
373            self.next_handle += 1;
374            self.last_url = url.to_string();
375            Ok(PageHandle(self.next_handle))
376        }
377        fn close(&mut self, _page: PageHandle) -> EngineResult<()> {
378            Ok(())
379        }
380        fn snapshot(&mut self, _page: PageHandle) -> EngineResult<Tree> {
381            Ok(Tree::from_root(Node::leaf(
382                Ref(1),
383                Role::Doc,
384                &self.last_url,
385            )))
386        }
387        fn act(&mut self, _: PageHandle, _: ActTarget, _: Action) -> EngineResult<()> {
388            Ok(())
389        }
390        fn wait(&mut self, _: PageHandle, _: WaitCondition, _: Duration) -> EngineResult<()> {
391            Ok(())
392        }
393        fn capture(&mut self, _: PageHandle, _: CaptureScope) -> EngineResult<PathBuf> {
394            Ok(PathBuf::from("/tmp/test.png"))
395        }
396        fn layout(&mut self, _: PageHandle, refs: &[Ref]) -> EngineResult<Vec<LayoutBox>> {
397            Ok(refs
398                .iter()
399                .map(|r| LayoutBox {
400                    r: *r,
401                    x: 0.0,
402                    y: 0.0,
403                    width: 1.0,
404                    height: 1.0,
405                    visible: true,
406                    z_index: 0,
407                })
408                .collect())
409        }
410        fn set_viewport(&mut self, _: PageHandle, _: Viewport) -> EngineResult<()> {
411            Ok(())
412        }
413        fn save_auth(&mut self, _: PageHandle) -> EngineResult<AuthBlob> {
414            Ok(AuthBlob {
415                bytes: self.last_url.as_bytes().to_vec(),
416            })
417        }
418        fn load_auth(&mut self, _: PageHandle, _: &AuthBlob) -> EngineResult<()> {
419            Ok(())
420        }
421        fn capabilities(&self) -> EngineCapabilities {
422            EngineCapabilities {
423                renders: false,
424                honors_viewport: false,
425                measures_layout: false,
426                persists_auth: false,
427                inspector_console: false,
428                inspector_network: false,
429                inspector_cookie_events: false,
430                name: "test",
431                version: "runtime-tests",
432            }
433        }
434    }
435
436    fn spawn_test_runtime() -> EngineRuntime {
437        EngineRuntime::spawn(|| Ok(Box::new(TestEngine::default()) as Box<dyn Engine>))
438            .expect("spawn")
439    }
440
441    #[test]
442    fn spawn_and_shutdown_cleanly() {
443        let mut rt = spawn_test_runtime();
444        rt.shutdown();
445        rt.shutdown();
446    }
447
448    #[test]
449    fn dispatch_blocks_until_reply() {
450        let rt = spawn_test_runtime();
451        let caps = rt.capabilities().unwrap();
452        assert_eq!(caps.name, "test");
453    }
454
455    #[test]
456    fn engine_construction_failure_reported() {
457        let err =
458            EngineRuntime::spawn(|| Err::<Box<dyn Engine>, _>(EngineError::Other("nope".into())))
459                .unwrap_err();
460        assert!(matches!(err, EngineError::Other(_)));
461    }
462
463    #[test]
464    fn calls_after_drop_error_with_closed() {
465        let mut rt = spawn_test_runtime();
466        rt.shutdown();
467        let err = rt.capabilities().unwrap_err();
468        assert!(matches!(err, EngineError::Closed));
469    }
470
471    /// Cover the round-trip path that used to live in
472    /// `tests/runtime_round_trip.rs`. The Engine impl is intentionally
473    /// trivial — this test verifies the dispatch channel, not engine
474    /// behavior.
475    #[test]
476    fn full_primitive_sequence_via_runtime() {
477        let rt = spawn_test_runtime();
478        let page = rt.open("https://example.com/login").unwrap();
479        rt.wait(page, WaitCondition::Stable, Duration::from_millis(0))
480            .unwrap();
481        let tree = rt.snapshot(page).unwrap();
482        assert!(tree.roots[0].label.contains("https://example.com/login"));
483        rt.act(
484            page,
485            ActTarget::Ref(Ref(3)),
486            Action::Fill { value: "x".into() },
487        )
488        .unwrap();
489        let auth = rt.save_auth(page).unwrap();
490        rt.load_auth(page, auth).unwrap();
491        rt.close(page).unwrap();
492        rt.close(page).unwrap();
493    }
494
495    #[test]
496    fn dispatch_serializes_calls() {
497        let rt = spawn_test_runtime();
498        let mut handles = Vec::new();
499        for i in 0..32 {
500            handles.push(rt.open(&format!("https://example.com/{i}")).unwrap());
501        }
502        let mut sorted = handles.clone();
503        sorted.sort();
504        sorted.dedup();
505        assert_eq!(sorted.len(), handles.len());
506    }
507}