Skip to main content

browser_control/registry/
mod.rs

1//! SQLite-backed registry of running browser instances.
2
3pub mod bidi_lock;
4mod db;
5pub mod foreground;
6pub mod naming;
7pub mod schema;
8pub mod scratches;
9pub mod tabs;
10pub mod words;
11
12pub use bidi_lock::{BidiLockBusy, BidiLockGuard, BidiLockRow};
13pub use foreground::ForegroundRow;
14pub use scratches::ScratchRow;
15pub use tabs::TabRow;
16
17use anyhow::{anyhow, bail, Context, Result};
18use fs2::FileExt;
19use rusqlite::{params, OpenFlags};
20use serde::{Deserialize, Serialize};
21use std::fs::OpenOptions;
22use std::net::{SocketAddr, TcpStream};
23use std::path::{Path, PathBuf};
24use std::time::Duration;
25
26use crate::detect::{Engine, Kind};
27
28/// One row in the `browsers` table.
29#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
30pub struct BrowserRow {
31    pub name: String,
32    pub kind: Kind,
33    pub engine: Engine,
34    pub pid: u32,
35    pub endpoint: String,
36    pub port: u16,
37    pub profile_dir: PathBuf,
38    pub executable: PathBuf,
39    pub headless: bool,
40    pub started_at: String,
41}
42
43/// Current registry liveness classification for a browser row.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum BrowserLiveness {
46    /// The recorded process exists and the debugging endpoint accepts TCP.
47    Alive,
48    /// The recorded process no longer exists. This is high-confidence stale
49    /// state and can be pruned.
50    DeadPid,
51    /// The recorded process exists, but the debugging endpoint did not accept
52    /// TCP right now. Treat as unavailable, but do not delete the row: short
53    /// endpoint outages can be transient during browser startup/restart.
54    EndpointUnreachable,
55}
56
57/// SQLite registry handle. SQLite-level WAL + `busy_timeout` handles
58/// concurrent reader/writer coordination across processes; we no longer
59/// hold a long-lived exclusive file lock for the lifetime of the
60/// handle. A short exclusive lock is taken only across the
61/// schema-migration window in `open_at` to serialise initial
62/// `CREATE TABLE` / `CREATE INDEX` against a concurrent first open.
63pub struct Registry {
64    conn: rusqlite::Connection,
65    /// Path the registry was opened at. Read by `bidi_lock_acquire` to
66    /// stamp the `BidiLockGuard`, whose `Drop` reopens a fresh connection
67    /// here to release the row (the guard outlives the borrowing handle).
68    db_path: PathBuf,
69}
70
71impl Registry {
72    /// Open the registry at the OS-standard location.
73    pub fn open() -> Result<Self> {
74        let p = crate::paths::registry_db_path()?;
75        Self::open_at(&p)
76    }
77
78    /// Open the registry at an explicit path.
79    pub fn open_at(path: &Path) -> Result<Self> {
80        if let Some(parent) = path.parent() {
81            if !parent.as_os_str().is_empty() {
82                std::fs::create_dir_all(parent)
83                    .with_context(|| format!("creating registry dir {}", parent.display()))?;
84            }
85        }
86
87        // Hold an exclusive file lock only across the initial schema
88        // migration. SQLite's own `CREATE TABLE IF NOT EXISTS` is
89        // idempotent and safe under concurrent execution, but
90        // narrowing the lock to this window keeps the historical
91        // serialisation guarantee for any future schema-altering
92        // change while letting steady-state CLI invocations proceed
93        // in parallel.
94        let lock_path = lock_path_for(path);
95        let lock_file = OpenOptions::new()
96            .create(true)
97            .read(true)
98            .write(true)
99            .truncate(false)
100            .open(&lock_path)
101            .with_context(|| format!("opening lock file {}", lock_path.display()))?;
102        FileExt::lock_exclusive(&lock_file)
103            .with_context(|| format!("acquiring exclusive lock on {}", lock_path.display()))?;
104
105        let conn = rusqlite::Connection::open_with_flags(
106            path,
107            OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_CREATE,
108        )
109        .with_context(|| format!("opening registry db {}", path.display()))?;
110
111        configure_conn(&conn)?;
112        schema::apply(&conn)?;
113
114        // Release the migration lock. From here on, SQLite's
115        // WAL + busy_timeout handles inter-process coordination
116        // for both reads and writes; CLI invocations no longer
117        // serialise on browser I/O.
118        let _ = FileExt::unlock(&lock_file);
119        drop(lock_file);
120
121        Ok(Self {
122            conn,
123            db_path: path.to_path_buf(),
124        })
125    }
126
127    /// Open an in-memory registry (tests only). No file lock taken.
128    pub fn open_in_memory() -> Result<Self> {
129        let conn = rusqlite::Connection::open_in_memory().context("opening in-memory registry")?;
130        // WAL is not supported for :memory:; only set synchronous.
131        let _ = conn.pragma_update(None, "synchronous", "NORMAL");
132        schema::apply(&conn)?;
133        Ok(Self {
134            conn,
135            db_path: PathBuf::from(":memory:"),
136        })
137    }
138
139    /// Insert (or replace) a row.
140    pub fn insert(&self, row: &BrowserRow) -> Result<()> {
141        db::execute(
142            &self.conn,
143            "INSERT OR REPLACE INTO browsers
144                    (name, kind, engine, pid, endpoint, port, profile_dir, executable, headless, started_at)
145                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
146            params![
147                row.name,
148                kind_to_str(row.kind),
149                engine_to_str(row.engine),
150                row.pid as i64,
151                row.endpoint,
152                row.port as i64,
153                row.profile_dir.to_string_lossy(),
154                row.executable.to_string_lossy(),
155                row.headless as i64,
156                row.started_at,
157            ],
158            || format!("inserting registry row {}", row.name),
159        )
160    }
161
162    /// Delete a row by name. No error if it does not exist.
163    pub fn delete(&self, name: &str) -> Result<()> {
164        db::execute(
165            &self.conn,
166            "DELETE FROM browsers WHERE name = ?1",
167            params![name],
168            || format!("deleting registry row {name}"),
169        )
170    }
171
172    /// Look up a row by name.
173    pub fn get_by_name(&self, name: &str) -> Result<Option<BrowserRow>> {
174        db::query_optional(
175            &self.conn,
176            "SELECT name, kind, engine, pid, endpoint, port, profile_dir, executable, headless, started_at FROM browsers WHERE name = ?1",
177            params![name],
178            row_from_sqlite,
179        )
180    }
181
182    /// All rows, no liveness check, ordered by started_at DESC.
183    pub fn list_all(&self) -> Result<Vec<BrowserRow>> {
184        db::query_vec(
185            &self.conn,
186            "SELECT name, kind, engine, pid, endpoint, port, profile_dir, executable, headless, started_at
187             FROM browsers ORDER BY started_at DESC",
188            [],
189            row_from_sqlite,
190        )
191    }
192
193    /// All rows of a given kind ordered by started_at DESC, without liveness check.
194    pub(crate) fn list_by_kind_all(&self, kind: Kind) -> Result<Vec<BrowserRow>> {
195        db::query_vec(
196            &self.conn,
197            "SELECT name, kind, engine, pid, endpoint, port, profile_dir, executable, headless, started_at
198             FROM browsers WHERE kind = ?1 ORDER BY started_at DESC",
199            params![kind_to_str(kind)],
200            row_from_sqlite,
201        )
202    }
203
204    /// All alive rows. Dead-PID rows are deleted as a side-effect; rows whose
205    /// endpoint is temporarily unreachable are omitted but retained.
206    pub fn list_alive(&self) -> Result<Vec<BrowserRow>> {
207        let all = self.list_all()?;
208        let mut alive = Vec::with_capacity(all.len());
209        for row in all {
210            match liveness(&row) {
211                BrowserLiveness::Alive => alive.push(row),
212                BrowserLiveness::DeadPid => {
213                    self.delete(&row.name)?;
214                }
215                BrowserLiveness::EndpointUnreachable => {}
216            }
217        }
218        Ok(alive)
219    }
220
221    /// First alive row of the given kind (most recent first). Dead-PID matches
222    /// are pruned; endpoint-unreachable rows are retained.
223    pub fn first_alive_by_kind(&self, kind: Kind) -> Result<Option<BrowserRow>> {
224        for row in self.list_by_kind_all(kind)? {
225            match liveness(&row) {
226                BrowserLiveness::Alive => return Ok(Some(row)),
227                BrowserLiveness::DeadPid => {
228                    self.delete(&row.name)?;
229                }
230                BrowserLiveness::EndpointUnreachable => {}
231            }
232        }
233        Ok(None)
234    }
235
236    /// Most recently started alive row across all kinds.
237    pub fn most_recent_alive(&self) -> Result<Option<BrowserRow>> {
238        for row in self.list_all()? {
239            match liveness(&row) {
240                BrowserLiveness::Alive => return Ok(Some(row)),
241                BrowserLiveness::DeadPid => {
242                    self.delete(&row.name)?;
243                }
244                BrowserLiveness::EndpointUnreachable => {}
245            }
246        }
247        Ok(None)
248    }
249}
250
251fn configure_conn(conn: &rusqlite::Connection) -> Result<()> {
252    // WAL allows concurrent readers + one writer per process group.
253    conn.pragma_update(None, "journal_mode", "WAL")
254        .context("setting journal_mode = WAL")?;
255    conn.pragma_update(None, "synchronous", "NORMAL")
256        .context("setting synchronous = NORMAL")?;
257    // `busy_timeout` is what makes concurrent invocations safe now that
258    // we no longer hold the long-lived advisory file lock. SQLite will
259    // retry a contended write for up to this duration before returning
260    // SQLITE_BUSY. Five seconds is generous for our workloads (single
261    // INSERT/UPDATE per CLI invocation) and short enough that a stuck
262    // process surfaces visibly instead of hanging forever.
263    conn.busy_timeout(Duration::from_secs(5))
264        .context("setting busy_timeout")?;
265    Ok(())
266}
267
268fn lock_path_for(db: &Path) -> PathBuf {
269    let mut name = db
270        .file_name()
271        .map(|n| n.to_os_string())
272        .unwrap_or_else(|| std::ffi::OsString::from("registry.db"));
273    name.push(".lock");
274    match db.parent() {
275        Some(p) if !p.as_os_str().is_empty() => p.join(name),
276        _ => PathBuf::from(name),
277    }
278}
279
280fn row_from_sqlite(r: &rusqlite::Row<'_>) -> Result<BrowserRow> {
281    let name: String = r.get(0)?;
282    let kind_s: String = r.get(1)?;
283    let engine_s: String = r.get(2)?;
284    let pid: i64 = r.get(3)?;
285    let endpoint: String = r.get(4)?;
286    let port: i64 = r.get(5)?;
287    let profile_dir: String = r.get(6)?;
288    let executable: String = r.get(7)?;
289    let headless: i64 = r.get(8)?;
290    let started_at: String = r.get(9)?;
291
292    Ok(BrowserRow {
293        name,
294        kind: parse_kind(&kind_s)?,
295        engine: parse_engine(&engine_s)?,
296        pid: pid as u32,
297        endpoint,
298        port: port as u16,
299        profile_dir: PathBuf::from(profile_dir),
300        executable: PathBuf::from(executable),
301        headless: headless != 0,
302        started_at,
303    })
304}
305
306fn kind_to_str(k: Kind) -> &'static str {
307    k.as_str()
308}
309
310fn parse_kind(s: &str) -> Result<Kind> {
311    Kind::parse(s).ok_or_else(|| anyhow!("invalid kind {s}"))
312}
313
314fn engine_to_str(e: Engine) -> &'static str {
315    match e {
316        Engine::Cdp => "cdp",
317        Engine::Bidi => "bidi",
318    }
319}
320
321fn parse_engine(s: &str) -> Result<Engine> {
322    match s {
323        "cdp" => Ok(Engine::Cdp),
324        "bidi" => Ok(Engine::Bidi),
325        _ => bail!("invalid engine {s}"),
326    }
327}
328
329/// Liveness check: PID exists AND a TCP connect to the local port succeeds.
330pub fn is_alive(row: &BrowserRow) -> bool {
331    liveness(row) == BrowserLiveness::Alive
332}
333
334/// Classify row liveness. Only [`BrowserLiveness::DeadPid`] is safe to prune.
335pub fn liveness(row: &BrowserRow) -> BrowserLiveness {
336    let pid = sysinfo::Pid::from_u32(row.pid);
337    let mut sys = sysinfo::System::new();
338    // Refresh only the target PID rather than the whole process table:
339    // these run per-row in `list_alive`/`first_alive_by_kind`/etc., and we
340    // only ever query this one PID below.
341    sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true);
342    if sys.process(pid).is_none() {
343        return BrowserLiveness::DeadPid;
344    }
345    let addr = SocketAddr::from(([127, 0, 0, 1], row.port));
346    if TcpStream::connect_timeout(&addr, Duration::from_millis(200)).is_ok() {
347        BrowserLiveness::Alive
348    } else {
349        BrowserLiveness::EndpointUnreachable
350    }
351}
352
353/// Cheap check: is process `pid` still running on this machine? Used by
354/// stale-row eviction in `scratches`, `tabs`, and `bidi_locks` to avoid
355/// keeping rows registered to a crashed CLI process.
356pub fn pid_alive(pid: u32) -> bool {
357    let pid = sysinfo::Pid::from_u32(pid);
358    let mut sys = sysinfo::System::new();
359    // Refresh only this PID, not the entire process table — this is hit
360    // per-row by stale-row eviction across scratches/tabs/bidi_locks.
361    sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true);
362    sys.process(pid).is_some()
363}
364
365/// Current Unix epoch seconds.
366pub fn now_epoch_s() -> i64 {
367    std::time::SystemTime::now()
368        .duration_since(std::time::UNIX_EPOCH)
369        .map(|d| d.as_secs() as i64)
370        .unwrap_or(0)
371}
372
373// -- ISO-8601 helpers --------------------------------------------------------
374
375/// Current time formatted as `YYYY-MM-DDTHH:MM:SSZ` (UTC).
376pub fn now_iso8601() -> String {
377    let secs = std::time::SystemTime::now()
378        .duration_since(std::time::UNIX_EPOCH)
379        .map(|d| d.as_secs() as i64)
380        .unwrap_or(0);
381    format_unix_seconds_as_iso8601(secs)
382}
383
384/// Format a Unix epoch second count as `YYYY-MM-DDTHH:MM:SSZ`.
385///
386/// Uses Howard Hinnant's `civil_from_days` algorithm.
387pub fn format_unix_seconds_as_iso8601(secs: i64) -> String {
388    // Split into days and time-of-day, handling negative seconds correctly.
389    let days = secs.div_euclid(86_400);
390    let tod = secs.rem_euclid(86_400);
391    let hour = (tod / 3600) as u32;
392    let minute = ((tod % 3600) / 60) as u32;
393    let second = (tod % 60) as u32;
394
395    let (y, m, d) = civil_from_days(days);
396    format!(
397        "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
398        y, m, d, hour, minute, second
399    )
400}
401
402/// Convert days since 1970-01-01 to (year, month, day) using Hinnant's algorithm.
403fn civil_from_days(z: i64) -> (i64, u32, u32) {
404    let z = z + 719_468;
405    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
406    let doe = (z - era * 146_097) as u64; // [0, 146096]
407    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365; // [0, 399]
408    let y = yoe as i64 + era * 400;
409    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365]
410    let mp = (5 * doy + 2) / 153; // [0, 11]
411    let d = (doy - (153 * mp + 2) / 5 + 1) as u32; // [1, 31]
412    let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32; // [1, 12]
413    let y = if m <= 2 { y + 1 } else { y };
414    (y, m, d)
415}
416
417// ---------------------------------------------------------------------------
418
419#[cfg(test)]
420mod tests {
421    use super::*;
422
423    fn sample_row(name: &str, kind: Kind, port: u16, started_at: &str) -> BrowserRow {
424        BrowserRow {
425            name: name.to_string(),
426            kind,
427            engine: kind.engine(),
428            pid: 99_999_999, // unlikely to exist
429            endpoint: format!("http://127.0.0.1:{port}"),
430            port,
431            profile_dir: PathBuf::from(format!("/tmp/profiles/{name}")),
432            executable: PathBuf::from("/usr/bin/example"),
433            headless: false,
434            started_at: started_at.to_string(),
435        }
436    }
437
438    #[test]
439    fn insert_then_get_round_trip() {
440        let reg = Registry::open_in_memory().unwrap();
441        let row = sample_row("alpha-bravo", Kind::Chrome, 9222, "2024-01-02T03:04:05Z");
442        reg.insert(&row).unwrap();
443        let got = reg.get_by_name("alpha-bravo").unwrap().unwrap();
444        assert_eq!(got, row);
445        assert!(reg.get_by_name("missing").unwrap().is_none());
446    }
447
448    #[test]
449    fn list_all_returns_all_rows() {
450        let reg = Registry::open_in_memory().unwrap();
451        reg.insert(&sample_row("a", Kind::Chrome, 9001, "2024-01-01T00:00:00Z"))
452            .unwrap();
453        reg.insert(&sample_row(
454            "b",
455            Kind::Firefox,
456            9002,
457            "2024-01-02T00:00:00Z",
458        ))
459        .unwrap();
460        reg.insert(&sample_row("c", Kind::Edge, 9003, "2024-01-03T00:00:00Z"))
461            .unwrap();
462        let all = reg.list_all().unwrap();
463        assert_eq!(all.len(), 3);
464        // ordered DESC by started_at
465        assert_eq!(all[0].name, "c");
466        assert_eq!(all[2].name, "a");
467    }
468
469    #[test]
470    fn delete_removes_row() {
471        let reg = Registry::open_in_memory().unwrap();
472        let row = sample_row("x", Kind::Brave, 9010, "2024-05-05T05:05:05Z");
473        reg.insert(&row).unwrap();
474        reg.delete("x").unwrap();
475        assert!(reg.get_by_name("x").unwrap().is_none());
476        // deleting a missing row is a no-op
477        reg.delete("ghost").unwrap();
478    }
479
480    #[test]
481    fn first_alive_by_kind_returns_most_recent() {
482        // We can't easily mock `is_alive`. Instead verify the underlying SQL ordering
483        // via the pub(crate) helper.
484        let reg = Registry::open_in_memory().unwrap();
485        reg.insert(&sample_row(
486            "older",
487            Kind::Chrome,
488            9101,
489            "2024-01-01T00:00:00Z",
490        ))
491        .unwrap();
492        reg.insert(&sample_row(
493            "newer",
494            Kind::Chrome,
495            9102,
496            "2024-06-01T00:00:00Z",
497        ))
498        .unwrap();
499        reg.insert(&sample_row(
500            "ff",
501            Kind::Firefox,
502            9103,
503            "2024-07-01T00:00:00Z",
504        ))
505        .unwrap();
506        let chromes = reg.list_by_kind_all(Kind::Chrome).unwrap();
507        assert_eq!(chromes.len(), 2);
508        assert_eq!(chromes[0].name, "newer");
509        assert_eq!(chromes[1].name, "older");
510
511        // first_alive_by_kind on these synthetic rows should find none alive
512        // and prune dead-process entries.
513        assert!(reg.first_alive_by_kind(Kind::Chrome).unwrap().is_none());
514        assert!(reg.list_by_kind_all(Kind::Chrome).unwrap().is_empty());
515    }
516
517    #[test]
518    fn list_alive_prunes_stale() {
519        let reg = Registry::open_in_memory().unwrap();
520        reg.insert(&sample_row("a", Kind::Chrome, 9201, "2024-01-01T00:00:00Z"))
521            .unwrap();
522        reg.insert(&sample_row("b", Kind::Chrome, 9202, "2024-01-02T00:00:00Z"))
523            .unwrap();
524        let alive = reg.list_alive().unwrap();
525        assert!(alive.is_empty());
526        assert!(reg.list_all().unwrap().is_empty());
527    }
528
529    #[test]
530    fn list_alive_retains_live_pid_with_unreachable_endpoint() {
531        let reg = Registry::open_in_memory().unwrap();
532        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
533        let port = listener.local_addr().unwrap().port();
534        drop(listener);
535        let mut row = sample_row(
536            "temporarily-unreachable",
537            Kind::Chrome,
538            port,
539            "2024-01-01T00:00:00Z",
540        );
541        row.pid = std::process::id();
542        reg.insert(&row).unwrap();
543
544        let alive = reg.list_alive().unwrap();
545        assert!(alive.is_empty());
546        assert!(reg
547            .get_by_name("temporarily-unreachable")
548            .unwrap()
549            .is_some());
550    }
551
552    #[test]
553    fn most_recent_alive_with_no_live_rows_is_none() {
554        let reg = Registry::open_in_memory().unwrap();
555        reg.insert(&sample_row("a", Kind::Chrome, 9301, "2024-01-01T00:00:00Z"))
556            .unwrap();
557        assert!(reg.most_recent_alive().unwrap().is_none());
558    }
559
560    #[test]
561    fn now_iso8601_format() {
562        let s = now_iso8601();
563        assert_eq!(s.len(), 20, "got {s}");
564        assert!(s.ends_with('Z'));
565        assert_eq!(&s[4..5], "-");
566        assert_eq!(&s[7..8], "-");
567        assert_eq!(&s[10..11], "T");
568        assert_eq!(&s[13..14], ":");
569        assert_eq!(&s[16..17], ":");
570
571        // Epoch sanity.
572        assert_eq!(format_unix_seconds_as_iso8601(0), "1970-01-01T00:00:00Z");
573    }
574
575    #[test]
576    fn iso8601_known_dates() {
577        let cases = [
578            (0_i64, "1970-01-01T00:00:00Z"),
579            (951_782_400, "2000-02-29T00:00:00Z"), // leap day
580            (1_700_000_000, "2023-11-14T22:13:20Z"),
581            (1_583_020_799, "2020-02-29T23:59:59Z"), // last second of leap day
582            (1_583_020_800, "2020-03-01T00:00:00Z"),
583            (1_577_836_799, "2019-12-31T23:59:59Z"), // end of year
584        ];
585        for (secs, want) in cases {
586            assert_eq!(format_unix_seconds_as_iso8601(secs), want, "epoch {secs}");
587        }
588    }
589
590    #[test]
591    fn concurrent_file_lock_serializes() {
592        use std::thread;
593
594        let tmp = tempfile::TempDir::new().unwrap();
595        let db_path = tmp.path().join("registry.db");
596
597        let p1 = db_path.clone();
598        let p2 = db_path.clone();
599        let t1 = thread::spawn(move || {
600            let reg = Registry::open_at(&p1).unwrap();
601            reg.insert(&BrowserRow {
602                name: "one".to_string(),
603                kind: Kind::Chrome,
604                engine: Engine::Cdp,
605                pid: 1,
606                endpoint: "http://127.0.0.1:9001".to_string(),
607                port: 9001,
608                profile_dir: PathBuf::from("/tmp/p1"),
609                executable: PathBuf::from("/usr/bin/chrome"),
610                headless: false,
611                started_at: "2024-01-01T00:00:00Z".to_string(),
612            })
613            .unwrap();
614        });
615        let t2 = thread::spawn(move || {
616            let reg = Registry::open_at(&p2).unwrap();
617            reg.insert(&BrowserRow {
618                name: "two".to_string(),
619                kind: Kind::Firefox,
620                engine: Engine::Bidi,
621                pid: 2,
622                endpoint: "ws://127.0.0.1:9002".to_string(),
623                port: 9002,
624                profile_dir: PathBuf::from("/tmp/p2"),
625                executable: PathBuf::from("/usr/bin/firefox"),
626                headless: false,
627                started_at: "2024-01-02T00:00:00Z".to_string(),
628            })
629            .unwrap();
630        });
631        t1.join().unwrap();
632        t2.join().unwrap();
633
634        let reg = Registry::open_at(&db_path).unwrap();
635        let all = reg.list_all().unwrap();
636        assert_eq!(all.len(), 2);
637        let names: Vec<&str> = all.iter().map(|r| r.name.as_str()).collect();
638        assert!(names.contains(&"one"));
639        assert!(names.contains(&"two"));
640    }
641
642    #[test]
643    fn open_at_creates_parent_dir_and_db() {
644        let tmp = tempfile::TempDir::new().unwrap();
645        let nested = tmp.path().join("a/b/c/registry.db");
646        let reg = Registry::open_at(&nested).unwrap();
647        reg.insert(&sample_row("x", Kind::Chrome, 9999, "2024-01-01T00:00:00Z"))
648            .unwrap();
649        assert!(nested.exists());
650        let lock = nested.parent().unwrap().join("registry.db.lock");
651        assert!(lock.exists());
652    }
653}