返回 last30days-skill
sqlite_snapshot.py
根目录 / skills / last30days / scripts / lib / sqlite_snapshot.py
1 """Bounded, consistent snapshots of browser SQLite databases."""
2
3 from contextlib import closing, nullcontext
4 import hashlib
5 from pathlib import Path
6 import sqlite3
7 import struct
8 import tempfile
9 import time
10
11
12 _WAL_SHM_ERRORS = {
13 sqlite3.SQLITE_IOERR_SHMOPEN,
14 sqlite3.SQLITE_IOERR_SHMSIZE,
15 sqlite3.SQLITE_IOERR_SHMLOCK,
16 sqlite3.SQLITE_IOERR_SHMMAP,
17 }
18 _LOCK_ERRORS = {sqlite3.SQLITE_BUSY, sqlite3.SQLITE_LOCKED}
19 _DATABASE_HEADER_SIZE = 100
20 _WAL_FILE_FORMAT = 2
21 _WAL_HEADER_SIZE = 32
22 _WAL_FRAME_HEADER_SIZE = 24
23
24
25 def _check_deadline(deadline: float) -> None:
26 if time.monotonic() >= deadline:
27 raise sqlite3.OperationalError("Timed out taking browser database snapshot")
28
29
30 def _backup(source_uri: str, destination: str, deadline: float) -> None:
31 def check_deadline(_status: int, _remaining: int, _total: int) -> None:
32 _check_deadline(deadline)
33
34 _check_deadline(deadline)
35 with (
36 closing(sqlite3.connect(source_uri, uri=True, timeout=0)) as reader,
37 closing(sqlite3.connect(destination, timeout=0)) as writer,
38 ):
39 reader.backup(writer, pages=128, progress=check_deadline, sleep=0.01)
40
41
42 def _file_state(path: Path) -> tuple[int, int, int, int, int]:
43 stat = path.stat()
44 return stat.st_dev, stat.st_ino, stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns
45
46
47 def _fingerprint(source: Path, deadline: float, *, copy_to: Path | None = None) -> bytes:
48 digest = hashlib.sha256()
49 with source.open("rb") as reader, (copy_to.open("xb") if copy_to else nullcontext()) as target:
50 while True:
51 _check_deadline(deadline)
52 block = reader.read(128 * 1024)
53 if not block:
54 return digest.digest()
55 digest.update(block)
56 if target is not None:
57 target.write(block)
58
59
60 def _validate_wal(wal: Path) -> None:
61 with wal.open("rb") as reader:
62 header = reader.read(_WAL_HEADER_SIZE)
63 if len(header) != _WAL_HEADER_SIZE:
64 raise sqlite3.OperationalError("Browser WAL has an incomplete header")
65 magic, version, page_size = struct.unpack_from(">III", header)
66 if (
67 magic not in (0x377F0682, 0x377F0683)
68 or version != 3_007_000
69 or not 512 <= page_size <= 65536
70 or page_size & (page_size - 1)
71 ):
72 raise sqlite3.OperationalError("Browser WAL has an invalid header")
73 # SQLite silently ignores a torn first frame. Leave recovery of any
74 # committed prefix ahead of a torn trailing frame to SQLite.
75 if wal.stat().st_size < _WAL_HEADER_SIZE + _WAL_FRAME_HEADER_SIZE + page_size:
76 raise sqlite3.OperationalError("Browser WAL has no complete frame")
77
78
79 def _is_wal_database(source: Path) -> bool:
80 with source.open("rb") as reader:
81 header = reader.read(_DATABASE_HEADER_SIZE)
82 return len(header) == _DATABASE_HEADER_SIZE and header[18] == header[19] == _WAL_FILE_FORMAT
83
84
85 def _refuses_readers(source_uri: str) -> bool:
86 try:
87 with closing(sqlite3.connect(source_uri, uri=True, timeout=0)) as probe:
88 probe.execute("PRAGMA schema_version").fetchone()
89 except sqlite3.OperationalError as exc:
90 return getattr(exc, "sqlite_errorcode", None) in _LOCK_ERRORS
91 return False
92
93
94 def _backup_file_copies(source: Path, destination: str, deadline: float, *, require_wal: bool) -> None:
95 wal = source.with_name(source.name + "-wal")
96 has_wal = wal.exists() and wal.stat().st_size > 0
97 if require_wal and not has_wal:
98 raise sqlite3.OperationalError("Browser WAL is empty")
99 files = [source, wal] if has_wal else [source]
100 states = [_file_state(path) for path in files]
101
102 with tempfile.TemporaryDirectory(prefix="last30days-browser-db-") as scratch:
103 copies = [Path(scratch) / path.name for path in files]
104 hashes = [_fingerprint(path, deadline, copy_to=copy) for path, copy in zip(files, copies)]
105
106 # A checkpoint or WAL reset can race the copy. Re-read every file
107 # and reject changes before letting SQLite replay the private copies
108 # using its own local shared-memory index.
109 if (
110 hashes != [_fingerprint(path, deadline) for path in files]
111 or states != [_file_state(path) for path in files]
112 ):
113 raise sqlite3.OperationalError("Browser database changed during snapshot")
114 if has_wal:
115 _validate_wal(copies[1])
116 _backup(copies[0].as_uri() + "?mode=ro", destination, deadline)
117
118
119 def copy_snapshot(
120 source: Path, destination: str, *, timeout: float = 1.0, wsl_wal_fallback: bool = False,
121 ) -> None:
122 """Back up committed database state, including WAL, to a private temp file."""
123 source = Path(source)
124 # Preserve the OS permission error used to explain browser-access denials;
125 # sqlite3.connect otherwise turns it into a generic OperationalError.
126 with source.open("rb"):
127 pass
128
129 deadline = time.monotonic() + timeout
130 source = source.resolve()
131 source_uri = source.as_uri() + "?mode=ro"
132 if _is_wal_database(source) and _refuses_readers(source_uri):
133 _backup_file_copies(source, destination, deadline, require_wal=False)
134 return
135 try:
136 _backup(source_uri, destination, deadline)
137 except sqlite3.OperationalError as exc:
138 if not wsl_wal_fallback or getattr(exc, "sqlite_errorcode", None) not in _WAL_SHM_ERRORS:
139 raise
140 _backup_file_copies(source, destination, deadline, require_wal=True)
141
141 lines PYTHON