chromey 2.41.0

Concurrent chrome devtools protocol automation library for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
//! Async file I/O with optional io_uring acceleration for chromey.
//!
//! On Linux with the `io_uring` feature, file operations are dispatched to a
//! dedicated worker thread that drives a raw io_uring ring. On all other
//! platforms, operations fall back to `tokio::fs`.
//!
//! The worker also supports TCP connect via io_uring Socket + Connect opcodes,
//! used for the initial CDP WebSocket connection.

// ── io_uring implementation ─────────────────────────────────────────────────

#[cfg(all(target_os = "linux", feature = "io_uring"))]
mod inner {
    use std::ffi::CString;
    use std::io;
    use std::net::SocketAddr;
    use std::sync::atomic::{AtomicBool, Ordering};
    use tokio::sync::{mpsc, oneshot};

    static URING_ENABLED: AtomicBool = AtomicBool::new(false);
    static URING_POOL: std::sync::OnceLock<mpsc::UnboundedSender<IoTask>> =
        std::sync::OnceLock::new();

    enum IoTask {
        WriteFile {
            path: String,
            data: Vec<u8>,
            tx: oneshot::Sender<io::Result<()>>,
        },
        ReadFile {
            path: String,
            tx: oneshot::Sender<io::Result<Vec<u8>>>,
        },
        TcpConnect {
            addr: SocketAddr,
            tx: oneshot::Sender<io::Result<std::net::TcpStream>>,
        },
    }

    fn probe_io_uring() -> Option<io_uring::IoUring> {
        match io_uring::IoUring::builder().build(64) {
            Ok(ring) => {
                tracing::info!("chromey: io_uring probe succeeded");
                Some(ring)
            }
            Err(e) => {
                tracing::info!("chromey: io_uring unavailable ({}), using tokio::fs", e);
                None
            }
        }
    }

    fn submit_and_reap(ring: &mut io_uring::IoUring) -> io::Result<i32> {
        ring.submit_and_wait(1)?;
        let cqe = ring
            .completion()
            .next()
            .ok_or_else(|| io::Error::new(io::ErrorKind::Other, "io_uring: no CQE after wait"))?;
        Ok(cqe.result())
    }

    fn uring_close(ring: &mut io_uring::IoUring, fd: i32) -> io::Result<()> {
        let close_e = io_uring::opcode::Close::new(io_uring::types::Fd(fd))
            .build()
            .user_data(0xC105E);
        unsafe {
            ring.submission()
                .push(&close_e)
                .map_err(|_| io::Error::new(io::ErrorKind::Other, "io_uring: SQ full on close"))?;
        }
        let res = submit_and_reap(ring)?;
        if res < 0 {
            return Err(io::Error::from_raw_os_error(-res));
        }
        Ok(())
    }

    fn uring_write_file(ring: &mut io_uring::IoUring, path: &str, data: &[u8]) -> io::Result<()> {
        let c_path =
            CString::new(path).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;

        let open_e =
            io_uring::opcode::OpenAt::new(io_uring::types::Fd(libc::AT_FDCWD), c_path.as_ptr())
                .flags(libc::O_WRONLY | libc::O_CREAT | libc::O_TRUNC)
                .mode(0o644)
                .build()
                .user_data(0x0BE4);
        unsafe {
            ring.submission()
                .push(&open_e)
                .map_err(|_| io::Error::new(io::ErrorKind::Other, "io_uring: SQ full on open"))?;
        }
        let fd = submit_and_reap(ring)?;
        if fd < 0 {
            return Err(io::Error::from_raw_os_error(-fd));
        }

        let write_result = uring_write_all(ring, fd, data);
        let close_result = uring_close(ring, fd);
        write_result?;
        close_result
    }

