lrclean 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.
lrclean/__init__.py ADDED
File without changes
lrclean/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from lrclean import cli
4
+
5
+ sys.exit(cli.main())
lrclean/backup.py ADDED
@@ -0,0 +1,385 @@
1
+ """What decides and writes in the backup (phase B1, rules 16 to 23).
2
+
3
+ Rule 16 (`check_manifest`) and rule 20 (`source_changed`) only read; each
4
+ decision is one expression on one line.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import json
11
+ import os
12
+ import sys
13
+ import threading
14
+ import time
15
+ from collections.abc import Sequence
16
+ from typing import NamedTuple
17
+
18
+ from lrclean import backup_plan, hashing, paths, store
19
+ from lrclean.backup_plan import ManifestError, Row
20
+
21
+ VERIFIED = "verified"
22
+ ALREADY_THERE = "already_there"
23
+ CONFLICT = "conflict"
24
+ CHANGED = "changed"
25
+ FAILED = "failed"
26
+ SKIPPED_PLACEHOLDER = "skipped_placeholder"
27
+ DEST_PLACEHOLDER = "dest_placeholder"
28
+ PART_SUFFIX = ".lrclean-part"
29
+ BLOCK = 1024 * 1024 # the block size `hashing.full_hash` reads
30
+
31
+
32
+ def check_manifest(
33
+ rows: Sequence[Row],
34
+ *,
35
+ archive_roots: list[str],
36
+ library_roots: list[str],
37
+ free_bytes=backup_plan.free_space,
38
+ exists=os.path.exists,
39
+ ) -> int:
40
+ n = backup_plan.archive_index(rows, archive_roots)
41
+ seen: set[str] = set()
42
+ needed = 0
43
+ for row in rows:
44
+ if any(backup_plan.is_inside(row.dest, library) for library in library_roots):
45
+ raise ManifestError(f"dest is in a library root: {row.dest}")
46
+ name = os.path.basename(os.path.normpath(row.dest))
47
+ # Windows drops a final dot or space and reads a colon as a stream: each can open the part file.
48
+ if name.endswith((".", " ")) or ":" in name or name.casefold().endswith(PART_SUFFIX):
49
+ raise ManifestError(f"dest has the name of a part file: {row.dest} (source {row.source})")
50
+ if row.bytes < 0:
51
+ raise ManifestError(f"negative size for {row.dest}")
52
+ key = paths.norm(os.path.normpath(row.dest))
53
+ if key in seen:
54
+ raise ManifestError(f"two rows share the dest {row.dest}")
55
+ seen.add(key)
56
+ if row.action == "copy" and not exists(paths.fs_path(row.dest)):
57
+ needed += row.bytes
58
+ if needed > free_bytes(archive_roots[n - 1]):
59
+ raise ManifestError(f"the manifest needs {needed} bytes, more than the free space")
60
+ return n
61
+
62
+
63
+ def source_changed(row: Row, *, stat=os.stat, attrs_of=None) -> bool:
64
+ try:
65
+ st = stat(paths.fs_path(row.source))
66
+ except OSError:
67
+ return True
68
+ attrs = attrs_of(row.source, st) if attrs_of else getattr(st, "st_file_attributes", 0)
69
+ return paths.is_placeholder(attrs) or (st.st_size, st.st_mtime_ns) != (row.bytes, row.mtime_ns)
70
+
71
+
72
+ def _dest_placeholder(row: Row, st, attrs_of) -> bool:
73
+ return paths.is_placeholder(attrs_of(row.dest, st) if attrs_of else getattr(st, "st_file_attributes", 0))
74
+
75
+
76
+ def open_part(path: str):
77
+ return open(paths.fs_path(path), "xb")
78
+
79
+
80
+ class _Ticked:
81
+ def __init__(self, handle, tick):
82
+ self._handle, self._tick = handle, tick
83
+
84
+ def __enter__(self):
85
+ self._handle.__enter__()
86
+ return self
87
+
88
+ def __exit__(self, *exc):
89
+ return self._handle.__exit__(*exc)
90
+
91
+ def read(self, *args):
92
+ data = self._handle.read(*args)
93
+ self._tick()
94
+ return data
95
+
96
+ def __getattr__(self, name):
97
+ return getattr(self._handle, name)
98
+
99
+
100
+ def ticked(opener, tick):
101
+ def open_(path):
102
+ handle = opener(path)
103
+ try:
104
+ tick()
105
+ except BaseException:
106
+ handle.close()
107
+ raise
108
+ return _Ticked(handle, tick)
109
+
110
+ return open_
111
+
112
+
113
+ def _remove_part(part: str) -> None:
114
+ if os.path.exists(paths.fs_path(part)):
115
+ os.remove(paths.fs_path(part))
116
+
117
+
118
+ def copy_row(
119
+ row: Row,
120
+ *,
121
+ tick=lambda: None,
122
+ stat=os.stat,
123
+ attrs_of=None,
124
+ opener=hashing.open_binary,
125
+ writer=open_part,
126
+ rename=os.rename,
127
+ utime=os.utime,
128
+ ) -> tuple[str, str]:
129
+ if row.action == "skip_placeholder":
130
+ return SKIPPED_PLACEHOLDER, ""
131
+ part = row.dest + PART_SUFFIX
132
+ try:
133
+ return _copy(row, part, tick, stat, attrs_of, ticked(opener, tick), writer, rename, utime)
134
+ except BaseException as exc:
135
+ try:
136
+ _remove_part(part)
137
+ except OSError:
138
+ pass # the part may stay; the next run removes it
139
+ if isinstance(exc, OSError):
140
+ return FAILED, ""
141
+ raise
142
+
143
+
144
+ def _copy(row, part, tick, stat, attrs_of, open_, writer, rename, utime) -> tuple[str, str]:
145
+ if source_changed(row, stat=stat, attrs_of=attrs_of):
146
+ return CHANGED, ""
147
+ if os.path.exists(paths.fs_path(row.dest)):
148
+ if _dest_placeholder(row, stat(paths.fs_path(row.dest)), attrs_of):
149
+ return DEST_PLACEHOLDER, ""
150
+ src_sha = hashing.full_hash(row.source, open_)
151
+ dest_sha = hashing.full_hash(row.dest, open_)
152
+ return (ALREADY_THERE if src_sha == dest_sha else CONFLICT), src_sha
153
+ os.makedirs(paths.fs_path(os.path.dirname(row.dest)), exist_ok=True)
154
+ digest = hashlib.sha256()
155
+ with open_(row.source) as source, writer(part) as out:
156
+ for block in iter(lambda: source.read(BLOCK), b""):
157
+ out.write(block)
158
+ digest.update(block)
159
+ out.flush()
160
+ tick()
161
+ os.fsync(out.fileno())
162
+ tick()
163
+ sha = digest.hexdigest()
164
+ if hashing.full_hash(part, open_) != sha:
165
+ _remove_part(part)
166
+ return FAILED, ""
167
+ if source_changed(row, stat=stat, attrs_of=attrs_of):
168
+ _remove_part(part)
169
+ return CHANGED, ""
170
+ rename(paths.fs_path(part), paths.fs_path(row.dest))
171
+ utime(paths.fs_path(row.dest), ns=(row.mtime_ns, row.mtime_ns))
172
+ return VERIFIED, sha
173
+
174
+
175
+ class Result(NamedTuple):
176
+ row: int
177
+ source: str
178
+ dest: str
179
+ state: str
180
+ sha256: str
181
+
182
+
183
+ class RunOutcome(NamedTuple):
184
+ results: list[Result]
185
+ stalled: bool
186
+
187
+
188
+ def exit_code(outcome: RunOutcome) -> int:
189
+ return 5 if outcome.stalled else 6 if any(r.state in (CONFLICT, CHANGED, FAILED, DEST_PLACEHOLDER) for r in outcome.results) else 0
190
+
191
+
192
+ def journal_name(n: int, started: str) -> str:
193
+ return f"backup-{n}-{started.replace('-', '').replace(':', '')}.jsonl"
194
+
195
+
196
+ def _verified_end(line: str):
197
+ """((source, dest), (dest bytes, dest mtime_ns, sha256, source bytes, source mtime_ns)) of a verified `end` line."""
198
+ try:
199
+ entry = json.loads(line)
200
+ if entry["event"] != "end" or entry["state"] != VERIFIED:
201
+ return None
202
+ key = (paths.norm(entry["source"]), paths.norm(entry["dest"]))
203
+ sha = entry["sha256"]
204
+ if not isinstance(sha, str):
205
+ return None
206
+ dest = (int(entry["dest_bytes"]), int(entry["dest_mtime_ns"]))
207
+ return key, (*dest, sha, int(entry["source_bytes"]), int(entry["source_mtime_ns"]))
208
+ except (ValueError, KeyError, TypeError):
209
+ return None
210
+
211
+
212
+ def read_verified(journal_dir: str, n: int) -> dict[tuple[str, str], tuple[int, int, str, int, int]]:
213
+ try:
214
+ names = sorted(os.listdir(paths.fs_path(journal_dir)))
215
+ except OSError:
216
+ return {}
217
+ found: dict[tuple[str, str], tuple[int, int, str, int, int]] = {}
218
+ for name in names:
219
+ if not (name.startswith(f"backup-{n}-") and name.endswith(".jsonl")):
220
+ continue
221
+ with open(paths.fs_path(os.path.join(journal_dir, name)), encoding="utf-8", errors="replace") as handle:
222
+ for line in handle:
223
+ hit = _verified_end(line)
224
+ if hit:
225
+ found[hit[0]] = hit[1]
226
+ return found
227
+
228
+
229
+ class Journal:
230
+ def __init__(self, path: str):
231
+ self.path = path
232
+ self.lock = threading.RLock()
233
+ self._checked = False
234
+
235
+ def write(self, event: str, **fields) -> None:
236
+ line = json.dumps({"event": event, "at": store.utc_now(), **fields})
237
+ with self.lock, open(paths.fs_path(self.path), "a+b") as handle:
238
+ if not self._checked:
239
+ self._checked = True
240
+ handle.seek(0, os.SEEK_END)
241
+ if handle.tell():
242
+ handle.seek(-1, os.SEEK_END)
243
+ if handle.read(1) != b"\n":
244
+ line = "\n" + line
245
+ handle.write((line + "\n").encode("utf-8"))
246
+ handle.flush()
247
+ os.fsync(handle.fileno())
248
+
249
+
250
+ def _dest_stat(dest: str) -> tuple[int, int] | None:
251
+ try:
252
+ st = os.stat(paths.fs_path(dest))
253
+ except OSError:
254
+ return None # never equals a recorded pair, so a destination that is gone is not skipped
255
+ return st.st_size, st.st_mtime_ns
256
+
257
+
258
+ def _journal_sha(row: Row, verified, stat, attrs_of) -> str:
259
+ """The journal's SHA-256 when it vouches for the destination as it is now, else ''."""
260
+ recorded = verified.get((paths.norm(row.source), paths.norm(row.dest)))
261
+ if recorded and recorded[:2] == _dest_stat(row.dest) and not source_changed(row, stat=stat, attrs_of=attrs_of):
262
+ if recorded[3:] == (row.bytes, row.mtime_ns): # the source the journal verified
263
+ return recorded[2]
264
+ return ""
265
+
266
+
267
+ def _run_copy(row: Row, **copy_args) -> tuple[str, str]:
268
+ try:
269
+ return copy_row(row, **copy_args)
270
+ except Exception:
271
+ return FAILED, ""
272
+
273
+
274
+ def run_manifest(
275
+ rows: Sequence[Row],
276
+ *,
277
+ journal_dir: str,
278
+ n: int,
279
+ started: str,
280
+ stall_seconds: float = 120,
281
+ clock=time.monotonic,
282
+ poll_seconds: float = 0.05,
283
+ abort=os._exit,
284
+ now=store.utc_now,
285
+ stat=os.stat,
286
+ attrs_of=None,
287
+ opener=hashing.open_binary,
288
+ writer=open_part,
289
+ rename=os.rename
290
+ ) -> RunOutcome:
291
+ os.makedirs(paths.fs_path(journal_dir), exist_ok=True)
292
+ if not rows:
293
+ return RunOutcome([], False)
294
+ verified = read_verified(journal_dir, n)
295
+ journal = Journal(os.path.join(journal_dir, journal_name(n, started)))
296
+ results: list[Result] = []
297
+ last = [clock()]
298
+ current = [(0, rows[0])] # the row in hand, replaced whole
299
+ finished = threading.Event()
300
+ errors: list[BaseException] = []
301
+
302
+ def tick():
303
+ last[0] = clock()
304
+
305
+ def work_row(i, row):
306
+ tick()
307
+ current[0] = (i, row)
308
+ if row.action != "copy":
309
+ state, sha = copy_row(row)
310
+ return Result(i, row.source, row.dest, state, sha)
311
+ fields = {"row": i, "source": row.source, "dest": row.dest}
312
+ try:
313
+ _remove_part(row.dest + PART_SUFFIX)
314
+ skip_sha = _journal_sha(row, verified, stat, attrs_of)
315
+ except Exception:
316
+ skip_sha = None # the row fails below, with its start and end lines
317
+ if skip_sha:
318
+ return Result(i, row.source, row.dest, VERIFIED, skip_sha)
319
+ journal.write("start", at=now(), **fields)
320
+ if skip_sha is None:
321
+ state, sha = FAILED, ""
322
+ else:
323
+ state, sha = _run_copy(
324
+ row, tick=tick, stat=stat, attrs_of=attrs_of, opener=opener, writer=writer, rename=rename
325
+ )
326
+ sha = sha if state in (VERIFIED, ALREADY_THERE) else ""
327
+ size, mtime = _dest_stat(row.dest) or (0, 0)
328
+ facts = {"dest_bytes": size, "dest_mtime_ns": mtime, "source_bytes": row.bytes, "source_mtime_ns": row.mtime_ns}
329
+ journal.write("end", at=now(), state=state, sha256=sha, **facts, **fields)
330
+ return Result(i, row.source, row.dest, state, sha)
331
+
332
+ def work():
333
+ try:
334
+ for i, row in enumerate(rows):
335
+ results.append(work_row(i, row))
336
+ except BaseException as exc: # the journal failed: the caller re-raises it
337
+ errors.append(exc)
338
+ finally:
339
+ finished.set()
340
+
341
+ threading.Thread(target=work, daemon=True).start()
342
+ while not finished.wait(poll_seconds):
343
+ if clock() - last[0] > stall_seconds:
344
+ with journal.lock:
345
+ if clock() - last[0] <= stall_seconds:
346
+ continue
347
+ i, row = current[0]
348
+ seconds = clock() - last[0]
349
+ journal.write("stalled", at=now(), row=i, source=row.source, dest=row.dest, seconds=seconds)
350
+ print(f"backup stalled on row {i} for {seconds:.0f} s: {row.source}", file=sys.stderr)
351
+ abort(5)
352
+ return RunOutcome(list(results), True)
353
+ if errors:
354
+ raise errors[0]
355
+ return RunOutcome(results, False)
356
+
357
+
358
+ def dry_run(
359
+ rows: Sequence[Row],
360
+ *,
361
+ journal_dir: str,
362
+ n: int,
363
+ stat=os.stat,
364
+ attrs_of=None,
365
+ exists=os.path.exists,
366
+ ) -> list[tuple[int, str]]:
367
+ verified = read_verified(journal_dir, n)
368
+ return [(i, _verdict(row, verified, stat, attrs_of, exists)) for i, row in enumerate(rows)]
369
+
370
+
371
+ def _verdict(row: Row, verified, stat, attrs_of, exists) -> str:
372
+ if row.action == "skip_placeholder":
373
+ return "skip_placeholder"
374
+ if source_changed(row, stat=stat, attrs_of=attrs_of):
375
+ return "changed"
376
+ if not exists(paths.fs_path(row.dest)):
377
+ return "copy"
378
+ recorded = verified.get((paths.norm(row.source), paths.norm(row.dest)))
379
+ try:
380
+ st = stat(paths.fs_path(row.dest))
381
+ except OSError:
382
+ return "dest_exists"
383
+ same = recorded is not None and recorded[:2] == (st.st_size, st.st_mtime_ns)
384
+ same = same and recorded[3:] == (row.bytes, row.mtime_ns) # the source the journal verified
385
+ return "already_verified" if same else "dest_placeholder" if _dest_placeholder(row, st, attrs_of) else "dest_exists"