1#![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
29type Job = Box<dyn FnOnce(&mut dyn Engine) + Send>;
31
32fn 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
42pub 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 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 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 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 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 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 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 type_text(
262 &self,
263 page: PageHandle,
264 text: &str,
265 mode: crate::engine::InputMode,
266 ) -> EngineResult<()> {
267 let text = text.to_string();
268 self.dispatch(move |e| e.type_text(page, &text, mode))
269 }
270
271 pub fn cursor_op(
272 &self,
273 page: PageHandle,
274 op: crate::engine::CursorOp,
275 mode: crate::engine::InputMode,
276 ) -> EngineResult<()> {
277 self.dispatch(move |e| e.cursor_op(page, op, mode))
278 }
279
280 pub fn scripts(&self, page: PageHandle) -> EngineResult<Vec<crate::inspector::ScriptEntry>> {
281 self.dispatch(move |e| e.scripts(page))
282 }
283
284 pub fn script_source(
285 &self,
286 page: PageHandle,
287 seq: u64,
288 ) -> EngineResult<Option<crate::inspector::ScriptSource>> {
289 self.dispatch(move |e| e.script_source(page, seq))
290 }
291
292 pub fn dom(
293 &self,
294 page: PageHandle,
295 r: vs_protocol::Ref,
296 extra_props: Vec<String>,
297 ) -> EngineResult<Option<crate::inspector::DomDetail>> {
298 self.dispatch(move |e| e.dom(page, r, &extra_props))
299 }
300
301 pub fn performance(
302 &self,
303 page: PageHandle,
304 ) -> EngineResult<crate::inspector::PerformanceMetrics> {
305 self.dispatch(move |e| e.performance(page))
306 }
307
308 pub fn capabilities(&self) -> EngineResult<EngineCapabilities> {
309 self.dispatch(|e| Ok(e.capabilities()))
310 }
311}
312
313impl Drop for EngineRuntime {
314 fn drop(&mut self) {
315 self.shutdown();
316 }
317}
318
319pub struct MainThreadDispatcher {
324 engine: Box<dyn Engine>,
325 rx: mpsc::Receiver<Job>,
326}
327
328impl MainThreadDispatcher {
329 pub fn tick(&mut self) -> Result<bool, ()> {
334 match self.rx.try_recv() {
335 Ok(job) => {
336 job(self.engine.as_mut());
337 Ok(true)
338 }
339 Err(mpsc::TryRecvError::Empty) => Ok(false),
340 Err(mpsc::TryRecvError::Disconnected) => Err(()),
341 }
342 }
343
344 pub fn tick_blocking(&mut self) -> Result<bool, ()> {
347 match self.rx.recv() {
348 Ok(job) => {
349 job(self.engine.as_mut());
350 Ok(true)
351 }
352 Err(_) => Err(()),
353 }
354 }
355}
356
357#[cfg(test)]
358mod tests {
359 use std::path::PathBuf;
360 use std::time::Duration;
361
362 use vs_protocol::{Node, Ref, Role, Tree};
363
364 use super::*;
365 use crate::engine::{
366 ActTarget, Action, AuthBlob, CaptureScope, EngineCapabilities, LayoutBox, Viewport,
367 WaitCondition,
368 };
369
370 #[derive(Default)]
375 struct TestEngine {
376 next_handle: u64,
377 last_url: String,
378 }
379
380 impl Engine for TestEngine {
381 fn open(&mut self, url: &str) -> EngineResult<PageHandle> {
382 self.next_handle += 1;
383 self.last_url = url.to_string();
384 Ok(PageHandle(self.next_handle))
385 }
386 fn close(&mut self, _page: PageHandle) -> EngineResult<()> {
387 Ok(())
388 }
389 fn snapshot(&mut self, _page: PageHandle) -> EngineResult<Tree> {
390 Ok(Tree::from_root(Node::leaf(
391 Ref(1),
392 Role::Doc,
393 &self.last_url,
394 )))
395 }
396 fn act(&mut self, _: PageHandle, _: ActTarget, _: Action) -> EngineResult<()> {
397 Ok(())
398 }
399 fn wait(&mut self, _: PageHandle, _: WaitCondition, _: Duration) -> EngineResult<()> {
400 Ok(())
401 }
402 fn capture(&mut self, _: PageHandle, _: CaptureScope) -> EngineResult<PathBuf> {
403 Ok(PathBuf::from("/tmp/test.png"))
404 }
405 fn layout(&mut self, _: PageHandle, refs: &[Ref]) -> EngineResult<Vec<LayoutBox>> {
406 Ok(refs
407 .iter()
408 .map(|r| LayoutBox {
409 r: *r,
410 x: 0.0,
411 y: 0.0,
412 width: 1.0,
413 height: 1.0,
414 visible: true,
415 z_index: 0,
416 })
417 .collect())
418 }
419 fn set_viewport(&mut self, _: PageHandle, _: Viewport) -> EngineResult<()> {
420 Ok(())
421 }
422 fn save_auth(&mut self, _: PageHandle) -> EngineResult<AuthBlob> {
423 Ok(AuthBlob {
424 bytes: self.last_url.as_bytes().to_vec(),
425 })
426 }
427 fn load_auth(&mut self, _: PageHandle, _: &AuthBlob) -> EngineResult<()> {
428 Ok(())
429 }
430 fn capabilities(&self) -> EngineCapabilities {
431 EngineCapabilities {
432 renders: false,
433 honors_viewport: false,
434 measures_layout: false,
435 persists_auth: false,
436 inspector_console: false,
437 inspector_network: false,
438 inspector_cookie_events: false,
439 name: "test",
440 version: "runtime-tests",
441 }
442 }
443 }
444
445 fn spawn_test_runtime() -> EngineRuntime {
446 EngineRuntime::spawn(|| Ok(Box::new(TestEngine::default()) as Box<dyn Engine>))
447 .expect("spawn")
448 }
449
450 #[test]
451 fn spawn_and_shutdown_cleanly() {
452 let mut rt = spawn_test_runtime();
453 rt.shutdown();
454 rt.shutdown();
455 }
456
457 #[test]
458 fn dispatch_blocks_until_reply() {
459 let rt = spawn_test_runtime();
460 let caps = rt.capabilities().unwrap();
461 assert_eq!(caps.name, "test");
462 }
463
464 #[test]
465 fn engine_construction_failure_reported() {
466 let err =
467 EngineRuntime::spawn(|| Err::<Box<dyn Engine>, _>(EngineError::Other("nope".into())))
468 .unwrap_err();
469 assert!(matches!(err, EngineError::Other(_)));
470 }
471
472 #[test]
473 fn calls_after_drop_error_with_closed() {
474 let mut rt = spawn_test_runtime();
475 rt.shutdown();
476 let err = rt.capabilities().unwrap_err();
477 assert!(matches!(err, EngineError::Closed));
478 }
479
480 #[test]
485 fn full_primitive_sequence_via_runtime() {
486 let rt = spawn_test_runtime();
487 let page = rt.open("https://example.com/login").unwrap();
488 rt.wait(page, WaitCondition::Stable, Duration::from_millis(0))
489 .unwrap();
490 let tree = rt.snapshot(page).unwrap();
491 assert!(tree.roots[0].label.contains("https://example.com/login"));
492 rt.act(
493 page,
494 ActTarget::Ref(Ref(3)),
495 Action::Fill { value: "x".into() },
496 )
497 .unwrap();
498 let auth = rt.save_auth(page).unwrap();
499 rt.load_auth(page, auth).unwrap();
500 rt.close(page).unwrap();
501 rt.close(page).unwrap();
502 }
503
504 #[test]
505 fn dispatch_serializes_calls() {
506 let rt = spawn_test_runtime();
507 let mut handles = Vec::new();
508 for i in 0..32 {
509 handles.push(rt.open(&format!("https://example.com/{i}")).unwrap());
510 }
511 let mut sorted = handles.clone();
512 sorted.sort();
513 sorted.dedup();
514 assert_eq!(sorted.len(), handles.len());
515 }
516}