    fn uring_write_all(ring: &mut io_uring::IoUring, fd: i32, data: &[u8]) -> io::Result<()> {
        if data.is_empty() {
            return Ok(());
        }
        let mut offset: u64 = 0;
        while (offset as usize) < data.len() {
            let remaining = &data[offset as usize..];
            let chunk_len = remaining.len().min(u32::MAX as usize) as u32;
            let write_e = io_uring::opcode::Write::new(
                io_uring::types::Fd(fd),
                remaining.as_ptr(),
                chunk_len,
            )
            .offset(offset)
            .build()
            .user_data(0x1417E);
            unsafe {
                ring.submission().push(&write_e).map_err(|_| {
                    io::Error::new(io::ErrorKind::Other, "io_uring: SQ full on write")
                })?;
            }
            let written = submit_and_reap(ring)?;
            if written < 0 {
                return Err(io::Error::from_raw_os_error(-written));
            }
            if written == 0 {
                return Err(io::Error::new(
                    io::ErrorKind::WriteZero,
                    "io_uring: write returned 0",
                ));
            }
            offset += written as u64;
        }
        Ok(())
    }

    fn uring_read_file(ring: &mut io_uring::IoUring, path: &str) -> io::Result<Vec<u8>> {
        let meta = std::fs::metadata(path)?;
        let len = meta.len() as usize;
        if len == 0 {
            return Ok(Vec::new());
        }

        let c_path =
            CString::new(path).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
        let open_e =
            io_uring::opcode::OpenAt::new(io_uring::types::Fd(libc::AT_FDCWD), c_path.as_ptr())
                .flags(libc::O_RDONLY)
                .build()
                .user_data(0x0BE4);
        unsafe {
            ring.submission()
                .push(&open_e)
                .map_err(|_| io::Error::new(io::ErrorKind::Other, "io_uring: SQ full on open"))?;
        }
        let fd = submit_and_reap(ring)?;
        if fd < 0 {
            return Err(io::Error::from_raw_os_error(-fd));
        }

        let mut buf = vec![0u8; len];
        let read_result = uring_read_exact(ring, fd, &mut buf);
        let close_result = uring_close(ring, fd);
        read_result?;
        close_result?;
        Ok(buf)
    }

    fn uring_read_exact(ring: &mut io_uring::IoUring, fd: i32, buf: &mut [u8]) -> io::Result<()> {
        let mut offset: u64 = 0;
        while (offset as usize) < buf.len() {
            let remaining = &mut buf[offset as usize..];
            let chunk_len = remaining.len().min(u32::MAX as usize) as u32;
            let read_e = io_uring::opcode::Read::new(
                io_uring::types::Fd(fd),
                remaining.as_mut_ptr(),
                chunk_len,
            )
            .offset(offset)
            .build()
            .user_data(0x4EAD);
            unsafe {
                ring.submission().push(&read_e).map_err(|_| {
                    io::Error::new(io::ErrorKind::Other, "io_uring: SQ full on read")
                })?;
            }
            let n = submit_and_reap(ring)?;
            if n < 0 {
                return Err(io::Error::from_raw_os_error(-n));
            }
            if n == 0 {
                return Err(io::Error::new(
                    io::ErrorKind::UnexpectedEof,
                    "io_uring: read returned 0",
                ));
            }
            offset += n as u64;
        }
        Ok(())
    }

