datadouble 0.0.7__tar.gz → 0.0.8__tar.gz

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.
Files changed (90) hide show
  1. {datadouble-0.0.7 → datadouble-0.0.8}/PKG-INFO +1 -1
  2. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/api.py +3 -1
  3. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/cli.py +13 -5
  4. datadouble-0.0.8/src/datadouble/images.py +429 -0
  5. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/promote.py +53 -15
  6. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/prune.py +44 -16
  7. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/run.py +49 -10
  8. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/signing.py +1 -1
  9. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/spec.py +16 -1
  10. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/staging.py +82 -29
  11. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/storage.py +1 -1
  12. {datadouble-0.0.7 → datadouble-0.0.8}/tests/test_commands_operations.py +3 -2
  13. {datadouble-0.0.7 → datadouble-0.0.8}/tests/test_operations.py +236 -20
  14. {datadouble-0.0.7 → datadouble-0.0.8}/tests/test_run.py +47 -0
  15. {datadouble-0.0.7 → datadouble-0.0.8}/tests/test_storage_images.py +140 -11
  16. datadouble-0.0.7/src/datadouble/images.py +0 -268
  17. {datadouble-0.0.7 → datadouble-0.0.8}/.gitignore +0 -0
  18. {datadouble-0.0.7 → datadouble-0.0.8}/LICENSE +0 -0
  19. {datadouble-0.0.7 → datadouble-0.0.8}/README.md +0 -0
  20. {datadouble-0.0.7 → datadouble-0.0.8}/pyproject.toml +0 -0
  21. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/__init__.py +0 -0
  22. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/announce.py +0 -0
  23. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/anonymize.py +0 -0
  24. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/boundary.py +0 -0
  25. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/catalog.py +0 -0
  26. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/channels.py +0 -0
  27. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/ci.py +0 -0
  28. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/closure.py +0 -0
  29. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/discover.py +0 -0
  30. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/engine.py +0 -0
  31. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/files.py +0 -0
  32. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/jailer.py +0 -0
  33. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/jsonpath.py +0 -0
  34. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/locales/__init__.py +0 -0
  35. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/locales/base.py +0 -0
  36. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/locales/data/first_names.txt +0 -0
  37. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/locales/data/sources.txt +0 -0
  38. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/locales/data/streets.txt +0 -0
  39. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/locales/data/surnames.txt +0 -0
  40. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/locales/gb.py +0 -0
  41. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/locales/us.py +0 -0
  42. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/locales/vocabulary.py +0 -0
  43. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/names.py +0 -0
  44. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/notify.py +0 -0
  45. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/objects.py +0 -0
  46. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/outcome.py +0 -0
  47. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/pii.py +0 -0
  48. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/planner.py +0 -0
  49. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/programs.py +0 -0
  50. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/progress.py +0 -0
  51. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/py.typed +0 -0
  52. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/redaction.py +0 -0
  53. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/registry.py +0 -0
  54. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/replicate.py +0 -0
  55. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/resolve.py +0 -0
  56. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/runtime.py +0 -0
  57. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/secrets.py +0 -0
  58. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/settings.py +0 -0
  59. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/strict.py +0 -0
  60. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/subset.py +0 -0
  61. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/verify.py +0 -0
  62. {datadouble-0.0.7 → datadouble-0.0.8}/src/datadouble/versions.py +0 -0
  63. {datadouble-0.0.7 → datadouble-0.0.8}/tests/conftest.py +0 -0
  64. {datadouble-0.0.7 → datadouble-0.0.8}/tests/fake_engine.py +0 -0
  65. {datadouble-0.0.7 → datadouble-0.0.8}/tests/fakes.py +0 -0
  66. {datadouble-0.0.7 → datadouble-0.0.8}/tests/test_anonymize_pii.py +0 -0
  67. {datadouble-0.0.7 → datadouble-0.0.8}/tests/test_api.py +0 -0
  68. {datadouble-0.0.7 → datadouble-0.0.8}/tests/test_catalog.py +0 -0
  69. {datadouble-0.0.7 → datadouble-0.0.8}/tests/test_ci.py +0 -0
  70. {datadouble-0.0.7 → datadouble-0.0.8}/tests/test_cli.py +0 -0
  71. {datadouble-0.0.7 → datadouble-0.0.8}/tests/test_closure.py +0 -0
  72. {datadouble-0.0.7 → datadouble-0.0.8}/tests/test_commands.py +0 -0
  73. {datadouble-0.0.7 → datadouble-0.0.8}/tests/test_discover.py +0 -0
  74. {datadouble-0.0.7 → datadouble-0.0.8}/tests/test_extends.py +0 -0
  75. {datadouble-0.0.7 → datadouble-0.0.8}/tests/test_files.py +0 -0
  76. {datadouble-0.0.7 → datadouble-0.0.8}/tests/test_jailer.py +0 -0
  77. {datadouble-0.0.7 → datadouble-0.0.8}/tests/test_jsonpath.py +0 -0
  78. {datadouble-0.0.7 → datadouble-0.0.8}/tests/test_locales.py +0 -0
  79. {datadouble-0.0.7 → datadouble-0.0.8}/tests/test_notify.py +0 -0
  80. {datadouble-0.0.7 → datadouble-0.0.8}/tests/test_objects.py +0 -0
  81. {datadouble-0.0.7 → datadouble-0.0.8}/tests/test_planner.py +0 -0
  82. {datadouble-0.0.7 → datadouble-0.0.8}/tests/test_programs.py +0 -0
  83. {datadouble-0.0.7 → datadouble-0.0.8}/tests/test_progress.py +0 -0
  84. {datadouble-0.0.7 → datadouble-0.0.8}/tests/test_prune_work.py +0 -0
  85. {datadouble-0.0.7 → datadouble-0.0.8}/tests/test_redaction.py +0 -0
  86. {datadouble-0.0.7 → datadouble-0.0.8}/tests/test_resolve_strict.py +0 -0
  87. {datadouble-0.0.7 → datadouble-0.0.8}/tests/test_runtime.py +0 -0
  88. {datadouble-0.0.7 → datadouble-0.0.8}/tests/test_spec.py +0 -0
  89. {datadouble-0.0.7 → datadouble-0.0.8}/tests/test_subset.py +0 -0
  90. {datadouble-0.0.7 → datadouble-0.0.8}/tests/test_transform.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: datadouble
