datadouble 0.0.3__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.
datadouble/staging.py ADDED
@@ -0,0 +1,346 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """Staging in non-production: ``fetch`` and ``activate``.
5
+
6
+ Staging is a local directory laid out like a store::
7
+
8
+ <staging>/<spec>/<group>/<engine>-<version>/
9
+ <generation>/image/ the unpacked image replicate copies from
10
+ <generation>/summary.json
11
+ channels/active.json the staging channel
12
+ copies.json copies made from this line (see replicate)
13
+
14
+ ``fetch`` reads the export store's channel and the image summary, and downloads
15
+ an image only when its generation is not staged yet. A generation is unpacked
16
+ under a temporary name and renamed when complete, under a lock, so ``replicate``
17
+ never copies a partial image. Staging keeps the newest generations, so
18
+ ``activate`` can move the staging channel back to an earlier one; a rollback
19
+ holds until a newer generation is fetched.
20
+
21
+ A spec with ``files`` has two lines per group: the database's and the files'
22
+ (decision 149). They travel together: ``fetch`` stages a generation on both or
23
+ neither, and ``activate`` moves both channels.
24
+ """
25
+
26
+ import fcntl
27
+ import os
28
+ import shutil
29
+ import uuid
30
+ from collections.abc import Generator
31
+ from contextlib import ExitStack, contextmanager
32
+ from enum import StrEnum
33
+ from pathlib import Path
34
+ from typing import TYPE_CHECKING
35
+
36
+ from pydantic import BaseModel, ConfigDict
37
+
38
+ from datadouble.channels import Channel, point_channel, read_channel
39
+ from datadouble.engine import check_owner
40
+ from datadouble.images import (
41
+ ImageSummary,
42
+ digest,
43
+ image_lines,
44
+ line_engine,
45
+ read_summary,
46
+ unpack,
47
+ )
48
+ from datadouble.names import Generation, GroupName
49
+ from datadouble.promote import check_signature
50
+ from datadouble.signing import SigningError
51
+ from datadouble.spec import FILES, CosignTrust, Fetch, ImageFormat, Spec
52
+ from datadouble.storage import FilesystemStore, Store
53
+
54
+ if TYPE_CHECKING:
55
+ from datadouble.registry import Registry
56
+
57
+
58
+ class StagingError(Exception):
59
+ """A fetch or activation that cannot go ahead."""
60
+
61
+
62
+ class FetchStatus(StrEnum):
63
+ """What ``fetch`` did for one image line."""
64
+
65
+ FETCHED = "fetched"
66
+ SKIPPED = "skipped"
67
+
68
+
69
+ class Fetched(BaseModel):
70
+ """The outcome of ``fetch`` for one image line."""
71
+
72
+ model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
73
+
74
+ prefix: str
75
+ generation: Generation
76
+ status: FetchStatus
77
+ removed: tuple[Generation, ...] = ()
78
+ """Older generations removed from staging to keep it to ``fetch.keep``."""
79
+
80
+
81
+ class Staging:
82
+ """The staging directory of one spec."""
83
+
84
+ def __init__(self, settings: Fetch) -> None:
85
+ """Use the staging directory in ``settings``."""
86
+ self.settings = settings
87
+ self.root = settings.staging
88
+ self.store = FilesystemStore(self.root, mode=0o600)
89
+ """Writes the staging channels with ``0600``; the rest of staging follows the umask."""
90
+
91
+ def line(self, prefix: str) -> Path:
92
+ """The directory of one image line."""
93
+ return self.root / prefix
94
+
95
+ def image(self, prefix: str, generation: Generation) -> Path:
96
+ """The unpacked image of a staged generation."""
97
+ return self.line(prefix) / generation / "image"
98
+
99
+ def staged(self, prefix: str) -> list[Generation]:
100
+ """Completely staged generations, oldest first."""
101
+ line = self.line(prefix)
102
+ return sorted(
103
+ Generation(path.name)
104
+ for path in line.iterdir()
105
+ if path.is_dir() and (path / "summary.json").is_file() and "." not in path.name
106
+ )
107
+
108
+ def summary(self, prefix: str, generation: Generation) -> ImageSummary:
109
+ """A staged generation's summary."""
110
+ path = self.line(prefix) / generation / "summary.json"
111
+ return ImageSummary.model_validate_json(path.read_bytes())
112
+
113
+ def channel(self, prefix: str) -> Channel | None:
114
+ """The staging channel of a line."""
115
+ return read_channel(self.store, prefix, self.settings.staging_channel)
116
+
117
+ def point(self, prefix: str, generation: Generation) -> Channel:
118
+ """Move the staging channel of a line."""
119
+ return point_channel(self.store, prefix, self.settings.staging_channel, generation)
120
+
121
+ @contextmanager
122
+ def locked(self, *prefixes: str) -> Generator[None]:
123
+ """Hold the lines' locks, in a fixed order, so one operation works on them at once."""
124
+ with ExitStack() as stack:
125
+ for prefix in sorted(set(prefixes)):
126
+ stack.enter_context(self._locked(prefix))
127
+ yield
128
+
129
+ @contextmanager
130
+ def _locked(self, prefix: str) -> Generator[None]:
131
+ line = self.line(prefix)
132
+ try:
133
+ line.mkdir(parents=True, exist_ok=True)
134
+ lock = (line / ".lock").open("w")
135
+ except OSError as error:
136
+ message = f"cannot use staging at {line}: {error.strerror}"
137
+ raise StagingError(message) from None
138
+ with lock as handle:
139
+ fcntl.flock(handle, fcntl.LOCK_EX)
140
+ try:
141
+ yield
142
+ finally:
143
+ fcntl.flock(handle, fcntl.LOCK_UN)
144
+
145
+ def lines(self, spec: str, group: str) -> list[str]:
146
+ """Image lines with anything staged, for a group."""
147
+ base = self.root / spec / group
148
+ if not base.is_dir():
149
+ return []
150
+ return sorted(f"{spec}/{group}/{path.name}" for path in base.iterdir() if path.is_dir())
151
+
152
+ def trim(self, prefix: str, keep: int) -> tuple[Generation, ...]:
153
+ """Remove all but the newest ``keep`` generations, and never the channel's target."""
154
+ channel = self.channel(prefix)
155
+ protected = {channel.generation} if channel else set[Generation]()
156
+ staged = self.staged(prefix)
157
+ removable = [g for g in staged[: max(len(staged) - keep, 0)] if g not in protected]
158
+ for generation in removable:
159
+ remove_directory(self.line(prefix) / generation)
160
+ for leftover in self.line(prefix).glob("*.partial-*"):
161
+ remove_directory(leftover)
162
+ return tuple(removable)
163
+
164
+
165
+ def remove_directory(path: Path) -> None:
166
+ """Move a directory aside and delete it, so a half-deleted one never looks staged."""
167
+ doomed = path.with_name(f"{path.name}.deleting-{uuid.uuid4().hex[:8]}")
168
+ path.rename(doomed)
169
+ shutil.rmtree(doomed, ignore_errors=True)
170
+
171
+
172
+ def choose_line(prefixes: list[str], engine_version: str | None, where: str) -> str:
173
+ """The configured engine version's line, or the newest."""
174
+ if engine_version is not None:
175
+ prefixes = [p for p in prefixes if p.rsplit("-", 1)[-1] == engine_version]
176
+ if not prefixes:
177
+ version = f" for engine version {engine_version}" if engine_version else ""
178
+ message = f"there are no images{version} in {where}"
179
+ raise StagingError(message)
180
+ return prefixes[-1]
181
+
182
+
183
+ def group_lines(spec: Spec, prefixes: list[str], where: str) -> tuple[str, ...]:
184
+ """A group's lines, which travel together: the database's, then any files line.
185
+
186
+ ``fetch.engine_version`` chooses among the database's lines; the files' line is the
187
+ newest.
188
+ """
189
+ version = spec.fetch.engine_version if spec.fetch else None
190
+ database = choose_line([p for p in prefixes if line_engine(p) == spec.engine], version, where)
191
+ if spec.files is None:
192
+ return (database,)
193
+ files = [p for p in prefixes if line_engine(p) == FILES]
194
+ if not files:
195
+ message = f"there are no files images in {where}"
196
+ raise StagingError(message)
197
+ return (database, files[-1])
198
+
199
+
200
+ def _download(
201
+ source: Store, summary: ImageSummary, image_format: ImageFormat, partial: Path
202
+ ) -> None:
203
+ archive = next((a for a in summary.archives if a.format is image_format), None)
204
+ if archive is None:
205
+ message = f"{summary.identity.summary_key()} has no {image_format} archive"
206
+ raise StagingError(message)
207
+ file = partial / "archive"
208
+ if not source.get_file(archive.key, file):
209
+ message = f"{archive.key} is missing from the export store"
210
+ raise StagingError(message)
211
+ if digest(file) != archive.digest:
212
+ message = f"{archive.key} does not match the hash in its summary"
213
+ raise StagingError(message)
214
+ unpack(file, partial)
215
+ file.unlink()
216
+
217
+
218
+ def fetch(
219
+ spec: Spec, registry: "Registry", *, groups: tuple[GroupName, ...] = ()
220
+ ) -> tuple[Fetched, ...]:
221
+ """Bring the export channel's image of each group into staging, if it is new.
222
+
223
+ A group's lines travel together: every line's channel must name the same
224
+ generation, and it is staged on all of them or none.
225
+ """
226
+ if spec.fetch is None or spec.trust is None:
227
+ message = "the spec needs `fetch` and `trust` sections to fetch images"
228
+ raise StagingError(message)
229
+ check_owner(registry.engine(spec.engine))
230
+ settings = spec.fetch
231
+ source = registry.store(*next(iter(settings.source.items())))
232
+ staging = Staging(settings)
233
+ results: list[Fetched] = []
234
+ for group in groups or tuple(spec.images):
235
+ lines = group_lines(spec, image_lines(source, spec.name, group), source.describe())
236
+ named: dict[str, Generation] = {}
237
+ for prefix in lines:
238
+ channel = read_channel(source, prefix, settings.channel)
239
+ if channel is None:
240
+ message = f"channel {settings.channel} of {prefix} has never been promoted to"
241
+ raise StagingError(message)
242
+ named[prefix] = channel.generation
243
+ if len(set(named.values())) > 1:
244
+ message = (
245
+ f"the {settings.channel} channels of {spec.name}/{group} name different"
246
+ f" generations ({', '.join(f'{p}: {g}' for p, g in named.items())});"
247
+ " promote may still be copying, so fetch again later"
248
+ )
249
+ raise StagingError(message)
250
+ with staging.locked(*lines):
251
+ results.extend(_fetch_lines(spec.trust.cosign, source, staging, lines, named[lines[0]]))
252
+ return tuple(results)
253
+
254
+
255
+ def _fetch_lines(
256
+ trust: CosignTrust,
257
+ source: Store,
258
+ staging: Staging,
259
+ lines: tuple[str, ...],
260
+ generation: Generation,
261
+ ) -> list[Fetched]:
262
+ """Stage ``generation`` on every line that lacks it, checking them all first."""
263
+ missing = {
264
+ prefix: _checked(trust, source, prefix, generation)
265
+ for prefix in lines
266
+ if generation not in staging.staged(prefix)
267
+ }
268
+ _stage(source, staging, missing, generation)
269
+ results: list[Fetched] = []
270
+ for prefix in lines:
271
+ if prefix in missing:
272
+ staging.point(prefix, generation)
273
+ removed = staging.trim(prefix, staging.settings.keep)
274
+ status = FetchStatus.FETCHED
275
+ else:
276
+ if staging.channel(prefix) is None:
277
+ staging.point(prefix, generation)
278
+ removed, status = (), FetchStatus.SKIPPED
279
+ results.append(
280
+ Fetched(prefix=prefix, generation=generation, status=status, removed=removed)
281
+ )
282
+ return results
283
+
284
+
285
+ def _checked(
286
+ trust: CosignTrust, source: Store, prefix: str, generation: Generation
287
+ ) -> ImageSummary:
288
+ """A generation's summary, with its signature checked."""
289
+ summary = read_summary(source, prefix, generation)
290
+ if summary is None:
291
+ message = f"the summary of {prefix}/{generation} is missing"
292
+ raise StagingError(message)
293
+ try:
294
+ check_signature(source, summary, trust)
295
+ except SigningError as error:
296
+ message = f"{prefix}/{generation}: {error}"
297
+ raise StagingError(message) from None
298
+ return summary
299
+
300
+
301
+ def _stage(
302
+ source: Store, staging: Staging, missing: dict[str, ImageSummary], generation: Generation
303
+ ) -> None:
304
+ """Download and unpack every line's image, then rename them all into place."""
305
+ partials: dict[str, Path] = {}
306
+ try:
307
+ for prefix, summary in missing.items():
308
+ partial = staging.line(prefix) / f"{generation}.partial-{os.getpid()}"
309
+ if partial.exists():
310
+ shutil.rmtree(partial)
311
+ partial.mkdir(parents=True)
312
+ partials[prefix] = partial
313
+ # Files images are physical only (decision 97).
314
+ image_format = (
315
+ ImageFormat.PHYSICAL if line_engine(prefix) == FILES else staging.settings.format
316
+ )
317
+ _download(source, summary, image_format, partial)
318
+ (partial / "summary.json").write_text(summary.model_dump_json(indent=2), "utf-8")
319
+ for prefix, partial in partials.items():
320
+ partial.rename(staging.line(prefix) / generation)
321
+ except BaseException:
322
+ for partial in partials.values():
323
+ shutil.rmtree(partial, ignore_errors=True)
324
+ raise
325
+
326
+
327
+ def activate(
328
+ spec: Spec, generation: Generation, *, groups: tuple[GroupName, ...] = ()
329
+ ) -> tuple[Channel, ...]:
330
+ """Point the staging channels of each group's lines at a staged generation, together."""
331
+ if spec.fetch is None:
332
+ message = "the spec needs a `fetch` section to activate a generation"
333
+ raise StagingError(message)
334
+ staging = Staging(spec.fetch)
335
+ channels: list[Channel] = []
336
+ for group in groups or tuple(spec.images):
337
+ lines = group_lines(spec, staging.lines(spec.name, group), str(staging.root))
338
+ with staging.locked(*lines):
339
+ for prefix in lines:
340
+ if generation not in staging.staged(prefix):
341
+ message = f"{generation} is not staged for {prefix}; staged: " + (
342
+ ", ".join(staging.staged(prefix)) or "none"
343
+ )
344
+ raise StagingError(message)
345
+ channels.extend(staging.point(prefix, generation) for prefix in lines)
346
+ return tuple(channels)
datadouble/storage.py ADDED
@@ -0,0 +1,222 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """Storage for finished, immutable artifacts: golden images and their summaries.
5
+
6
+ Stores are addressed by keys like ``spec/group/postgres-18/<generation>.summary.json``.
7
+ Storage adapters register under the ``datadouble.stores`` entry point group;
8
+ each entry point names a callable that takes the store's settings from the
9
+ spec and returns a :class:`Store`. The filesystem store lives here.
10
+
11
+ The filesystem store gives every file it writes its ``mode`` setting (``0640`` by
12
+ default) and every directory it creates that mode plus the search bit wherever
13
+ the mode has the read bit, whatever the umask, so another program, such as a
14
+ web server in front of an export store, can read what ``promote`` wrote.
15
+
16
+ A store that cannot list its keys, such as a web server, raises
17
+ :class:`ListingUnsupportedError` from ``list``; readers then use the index
18
+ ``promote`` writes under each ``<spec>/<group>/`` (see :mod:`datadouble.images`).
19
+ """
20
+
21
+ import os
22
+ import re
23
+ import shutil
24
+ import stat
25
+ import tempfile
26
+ from collections.abc import Mapping
27
+ from pathlib import Path
28
+ from typing import Protocol
29
+
30
+ from pydantic import BaseModel, ConfigDict, JsonValue, field_validator
31
+
32
+ from datadouble.settings import parse_settings
33
+
34
+
35
+ class StoreError(Exception):
36
+ """A store operation or configuration that failed."""
37
+
38
+
39
+ class ListingUnsupportedError(StoreError):
40
+ """A store that cannot list its keys; readers use the index ``promote`` writes."""
41
+
42
+
43
+ _KEY = re.compile(r"^[A-Za-z0-9._-]+(?:/[A-Za-z0-9._-]+)*$")
44
+
45
+
46
+ def check_key(key: str) -> str:
47
+ """Return ``key`` if it is a relative path of safe components."""
48
+ if not _KEY.match(key) or any(part in {".", ".."} for part in key.split("/")):
49
+ message = f"{key!r} is not a valid store key"
50
+ raise StoreError(message)
51
+ return key
52
+
53
+
54
+ class Store(Protocol):
55
+ """A place images are written to and read from."""
56
+
57
+ def describe(self) -> str:
58
+ """Where the store is, for manifests and messages; never includes credentials."""
59
+ ...
60
+
61
+ def put_file(self, key: str, source: Path) -> None:
62
+ """Write a file under ``key``, replacing nothing half-written on failure."""
63
+ ...
64
+
65
+ def put_bytes(self, key: str, data: bytes) -> None:
66
+ """Write bytes under ``key``."""
67
+ ...
68
+
69
+ def get_bytes(self, key: str) -> bytes | None:
70
+ """The bytes under ``key``, or None if there are none."""
71
+ ...
72
+
73
+ def get_file(self, key: str, destination: Path) -> bool:
74
+ """Copy ``key`` to ``destination``; False if there is no such key."""
75
+ ...
76
+
77
+ def list(self, prefix: str) -> list[str]:
78
+ """Keys starting with ``prefix``, sorted.
79
+
80
+ Raises :class:`ListingUnsupportedError` if the store cannot list keys.
81
+ """
82
+ ...
83
+
84
+ def delete(self, key: str) -> None:
85
+ """Remove ``key``; removing a key that does not exist is not an error."""
86
+ ...
87
+
88
+
89
+ DEFAULT_MODE = 0o640
90
+ """The mode of the files the filesystem store writes unless its ``mode`` says otherwise."""
91
+
92
+ _MODE = re.compile(r"0?[0-7]{3}")
93
+ _OWNER_READ_WRITE = stat.S_IRUSR | stat.S_IWUSR
94
+ _OTHERS_WRITE = stat.S_IWGRP | stat.S_IWOTH
95
+
96
+
97
+ def directory_mode(mode: int) -> int:
98
+ """``mode`` plus the search bit wherever it has the read bit (``0640`` gives ``0750``)."""
99
+ return mode | (mode & 0o444) >> 2
100
+
101
+
102
+ class FilesystemSettings(BaseModel):
103
+ """Settings for the filesystem store."""
104
+
105
+ model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
106
+
107
+ path: Path
108
+ mode: str = f"{DEFAULT_MODE:04o}"
109
+ """The mode of every file the store writes, as an octal string such as ``"0640"``."""
110
+
111
+ @field_validator("mode")
112
+ @classmethod
113
+ def _check_mode(cls, mode: str) -> str:
114
+ if not _MODE.fullmatch(mode):
115
+ message = "must be three octal digits with an optional leading 0, such as 0640"
116
+ raise ValueError(message)
117
+ bits = int(mode, 8)
118
+ if bits & _OWNER_READ_WRITE != _OWNER_READ_WRITE or bits & _OTHERS_WRITE:
119
+ message = "must let the owner read and write and nobody else write, such as 0640"
120
+ raise ValueError(message)
121
+ return mode
122
+
123
+ @property
124
+ def permissions(self) -> int:
125
+ """``mode`` as a number."""
126
+ return int(self.mode, 8)
127
+
128
+
129
+ class FilesystemStore:
130
+ """A directory, local or a network share. Writes go to a temporary file first."""
131
+
132
+ def __init__(self, root: Path, mode: int = DEFAULT_MODE) -> None:
133
+ """Store under ``root``, which is created if needed, writing files with ``mode``."""
134
+ self.root = root
135
+ self.mode = mode
136
+
137
+ def _path(self, key: str) -> Path:
138
+ return self.root / check_key(key)
139
+
140
+ def describe(self) -> str:
141
+ """The directory."""
142
+ return f"filesystem:{self.root}"
143
+
144
+ def _directories(self, directory: Path) -> None:
145
+ """Create ``directory`` and missing parents, each with the directory mode."""
146
+ missing: list[Path] = []
147
+ while not directory.is_dir():
148
+ missing.append(directory)
149
+ directory = directory.parent
150
+ for path in reversed(missing):
151
+ try:
152
+ path.mkdir(mode=directory_mode(self.mode))
153
+ except FileExistsError:
154
+ continue
155
+ path.chmod(directory_mode(self.mode))
156
+
157
+ def _write(self, key: str, write: "_Writer") -> None:
158
+ target = self._path(key)
159
+ try:
160
+ self._directories(target.parent)
161
+ handle, temporary = tempfile.mkstemp(dir=target.parent, prefix=".partial-")
162
+ except OSError as error:
163
+ message = f"cannot write {key} to {self.describe()}: {error.strerror}"
164
+ raise StoreError(message) from None
165
+ os.close(handle)
166
+ try:
167
+ write(Path(temporary))
168
+ try:
169
+ Path(temporary).chmod(self.mode)
170
+ except OSError as error:
171
+ message = f"cannot set the mode of {key} in {self.describe()}: {error.strerror}"
172
+ raise StoreError(message) from None
173
+ Path(temporary).replace(target)
174
+ except BaseException:
175
+ Path(temporary).unlink(missing_ok=True)
176
+ raise
177
+
178
+ def put_file(self, key: str, source: Path) -> None:
179
+ """Copy ``source`` into the store."""
180
+ self._write(key, lambda temporary: shutil.copyfile(source, temporary))
181
+
182
+ def put_bytes(self, key: str, data: bytes) -> None:
183
+ """Write ``data`` into the store."""
184
+ self._write(key, lambda temporary: temporary.write_bytes(data))
185
+
186
+ def get_bytes(self, key: str) -> bytes | None:
187
+ """Read a key's bytes."""
188
+ path = self._path(key)
189
+ return path.read_bytes() if path.is_file() else None
190
+
191
+ def get_file(self, key: str, destination: Path) -> bool:
192
+ """Copy a key out of the store."""
193
+ path = self._path(key)
194
+ if not path.is_file():
195
+ return False
196
+ shutil.copyfile(path, destination)
197
+ return True
198
+
199
+ def delete(self, key: str) -> None:
200
+ """Remove a key."""
201
+ self._path(key).unlink(missing_ok=True)
202
+
203
+ def list(self, prefix: str) -> list[str]:
204
+ """Keys under the store root starting with ``prefix``."""
205
+ if not self.root.is_dir():
206
+ return []
207
+ keys = (
208
+ path.relative_to(self.root).as_posix()
209
+ for path in self.root.rglob("*")
210
+ if path.is_file() and not path.name.startswith(".partial-")
211
+ )
212
+ return sorted(key for key in keys if key.startswith(prefix))
213
+
214
+
215
+ class _Writer(Protocol):
216
+ def __call__(self, temporary: Path, /) -> object: ...
217
+
218
+
219
+ def filesystem_store(settings: Mapping[str, JsonValue]) -> Store:
220
+ """Build a filesystem store from its spec settings (``path``, ``mode``)."""
221
+ parsed = parse_settings(FilesystemSettings, settings, "filesystem store")
222
+ return FilesystemStore(parsed.path, parsed.permissions)