    fn uring_tcp_connect(
        ring: &mut io_uring::IoUring,
        addr: SocketAddr,
    ) -> io::Result<std::net::TcpStream> {
        use std::os::unix::io::FromRawFd;

        let domain = match addr {
            SocketAddr::V4(_) => libc::AF_INET,
            SocketAddr::V6(_) => libc::AF_INET6,
        };

        let socket_e = io_uring::opcode::Socket::new(
            domain,
            libc::SOCK_STREAM | libc::SOCK_NONBLOCK | libc::SOCK_CLOEXEC,
            0,
        )
        .build()
        .user_data(0x50CE7);
        unsafe {
            ring.submission()
                .push(&socket_e)
                .map_err(|_| io::Error::new(io::ErrorKind::Other, "io_uring: SQ full on socket"))?;
        }
        let fd = submit_and_reap(ring)?;
        if fd < 0 {
            return Err(io::Error::from_raw_os_error(-fd));
        }

        let (sa_ptr, sa_len) = match addr {
            SocketAddr::V4(v4) => {
                let sa = libc::sockaddr_in {
                    sin_family: libc::AF_INET as libc::sa_family_t,
                    sin_port: v4.port().to_be(),
                    sin_addr: libc::in_addr {
                        s_addr: u32::from_ne_bytes(v4.ip().octets()),
                    },
                    sin_zero: [0; 8],
                };
                let ptr = &sa as *const libc::sockaddr_in as *const libc::sockaddr;
                (ptr, std::mem::size_of::<libc::sockaddr_in>() as u32)
            }
            SocketAddr::V6(v6) => {
                let sa = libc::sockaddr_in6 {
                    sin6_family: libc::AF_INET6 as libc::sa_family_t,
                    sin6_port: v6.port().to_be(),
                    sin6_flowinfo: v6.flowinfo(),
                    sin6_addr: libc::in6_addr {
                        s6_addr: v6.ip().octets(),
                    },
                    sin6_scope_id: v6.scope_id(),
                };
                let ptr = &sa as *const libc::sockaddr_in6 as *const libc::sockaddr;
                (ptr, std::mem::size_of::<libc::sockaddr_in6>() as u32)
            }
        };

        let connect_e = io_uring::opcode::Connect::new(io_uring::types::Fd(fd), sa_ptr, sa_len)
            .build()
            .user_data(0xC044);
        unsafe {
            ring.submission().push(&connect_e).map_err(|_| {
                libc::close(fd);
                io::Error::new(io::ErrorKind::Other, "io_uring: SQ full on connect")
            })?;
        }

        let res = submit_and_reap(ring)?;
        if res < 0 && res != -libc::EINPROGRESS {
            let _ = uring_close(ring, fd);
            return Err(io::Error::from_raw_os_error(-res));
        }

        let stream = unsafe { std::net::TcpStream::from_raw_fd(fd) };
        Ok(stream)
    }

    fn worker_loop(mut rx: mpsc::UnboundedReceiver<IoTask>, mut ring: io_uring::IoUring) {
        while let Some(task) = rx.blocking_recv() {
            match task {
                IoTask::WriteFile { path, data, tx } => {
                    let _ = tx.send(uring_write_file(&mut ring, &path, &data));
                }
                IoTask::ReadFile { path, tx } => {
                    let _ = tx.send(uring_read_file(&mut ring, &path));
                }
                IoTask::TcpConnect { addr, tx } => {
                    let _ = tx.send(uring_tcp_connect(&mut ring, addr));
                }
            }
        }
        drop(ring);
    }

    // ── Public API ──────────────────────────────────────────────────────────

    pub fn init() -> bool {
        if URING_ENABLED.load(Ordering::Acquire) {
            return true;
        }
        let ring = match probe_io_uring() {
            Some(r) => r,
            None => return false,
        };
        let (tx, rx) = mpsc::unbounded_channel();
        let builder = std::thread::Builder::new().name("chromey-uring-worker".into());
        match builder.spawn(move || worker_loop(rx, ring)) {
            Ok(_) => {
                if URING_POOL.set(tx).is_ok() {
                    URING_ENABLED.store(true, Ordering::Release);
                }
            }
            Err(e) => {
                tracing::warn!("Failed to spawn chromey io_uring worker: {}", e);
                return false;
            }
        }
        URING_ENABLED.load(Ordering::Acquire)
    }

