irsync 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
irsync/snapshot.py ADDED
@@ -0,0 +1,346 @@
1
+ """Inode snapshots of a directory tree, written as JSONL for diffing across runs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime as dt
6
+ import json
7
+ import logging
8
+ import stat
9
+ from collections.abc import Iterable
10
+ from pathlib import Path
11
+ from typing import Literal, TypedDict
12
+
13
+ from irsync import __version__
14
+ from irsync.statx import btime_ns as _btime_ns
15
+
16
+ SNAPSHOT_FILENAME: str = ".irsync_snapshot.jsonl"
17
+ LOCKFILE_NAME: str = ".irsync.lock"
18
+ SNAPSHOT_TEMPFILE_PREFIX: str = ".irsync-snap-"
19
+
20
+
21
+ class SnapshotMismatch(Exception):
22
+ """Raised when a snapshot's recorded source root doesn't match the caller's."""
23
+
24
+
25
+ class Header(TypedDict):
26
+ """Provenance metadata stored as the first line of a snapshot file."""
27
+
28
+ source_root: str
29
+ irsync_version: str
30
+ created_at_utc: str
31
+
32
+
33
+ class Row(TypedDict):
34
+ """One JSONL row capturing inode identity for a single tree entry."""
35
+
36
+ dev: int
37
+ ino: int
38
+ type: Literal["f", "d", "l", "o"]
39
+ nlink: int
40
+ size: int
41
+ mtime_ns: int # st_mtime_ns; combined with size, defends against inode reuse
42
+ btime_ns: (
43
+ int # statx birth time; tiebreaker that survives rename, -1 if unsupported
44
+ )
45
+ path: str # POSIX relative path from snapshot root
46
+
47
+
48
+ def _crosses_boundary(*, entry_dev: int, root_dev: int, xdev: bool) -> bool:
49
+ """Return True if this entry sits on another filesystem and will be skipped.
50
+
51
+ Extracted so the boundary decision is directly testable: creating a real
52
+ nested mount requires privileges the test suite does not have.
53
+
54
+ Args:
55
+ entry_dev: The entry's ``st_dev``.
56
+ root_dev: The snapshot root's ``st_dev``.
57
+ xdev: If True, filesystem boundaries are enforced.
58
+
59
+ Returns:
60
+ True if ``xdev`` is enabled and ``entry_dev`` differs from ``root_dev``.
61
+ """
62
+ return xdev and entry_dev != root_dev
63
+
64
+
65
+ def _file_type_char(
66
+ mode: int, is_dir: bool, is_symlink: bool
67
+ ) -> Literal["f", "d", "l", "o"]:
68
+ """Classify a stat ``mode`` into a single-character type tag."""
69
+ if is_dir:
70
+ return "d"
71
+ if is_symlink:
72
+ return "l"
73
+ if (mode & 0o170000) == 0o100000:
74
+ return "f"
75
+ return "o"
76
+
77
+
78
+ def snapshot_tree(
79
+ root: Path,
80
+ *,
81
+ xdev: bool = True,
82
+ include_other: bool = False,
83
+ ) -> list[Row]:
84
+ """Walk ``root`` without following symlinks and return JSONL-friendly rows.
85
+
86
+ The root entry itself is included as ``path == "."``. The snapshot file
87
+ (:data:`SNAPSHOT_FILENAME`) at the root is excluded so the snapshot remains
88
+ self-consistent across runs.
89
+
90
+ Args:
91
+ root: Directory to snapshot.
92
+ xdev: If True, do not cross filesystem boundaries.
93
+ include_other: If True, include sockets/devices/pipes as type ``"o"``.
94
+
95
+ Returns:
96
+ A list of :class:`Row` records, one per included entry.
97
+
98
+ Raises:
99
+ SystemExit: If ``root`` does not exist or is not a directory.
100
+ """
101
+ root = root.resolve()
102
+ rows: list[Row] = []
103
+ skipped_mounts: list[str] = []
104
+
105
+ try:
106
+ st_root = root.lstat()
107
+ except FileNotFoundError as e:
108
+ raise SystemExit(f"Root path does not exist: {root}") from e
109
+ if not stat.S_ISDIR(st_root.st_mode):
110
+ raise SystemExit(f"Root path is not a directory: {root}")
111
+
112
+ root_dev = st_root.st_dev
113
+
114
+ rows.append(
115
+ Row(
116
+ dev=int(st_root.st_dev),
117
+ ino=int(st_root.st_ino),
118
+ type="d",
119
+ nlink=int(st_root.st_nlink),
120
+ size=int(st_root.st_size),
121
+ mtime_ns=int(st_root.st_mtime_ns),
122
+ btime_ns=_btime_ns(root),
123
+ path=".",
124
+ )
125
+ )
126
+
127
+ # 10th-F5: explicit-stack DFS instead of recursive walk(). The
128
+ # recursive form added one Python frame per directory level, so a
129
+ # tree deeper than sys.getrecursionlimit() (default ~1000) raised
130
+ # RecursionError mid-walk and left the user with no snapshot.
131
+ stack: list[Path] = [root]
132
+ while stack:
133
+ dir_path = stack.pop()
134
+ try:
135
+ entries = list(dir_path.iterdir())
136
+ except (PermissionError, FileNotFoundError, NotADirectoryError):
137
+ continue
138
+ for entry in entries:
139
+ try:
140
+ st = entry.lstat()
141
+ except (FileNotFoundError, PermissionError):
142
+ continue
143
+
144
+ rel = entry.relative_to(root).as_posix()
145
+
146
+ # Skip irsync's reserved files at the source root: the snapshot
147
+ # itself, the lockfile, and any orphan tempfiles from a killed
148
+ # _atomic_write_snapshot. Subdirectory files with the same names
149
+ # are still included (this is the H1/NEW-H2 anchored-exclude
150
+ # principle: only the root entries are reserved). Naturally
151
+ # limited to root since `relative_to(root)` of a subdir entry
152
+ # always contains "/".
153
+ if rel in (SNAPSHOT_FILENAME, LOCKFILE_NAME):
154
+ continue
155
+ if "/" not in rel and rel.startswith(SNAPSHOT_TEMPFILE_PREFIX):
156
+ continue
157
+
158
+ is_dir = stat.S_ISDIR(st.st_mode)
159
+ is_symlink = stat.S_ISLNK(st.st_mode)
160
+
161
+ ftype = _file_type_char(st.st_mode, is_dir, is_symlink)
162
+ if ftype == "o" and not include_other:
163
+ continue
164
+
165
+ crosses = _crosses_boundary(
166
+ entry_dev=int(st.st_dev), root_dev=int(root_dev), xdev=xdev
167
+ )
168
+ if crosses:
169
+ if is_dir and not is_symlink:
170
+ skipped_mounts.append(rel)
171
+ continue
172
+
173
+ rows.append(
174
+ Row(
175
+ dev=int(st.st_dev),
176
+ ino=int(st.st_ino),
177
+ type=ftype,
178
+ nlink=int(st.st_nlink),
179
+ size=int(st.st_size),
180
+ mtime_ns=int(st.st_mtime_ns),
181
+ btime_ns=_btime_ns(entry),
182
+ path=rel,
183
+ )
184
+ )
185
+ # Descend into directories without following symlinks.
186
+ if is_dir and not is_symlink:
187
+ stack.append(entry)
188
+
189
+ if skipped_mounts:
190
+ shown = ", ".join(sorted(skipped_mounts)[:5])
191
+ more = (
192
+ f" (and {len(skipped_mounts) - 5} more)" if len(skipped_mounts) > 5 else ""
193
+ )
194
+ logging.warning(
195
+ "Skipped %d path(s) on a separate filesystem; they are NOT backed "
196
+ "up (rsync runs with --one-file-system too): %s%s",
197
+ len(skipped_mounts),
198
+ shown,
199
+ more,
200
+ )
201
+
202
+ return rows
203
+
204
+
205
+ def write_snapshot(
206
+ rows: Iterable[Row],
207
+ *,
208
+ source_root: Path,
209
+ out_file: Path,
210
+ ) -> None:
211
+ """Write a snapshot with a provenance header line followed by row lines.
212
+
213
+ The header records the resolved source root, irsync version, and a UTC
214
+ timestamp so a stale snapshot from a different tree can be rejected
215
+ before being used as a diff baseline.
216
+
217
+ Args:
218
+ rows: Snapshot rows.
219
+ source_root: The directory the snapshot covers; resolved to absolute.
220
+ out_file: Destination path; parent must exist.
221
+ """
222
+ header: dict[str, Header] = {
223
+ "_meta": Header(
224
+ source_root=str(source_root.resolve()),
225
+ irsync_version=__version__,
226
+ created_at_utc=dt.datetime.now(dt.UTC).isoformat(),
227
+ )
228
+ }
229
+ # 10th-F1: errors="surrogateescape" lets paths containing arbitrary
230
+ # non-UTF-8 bytes (legal on Linux, surfaced by os.listdir as surrogate
231
+ # codepoints) round-trip the file boundary instead of raising
232
+ # UnicodeEncodeError mid-snapshot.
233
+ with out_file.open(
234
+ "w", encoding="utf-8", errors="surrogateescape", newline="\n"
235
+ ) as f:
236
+ f.write(json.dumps(header, separators=(",", ":"), ensure_ascii=False))
237
+ f.write("\n")
238
+ for r in rows:
239
+ f.write(json.dumps(r, separators=(",", ":"), ensure_ascii=False))
240
+ f.write("\n")
241
+
242
+
243
+ def read_snapshot(
244
+ file: Path,
245
+ *,
246
+ expected_source_root: Path,
247
+ ) -> tuple[Header | None, list[Row]]:
248
+ """Read a snapshot file written by :func:`write_snapshot`.
249
+
250
+ If the first line is a header object (``{"_meta": ...}``), it is parsed
251
+ and validated against ``expected_source_root``. A header from a
252
+ different source tree raises :class:`SnapshotMismatch` so the caller
253
+ can refuse to use it as a diff baseline. Files without a header (legacy
254
+ format) return ``None`` for the header and are otherwise read as rows.
255
+
256
+ Args:
257
+ file: Snapshot file path.
258
+ expected_source_root: The current source root; the header's
259
+ ``source_root`` must match this when present.
260
+
261
+ Returns:
262
+ ``(header_or_none, rows)``.
263
+
264
+ Raises:
265
+ SnapshotMismatch: If the header's source root doesn't match.
266
+ SystemExit: If a row is malformed.
267
+ """
268
+ # 10th-F4: stream line by line instead of read_text + split("\n"). The
269
+ # old approach materialized the whole file as one str plus a list of
270
+ # line strs (~2× file size in RAM); for a multi-million-row tree that
271
+ # was a hard cap before compute_changes even started building its dict
272
+ # indexes. errors="surrogateescape" mirrors the writer so non-UTF-8
273
+ # bytes in paths round-trip back to the same surrogate codepoints
274
+ # (10th-F1).
275
+ header: Header | None = None
276
+ rows: list[Row] = []
277
+ with file.open("r", encoding="utf-8", errors="surrogateescape") as f:
278
+ first_line = ""
279
+ first_lineno = 0
280
+ for ln, line in enumerate(f, 1):
281
+ if line.strip():
282
+ first_line = line
283
+ first_lineno = ln
284
+ break
285
+ if not first_line:
286
+ return None, []
287
+
288
+ try:
289
+ first = json.loads(first_line)
290
+ except json.JSONDecodeError as e:
291
+ raise SystemExit(f"Malformed JSONL at {file}:{first_lineno}: {e}") from e
292
+
293
+ if isinstance(first, dict) and "_meta" in first:
294
+ meta = first["_meta"]
295
+ header = Header(
296
+ source_root=meta.get("source_root", ""),
297
+ irsync_version=meta.get("irsync_version", ""),
298
+ created_at_utc=meta.get("created_at_utc", ""),
299
+ )
300
+ expected = str(expected_source_root.resolve())
301
+ if header["source_root"] != expected:
302
+ raise SnapshotMismatch(
303
+ f"Snapshot at {file} was taken of {header['source_root']!r}, "
304
+ f"but the current source root is {expected!r}. Refusing to use it "
305
+ "as a diff baseline."
306
+ )
307
+ else:
308
+ # Legacy headerless: the first line is itself a row.
309
+ rows.append(_validate_row(first, file, first_lineno))
310
+
311
+ for ln, line in enumerate(f, first_lineno + 1):
312
+ if not line.strip():
313
+ continue
314
+ try:
315
+ obj = json.loads(line)
316
+ except json.JSONDecodeError as e:
317
+ raise SystemExit(f"Malformed JSONL at {file}:{ln}: {e}") from e
318
+ rows.append(_validate_row(obj, file, ln))
319
+ return header, rows
320
+
321
+
322
+ def _validate_row(obj: dict[str, object], file: Path, lineno: int) -> Row:
323
+ """Validate a parsed row dict and apply legacy-snapshot defaults.
324
+
325
+ Applied to every row :func:`read_snapshot` parses, headered or legacy
326
+ headerless. Raises :class:`SystemExit` with a precise location on
327
+ missing keys or an invalid type tag (7th-M2).
328
+ """
329
+ for k in ("dev", "ino", "type", "nlink", "size", "path"):
330
+ if k not in obj:
331
+ raise SystemExit(f"Missing key '{k}' in {file}:{lineno}")
332
+ if obj["type"] not in ("f", "d", "l", "o"):
333
+ # 7th-M2: corrupted rows with unknown types were silently kept
334
+ # and later filtered out by compute_changes' type whitelist,
335
+ # hiding inode-level corruption. Refuse the whole snapshot.
336
+ raise SystemExit(
337
+ f"Invalid type {obj['type']!r} in {file}:{lineno} "
338
+ "(expected one of 'f', 'd', 'l', 'o')"
339
+ )
340
+ # mtime_ns and btime_ns were added in later passes; tolerate snapshots
341
+ # written by older versions by defaulting to a sentinel (-1). Missing
342
+ # mtime forces a conservative fallback in compute_moves; missing btime
343
+ # just disables the btime tiebreaker.
344
+ obj.setdefault("mtime_ns", -1)
345
+ obj.setdefault("btime_ns", -1)
346
+ return obj # type: ignore[return-value]
irsync/statx.py ADDED
@@ -0,0 +1,139 @@
1
+ """ctypes wrapper around Linux ``statx(2)`` to read inode birth time (btime).
2
+
3
+ Why this exists
4
+ ---------------
5
+ The 5th-pass NEW-H1 attempt to use ``ctime_ns`` as an inode-reuse tiebreaker
6
+ failed because ``rename(2)`` updates ctime — the gate refused legitimate
7
+ renames whenever the wall clock had advanced. ``btime`` (a.k.a. crtime) is
8
+ the right field: it is set when the inode is allocated and never changes
9
+ afterward. A genuine rename preserves it; an inode-reuse event always gets
10
+ a fresh value.
11
+
12
+ ``btime`` is exposed by ``statx(2)`` (Linux 4.11+, glibc 2.28+) but is NOT
13
+ in Python's stdlib ``os.stat`` result. This module provides a tiny ctypes
14
+ wrapper around ``libc.statx`` that returns the inode's birth time as
15
+ nanoseconds since the epoch.
16
+
17
+ Fallback behaviour
18
+ ------------------
19
+ If the platform isn't Linux, libc lacks ``statx``, statx fails, or the
20
+ filesystem doesn't report btime (older ext4 without ``-O extent``, FAT,
21
+ NFSv3, etc.), :func:`btime_ns` returns ``-1``. Callers must treat ``-1``
22
+ as "unknown" and fall back to the size+mtime move gate (the pre-5th-pass
23
+ behaviour, which is correct for nanosecond-precision local filesystems).
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import ctypes
29
+ import os
30
+ import sys
31
+ from pathlib import Path
32
+
33
+ # statx flags
34
+ _AT_FDCWD: int = -100
35
+ _AT_SYMLINK_NOFOLLOW: int = 0x100
36
+
37
+ # statx mask bit selecting btime
38
+ _STATX_BTIME: int = 0x800
39
+
40
+
41
+ class _StatxTimestamp(ctypes.Structure):
42
+ _fields_ = (
43
+ ("tv_sec", ctypes.c_int64),
44
+ ("tv_nsec", ctypes.c_uint32),
45
+ ("__reserved", ctypes.c_int32),
46
+ )
47
+
48
+
49
+ class _Statx(ctypes.Structure):
50
+ # Layout per Linux uapi/linux/stat.h. We only read stx_mask + stx_btime
51
+ # but must declare all fields up to that point so the offsets line up.
52
+ _fields_ = (
53
+ ("stx_mask", ctypes.c_uint32),
54
+ ("stx_blksize", ctypes.c_uint32),
55
+ ("stx_attributes", ctypes.c_uint64),
56
+ ("stx_nlink", ctypes.c_uint32),
57
+ ("stx_uid", ctypes.c_uint32),
58
+ ("stx_gid", ctypes.c_uint32),
59
+ ("stx_mode", ctypes.c_uint16),
60
+ ("__spare0", ctypes.c_uint16),
61
+ ("stx_ino", ctypes.c_uint64),
62
+ ("stx_size", ctypes.c_uint64),
63
+ ("stx_blocks", ctypes.c_uint64),
64
+ ("stx_attributes_mask", ctypes.c_uint64),
65
+ ("stx_atime", _StatxTimestamp),
66
+ ("stx_btime", _StatxTimestamp),
67
+ ("stx_ctime", _StatxTimestamp),
68
+ ("stx_mtime", _StatxTimestamp),
69
+ ("stx_rdev_major", ctypes.c_uint32),
70
+ ("stx_rdev_minor", ctypes.c_uint32),
71
+ ("stx_dev_major", ctypes.c_uint32),
72
+ ("stx_dev_minor", ctypes.c_uint32),
73
+ ("stx_mnt_id", ctypes.c_uint64),
74
+ ("stx_dio_mem_align", ctypes.c_uint32),
75
+ ("stx_dio_offset_align", ctypes.c_uint32),
76
+ ("__spare3", ctypes.c_uint64 * 12),
77
+ )
78
+
79
+
80
+ def _load_statx() -> ctypes._NamedFuncPointer | None:
81
+ """Return ``libc.statx`` if available on this platform, else ``None``."""
82
+ if sys.platform != "linux":
83
+ return None
84
+ try:
85
+ libc = ctypes.CDLL("libc.so.6", use_errno=True)
86
+ except OSError:
87
+ return None
88
+ if not hasattr(libc, "statx"):
89
+ return None
90
+ fn = libc.statx
91
+ fn.argtypes = (
92
+ ctypes.c_int,
93
+ ctypes.c_char_p,
94
+ ctypes.c_int,
95
+ ctypes.c_uint,
96
+ ctypes.POINTER(_Statx),
97
+ )
98
+ fn.restype = ctypes.c_int
99
+ return fn
100
+
101
+
102
+ _STATX = _load_statx()
103
+
104
+
105
+ def is_available() -> bool:
106
+ """Return True iff ``statx`` is callable on this platform."""
107
+ return _STATX is not None
108
+
109
+
110
+ def btime_ns(path: Path | str) -> int:
111
+ """Return inode birth time of ``path`` in nanoseconds since the epoch.
112
+
113
+ Returns ``-1`` when btime cannot be determined: statx is unavailable,
114
+ the path is missing, or the filesystem doesn't report btime. Callers
115
+ must treat ``-1`` as "unknown" and fall back to coarser gates.
116
+
117
+ Args:
118
+ path: Path to stat. Symlinks are NOT followed (parity with
119
+ :func:`pathlib.Path.lstat`).
120
+
121
+ Returns:
122
+ Birth time in nanoseconds since the epoch, or ``-1`` if unknown.
123
+ """
124
+ if _STATX is None:
125
+ return -1
126
+ buf = _Statx()
127
+ rc = _STATX(
128
+ _AT_FDCWD,
129
+ os.fsencode(os.fspath(path)),
130
+ _AT_SYMLINK_NOFOLLOW,
131
+ _STATX_BTIME,
132
+ ctypes.byref(buf),
133
+ )
134
+ if rc != 0:
135
+ return -1
136
+ if not (buf.stx_mask & _STATX_BTIME):
137
+ # Kernel/FS combination doesn't report btime for this file.
138
+ return -1
139
+ return int(buf.stx_btime.tv_sec) * 1_000_000_000 + int(buf.stx_btime.tv_nsec)