3
- Version: 0.0.7
3
+ Version: 0.0.8
4
4
  Summary: Realistic, safe copies of production data for development and testing
5
5
  Project-URL: Homepage, https://datadouble.tightlinesoftware.com/
6
6
  Project-URL: Source, https://github.com/datadouble/datadouble
@@ -344,7 +344,8 @@ class PromoteRequest(_Groups):
344
344
 
345
345
  command: Literal[Command.PROMOTE]
346
346
  generation: Generation | None = None
347
- """The generation to promote; the newest in the build's store when omitted."""
347
+ """The generation to promote, by ID or directory name; the newest in the build's store
348
+ when omitted."""
348
349
 
349
350
 
350
351
  class FetchRequest(_Groups):
@@ -358,6 +359,7 @@ class ActivateRequest(_Groups):
358
359
 
359
360
  command: Literal[Command.ACTIVATE]
360
361
  generation: Generation
362
+ """The staged generation, by ID or directory name."""
361
363
 
362
364
 
363
365
  class ReplicateRequest(_Groups):
@@ -301,14 +301,19 @@ def _group_arguments(parser: argparse.ArgumentParser) -> None:
301
301
  def _operation_parsers(add: _Add) -> None:
302
302
  promote = add(api.Command.PROMOTE, "copy verified, signed images to the export stores")
303
303
  _group_arguments(promote)
304
- promote.add_argument("--generation", help="the generation to promote (default: the newest)")
304
+ promote.add_argument(
305
+ "--generation",
306
+ help="the generation to promote, by ID or directory name (default: the newest)",
307
+ )
305
308
  fetch = add(api.Command.FETCH, "bring new promoted images into staging")
306
309
  _group_arguments(fetch)
307
310
  activate = add(
308
311
  api.Command.ACTIVATE,
309
312
  "point the staging channel at a staged generation, such as an older one to roll back",
310
313
  )
311
- activate.add_argument("generation", help="the staged generation to point the channel at")
314
+ activate.add_argument(
315
+ "generation", help="the staged generation to point the channel at, by ID or directory name"
316
+ )
312
317
  _group_arguments(activate)
