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,114 @@
1
+ """Repository diff class."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING
6
+
7
+ if TYPE_CHECKING:
8
+ from debkit.repo.package import Package
9
+ from debkit.repo.packages import PackagesDiff
10
+
11
+
12
+ class RepoDiff:
13
+ """How a repository differs from an earlier state, one `PackagesDiff` per index slot.
14
+
15
+ Attributes:
16
+ slots: Each compared component and arch → how its packages changed.
17
+ """
18
+
19
+ def __init__(self) -> None:
20
+ """Initialize RepoDiff."""
21
+ self.slots: dict[tuple[str, str], PackagesDiff] = {}
22
+
23
+ def dump(self) -> dict[str, dict[str, dict[str, list[Package]]]]:
24
+ """Dump RepoDiff to dict.
25
+
26
+ Returns:
27
+ Each bucket (`added`, `removed`, `updated`, `old_versions`) → component → arch →
28
+ its packages.
29
+ """
30
+ ret: dict[str, dict[str, dict[str, list[Package]]]] = {
31
+ "added": {},
32
+ "removed": {},
33
+ "updated": {},
34
+ "old_versions": {},
35
+ }
36
+ for (component, arch), pkgs_diff in self.slots.items():
37
+ for bucket, pkgs in pkgs_diff._asdict().items():
38
+ ret[bucket].setdefault(component, {})[arch] = list(pkgs.values())
39
+ return ret
40
+
41
+ def record(self, component: str, arch: str, pkgs_diff: PackagesDiff) -> None:
42
+ """Record how one slot changed.
43
+
44
+ Args:
45
+ component: component name
46
+ arch: architecture
47
+ pkgs_diff: how its packages changed
48
+ """
49
+ self.slots[component, arch] = pkgs_diff
50
+
51
+ def get_pkgs_to_copy(self) -> list[Package]:
52
+ """Get list of packages to copy.
53
+
54
+ Returns:
55
+ List of packages to copy
56
+ """
57
+ pkgs: list[Package] = []
58
+ for pkgs_diff in self.slots.values():
59
+ pkgs.extend(pkgs_diff.added.values())
60
+ for pkgs_diff in self.slots.values():
61
+ pkgs.extend(pkgs_diff.updated.values())
62
+ return pkgs
63
+
64
+ def count_pkgs_to_copy(self) -> int:
65
+ """Get count of distinct payloads to copy; an `all` package in several arches counts once.
66
+
67
+ Returns:
68
+ Count of packages to copy
69
+ """
70
+ return len(self.get_filenames_to_copy())
71
+
72
+ def get_filenames_to_copy(self) -> set[str]:
73
+ """Get list of filenames to copy.
74
+
75
+ Returns:
76
+ List of filenames to copy
77
+ """
78
+ return {str(pkg) for pkg in self.get_pkgs_to_copy()}
79
+
80
+ def get_pkgs_to_remove(self) -> list[Package]:
81
+ """Get list of packages to remove.
82
+
83
+ Returns:
84
+ List of packages to remove
85
+ """
86
+ # old versions are not removed: a package of the same name may be among the added ones
87
+ return [pkg for pkgs_diff in self.slots.values() for pkg in pkgs_diff.removed.values()]
88
+
89
+ def count_pkgs_to_remove(self) -> int:
90
+ """Get count of distinct payloads to remove; an `all` package in several arches counts once.
91
+
92
+ Returns:
93
+ Count of packages to remove
94
+ """
95
+ return len(self.get_filenames_to_remove())
96
+
97
+ def get_filenames_to_remove(self) -> set[str]:
98
+ """Get list of filenames to remove.
99
+
100
+ Returns:
101
+ List of filenames to remove
102
+ """
103
+ return {str(pkg) for pkg in self.get_pkgs_to_remove()}
104
+
105
+ def is_empty(self) -> bool:
106
+ """Check if RepoDiff is empty.
107
+
108
+ `record` stores every component and arch it compared, so an unchanged slot holds
109
+ empty buckets and counts as empty.
110
+
111
+ Returns:
112
+ True if no slot lists a package, False otherwise
113
+ """
114
+ return all(pkgs_diff.is_empty() for pkgs_diff in self.slots.values())
debkit/repo/repo_rw.py ADDED
@@ -0,0 +1,444 @@
1
+ """Class containing repository with write ability.
2
+
3
+ Inherits from Repo.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import logging
9
+ import re
10
+ from email.utils import formatdate
11
+ from typing import TYPE_CHECKING, NamedTuple
12
+
13
+ from txstore import StorageException, StorageNull, compare_digests, normalize_digests
14
+
15
+ from debkit.repo import Repo
16
+ from debkit.repo.component import Component
17
+ from debkit.repo.params import FLAT_COMPONENT, SOURCE_ARCH
18
+ from debkit.repo.shared_root import (
19
+ ConsistencyLists,
20
+ SharedRoot,
21
+ missing_and_unclaimed,
22
+ shared_root_claims,
23
+ unlisted_shared_root,
24
+ )
25
+
26
+ if TYPE_CHECKING:
27
+ from txstore import Storage
28
+
29
+ from debkit.repo.package import Package
30
+
31
+ logger = logging.getLogger(__name__)
32
+ logger.addHandler(logging.NullHandler())
33
+
34
+
35
+ class CheckReport(NamedTuple):
36
+ """What `RepoRW.check` found in the repository's own storage, and what it fixed.
37
+
38
+ Attributes:
39
+ missing: Payloads and parsed component indices the listing lacks, sorted.
40
+ orphans: Listed paths that no index claims, sorted.
41
+ failed: Payloads that failed verification or could not be read.
42
+ fixed: Payloads and orphans deleted.
43
+ """
44
+
45
+ missing: list[str]
46
+ orphans: list[str]
47
+ failed: int
48
+ fixed: int
49
+
50
+
51
+ class RepoRW(Repo):
52
+ """A `Repo` that inserts, removes, checks, and saves.
53
+
54
+ Whether anything changed is the caller's diff against a snapshot; `save` writes only the
55
+ containers that changed, then the root Release that lists them.
56
+ """
57
+
58
+ def setup(self, fields: dict[str, str] | None = None) -> None:
59
+ """Setup the repository.
60
+
61
+ A flat layout has one component slot and its Release lists no components, so a
62
+ `Components` field is dropped -> [VALIDATION.md](VALIDATION.md#repository-index-paths).
63
+
64
+ Args:
65
+ fields: The fields to set. Defaults to None.
66
+ """
67
+ logger.info("Setting up a new repository.")
68
+ if fields is not None and self.params.is_flat:
69
+ fields = {key: value for key, value in fields.items() if key != "Components"}
70
+ self.release.setup(fields=fields)
71
+
72
+ def save(self) -> bool:
73
+ """Save the repository.
74
+
75
+ Returns:
76
+ True if a component saved, False otherwise.
77
+ """
78
+ saved: bool = False
79
+ for component in self.components.values():
80
+ saved = component.save() or saved
81
+
82
+ if saved:
83
+ self.release.fields["Date"] = formatdate(localtime=False, usegmt=True)
84
+ # a flat Release lists no components; its single slot keeps whatever name it loaded
85
+ if not self.params.is_flat:
86
+ self.release.fields["Components"] = " ".join(self.components)
87
+ # the fields just changed, and so did the index digests the components recorded
88
+ self.release.modified = True
89
+ self.release.save()
90
+
91
+ return saved
92
+
93
+ def reset(self) -> None:
94
+ """Reset the repository."""
95
+ self.components = {}
96
+ self.release.reset()
97
+
98
+ def remove_pkg(self, fields_patterns: dict[str, re.Pattern[str]]) -> bool:
99
+ """Drop packages matching ``fields_patterns`` from the indices and delete their payloads.
100
+
101
+ Several arch indices list one `all` payload, so each payload is deleted once. A payload
102
+ another dist sharing the root lists is kept, and so is every payload while another
103
+ dist's claims are unknown -> [VALIDATION.md](VALIDATION.md#index-selection).
104
+
105
+ Args:
106
+ fields_patterns: Compiled pattern per package field.
107
+
108
+ Raises:
109
+ StorageException: If the backend fails to delete a payload.
110
+
111
+ Returns:
112
+ True iff at least one package was removed.
113
+ """
114
+ logger.info(
115
+ "Removing packages with fields patterns: %s",
116
+ {field: rx.pattern for field, rx in fields_patterns.items()},
117
+ )
118
+
119
+ removed: set[str] = set()
120
+ for component in self.components.values():
121
+ removed |= component.remove_pkg(fields_patterns)
122
+ if not removed:
123
+ return False
124
+
125
+ shared = self.shared_root()
126
+ for filename in sorted(removed):
127
+ if not shared.deletable(filename):
128
+ logger.info(
129
+ "Keep package: %s (another dist sharing the root may list it)", filename
130
+ )
131
+ continue
132
+ self.delete(filename)
133
+ return True
134
+
135
+ def binary_archs(self) -> list[str]:
136
+ """Get the repository architectures a binary package can be inserted into.
137
+
138
+ A mirrored `Sources` index is read-only, so `source` never receives a `.deb`
139
+ -> [VALIDATION.md](VALIDATION.md#sources-stanzas). The empty arch names no
140
+ `binary-<arch>/` directory, so only a flat repo inserts under it
141
+ -> [VALIDATION.md](VALIDATION.md#architectures).
142
+
143
+ Returns:
144
+ The repository architectures without the source one.
145
+ """
146
+ return [
147
+ arch
148
+ for arch in self.get_archs()
149
+ if arch != SOURCE_ARCH and (arch or self.params.is_flat)
150
+ ]
151
+
152
+ def insert_pkg(self, component_name: str, arch: str, package: Package) -> None:
153
+ """Add deb package object to the repo.
154
+
155
+ A flat layout has one component slot, so ``component_name`` is ignored there and the
156
+ package joins the component the repo loaded
157
+ -> [VALIDATION.md](VALIDATION.md#repository-index-paths).
158
+
159
+ Args:
160
+ component_name: The name of the component.
161
+ arch: The architecture.
162
+ package: The Package object to insert.
163
+ """
164
+ if self.params.is_flat:
165
+ component_name = next(iter(self.components), FLAT_COMPONENT)
166
+
167
+ if component_name in self.components:
168
+ component = self.components[component_name]
169
+ else:
170
+ component = Component(self.storage, self.params, self.release, component_name)
171
+ component.setup([arch])
172
+ self.components[component_name] = component
173
+
174
+ component.insert_pkg(arch, package)
175
+
176
+ def transfer_from(
177
+ self, source_storage: Storage, path_src: str, path_dst: str | None = None
178
+ ) -> dict[str, str]:
179
+ """Transfer a file from an external storage into this repo's storage.
180
+
181
+ The destination storage applies its own ACL -> txstore.
182
+
183
+ Args:
184
+ source_storage: The storage to read from.
185
+ path_src: Source path in `source_storage`.
186
+ path_dst: Destination path in this repo. Defaults to `path_src`.
187
+
188
+ Returns:
189
+ Digests of the transferred object.
190
+ """
191
+ return source_storage.transfer(path_src, self.storage, path_dst=path_dst)
192
+
193
+ def metadata_agrees(self, path: str, digests: dict[str, str]) -> bool:
194
+ """Report whether the stored metadata of `path` records `digests`.
195
+
196
+ The digest-skip decision shared by payloads and indices: one metadata round trip,
197
+ never a read of the object; normalization and comparison stay in txstore's digest
198
+ helpers -> [CRYPTO.md](CRYPTO.md#implementation-rules). The caller has already
199
+ established that `path` exists and that digest verification is on.
200
+
201
+ Args:
202
+ path: The object path.
203
+ digests: The digests another repository records for the object.
204
+
205
+ Returns:
206
+ True when the held copy matches and need not be transferred.
207
+ """
208
+ return compare_digests(digests, normalize_digests(self.storage.get_metadata(path)))
209
+
210
+ def release_agrees(self, path: str, digests: dict[str, str]) -> bool:
211
+ """Report whether this repository's loaded root Release records `digests` for an index.
212
+
213
+ The Release is already loaded, so its digest block costs nothing, while
214
+ `metadata_agrees` is a round trip per key and a full Debian Release lists hundreds of
215
+ indices -> [VALIDATION.md](VALIDATION.md#index-selection).
216
+
217
+ Args:
218
+ path: The index's storage path, identical in both repositories.
219
+ digests: The digests another repository's Release records for it.
220
+
221
+ Returns:
222
+ True when this Release records matching digests under its own layout's key.
223
+ """
224
+ held = self.release.digests.get(self.params.release_key(path))
225
+ if not held:
226
+ return False
227
+ return compare_digests(digests, normalize_digests(held))
228
+
229
+ def held_digests(self, path: str) -> dict[str, str] | None:
230
+ """Return the digests of the bytes this repo's storage holds at `path`, if any.
231
+
232
+ Args:
233
+ path: The object path.
234
+
235
+ Returns:
236
+ Its digests, or None when the storage does not hold it.
237
+ """
238
+ if not self.storage.exists(path):
239
+ return None
240
+ return self._read_digests(path)
241
+
242
+ def shared_root(
243
+ self, existing: set[str] | None = None, *, with_digests: bool = False
244
+ ) -> SharedRoot:
245
+ """Collect what the other dists sharing this repository's root claim.
246
+
247
+ A flat layout is never listed, since it has no `dists/` tree to share
248
+ -> [VALIDATION.md](VALIDATION.md#index-selection).
249
+
250
+ Args:
251
+ existing: Paths this repository's storage listing returned; None lists it, so a
252
+ caller that already listed it judges claims against the same listing.
253
+ with_digests: Also collect the digests the other dists record, for a caller that
254
+ judges a payload's bytes. Defaults to False.
255
+
256
+ Returns:
257
+ The claims; unknown when the storage cannot list, so only the own index tree is
258
+ deletable.
259
+ """
260
+ return shared_root_claims(self.storage, self.params, existing, with_digests=with_digests)
261
+
262
+ def consistency_lists(
263
+ self, payloads: set[str], *, with_digests: bool = False
264
+ ) -> ConsistencyLists:
265
+ """List what this repository's own storage lacks and what it holds unclaimed.
266
+
267
+ Missing are the payloads and the parsed component indices the listing lacks:
268
+ the root Release files were just read and nothing is probed, so a listing that
269
+ disagrees with a read cannot make them missing. Orphans are listed paths that
270
+ neither the package set nor the index set holds, and no other dist sharing the root
271
+ claims -> [CONFIG.md](CONFIG.md#check).
272
+
273
+ Args:
274
+ payloads: The payload paths the indices list, from `_payload_files()`.
275
+ with_digests: Also collect the digests the other dists record, for a caller that
276
+ judges a corrupt payload. Defaults to False.
277
+
278
+ Returns:
279
+ Missing and orphan paths, sorted, and the shared root claims from the same
280
+ listing; both lists empty and the claims unknown when the storage cannot list.
281
+ """
282
+ existing_files = self.held_paths()
283
+ if existing_files is None:
284
+ return ConsistencyLists([], [], unlisted_shared_root(self.params))
285
+
286
+ indices = self._get_indices()
287
+ missing, orphans = missing_and_unclaimed(payloads, indices, existing_files)
288
+ shared = self.shared_root(existing_files, with_digests=with_digests)
289
+ orphans = {file for file in orphans if shared.deletable(file)}
290
+ parsed = {
291
+ path for component in self.components.values() for path in component.get_indices_paths()
292
+ }
293
+ root_files = set(self.release.get_indices_paths())
294
+ missing |= (parsed & indices.keys()) - root_files - existing_files
295
+ return ConsistencyLists(sorted(missing), sorted(orphans), shared)
296
+
297
+ def check(self, *, fix: bool = False) -> CheckReport:
298
+ """Check the repository against its own indices: verify its payloads, then purge.
299
+
300
+ With `fix`, every orphan is deleted after the payload verify, which deletes the corrupt
301
+ payloads -> [CONFIG.md](CONFIG.md#check).
302
+
303
+ Args:
304
+ fix: Delete corrupt payloads and orphans, and record each valid payload's
305
+ digests. Defaults to False.
306
+
307
+ Returns:
308
+ The missing and orphan paths, and the failed and fixed counts.
309
+ """
310
+ report = self.verify_payloads(fix=fix)
311
+ if not fix:
312
+ return report
313
+ return report._replace(fixed=report.fixed + self._purge(report.orphans))
314
+
315
+ def verify_payloads(self, *, fix: bool = False) -> CheckReport:
316
+ """Read back and verify every payload the indices list; orphans are only reported.
317
+
318
+ With `fix`, a corrupt payload is deleted, so a later sync or insert places it again,
319
+ while a valid one has the digests read back recorded as object metadata, which the
320
+ sync's held-payload skip reads -> [CONFIG.md](CONFIG.md#check). A corrupt payload whose
321
+ bytes another dist sharing the root records is kept for that dist, and so is every one
322
+ while another dist's payloads are unknown
323
+ -> [VALIDATION.md](VALIDATION.md#index-selection).
324
+
325
+ Args:
326
+ fix: Delete corrupt payloads, and record each valid payload's digests. Defaults
327
+ to False.
328
+
329
+ Returns:
330
+ The missing and orphan paths, and the failed and fixed counts.
331
+ """
332
+ payload_set = self._payload_files()
333
+ missing, orphans, shared = self.consistency_lists(payload_set, with_digests=fix)
334
+ payloads = sorted(payload_set)
335
+ absent = set(missing)
336
+ failed = 0
337
+ fixed = 0
338
+
339
+ for cnt, file in enumerate(payloads, start=1):
340
+ if file in absent:
341
+ logger.warning("Skip (%d/%d): %s (missing)", cnt, len(payloads), file)
342
+ continue
343
+
344
+ try:
345
+ valid, digests = self._verify_file(file, progress=(cnt, len(payloads)))
346
+ if valid:
347
+ if fix:
348
+ self.record_digests(file, digests)
349
+ continue
350
+ logger.warning("Checksum verify failed: %s", file)
351
+ failed += 1
352
+ if not fix:
353
+ continue
354
+ if shared.corrupt_deletable(file, digests):
355
+ self.delete(file)
356
+ fixed += 1
357
+ else:
358
+ logger.warning(
359
+ "Keep: %s (another dist sharing the root may record its bytes)", file
360
+ )
361
+ except StorageException as exc:
362
+ logger.error("Error checking file: %s: %s", file, exc)
363
+ failed += 1
364
+
365
+ return CheckReport(missing, orphans, failed, fixed)
366
+
367
+ def _purge(self, orphans: list[str]) -> int:
368
+ """Delete each orphan, logging the ones the backend refuses.
369
+
370
+ Args:
371
+ orphans: Listed paths no index claims and no other dist sharing the root claims.
372
+
373
+ Returns:
374
+ How many orphans were deleted.
375
+ """
376
+ fixed = 0
377
+ for file in orphans:
378
+ try:
379
+ self.delete(file)
380
+ fixed += 1
381
+ except StorageException as exc:
382
+ logger.error("Error deleting file: %s: %s", file, exc)
383
+ return fixed
384
+
385
+ def held_paths(self) -> set[str] | None:
386
+ """List the paths this repository's storage holds.
387
+
388
+ Returns:
389
+ Every listed path, or None when the storage cannot list, which proves nothing
390
+ missing and nothing orphaned.
391
+ """
392
+ try:
393
+ return set(self.storage.list())
394
+ except NotImplementedError:
395
+ return None
396
+
397
+ def delete(self, file: str) -> None:
398
+ """Delete `file` from this repository's storage, logging it.
399
+
400
+ Args:
401
+ file: Object path to delete.
402
+ """
403
+ logger.info("Delete: %s", file)
404
+ self.storage.delete(file)
405
+
406
+ def record_digests(self, file: str, digests: dict[str, str]) -> None:
407
+ """Record `digests` as the object metadata of `file`, which the sync's skip reads.
408
+
409
+ Args:
410
+ file: Object path in this repository's storage.
411
+ digests: The digests of the bytes it holds.
412
+ """
413
+ self.storage.add_metadata(file, digests)
414
+
415
+ def _verify_file(self, file: str, progress: tuple[int, int]) -> tuple[bool, dict[str, str]]:
416
+ """Read a payload back and verify it against the indices; nothing is written.
417
+
418
+ Args:
419
+ file: The payload path.
420
+ progress: Current and total payload counts, for the log.
421
+
422
+ Returns:
423
+ Whether the file is valid, and the digests of the bytes read back.
424
+ """
425
+ logger.info("Verify (%d/%d): %s", progress[0], progress[1], file)
426
+
427
+ digests = self._read_digests(file)
428
+
429
+ if self.params.verify_digests and not self.verify_checksum(file, digests):
430
+ return False, digests
431
+
432
+ return True, digests
433
+
434
+ def _read_digests(self, path: str) -> dict[str, str]:
435
+ """Read an object of this repo's storage through and return its digests.
436
+
437
+ Args:
438
+ path: The object path.
439
+
440
+ Returns:
441
+ Its digests.
442
+ """
443
+ # read through to a digest sink -> [ROADMAP.md](ROADMAP.md#known-deviations)
444
+ return self.storage.transfer(path, StorageNull())