    async fn try_uring<T>(
        make_task: impl FnOnce(oneshot::Sender<io::Result<T>>) -> IoTask,
    ) -> Option<io::Result<T>> {
        if !URING_ENABLED.load(Ordering::Acquire) {
            return None;
        }
        let sender = URING_POOL.get()?;
        let (tx, rx) = oneshot::channel();
        if sender.send(make_task(tx)).is_err() {
            return Some(Err(io::Error::new(
                io::ErrorKind::BrokenPipe,
                "chromey io_uring worker channel closed",
            )));
        }
        match rx.await {
            Ok(result) => Some(result),
            Err(_) => Some(Err(io::Error::new(
                io::ErrorKind::BrokenPipe,
                "chromey io_uring worker dropped the response",
            ))),
        }
    }

    pub async fn write_file(path: String, data: Vec<u8>) -> io::Result<()> {
        if let Some(result) = try_uring(|tx| IoTask::WriteFile {
            path: path.clone(),
            data: data.clone(),
            tx,
        })
        .await
        {
            return result;
        }
        tokio::fs::write(&path, &data).await
    }

    pub async fn read_file(path: String) -> io::Result<Vec<u8>> {
        if let Some(result) = try_uring(|tx| IoTask::ReadFile {
            path: path.clone(),
            tx,
        })
        .await
        {
            return result;
        }
        tokio::fs::read(&path).await
    }

    pub async fn tcp_connect(addr: SocketAddr) -> io::Result<std::net::TcpStream> {
        if let Some(result) = try_uring(|tx| IoTask::TcpConnect { addr, tx }).await {
            return result;
        }
        tokio::task::spawn_blocking(move || std::net::TcpStream::connect(addr))
            .await
            .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?
    }

    pub fn is_enabled() -> bool {
        URING_ENABLED.load(Ordering::Acquire)
    }
}

// ── Fallback (non-Linux / no io_uring feature) ──────────────────────────────

#[cfg(not(all(target_os = "linux", feature = "io_uring")))]
mod inner {
    use std::io;
    use std::net::SocketAddr;

    pub fn init() -> bool {
        false
    }

    pub async fn write_file(path: String, data: Vec<u8>) -> io::Result<()> {
        tokio::fs::write(&path, &data).await
    }

    pub async fn read_file(path: String) -> io::Result<Vec<u8>> {
        tokio::fs::read(&path).await
    }

    pub async fn tcp_connect(addr: SocketAddr) -> io::Result<std::net::TcpStream> {
        tokio::task::spawn_blocking(move || std::net::TcpStream::connect(addr))
            .await
            .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?
    }

    pub fn is_enabled() -> bool {
        false
    }
}

// ── Re-exports ──────────────────────────────────────────────────────────────

pub use inner::init;
pub use inner::is_enabled;
pub use inner::read_file;
pub use inner::tcp_connect;
pub use inner::write_file;

// ── Tests ───────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_write_read_roundtrip() {
        let path = std::env::temp_dir()
            .join("chromey_uring_test_roundtrip")
            .display()
            .to_string();
        let payload = b"chromey uring test".to_vec();

        write_file(path.clone(), payload.clone()).await.unwrap();
        let read_back = read_file(path.clone()).await.unwrap();
        assert_eq!(read_back, payload);

        let _ = tokio::fs::remove_file(&path).await;
    }

    #[tokio::test]
    async fn test_tcp_connect_loopback() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();

        let accept = tokio::spawn(async move { listener.accept().await });
        let connect = tokio::spawn(async move { tcp_connect(addr).await });

        let (a, c) = tokio::join!(accept, connect);
        assert!(a.unwrap().is_ok());
        assert!(c.unwrap().is_ok());
    }

    #[tokio::test]
    async fn test_tcp_connect_refused() {
        let addr: std::net::SocketAddr = "127.0.0.1:1".parse().unwrap();
        assert!(tcp_connect(addr).await.is_err());
    }

    #[tokio::test]
    async fn test_init_idempotent() {
        let r1 = init();
        let r2 = init();
        assert_eq!(r1, r2);
    }
}