313
318
  replicate = add(
314
319
  api.Command.REPLICATE, "fill the pool, or make on-demand copies, and announce them"
@@ -908,12 +913,14 @@ def _operation_lines(
908
913
  match response:
909
914
  case api.PromoteResponse():
910
915
  return [
911
- f"promoted {p.summary.identity.prefix()}/{p.summary.identity.generation} "
916
+ f"promoted {p.summary.identity.location()} ({p.summary.identity.generation}) "
912
917
  f"to channel {p.channel} in {', '.join(p.stores)}"
913
918
  for p in response.promoted
914
919
  ]
915
920
  case api.FetchResponse():
916
- return [f"{f.prefix}: {f.status} {f.generation}" for f in response.fetched]
921
+ return [
922
+ f"{f.prefix}: {f.status} {f.directory} ({f.generation})" for f in response.fetched
923
+ ]
917
924
  case api.ActivateResponse():
918
925
  return [f"channel {c.name} now points at {c.generation}" for c in response.channels]
919
926
  case api.CopiesResponse():
@@ -931,7 +938,8 @@ def _operation_lines(
931
938
  case api.PruneResponse():
932
939
  verb = "would remove" if response.result.dry_run else "removed"
933
940
  lines = [
934
- f" {verb} {p.prefix}/{p.generation} from {p.location} ({p.bytes} bytes)"
941
+ f" {verb} {p.prefix}/{p.directory or p.generation} from {p.location}"
942
+ f" ({p.bytes} bytes)"
935
943
  for p in response.result.removed
936
944
  ]
937
945
  lines.extend(f" {verb} copy {c}" for c in response.result.copies_removed)
@@ -0,0 +1,429 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """Golden images: identity, packing, and the image summary stored beside each one.
5
+
6
+ An image is identified by spec, group, engine, engine version and generation.
7
+ Each generation of an image line has a directory of its own, named for people
8
+ to read: the build's start time in UTC and the exact server version that
9
+ built it (see :func:`generation_directory`). Each requested format is packed
10
+ there as its own compressed tar archive holding the engine's files under
11
+ ``image/`` and the build manifest as ``manifest.json``. The image summary, a
12
+ few kilobytes of JSON, sits next to the archives so it can be read without
13
+ downloading them:
14
+
15
+ shop/all/postgres-18/
16
+ 20261204T151100Z-18.1/
17
+ logical.tar.gz
18
+ physical.tar.gz
19
+ summary.json
20
+
21
+ The generation ID stays the image's identity: the summary, channels and PV
22
+ labels name it. Stores that cannot list keys, such as a web server, are read
23
+ through an index ``promote`` writes under each ``<spec>/<group>/``
24
+ (``index.json``), naming the group's image lines and, in each, the generations
25
+ with a summary and their directories.
26
+ """
27
+
28
+ import datetime as dt
29
+ import hashlib
30
+ import re
31
+ import secrets
32
+ import sys
33
+ import tarfile
34
+ import time
35
+ from collections.abc import Mapping
36
+ from pathlib import Path
37
+ from typing import Annotated, Literal
38
+
39
+ from pydantic import AfterValidator, AwareDatetime, BaseModel, ConfigDict, ValidationError
40
+
41
+ from datadouble.names import EngineName, Generation, GroupName, SpecName
42
+ from datadouble.spec import ImageFormat, Locale, Strict
43
+ from datadouble.storage import ListingUnsupportedError, Store
44
+
45
+ CODEC: Literal["gz"] = "gz"
46
+ """Compression for image archives (gzip, from the standard library)."""
47
+ _CHUNK = 1 << 20
48
+ SUMMARY = "summary.json"
49
+ """The name of the image summary in a generation's directory."""
50
+
51
+
52
+ class ImageError(Exception):
53
+ """An image archive that cannot be written or read."""
54
+
55
+
56
+ class _Model(BaseModel):
57
+ model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
58
+
59
+
60
+ def new_generation(now_ms: int | None = None) -> Generation:
61
+ """A generation ID: 12 hex digits of milliseconds since 1970, then 4 random ones.
62
+
63
+ IDs sort by build time.
64
+ """
65
+ millis = time.time_ns() // 1_000_000 if now_ms is None else now_ms
66
+ return Generation(f"{millis:012x}{secrets.token_hex(2)}")
67
+
68
+
69
+ _STAMP = "%Y%m%dT%H%M%SZ"
70
+ _UNSAFE = re.compile(r"[^A-Za-z0-9._-]")
71
+ _ID = re.compile(r"[0-9a-f]{16}")
72
+
73
+
74
+ def _one_segment(name: str) -> str:
75
+ if not re.fullmatch(r"[A-Za-z0-9._-]+", name) or name in {".", ".."}:
76
+ message = f"{name!r} is not a generation directory's name"
77
+ raise ValueError(message)
78
+ return name
79
+
80
+
81
+ DirectoryName = Annotated[str, AfterValidator(_one_segment)]
82
+ """A generation directory's name: one path segment of the characters store keys allow."""
83
+
84
+
85
+ def warn(message: str) -> None:
86
+ """Say on standard error that something was skipped; standard output stays clean."""
87
+ sys.stderr.write(f"warning: {message}\n")
88
+
89
+
90
+ def generation_time(generation: Generation) -> dt.datetime | None:
91
+ """When a generation's build started, from its ID; None if it is no generation ID."""
92
+ if not _ID.fullmatch(generation):
93
+ return None
94
+ return dt.datetime.fromtimestamp(int(generation[:12], 16) / 1000, tz=dt.UTC)
95
+
96
+
97
+ def _stamp(generation: Generation) -> str | None:
98
+ started = generation_time(generation)
99
+ return None if started is None else started.strftime(_STAMP)
100
+
101
+
102
+ def generation_directory(
103
+ generation: Generation, server_version: str, taken: Mapping[str, Generation]
104
+ ) -> str:
105
+ """The directory name of a generation in its image line.
106
+
107
+ It is the build's start time in UTC to the second, from the generation ID,
108
+ a dash, and the exact server version that built it, such as
109
+ ``20261204T151100Z-8.4.11``. Characters a store key cannot hold become
110
+ ``_``. If another generation in ``taken`` (directory to generation) holds
111
+ that name, a dash and the ID's last four hex digits follow, and if that is
112
+ taken too, a dash and the whole ID.
113
+ """
114
+ stamp = _stamp(generation)
115
+ if stamp is None:
116
+ message = f"{generation!r} is not a generation ID"
117
+ raise ImageError(message)
118
+ name = f"{stamp}-{_UNSAFE.sub('_', server_version)}"
119
+ for candidate in (name, f"{name}-{generation[-4:]}"):
120
+ if taken.get(candidate, generation) == generation:
121
+ return candidate
122
+ return f"{name}-{generation}"
123
+
124
+
125
+ class ImageIdentity(_Model):
126
+ """What an image is: the parts consumers select by, and where it is stored."""
127
+
128
+ spec: SpecName
129
+ group: GroupName
130
+ engine: EngineName
131
+ engine_version: str
132
+ """The major version of the server that restores the image."""
133
+ generation: Generation
134
+ directory: DirectoryName
135
+ """The generation's directory in its image line (:func:`generation_directory`)."""
136
+
137
+ def prefix(self) -> str:
138
+ """The store directory holding this image's generations."""
139
+ return f"{self.spec}/{self.group}/{self.engine}-{self.engine_version}"
140
+
141
+ def location(self) -> str:
142
+ """The store directory of this generation."""
143
+ return f"{self.prefix()}/{self.directory}"
144
+
145
+ def archive_key(self, image_format: ImageFormat) -> str:
146
+ """The store key of one format's archive."""
147
+ return f"{self.location()}/{image_format}.tar.{CODEC}"
148
+
149
+ def summary_key(self) -> str:
150
+ """The store key of the image summary."""
151
+ return f"{self.location()}/{SUMMARY}"
152
+
153
+ def report_key(self) -> str:
154
+ """The store key of the verification report."""
155
+ return f"{self.location()}/verify.json"
156
+
157
+ def bundle_key(self) -> str:
158
+ """The store key of the signature bundle."""
159
+ return f"{self.location()}/sigstore.json"
160
+
161
+
162
+ class Digest(_Model):
163
+ """A file's SHA-256 and size."""
164
+
165
+ sha256: str
166
+ size: int
167
+
168
+
169
+ def digest(path: Path) -> Digest:
170
+ """Hash a file."""
171
+ sha = hashlib.sha256()
172
+ with path.open("rb") as handle:
173
+ while chunk := handle.read(_CHUNK):
174
+ sha.update(chunk)
175
+ return Digest(sha256=sha.hexdigest(), size=path.stat().st_size)
176
+
177
+
178
+ class ImageArchive(_Model):
179
+ """One format of an image."""
180
+
181
+ format: ImageFormat
182
+ key: str
183
+ codec: Literal["gz"] = CODEC
184
+ digest: Digest
185
+
186
+
187
+ class Verification(_Model):
188
+ """The outcome of ``verify``, as summarized for consumers."""
189
+
190
+ passed: bool
191
+ locales: tuple[Locale, ...] = (Locale.US,)
192
+ """The locale packs the PII scan ran. Summaries written without them
193
+ come from versions whose scan had only the ``us`` checks."""
194
+ checks: int
195
+ failed: int
196
+
197
+
198
+ class ImageSummary(_Model):
199
+ """The small file stored beside each image, readable without downloading it."""
200
+
201
+ summary_format: Literal[2] = 2
202
+ identity: ImageIdentity
203
+ built_at: AwareDatetime
204
+ archives: tuple[ImageArchive, ...]
205
+ manifest_sha256: str
206
+ verification: Verification
207
+ strict: Strict
208
+ """The strict-mode levels the image was built with."""
209
+ server_version: str
210
+ """The exact version of the server that wrote the image; the identity names its line."""
211
+ accounts: tuple[str, ...] = ()
212
+ """The users of the accounts physical copies carry (``package.accounts``)."""
213
+ signature: str | None = None
214
+ """The store key of the signature bundle, if the image is signed."""
215
+
216
+
217
+ def pack(source: Path, manifest: bytes, destination: Path) -> Digest:
218
+ """Write ``source``'s contents and ``manifest`` into a compressed tar archive."""
219
+ manifest_file = destination.with_name(destination.name + ".manifest.json")
220
+ manifest_file.write_bytes(manifest)
221
+ try:
222
+ with tarfile.open(destination, "w:gz", compresslevel=6) as archive:
223
+ archive.add(manifest_file, arcname="manifest.json")
224
+ archive.add(source, arcname="image")
225
+ finally:
226
+ manifest_file.unlink(missing_ok=True)
227
+ return digest(destination)
228
+
229
+
230
+ def unpack(archive: Path, destination: Path) -> tuple[Path, bytes]:
231
+ """Extract an archive safely; return the image directory and the manifest."""
232
+ destination.mkdir(parents=True, exist_ok=True)
233
+ try:
234
+ with tarfile.open(archive, "r:gz") as opened:
235
+ opened.extractall(destination, filter="data")
236
+ except (tarfile.TarError, OSError) as error:
237
+ message = f"cannot unpack {archive.name}: {error}"
238
+ raise ImageError(message) from None
239
+ manifest = destination / "manifest.json"
240
+ image = destination / "image"
241
+ if not manifest.is_file() or not image.is_dir():
242
+ message = f"{archive.name} is not a Datadouble image"
243
+ raise ImageError(message)
244
+ return image, manifest.read_bytes()
245
+
246
+
247
+ _LINE_DEPTH = 4 # spec/group/engine-version/directory/file
248
+ INDEX = "index.json"
249
+ """The name of the index under each ``<spec>/<group>/``."""
250
+
251
+
252
+ class IndexedGeneration(_Model):
253
+ """One generation in an image index, and its directory."""
254
+
255
+ generation: Generation
256
+ directory: DirectoryName
257
+
258
+
259
+ class ImageIndex(_Model):
260
+ """A group's image lines and generations, for stores that cannot list keys."""
261
+
262
+ index_format: Literal[2] = 2
263
+ lines: dict[str, tuple[IndexedGeneration, ...]]
264
+ """Each image line (``<engine>-<version>``) and its generations with a summary, oldest
265
+ first."""
266
+
267
+
268
+ def index_key(spec: str, group: str) -> str:
269
+ """The store key of a group's index."""
270
+ return f"{spec}/{group}/{INDEX}"
271
+
272
+
273
+ def read_index(store: Store, spec: str, group: str) -> ImageIndex:
274
+ """A group's index; empty if the store has none."""
275
+ key = index_key(spec, group)
276
+ data = store.get_bytes(key)
277
+ if data is None:
278
+ return ImageIndex(lines={})
279
+ try:
280
+ return ImageIndex.model_validate_json(data)
281
+ except ValidationError:
282
+ message = f"{key} in {store.describe()} is not a valid image index"
283
+ raise ImageError(message) from None
284
+
285
+
286
+ def write_index(store: Store, spec: str, group: str) -> ImageIndex:
287
+ """List a group's image lines and generations and write them as its index."""
288
+ index = ImageIndex(
289
+ lines={
290
+ prefix.rsplit("/", 1)[1]: tuple(
291
+ IndexedGeneration(generation=generation, directory=directory)
292
+ for generation, directory in stored(store, prefix).items()
293
+ )
294
+ for prefix in image_lines(store, spec, group)
295
+ }
296
+ )
297
+ store.put_bytes(index_key(spec, group), index.model_dump_json(indent=2).encode())
298
+ return index
299
+
300
+
301
+ def image_lines(store: Store, spec: str, group: str) -> list[str]:
302
+ """The ``<spec>/<group>/<engine>-<version>`` prefixes a store holds images under.
303
+
304
+ A store that cannot list keys is read through the group's index.
305
+ """
306
+ try:
307
+ found = {
308
+ "/".join(key.split("/")[:3])
309
+ for key in store.list(f"{spec}/{group}/")
310
+ if key.endswith(f"/{SUMMARY}") and key.count("/") == _LINE_DEPTH
311
+ }
312
+ except ListingUnsupportedError:
313
+ found = {f"{spec}/{group}/{line}" for line in read_index(store, spec, group).lines}
314
+ return sorted(found, key=_version_order)
315
+
316
+
317
+ def version_key(version: str) -> tuple[int, ...]:
318
+ """A version's numbers, to compare versions numerically: ``8.4.9`` before ``8.4.13``."""
319
+ return tuple(int(part) for part in re.findall(r"[0-9]+", version))
320
+
321
+
322
+ def _version_order(prefix: str) -> tuple[int, ...]:
323
+ return version_key(prefix.rsplit("-", 1)[-1])
324
+
325
+
326
+ def line_engine(prefix: str) -> str:
327
+ """The engine of an image line, from its ``<spec>/<group>/<engine>-<version>`` prefix."""
328
+ return prefix.rsplit("/", 1)[-1].rpartition("-")[0]
329
+
330
+
331
+ def current_lines(prefixes: list[str], keep: int) -> set[str]:
332
+ """Each engine's newest ``keep`` lines; a files line is never older than a database's."""
333
+ by_engine: dict[str, list[str]] = {}
334
+ for prefix in sorted(prefixes, key=_version_order):
335
+ by_engine.setdefault(line_engine(prefix), []).append(prefix)
336
+ return {prefix for lines in by_engine.values() for prefix in lines[-keep:]}
337
+
338
+
339
+ def summary_at(store: Store, key: str) -> ImageSummary | None:
340
+ """The summary under ``key``; None if there is none, or (with a warning) it is unreadable."""
341
+ data = store.get_bytes(key)
342
+ if data is None:
343
+ return None
344
+ try:
345
+ return ImageSummary.model_validate_json(data)
346
+ except ValidationError:
347
+ # One unreadable summary, such as one an older version wrote, must not
348
+ # hide the rest of the line.
349
+ warn(f"skipping {key} in {store.describe()}: it is not a valid image summary")
350
+ return None
351
+
352
+
353
+ def _listed(store: Store, prefix: str, start: str) -> dict[Generation, ImageSummary]:
354
+ """The summaries in the generation directories under ``prefix`` named ``start...``.
355
+
356
+ A summary counts only in the directory its identity names.
357
+ """
358
+ found: dict[Generation, ImageSummary] = {}
359
+ for key in store.list(f"{prefix}/{start}"):
360
+ if key.endswith(f"/{SUMMARY}") and key.count("/") == prefix.count("/") + 2:
361
+ summary = summary_at(store, key)
362
+ if summary is not None and summary.identity.summary_key() == key:
363
+ found[summary.identity.generation] = summary
364
+ return found
365
+
366
+
367
+ def stored(store: Store, prefix: str) -> dict[Generation, str]:
368
+ """The generations with a summary under an image line, oldest first, and their directories.
369
+
370
+ A store that cannot list keys is read through the group's index.
371
+ """
372
+ try:
373
+ found = {g: s.identity.directory for g, s in _listed(store, prefix, "").items()}
374
+ except ListingUnsupportedError:
375
+ spec, group, line = prefix.split("/")
376
+ entries = read_index(store, spec, group).lines.get(line, ())
377
+ found = {entry.generation: entry.directory for entry in entries}
378
+ return dict(sorted(found.items()))
379
+
380
+
381
+ def named(directories: Mapping[Generation, str], name: str) -> Generation | None:
382
+ """The generation a name means: a generation ID, or the name of its directory."""
383
+ if name in directories:
384
+ return Generation(name)
385
+ return next((g for g, directory in directories.items() if directory == name), None)
386
+
387
+
388
+ def generations(store: Store, prefix: str) -> list[Generation]:
389
+ """The generations with a summary under an image line, oldest first."""
390
+ return list(stored(store, prefix))
391
+
392
+
393
+ def read_summary(store: Store, prefix: str, generation: Generation) -> ImageSummary | None:
394
+ """A generation's image summary, if the store has it.
395
+
396
+ A store that can list keys is searched among the directories named for the
397
+ generation's start time; one that cannot is read through the group's index.
398
+ """
399
+ stamp = _stamp(generation)
400
+ if stamp is None:
401
+ return None
402
+ try:
403
+ return _listed(store, prefix, f"{stamp}-").get(generation)
404
+ except ListingUnsupportedError:
405
+ directory = stored(store, prefix).get(generation)
406
+ if directory is None:
407
+ return None
408
+ key = f"{prefix}/{directory}/{SUMMARY}"
409
+ summary = summary_at(store, key)
410
+ if summary is None or summary.identity.summary_key() != key:
411
+ return None
412
+ return summary if summary.identity.generation == generation else None
413
+
414
+
415
+ def outdated(versions: Mapping[Generation, str]) -> set[Generation]:
416
+ """The generations built by an older server than the newest generation's.
417
+
418
+ The newest generation by build time is the reference, so it is never
419
+ outdated, even when an older server built it than built one before it.
420
+ """
421
+ if not versions:
422
+ return set()
423
+ reference = version_key(versions[max(versions)])
424
+ return {g for g, version in versions.items() if version_key(version) < reference}
425
+
426
+
427
+ def version_line(version: str, parts: int) -> str:
428
+ """The compatibility line of a server version: its first ``parts`` numbers."""
429
+ return ".".join(version.split(".")[:parts])
@@ -30,12 +30,15 @@ from datadouble.images import (
30
30
  digest,
31
31
  generations,
32
32
  image_lines,
33
+ line_engine,
34
+ named,
33
35
  read_summary,
36
+ stored,
34
37
  write_index,
35
38
  )
36
39
  from datadouble.names import Generation, GroupName
37
40
  from datadouble.signing import SigningError, bundle_key, verify
38
- from datadouble.spec import CosignTrust, Spec, Strict
41
+ from datadouble.spec import FILES, CosignTrust, Spec, Strict
39
42
  from datadouble.storage import Store
40
43
 
41
44
  if TYPE_CHECKING:
@@ -84,7 +87,7 @@ def check_signature(store: Store, summary: ImageSummary, trust: CosignTrust) ->
84
87
 
85
88
 
86
89
  def _problems(summary: ImageSummary, required: Strict) -> list[str]:
87
- name = f"{summary.identity.prefix()}/{summary.identity.generation}"
90
+ name = summary.identity.location()
88
91
  problems: list[str] = []
89
92
  verification = summary.verification
90
93
  if not verification.passed or verification.failed or not verification.checks:
@@ -115,18 +118,41 @@ class _Promotion:
115
118
  ]
116
119
  self.scratch = scratch
117
120
 
118
- def candidate(self, prefix: str, generation: Generation | None) -> _Candidate | str | None:
119
- """The image to promote from one line, the reasons it may not be, or None."""
120
- known = generations(self.source, prefix)
121
- chosen = generation or known[-1]
122
- summary = read_summary(self.source, prefix, chosen) if chosen in known else None
121
+ def chosen(
122
+ self, group: str, prefixes: list[str], name: str
123
+ ) -> tuple[Generation, list[str]] | str:
124
+ """The generation ``name`` means and the lines holding it, or why there is none.
125
+
126
+ A directory's name is looked up on the group's database lines, since the
127
+ files line's directory carries another server version; the ID it finds
128
+ then names the generation on every line. A spec with ``files`` needs it on
129
+ a files line too, as the group's lines travel together.
130
+ """
131
+ known = {prefix: stored(self.source, prefix) for prefix in prefixes}
132
+ database = [p for p in prefixes if line_engine(p) == self.spec.engine]
133
+ found = next((g for p in database if (g := named(known[p], name)) is not None), None)
134
+ if found is None:
135
+ return f"{self.spec.name}/{group}: no generation {name}"
136
+ lines = [p for p in prefixes if found in known[p]]
137
+ if self.spec.files is not None and not any(line_engine(p) == FILES for p in lines):
138
+ return f"{self.spec.name}/{group}: generation {found} has no files image"
139
+ return found, lines
140
+
141
+ def candidate(self, prefix: str, generation: Generation | None) -> _Candidate | str:
142
+ """The image to promote from one line (its newest without ``generation``), or why not."""
143
+ if generation is None:
144
+ known = generations(self.source, prefix)
145
+ if not known:
146
+ return f"{prefix}: no generation has a readable summary"
147
+ generation = known[-1]
148
+ summary = read_summary(self.source, prefix, generation)
123
149
  if summary is None:
124
- return None
150
+ return f"{prefix}: the summary of {generation} is missing"
125
151
  problems = _problems(summary, self.settings.strict)
126
152
  try:
127
153
  bundle = check_signature(self.source, summary, self.trust)
128
154
  except SigningError as error:
129
- problems.append(f"{prefix}/{summary.identity.generation}: {error}")
155
+ problems.append(f"{summary.identity.location()}: {error}")
130
156
  bundle = b""
131
157
  files: dict[str, Path] = {}
132
158
  for archive in summary.archives:
@@ -140,7 +166,7 @@ class _Promotion:
140
166
 
141
167
  def copy(self, candidate: _Candidate) -> Promoted:
142
168
  summary = candidate.summary
143
- report_key = summary.identity.summary_key().replace(".summary.json", ".verify.json")
169
+ report_key = summary.identity.report_key()
144
170
  report = self.source.get_bytes(report_key)
145
171
  for target in self.targets:
146
172
  for key, local in candidate.files.items():
@@ -151,10 +177,13 @@ class _Promotion:
151
177
  target.put_bytes(
152
178
  summary.identity.summary_key(), summary.model_dump_json(indent=2).encode()
153
179
  )
180
+ # The index names the generation's directory before the channel names
181
+ # the generation, so a fetch through the index never finds a channel
182
+ # pointing at a generation it cannot locate.
183
+ write_index(target, summary.identity.spec, summary.identity.group)
154
184
  point_channel(
155
185
  target, candidate.prefix, self.settings.channel, summary.identity.generation
156
186
  )
157
- write_index(target, summary.identity.spec, summary.identity.group)
158
187
  return Promoted(
159
188
  summary=summary,
160
189
  channel=self.settings.channel,
@@ -169,7 +198,10 @@ def promote(
169
198
  groups: tuple[GroupName, ...] = (),
170
199
  generation: Generation | None = None,
171
200
  ) -> tuple[Promoted, ...]:
172
- """Promote the newest (or the given) generation of each group; all or nothing."""
201
+ """Promote the newest (or the given) generation of each group; all or nothing.
202
+
203
+ ``generation`` is a generation ID or the name of its directory.
204
+ """
173
205
  require_inside("promote", registry)
174
206
  with tempfile.TemporaryDirectory(prefix="dd-promote-") as directory:
175
207
  promotion = _Promotion(spec, registry, Path(directory))
@@ -180,11 +212,17 @@ def promote(
180
212
  prefixes = image_lines(promotion.source, spec.name, group)
181
213
  if not prefixes:
182
214
  problems.append(f"{spec.name}/{group}: no images in {promotion.source.describe()}")
183
- found = [promotion.candidate(prefix, generation) for prefix in prefixes]
215
+ continue
216
+ if generation is None:
217
+ found = [promotion.candidate(prefix, None) for prefix in prefixes]
218
+ else:
219
+ chosen = promotion.chosen(group, prefixes, generation)
220
+ if isinstance(chosen, str):
221
+ problems.append(chosen)
222
+ continue
223
+ found = [promotion.candidate(prefix, chosen[0]) for prefix in chosen[1]]
184
224
  problems.extend(item for item in found if isinstance(item, str))
185
225
  candidates.extend(item for item in found if isinstance(item, _Candidate))
186
- if prefixes and generation is not None and all(item is None for item in found):
187
- problems.append(f"{spec.name}/{group}: no generation {generation}")
188
226
  if problems:
189
227
  raise PromoteError(tuple(problems))
190
228
  return tuple(promotion.copy(candidate) for candidate in candidates)