debkit 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.
@@ -0,0 +1,433 @@
1
+ """Mirror a Debian repository: the `RepoSync` operation.
2
+
3
+ `RepoSync` plans the copy and delete lists and transfers them; the index set it mirrors is
4
+ `Repo._get_indices`, whose rules are in `index_selection`.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import logging
10
+ from collections.abc import Collection
11
+ from typing import TYPE_CHECKING, NamedTuple
12
+
13
+ from txstore import StorageException, StorageNotFoundException, compare_digests
14
+
15
+ from debkit.repo import IndexTarget, Repo
16
+ from debkit.repo.hashes import ChecksumException
17
+ from debkit.repo.shared_root import SharedRoot, missing_and_unclaimed
18
+
19
+ if TYPE_CHECKING:
20
+ from debkit.repo.package import Package
21
+ from debkit.repo.repo_diff import RepoDiff
22
+ from debkit.repo.repo_rw import RepoRW
23
+
24
+
25
+ logger = logging.getLogger(__name__)
26
+ logger.addHandler(logging.NullHandler())
27
+
28
+ TRANSFER_MAX_ERR_RETRIES = 3
29
+
30
+
31
+ class SyncPlan(NamedTuple):
32
+ """One pass of a sync, as `RepoSync.build_sync_lists` plans it.
33
+
34
+ Attributes:
35
+ copy: Paths to copy from the source, payloads before indices.
36
+ delete: Paths to delete from the target.
37
+ unproven: Paths in `copy` no load or parse proved the source publishes, which `sync` skips
38
+ when the source lacks them.
39
+ """
40
+
41
+ copy: list[str]
42
+ delete: list[str]
43
+ unproven: set[str]
44
+
45
+ def is_empty(self) -> bool:
46
+ """Report whether the pass has nothing to copy or delete.
47
+
48
+ Returns:
49
+ True when both `copy` and `delete` are empty.
50
+ """
51
+ return not self.copy and not self.delete
52
+
53
+
54
+ class RepoSyncException(Exception):
55
+ """Exception raised for errors in sync to the repository."""
56
+
57
+ def __init__(self, message: str) -> None:
58
+ """Initialize with error message."""
59
+ super().__init__(f"Repo sync: {message}")
60
+
61
+
62
+ def _settle_overwrites(
63
+ shared: SharedRoot, replaced: dict[str, dict[str, str]], target_repo: RepoRW
64
+ ) -> set[str]:
65
+ """Refuse a plan that overwrites a payload another dist of the shared root pins.
66
+
67
+ A refused payload whose held bytes are already the source's changes nothing, so its digests
68
+ are recorded and it needs no copy; skipping any other copy would leave the own Release
69
+ naming bytes the target does not hold -> [VALIDATION.md](VALIDATION.md#index-selection).
70
+
71
+ Args:
72
+ shared: The claims of the other dists, with the digests their indices record.
73
+ replaced: Each held payload the plan overwrites -> the digests the source records.
74
+ target_repo: The target repo, read back for a refused payload.
75
+
76
+ Raises:
77
+ RepoSyncException: If a held payload whose bytes differ from the source's would be
78
+ overwritten while another dist records other bytes for it, records it without a
79
+ SHA digest, or did not load.
80
+
81
+ Returns:
82
+ The refused payloads the target already holds unchanged.
83
+ """
84
+ unchanged: set[str] = set()
85
+ conflicting: list[str] = []
86
+ for path in sorted(replaced):
87
+ if shared.replaceable(path, replaced[path]):
88
+ continue
89
+ held = target_repo.held_digests(path)
90
+ if held is not None and compare_digests(held, replaced[path]):
91
+ target_repo.record_digests(path, held)
92
+ unchanged.add(path)
93
+ else:
94
+ conflicting.append(path)
95
+ if conflicting:
96
+ cause = (
97
+ "another dist of the shared root records other bytes, or no SHA digest, for them"
98
+ if shared.complete
99
+ else "another dist of the shared root did not load, so the bytes it records are unknown"
100
+ )
101
+ raise RepoSyncException(
102
+ f"{len(conflicting)} held payload(s) would be overwritten, but {cause}: "
103
+ f"{', '.join(conflicting)}"
104
+ )
105
+ return unchanged
106
+
107
+
108
+ class RepoSync(Repo):
109
+ """Class that extends Repo with sync functionality."""
110
+
111
+ def build_sync_lists(self, target_repo: RepoRW, indices_only: bool = False) -> SyncPlan:
112
+ """Build filelists for sync.
113
+
114
+ Process some optimizations for reduce copy and remove lists.
115
+
116
+ Args:
117
+ target_repo: The target repo to sync with.
118
+ indices_only: Force the index pass and plan no payload copy or deletion. Defaults to
119
+ False.
120
+
121
+ Returns:
122
+ The paths to copy, the paths to delete, and the copied index paths no load or parse
123
+ proved the source publishes.
124
+ """
125
+ listed = target_repo.held_paths()
126
+ can_list = listed is not None
127
+ existing_files = listed if listed is not None else set()
128
+
129
+ indices = self._get_indices()
130
+
131
+ copy_list: list[str] = []
132
+ delete_list: list[str] = []
133
+ forced = True
134
+ if not indices_only:
135
+ diff = self.diff(target_repo.snapshot())
136
+ # an index-only source change (i18n, dep11) leaves the package diff empty, and a
137
+ # target index skipped as unreadable leaves the Release hashes equal
138
+ forced = (
139
+ self.release.content_sha256 != target_repo.release.content_sha256
140
+ or not diff.is_empty()
141
+ )
142
+ copy_list, delete_list = self._plan_payloads(
143
+ diff, indices, target_repo, existing_files, can_list=can_list
144
+ )
145
+
146
+ logger.info(" indices: %d objects", len(indices))
147
+ logger.info(" target repo: %d objects already existing", len(existing_files))
148
+
149
+ index_copies = self._indices_to_copy(
150
+ indices, target_repo, existing_files, forced=forced, can_list=can_list
151
+ )
152
+ unproven = {
153
+ file
154
+ for file in index_copies
155
+ if not indices[file].known_published and file not in existing_files
156
+ }
157
+
158
+ return SyncPlan(copy_list + index_copies, delete_list, unproven)
159
+
160
+ def _plan_payloads(
161
+ self,
162
+ diff: RepoDiff,
163
+ indices: Collection[str],
164
+ target_repo: RepoRW,
165
+ existing_files: set[str],
166
+ *,
167
+ can_list: bool,
168
+ ) -> tuple[list[str], list[str]]:
169
+ """Plan the payload copies and deletions a package diff and the target listing call for.
170
+
171
+ Args:
172
+ diff: This repo against the target.
173
+ indices: Every index path the index set holds.
174
+ target_repo: The target repo to sync with.
175
+ existing_files: Paths the target listing returned.
176
+ can_list: Whether `existing_files` is a real listing of the target.
177
+
178
+ Returns:
179
+ Payloads to copy, repairs included, and payloads to delete, orphans included; both
180
+ sorted.
181
+ """
182
+ all_pkg_files = self._payload_files()
183
+ copy_pkg_files = diff.get_filenames_to_copy() & all_pkg_files
184
+ # a vanished stanza naming an index must not delete what the index set keeps, and a
185
+ # payload dropped from one arch index stays while another source index lists it
186
+ # -> [VALIDATION.md](VALIDATION.md#index-selection)
187
+ remove_pkg_files = self._drop_release_owned(diff.get_filenames_to_remove()) - all_pkg_files
188
+
189
+ # missing packages a previous failed sync left, and orphans; an unlisted target
190
+ # proves neither
191
+ repair_files: set[str] = set()
192
+ purge_files: set[str] = set()
193
+ if can_list:
194
+ repair_files, purge_files = missing_and_unclaimed(
195
+ all_pkg_files, indices, existing_files, planned=copy_pkg_files | remove_pkg_files
196
+ )
197
+ source_digests = self._source_digests(diff.get_pkgs_to_copy())
198
+ copy_pkg_files = self._reduce_copies(
199
+ source_digests, copy_pkg_files, target_repo, existing_files
200
+ )
201
+ # what a copy overwrites: a held payload whose stored digests disagree
202
+ replaced = {path: source_digests[path] for path in copy_pkg_files & existing_files}
203
+ # another dist sharing the root keeps its tree and the payloads it lists, and the bytes
204
+ # its indices pin; reading those claims loads every other dist, so only a pass that
205
+ # deletes or overwrites a held payload reads them
206
+ if can_list and (purge_files or remove_pkg_files or replaced):
207
+ shared = target_repo.shared_root(existing_files, with_digests=bool(replaced))
208
+ purge_files = {file for file in purge_files if shared.deletable(file)}
209
+ remove_pkg_files = {file for file in remove_pkg_files if shared.deletable(file)}
210
+ copy_pkg_files -= _settle_overwrites(shared, replaced, target_repo)
211
+ # files a previous failed sync never got to delete
212
+ remove_pkg_files &= existing_files
213
+
214
+ logger.info(" source repo: %d packages (total)", len(all_pkg_files))
215
+ logger.info(" to copy: %d packages", len(copy_pkg_files))
216
+ logger.info(" to remove: %d packages", len(remove_pkg_files))
217
+ logger.info(" to repair: %d objects (corrupted or missing)", len(repair_files))
218
+ logger.info(" to purge: %d objects (orphans)", len(purge_files))
219
+
220
+ return sorted(copy_pkg_files | repair_files), sorted(remove_pkg_files | purge_files)
221
+
222
+ @staticmethod
223
+ def _source_digests(packages: list[Package]) -> dict[str, dict[str, str]]:
224
+ """Map each payload a diff copies to the digests the source records for it.
225
+
226
+ Args:
227
+ packages: Packages the diff copies, one per index naming them.
228
+
229
+ Returns:
230
+ Payload path -> the digests of its first-seen package; differing digests from
231
+ another index are logged.
232
+ """
233
+ seen: dict[str, dict[str, str]] = {}
234
+ for package in packages:
235
+ path = str(package)
236
+ digests = package.get_digests()
237
+ if path not in seen:
238
+ seen[path] = digests
239
+ elif digests != seen[path]:
240
+ logger.warning("%s has inconsistent digests across indices in source repo", path)
241
+ return seen
242
+
243
+ def _reduce_copies(
244
+ self,
245
+ source_digests: dict[str, dict[str, str]],
246
+ copy_files: set[str],
247
+ target_repo: RepoRW,
248
+ existing_files: set[str],
249
+ ) -> set[str]:
250
+ """Drop the payloads the target already holds unchanged, as a terminated sync leaves them.
251
+
252
+ Args:
253
+ source_digests: Each copied payload -> the digests the source records.
254
+ copy_files: Payload paths to copy.
255
+ target_repo: The target repo to sync with.
256
+ existing_files: Paths the target listing returned.
257
+
258
+ Returns:
259
+ `copy_files` without the payloads the target already holds.
260
+ """
261
+ held = copy_files & existing_files
262
+ if not self.params.verify_digests:
263
+ return copy_files - held
264
+ ret = set(copy_files)
265
+ for path in sorted(held):
266
+ if target_repo.metadata_agrees(path, source_digests[path]):
267
+ ret.discard(path)
268
+ else:
269
+ logger.warning(
270
+ "%s have not valid checksums in target repo. It will be copied again.", path
271
+ )
272
+ return ret
273
+
274
+ def _indices_to_copy(
275
+ self,
276
+ indices: dict[str, IndexTarget],
277
+ target_repo: RepoRW,
278
+ existing_files: set[str],
279
+ *,
280
+ forced: bool,
281
+ can_list: bool,
282
+ ) -> list[str]:
283
+ """Decide which indices this sync copies -> [VALIDATION.md](VALIDATION.md#index-selection).
284
+
285
+ Args:
286
+ indices: The sync index set, from `_get_indices()`.
287
+ target_repo: The target repo to sync with.
288
+ existing_files: Paths the target listing returned.
289
+ forced: Whether a package or Release change already forces the index pass.
290
+ can_list: Whether `existing_files` is a real listing of the target.
291
+
292
+ Returns:
293
+ Index paths to copy, empty when nothing forces the pass.
294
+ """
295
+ # an absent entry no load or parse proved is expected absent, so it never forces
296
+ if can_list and not forced:
297
+ forced = any(
298
+ target.known_published and file not in existing_files
299
+ for file, target in indices.items()
300
+ )
301
+
302
+ if not forced:
303
+ return []
304
+ return self._reduce_indices(indices, target_repo, existing_files)
305
+
306
+ def _reduce_indices(
307
+ self,
308
+ indices: dict[str, IndexTarget],
309
+ target_repo: RepoRW,
310
+ existing_files: set[str],
311
+ ) -> list[str]:
312
+ """Drop indices the target already holds unchanged.
313
+
314
+ Agreeing root Release digest blocks settle a held entry first (free), then its
315
+ stored metadata (one round trip); nothing settles an absent entry, and the
316
+ source is never probed -> [VALIDATION.md](VALIDATION.md#index-selection).
317
+
318
+ Args:
319
+ indices: Index path → expected digests and whether the source is known to publish it.
320
+ target_repo: The target repo to sync with.
321
+ existing_files: Objects already present in the target.
322
+
323
+ Returns:
324
+ Index paths still to copy.
325
+ """
326
+ target_loaded = target_repo.release.is_loaded
327
+ ret: list[str] = []
328
+ for file, target in indices.items():
329
+ held = file in existing_files
330
+
331
+ if held and target.digests and self.params.verify_digests and target_loaded:
332
+ if target_repo.release_agrees(file, target.digests):
333
+ continue
334
+ if target_repo.metadata_agrees(file, target.digests):
335
+ continue
336
+ logger.debug(
337
+ "%s has different checksums in target repo. It will be copied again.", file
338
+ )
339
+
340
+ ret.append(file)
341
+
342
+ logger.info(" indices: %d objects to copy", len(ret))
343
+ return ret
344
+
345
+ def _transfer_file(
346
+ self,
347
+ file: str,
348
+ target_repo: RepoRW,
349
+ progress: tuple[int, int],
350
+ *,
351
+ missing_ok: bool = False,
352
+ ) -> bool:
353
+ """Transfer a file from this repo to another repo.
354
+
355
+ Save digests of the file in metadata.
356
+
357
+ Args:
358
+ file: The file to transfer.
359
+ target_repo: The target repo to transfer to.
360
+ progress: Progress of transfer - current of total objects.
361
+ missing_ok: Skip the file when the source lacks it, as for an index nothing proved
362
+ published -> [VALIDATION.md](VALIDATION.md#index-selection).
363
+
364
+ Raises:
365
+ ChecksumException: If the checksum verification fails.
366
+
367
+ Returns:
368
+ True when the file needs no retry: it was transferred, or `missing_ok` is set and the
369
+ source lacks it. False otherwise.
370
+ """
371
+ logger.info("Copy (%d/%d): %s", progress[0], progress[1], file)
372
+
373
+ try:
374
+ digests = target_repo.transfer_from(self.storage, file, path_dst=file)
375
+ except StorageNotFoundException as exc:
376
+ if missing_ok:
377
+ logger.debug("%s listed in Release but missing in source. Skipped.", file)
378
+ return True
379
+ logger.error("Error transfer file %s: %s", file, exc)
380
+ return False
381
+ except StorageException as exc:
382
+ logger.error("Error transfer file %s: %s", file, exc)
383
+ return False
384
+
385
+ if self.params.verify_digests and not self.verify_checksum(file, digests):
386
+ target_repo.delete(file)
387
+ raise ChecksumException(f"Content verify mismatch in {file}")
388
+
389
+ target_repo.record_digests(file, digests)
390
+
391
+ return True
392
+
393
+ def sync(self, target_repo: RepoRW, plan: SyncPlan) -> None:
394
+ """Sync this repo with another repo.
395
+
396
+ Either every object transfers or the sync raises: a target that holds a new
397
+ root `Release` describing objects it never received would advertise content
398
+ it cannot serve. The caller wraps the run in a transaction, so raising leaves
399
+ the target at its previous consistent state
400
+ -> [STORAGE.md](STORAGE.md#transactions). An `unproven` path the source lacks
401
+ is the one exception: the source serves it no more than the target will
402
+ -> [VALIDATION.md](VALIDATION.md#index-selection).
403
+
404
+ Args:
405
+ target_repo: The target repo to sync with.
406
+ plan: What to copy and delete, as `build_sync_lists` planned it.
407
+
408
+ Raises:
409
+ RepoSyncException: If any object still fails after the retries.
410
+ ChecksumException: If a transferred object does not match its expected
411
+ digests; it is never retried → [CRYPTO.md](CRYPTO.md#verification-failures).
412
+ """
413
+ # each pass retries only what the previous one failed; a transient error should not
414
+ # fail the whole run
415
+ pending = plan.copy
416
+ for _ in range(TRANSFER_MAX_ERR_RETRIES):
417
+ total = len(pending)
418
+ pending = [
419
+ name
420
+ for cnt, name in enumerate(pending, start=1)
421
+ if not self._transfer_file(
422
+ name, target_repo, progress=(cnt, total), missing_ok=name in plan.unproven
423
+ )
424
+ ]
425
+ if not pending:
426
+ break
427
+ else:
428
+ logger.debug("failed packages: %s", pending)
429
+ raise RepoSyncException("Max retries reached.")
430
+
431
+ # delete objects
432
+ for name in plan.delete:
433
+ target_repo.delete(name)