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/__init__.py +10 -0
- datadouble/announce.py +380 -0
- datadouble/anonymize.py +165 -0
- datadouble/api.py +1159 -0
- datadouble/boundary.py +47 -0
- datadouble/catalog.py +677 -0
- datadouble/channels.py +62 -0
- datadouble/ci.py +1357 -0
- datadouble/cli.py +940 -0
- datadouble/closure.py +712 -0
- datadouble/engine.py +435 -0
- datadouble/files.py +78 -0
- datadouble/images.py +265 -0
- datadouble/jailer.py +403 -0
- datadouble/names.py +114 -0
- datadouble/notify.py +262 -0
- datadouble/objects.py +195 -0
- datadouble/outcome.py +27 -0
- datadouble/pii.py +109 -0
- datadouble/planner.py +1492 -0
- datadouble/programs.py +68 -0
- datadouble/promote.py +190 -0
- datadouble/prune.py +258 -0
- datadouble/py.typed +0 -0
- datadouble/redaction.py +131 -0
- datadouble/registry.py +128 -0
- datadouble/replicate.py +562 -0
- datadouble/resolve.py +201 -0
- datadouble/run.py +1075 -0
- datadouble/runtime.py +154 -0
- datadouble/secrets.py +57 -0
- datadouble/settings.py +81 -0
- datadouble/signing.py +98 -0
- datadouble/spec.py +1590 -0
- datadouble/staging.py +346 -0
- datadouble/storage.py +222 -0
- datadouble/strict.py +498 -0
- datadouble/subset.py +406 -0
- datadouble/verify.py +171 -0
- datadouble/versions.py +25 -0
- datadouble-0.0.3.dist-info/METADATA +36 -0
- datadouble-0.0.3.dist-info/RECORD +45 -0
- datadouble-0.0.3.dist-info/WHEEL +4 -0
- datadouble-0.0.3.dist-info/entry_points.txt +12 -0
- datadouble-0.0.3.dist-info/licenses/LICENSE +21 -0
datadouble/spec.py
ADDED
|
@@ -0,0 +1,1590 @@
|
|
|
1
|
+
# Copyright (c) 2026- Tight Line LLC
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""The spec: what to extract, how to anonymize it, and where images go.
|
|
5
|
+
|
|
6
|
+
Specs are written in YAML or JSON and parsed once, at the boundary, into the
|
|
7
|
+
frozen models below. :func:`spec_schema` publishes the same models as a JSON
|
|
8
|
+
Schema, so the two formats cannot disagree.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import datetime as dt
|
|
12
|
+
import hashlib
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from enum import StrEnum
|
|
17
|
+
from pathlib import Path, PurePosixPath
|
|
18
|
+
from typing import Annotated, Literal
|
|
19
|
+
|
|
20
|
+
import yaml
|
|
21
|
+
from pydantic import (
|
|
22
|
+
AwareDatetime,
|
|
23
|
+
BaseModel,
|
|
24
|
+
ConfigDict,
|
|
25
|
+
Field,
|
|
26
|
+
JsonValue,
|
|
27
|
+
TypeAdapter,
|
|
28
|
+
ValidationError,
|
|
29
|
+
field_validator,
|
|
30
|
+
model_validator,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
from datadouble.catalog import ObjectKind
|
|
34
|
+
from datadouble.names import (
|
|
35
|
+
DEFAULT_GROUP,
|
|
36
|
+
EngineName,
|
|
37
|
+
FileDigest,
|
|
38
|
+
GroupName,
|
|
39
|
+
SourceName,
|
|
40
|
+
SpecName,
|
|
41
|
+
check_name,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class SpecError(Exception):
|
|
46
|
+
"""A spec that cannot be read or does not validate."""
|
|
47
|
+
|
|
48
|
+
def __init__(self, message: str, details: tuple[tuple[str, str], ...] = ()) -> None:
|
|
49
|
+
"""Keep the per-field problems alongside the summary."""
|
|
50
|
+
super().__init__(message)
|
|
51
|
+
self.details = details
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class _Model(BaseModel):
|
|
55
|
+
model_config = ConfigDict(
|
|
56
|
+
strict=True, frozen=True, extra="forbid", use_attribute_docstrings=True
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class StrictLevel(StrEnum):
|
|
61
|
+
"""How strict mode treats tables, columns and requirements that differ from the catalog lock.
|
|
62
|
+
|
|
63
|
+
- ``off``: warn about new tables, new columns, changed columns and new
|
|
64
|
+
requirements.
|
|
65
|
+
- ``tables``: fail on new tables and new requirements, and warn about new
|
|
66
|
+
and changed columns.
|
|
67
|
+
- ``columns``: fail on new tables, new columns, changed columns and new
|
|
68
|
+
requirements. This is the default.
|
|
69
|
+
|
|
70
|
+
Requirements are the extensions, plugins and modules a source uses.
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
OFF = "off"
|
|
74
|
+
TABLES = "tables"
|
|
75
|
+
COLUMNS = "columns"
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class ObjectLevel(StrEnum):
|
|
79
|
+
"""How strict mode treats one kind of object that differs from the catalog lock.
|
|
80
|
+
|
|
81
|
+
- ``off``: compare nothing, unless a difference breaks something.
|
|
82
|
+
- ``warn``: name each new, changed or removed object. This is the default.
|
|
83
|
+
- ``fail``: fail the plan on any difference.
|
|
84
|
+
"""
|
|
85
|
+
|
|
86
|
+
OFF = "off"
|
|
87
|
+
WARN = "warn"
|
|
88
|
+
FAIL = "fail"
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class StrictKind(StrEnum):
|
|
92
|
+
"""The kinds of thing strict mode has a setting for."""
|
|
93
|
+
|
|
94
|
+
DATA = "data"
|
|
95
|
+
FUNCTIONS = "functions"
|
|
96
|
+
VIEWS = "views"
|
|
97
|
+
TRIGGERS = "triggers"
|
|
98
|
+
TYPES = "types"
|
|
99
|
+
SEQUENCES = "sequences"
|
|
100
|
+
EVENTS = "events"
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
_STRICT_ORDER: dict[StrictLevel | ObjectLevel, int] = {
|
|
104
|
+
StrictLevel.OFF: 0,
|
|
105
|
+
StrictLevel.TABLES: 1,
|
|
106
|
+
StrictLevel.COLUMNS: 2,
|
|
107
|
+
ObjectLevel.OFF: 0,
|
|
108
|
+
ObjectLevel.WARN: 1,
|
|
109
|
+
ObjectLevel.FAIL: 2,
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _yaml_off(value: object) -> object:
|
|
114
|
+
# YAML 1.1 reads `off` as false.
|
|
115
|
+
return "off" if value is False else value
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class Strict(_Model):
|
|
119
|
+
"""Strict mode's level for each kind of catalog object.
|
|
120
|
+
|
|
121
|
+
Strict mode compares the source's catalog with the catalog lock, and warns
|
|
122
|
+
or fails on what differs. Each kind has its own level. Kinds left
|
|
123
|
+
out take their defaults.
|
|
124
|
+
|
|
125
|
+
Some differences fail the plan whatever the levels: a removed table or
|
|
126
|
+
column, a table whose keys changed, a removed requirement or one at
|
|
127
|
+
another version, and any difference that breaks something.
|
|
128
|
+
"""
|
|
129
|
+
|
|
130
|
+
data: StrictLevel = StrictLevel.COLUMNS
|
|
131
|
+
"""Strict mode's level for tables, columns and requirements: ``off``,
|
|
132
|
+
``tables`` or ``columns``."""
|
|
133
|
+
functions: ObjectLevel = ObjectLevel.WARN
|
|
134
|
+
"""Strict mode's level for functions, procedures and packages of routines:
|
|
135
|
+
``off``, ``warn`` or ``fail``."""
|
|
136
|
+
views: ObjectLevel = ObjectLevel.WARN
|
|
137
|
+
"""Strict mode's level for views and materialized views: ``off``, ``warn``
|
|
138
|
+
or ``fail``."""
|
|
139
|
+
triggers: ObjectLevel = ObjectLevel.WARN
|
|
140
|
+
"""Strict mode's level for triggers: ``off``, ``warn`` or ``fail``."""
|
|
141
|
+
types: ObjectLevel = ObjectLevel.WARN
|
|
142
|
+
"""Strict mode's level for user-defined types and domains: ``off``,
|
|
143
|
+
``warn`` or ``fail``."""
|
|
144
|
+
sequences: ObjectLevel = ObjectLevel.WARN
|
|
145
|
+
"""Strict mode's level for sequences: ``off``, ``warn`` or ``fail``."""
|
|
146
|
+
events: ObjectLevel = ObjectLevel.WARN
|
|
147
|
+
"""Strict mode's level for scheduled events, such as MySQL's: ``off``,
|
|
148
|
+
``warn`` or ``fail``."""
|
|
149
|
+
|
|
150
|
+
@field_validator("*", mode="before")
|
|
151
|
+
@classmethod
|
|
152
|
+
def _off(cls, value: object) -> object:
|
|
153
|
+
return _yaml_off(value)
|
|
154
|
+
|
|
155
|
+
def level(self, kind: StrictKind) -> StrictLevel | ObjectLevel:
|
|
156
|
+
"""The level set for ``kind``."""
|
|
157
|
+
level: StrictLevel | ObjectLevel = getattr(self, kind.value)
|
|
158
|
+
return level
|
|
159
|
+
|
|
160
|
+
def weaker(self, required: "Strict") -> tuple[StrictKind, ...]:
|
|
161
|
+
"""The kinds whose level here is less strict than ``required``'s."""
|
|
162
|
+
return tuple(
|
|
163
|
+
kind
|
|
164
|
+
for kind in StrictKind
|
|
165
|
+
if _STRICT_ORDER[self.level(kind)] < _STRICT_ORDER[required.level(kind)]
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
def failing(self) -> bool:
|
|
169
|
+
"""Whether any kind of object is set to ``fail``."""
|
|
170
|
+
return any(self.level(kind) is ObjectLevel.FAIL for kind in StrictKind)
|
|
171
|
+
|
|
172
|
+
@classmethod
|
|
173
|
+
def lowest(cls) -> "Strict":
|
|
174
|
+
"""Every kind at ``off``: what a build without a catalog lock compared."""
|
|
175
|
+
off = ObjectLevel.OFF
|
|
176
|
+
return cls(
|
|
177
|
+
data=StrictLevel.OFF,
|
|
178
|
+
functions=off,
|
|
179
|
+
views=off,
|
|
180
|
+
triggers=off,
|
|
181
|
+
types=off,
|
|
182
|
+
sequences=off,
|
|
183
|
+
events=off,
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
class StrictOverrides(_Model):
|
|
188
|
+
"""Levels a request sets over the spec's ``strict``, for the kinds it names."""
|
|
189
|
+
|
|
190
|
+
data: StrictLevel | None = None
|
|
191
|
+
functions: ObjectLevel | None = None
|
|
192
|
+
views: ObjectLevel | None = None
|
|
193
|
+
triggers: ObjectLevel | None = None
|
|
194
|
+
types: ObjectLevel | None = None
|
|
195
|
+
sequences: ObjectLevel | None = None
|
|
196
|
+
events: ObjectLevel | None = None
|
|
197
|
+
|
|
198
|
+
@field_validator("*", mode="before")
|
|
199
|
+
@classmethod
|
|
200
|
+
def _off(cls, value: object) -> object:
|
|
201
|
+
return _yaml_off(value)
|
|
202
|
+
|
|
203
|
+
def over(self, strict: Strict) -> Strict:
|
|
204
|
+
"""``strict`` with these levels in place of its own."""
|
|
205
|
+
return strict.model_copy(update=self.model_dump(exclude_none=True))
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _strict_mapping(value: object) -> object:
|
|
209
|
+
match value:
|
|
210
|
+
case str() | False:
|
|
211
|
+
message = (
|
|
212
|
+
"`strict` is a mapping of levels per kind, such as `strict: {data: tables}`; "
|
|
213
|
+
"kinds left out take their defaults"
|
|
214
|
+
)
|
|
215
|
+
raise ValueError(message)
|
|
216
|
+
case _:
|
|
217
|
+
return value
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
class Strategy(StrEnum):
|
|
221
|
+
"""How the planner computes the subset. The subsetting design explains both strategies.
|
|
222
|
+
|
|
223
|
+
- ``auto``: nested queries when the selection graph has no cycle, the
|
|
224
|
+
engine can run them, and no reference joins two sources. Keys
|
|
225
|
+
otherwise. This is the default.
|
|
226
|
+
- ``nested``: strategy A. One nested query per table, pushed down to the
|
|
227
|
+
source.
|
|
228
|
+
- ``keys``: strategy B. Collect keys, compute the closure of rows to copy,
|
|
229
|
+
then fetch the rows by key.
|
|
230
|
+
"""
|
|
231
|
+
|
|
232
|
+
AUTO = "auto"
|
|
233
|
+
NESTED = "nested"
|
|
234
|
+
KEYS = "keys"
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
class Unselected(StrEnum):
|
|
238
|
+
"""What happens to a kept table that no seed or followed reference selects.
|
|
239
|
+
|
|
240
|
+
- ``fail``: fail the plan, naming each such table. This is the default.
|
|
241
|
+
- ``none``: copy none of the table's rows, and warn.
|
|
242
|
+
- ``all``: copy every row of the table.
|
|
243
|
+
"""
|
|
244
|
+
|
|
245
|
+
FAIL = "fail"
|
|
246
|
+
NONE = "none"
|
|
247
|
+
ALL = "all"
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
class ImageFormat(StrEnum):
|
|
251
|
+
"""The golden image formats.
|
|
252
|
+
|
|
253
|
+
- ``physical``: the engine's own on-disk form. It is the fastest to clone
|
|
254
|
+
and start, but it is tied to the server version.
|
|
255
|
+
- ``logical``: a portable export, which restores into other server
|
|
256
|
+
versions.
|
|
257
|
+
"""
|
|
258
|
+
|
|
259
|
+
PHYSICAL = "physical"
|
|
260
|
+
LOGICAL = "logical"
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
class OnMissing(StrEnum):
|
|
264
|
+
"""What to do with a reference whose parent row is not followed.
|
|
265
|
+
|
|
266
|
+
- ``null``: set the referencing columns to null.
|
|
267
|
+
- ``stub``: insert a placeholder parent row.
|
|
268
|
+
- ``drop``: leave the referencing row out.
|
|
269
|
+
"""
|
|
270
|
+
|
|
271
|
+
NULL = "null"
|
|
272
|
+
STUB = "stub"
|
|
273
|
+
DROP = "drop"
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
class FakerKind(StrEnum):
|
|
277
|
+
"""The kinds of fake value the ``faker`` strategy generates."""
|
|
278
|
+
|
|
279
|
+
FIRST_NAME = "first_name"
|
|
280
|
+
LAST_NAME = "last_name"
|
|
281
|
+
NAME = "name"
|
|
282
|
+
EMAIL = "email"
|
|
283
|
+
USER_NAME = "user_name"
|
|
284
|
+
PHONE_NUMBER = "phone_number"
|
|
285
|
+
STREET_ADDRESS = "street_address"
|
|
286
|
+
CITY = "city"
|
|
287
|
+
POSTCODE = "postcode"
|
|
288
|
+
COMPANY = "company"
|
|
289
|
+
IPV4 = "ipv4"
|
|
290
|
+
URL = "url"
|
|
291
|
+
TEXT = "text"
|
|
292
|
+
DATE_OF_BIRTH = "date_of_birth"
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
# Secrets are referred to, never written into specs.
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
class EnvSecret(_Model):
|
|
299
|
+
"""A secret read from an environment variable, written ``{env: NAME}``."""
|
|
300
|
+
|
|
301
|
+
env: str = Field(min_length=1)
|
|
302
|
+
"""The environment variable that holds the secret. Must not be empty."""
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
class FileSecret(_Model):
|
|
306
|
+
"""A secret read from a file, such as a mounted Kubernetes Secret, written ``{file: PATH}``."""
|
|
307
|
+
|
|
308
|
+
file: Path
|
|
309
|
+
"""The path of the file that holds the secret."""
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
type SecretRef = Annotated[
|
|
313
|
+
EnvSecret | FileSecret,
|
|
314
|
+
Field(
|
|
315
|
+
description=(
|
|
316
|
+
"A reference to a secret, so that the spec never holds the secret itself. "
|
|
317
|
+
"`{env: NAME}` reads it from an environment variable, and `{file: PATH}` "
|
|
318
|
+
"reads it from a file."
|
|
319
|
+
)
|
|
320
|
+
),
|
|
321
|
+
]
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
class Source(_Model):
|
|
325
|
+
"""One server to copy from.
|
|
326
|
+
|
|
327
|
+
Datadouble checks the fields below. The engine adapter checks the settings
|
|
328
|
+
inside ``connection`` and ``server``, since only it knows their fields. Its
|
|
329
|
+
README lists them.
|
|
330
|
+
"""
|
|
331
|
+
|
|
332
|
+
engine: EngineName
|
|
333
|
+
"""The engine adapter that reads this source, such as ``postgres``. Every
|
|
334
|
+
source of a spec must use the same one."""
|
|
335
|
+
connection: dict[str, JsonValue] = Field(default_factory=dict[str, JsonValue])
|
|
336
|
+
"""Where the server is and what to read. The engine adapter checks these
|
|
337
|
+
settings."""
|
|
338
|
+
image: str | None = None
|
|
339
|
+
"""The vendor image that working databases and engine tools run in. By
|
|
340
|
+
default, the engine adapter picks the official image for the newest
|
|
341
|
+
source's version. Either every source gives the same image, or none does."""
|
|
342
|
+
server: dict[str, JsonValue] = Field(default_factory=dict[str, JsonValue])
|
|
343
|
+
"""Settings for the engine's working servers, such as PostgreSQL's
|
|
344
|
+
``shared_preload_libraries``. The engine adapter checks them. Every source
|
|
345
|
+
must give the same settings, because one working server holds every source."""
|
|
346
|
+
omit: tuple[str, ...] = ()
|
|
347
|
+
"""Requirements this source uses that copies leave out, by name.
|
|
348
|
+
Requirements are extensions, plugins and modules. Anything that uses an
|
|
349
|
+
omitted requirement must be excluded too, or the build fails."""
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
class Follow(_Model):
|
|
353
|
+
"""Which references to follow down, from parent rows to their child rows.
|
|
354
|
+
|
|
355
|
+
Parents of copied rows are always copied. Children are copied only along
|
|
356
|
+
the edges listed here.
|
|
357
|
+
"""
|
|
358
|
+
|
|
359
|
+
down: tuple[str, ...] = ()
|
|
360
|
+
"""Child edges to follow, each written ``parent -> child``. Write
|
|
361
|
+
``parent -> child.column`` to name the referencing column."""
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
class EdgePolicy(_Model):
|
|
365
|
+
"""What to do with one reference, keyed ``child.column -> parent`` in ``subset.edges``.
|
|
366
|
+
|
|
367
|
+
Give exactly one of ``follow: all`` or ``on_missing``.
|
|
368
|
+
"""
|
|
369
|
+
|
|
370
|
+
follow: Literal["all"] | None = None
|
|
371
|
+
"""``all`` copies every row of the parent table, not only the referenced
|
|
372
|
+
ones. Give this or ``on_missing``, not both."""
|
|
373
|
+
on_missing: OnMissing | None = None
|
|
374
|
+
"""What to do when the referenced parent row is not followed: ``null``,
|
|
375
|
+
``stub`` or ``drop``. Give this or ``follow: all``, not both."""
|
|
376
|
+
|
|
377
|
+
@field_validator("on_missing", mode="before")
|
|
378
|
+
@classmethod
|
|
379
|
+
def _yaml_null(cls, value: object) -> object:
|
|
380
|
+
# `on_missing: null` in YAML is a null value, not the string "null".
|
|
381
|
+
# Defaults are not validated, so None here was written explicitly.
|
|
382
|
+
return OnMissing.NULL.value if value is None else value
|
|
383
|
+
|
|
384
|
+
@model_validator(mode="after")
|
|
385
|
+
def _exactly_one(self) -> "EdgePolicy":
|
|
386
|
+
if (self.follow is None) == (self.on_missing is None):
|
|
387
|
+
message = "give exactly one of `follow: all` or `on_missing`"
|
|
388
|
+
raise ValueError(message)
|
|
389
|
+
return self
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
class VirtualForeignKey(_Model):
|
|
393
|
+
"""A reference the schema does not declare.
|
|
394
|
+
|
|
395
|
+
In ``subset.virtual_fks``, each is keyed ``child.column -> parent``.
|
|
396
|
+
Subsetting follows it like a declared foreign key, for every row or only
|
|
397
|
+
for the rows ``when`` selects.
|
|
398
|
+
"""
|
|
399
|
+
|
|
400
|
+
when: str | None = None
|
|
401
|
+
"""A condition on the child row, in the source's own query language. The
|
|
402
|
+
reference holds only for rows that match it, such as
|
|
403
|
+
``subject_type = 'Post'`` for a polymorphic reference. Without it, the
|
|
404
|
+
reference holds for every row."""
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
class JailerSubset(_Model):
|
|
408
|
+
"""A subset designed in Jailer's GUI, which Datadouble reads again on every run.
|
|
409
|
+
|
|
410
|
+
The Jailer compatibility page explains what Datadouble takes from it.
|
|
411
|
+
"""
|
|
412
|
+
|
|
413
|
+
model: Path
|
|
414
|
+
"""The Jailer extraction model, a ``.jm`` file."""
|
|
415
|
+
datamodel: Path
|
|
416
|
+
"""The Jailer data model folder that the model was designed against."""
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
class Subset(_Model):
|
|
420
|
+
"""Which rows to copy.
|
|
421
|
+
|
|
422
|
+
You give starting conditions, called seeds, and say which references to
|
|
423
|
+
follow. The planner derives every other table's rows from them. Instead,
|
|
424
|
+
``jailer`` can name a subset designed in Jailer.
|
|
425
|
+
"""
|
|
426
|
+
|
|
427
|
+
as_of: AwareDatetime | None = None
|
|
428
|
+
"""The anchor time that conditions refer to as ``:as_of``, with a time
|
|
429
|
+
zone. The plan resolves it once, so every query uses the same time.
|
|
430
|
+
Defaults to the moment the generation started, to the second, which
|
|
431
|
+
resuming keeps. For ``datadouble plan`` alone, the moment it runs."""
|
|
432
|
+
strategy: Strategy = Strategy.AUTO
|
|
433
|
+
"""How the planner computes the subset: ``auto``, ``nested`` or ``keys``.
|
|
434
|
+
The ``--strategy`` option overrides it."""
|
|
435
|
+
seeds: dict[str, str] = Field(default_factory=dict[str, str])
|
|
436
|
+
"""Starting conditions, in the source's own query language, by table. Keys
|
|
437
|
+
are table names or globs, such as ``"*": "TRUE"``. A table's own name wins
|
|
438
|
+
over a glob."""
|
|
439
|
+
follow: Follow = Follow()
|
|
440
|
+
"""Which references to follow down from parent rows to child rows, listed
|
|
441
|
+
under ``down``. Parents of copied rows are always copied."""
|
|
442
|
+
edges: dict[str, EdgePolicy] = Field(default_factory=dict[str, EdgePolicy])
|
|
443
|
+
"""What to do with particular references, keyed ``child.column -> parent``:
|
|
444
|
+
copy every parent row with ``follow: all``, or fall back with
|
|
445
|
+
``on_missing``."""
|
|
446
|
+
virtual_fks: dict[str, VirtualForeignKey] = Field(default_factory=dict[str, VirtualForeignKey])
|
|
447
|
+
"""References the schema does not declare, keyed ``child.column -> parent``.
|
|
448
|
+
Subsetting follows them like declared foreign keys."""
|
|
449
|
+
unselected: Unselected | None = None
|
|
450
|
+
"""What happens to a kept table that no seed or followed reference selects:
|
|
451
|
+
``fail``, ``none`` or ``all``. Defaults to ``fail``. With ``jailer``, a
|
|
452
|
+
table that Jailer doesn't reach keeps no rows, as with ``none``."""
|
|
453
|
+
jailer: JailerSubset | None = None
|
|
454
|
+
"""A subset designed in Jailer. It replaces ``seeds``, ``follow``,
|
|
455
|
+
``edges``, ``virtual_fks`` and ``unselected``, so a spec cannot give both."""
|
|
456
|
+
|
|
457
|
+
@model_validator(mode="after")
|
|
458
|
+
def _one_source(self) -> "Subset":
|
|
459
|
+
if self.jailer is not None and (
|
|
460
|
+
self.seeds
|
|
461
|
+
or self.follow.down
|
|
462
|
+
or self.edges
|
|
463
|
+
or self.virtual_fks
|
|
464
|
+
or self.unselected is not None
|
|
465
|
+
):
|
|
466
|
+
message = (
|
|
467
|
+
"a subset from Jailer cannot also have seeds, follow, edges, virtual_fks "
|
|
468
|
+
"or unselected; change the Jailer model, or import it "
|
|
469
|
+
"(datadouble import-jailer) and edit that"
|
|
470
|
+
)
|
|
471
|
+
raise ValueError(message)
|
|
472
|
+
return self
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
class FakerRule(_Model):
|
|
476
|
+
"""Replace each value with a deterministic fake value, such as ``{faker: email}``.
|
|
477
|
+
|
|
478
|
+
The same input gets the same fake value of a kind in every table, so joins
|
|
479
|
+
on the column still match. In a ``unique`` column, a value whose fake
|
|
480
|
+
collides with another's gets a different one.
|
|
481
|
+
"""
|
|
482
|
+
|
|
483
|
+
faker: FakerKind
|
|
484
|
+
"""The kind of fake value to generate, such as ``name`` or ``email``."""
|
|
485
|
+
unique: bool = False
|
|
486
|
+
"""Whether every fake value in the column must be different. The generator
|
|
487
|
+
retries until it finds an unused value, or fails the run."""
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
class HashOptions(_Model):
|
|
491
|
+
"""Options for the ``hash`` strategy."""
|
|
492
|
+
|
|
493
|
+
length: int = Field(default=16, ge=8, le=64)
|
|
494
|
+
"""How many hexadecimal characters the hash has, from 8 to 64. In integer
|
|
495
|
+
columns, the hash is a 32-bit integer instead."""
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
class HashRule(_Model):
|
|
499
|
+
"""Replace each value with a keyed hash, so equal inputs stay equal."""
|
|
500
|
+
|
|
501
|
+
hash: HashOptions
|
|
502
|
+
"""Options for the hash. Write ``{}`` to take the defaults."""
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
class NullOptions(_Model):
|
|
506
|
+
"""The ``null`` strategy has no options, so it is written ``null: {}``."""
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
class NullRule(_Model):
|
|
510
|
+
"""Set each value to null."""
|
|
511
|
+
|
|
512
|
+
null: NullOptions
|
|
513
|
+
"""No options: write ``{}``."""
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
class FormatPreservingOptions(_Model):
|
|
517
|
+
"""Options for the ``format_preserving`` strategy."""
|
|
518
|
+
|
|
519
|
+
luhn: bool = False
|
|
520
|
+
"""Whether to keep the Luhn check digit valid, as card numbers need."""
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
class FormatPreservingRule(_Model):
|
|
524
|
+
"""Replace digits with digits and letters with letters, so each value keeps its shape."""
|
|
525
|
+
|
|
526
|
+
format_preserving: FormatPreservingOptions
|
|
527
|
+
"""Options for the strategy. Write ``{}`` to take the defaults."""
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
class ExpressionRule(_Model):
|
|
531
|
+
"""Replace each value with an engine-native expression over the row.
|
|
532
|
+
|
|
533
|
+
A ``where`` condition can limit the change to some rows.
|
|
534
|
+
"""
|
|
535
|
+
|
|
536
|
+
expression: str = Field(min_length=1)
|
|
537
|
+
"""The new value, as an expression in the engine's own language, such as
|
|
538
|
+
SQL for PostgreSQL. Must not be empty."""
|
|
539
|
+
where: str | None = None
|
|
540
|
+
"""A condition in the engine's own language. Only rows that match it
|
|
541
|
+
change. Without it, every row changes."""
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
type Rule = Annotated[
|
|
545
|
+
FakerRule | HashRule | NullRule | FormatPreservingRule | ExpressionRule,
|
|
546
|
+
Field(
|
|
547
|
+
union_mode="left_to_right",
|
|
548
|
+
description=(
|
|
549
|
+
"One column's anonymization rule. It names exactly one strategy: `faker`, "
|
|
550
|
+
"`hash`, `null`, `format_preserving` or `expression`."
|
|
551
|
+
),
|
|
552
|
+
),
|
|
553
|
+
]
|
|
554
|
+
|
|
555
|
+
|
|
556
|
+
class Hook(_Model):
|
|
557
|
+
"""A native script run before load, such as one that sets server settings or adds extensions."""
|
|
558
|
+
|
|
559
|
+
sql: str = Field(min_length=1)
|
|
560
|
+
"""The script, in the engine's own language. Must not be empty."""
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
class TransformHook(_Model):
|
|
564
|
+
"""A native script run after the column rules, which declares the columns it rewrites."""
|
|
565
|
+
|
|
566
|
+
sql: str = Field(min_length=1)
|
|
567
|
+
"""The script, in the engine's own language. Must not be empty."""
|
|
568
|
+
rewrites: tuple[str, ...] = ()
|
|
569
|
+
"""The columns the script rewrites, as ``table.column``. The plan fails if
|
|
570
|
+
one names a column the source doesn't have, and the transform stage
|
|
571
|
+
records them. Datadouble takes the list on trust, and ``verify`` checks
|
|
572
|
+
the result."""
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
class Hooks(_Model):
|
|
576
|
+
"""Native scripts run around load and transform.
|
|
577
|
+
|
|
578
|
+
Not every engine supports hooks. The plan fails if a spec gives
|
|
579
|
+
hooks to an engine that doesn't.
|
|
580
|
+
"""
|
|
581
|
+
|
|
582
|
+
before_load: tuple[Hook, ...] = ()
|
|
583
|
+
"""Scripts run in each working database before the copied data is loaded."""
|
|
584
|
+
after_transform: tuple[TransformHook, ...] = ()
|
|
585
|
+
"""Scripts run after every column rule, and before ``package`` and
|
|
586
|
+
``verify``, so verification covers what they change."""
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
type ObjectRoot = Annotated[
|
|
590
|
+
dict[ObjectKind, str],
|
|
591
|
+
Field(
|
|
592
|
+
min_length=1,
|
|
593
|
+
max_length=1,
|
|
594
|
+
description=(
|
|
595
|
+
"An object that code outside Datadouble expects in an image, written as its "
|
|
596
|
+
"kind and its name: `{function: public.uuid_generate_v4}`. Names match from "
|
|
597
|
+
"the right, like table names. Where routines are overloaded, add the argument "
|
|
598
|
+
'types as the catalog spells them: `{function: "public.total(integer)"}`. '
|
|
599
|
+
"A PostgreSQL trigger's name is `table.trigger`, as in "
|
|
600
|
+
"`{trigger: orders.audit}`."
|
|
601
|
+
),
|
|
602
|
+
),
|
|
603
|
+
]
|
|
604
|
+
|
|
605
|
+
|
|
606
|
+
class PulledRows(StrEnum):
|
|
607
|
+
"""Which rows of a table a standalone group pulls into its image.
|
|
608
|
+
|
|
609
|
+
- ``referenced``: the rows that the image's rows reference, plus the rows
|
|
610
|
+
that reference them where the spec follows references down. This is the
|
|
611
|
+
default.
|
|
612
|
+
- ``all``: every row of the source table.
|
|
613
|
+
- ``none``: no rows, only the table's structure.
|
|
614
|
+
"""
|
|
615
|
+
|
|
616
|
+
REFERENCED = "referenced"
|
|
617
|
+
ALL = "all"
|
|
618
|
+
NONE = "none"
|
|
619
|
+
|
|
620
|
+
|
|
621
|
+
class ImageGroup(_Model):
|
|
622
|
+
"""One image built from the shared extract.
|
|
623
|
+
|
|
624
|
+
The image holds the tables that the group's ``include`` patterns match.
|
|
625
|
+
"""
|
|
626
|
+
|
|
627
|
+
include: tuple[str, ...] = Field(min_length=1)
|
|
628
|
+
"""The tables in the image, as globs matched from the right. At least one
|
|
629
|
+
is needed."""
|
|
630
|
+
requires: tuple[GroupName, ...] = ()
|
|
631
|
+
"""Other groups that this group's references may point into. A reference
|
|
632
|
+
from this group to rows in another group fails the plan unless that group
|
|
633
|
+
is listed here, directly or through a listed group's own ``requires``, or
|
|
634
|
+
the reference has ``on_missing: null``. A reference with ``on_missing:
|
|
635
|
+
stub`` or ``drop`` cannot leave its group at all. Each listed group must
|
|
636
|
+
be a group in ``images``. A standalone group cannot have any."""
|
|
637
|
+
standalone: bool = False
|
|
638
|
+
"""Whether the image must work on its own. If true, package planning pulls
|
|
639
|
+
into the image whatever its tables and objects need from outside the
|
|
640
|
+
group."""
|
|
641
|
+
objects: tuple[ObjectRoot, ...] = ()
|
|
642
|
+
"""Objects that code outside Datadouble expects in this image, such as
|
|
643
|
+
``{function: public.uuid_generate_v4}``. They join the image's closure,
|
|
644
|
+
the set of everything the image must contain."""
|
|
645
|
+
rows: dict[str, PulledRows] = Field(default_factory=dict[str, PulledRows])
|
|
646
|
+
"""Which rows a standalone group pulls in, in place of the default
|
|
647
|
+
``referenced``. Keys are a table name or glob, or a reference
|
|
648
|
+
``child.column -> parent``, which wins over a table key. Values are
|
|
649
|
+
``referenced``, ``all`` or ``none``. Needs ``standalone: true``."""
|
|
650
|
+
|
|
651
|
+
@model_validator(mode="after")
|
|
652
|
+
def _alone(self) -> "ImageGroup":
|
|
653
|
+
if self.standalone and self.requires:
|
|
654
|
+
message = "a standalone group works on its own, so it cannot also have `requires`"
|
|
655
|
+
raise ValueError(message)
|
|
656
|
+
if self.rows and not self.standalone:
|
|
657
|
+
message = "`rows` says what a standalone group pulls in; set `standalone: true`"
|
|
658
|
+
raise ValueError(message)
|
|
659
|
+
return self
|
|
660
|
+
|
|
661
|
+
|
|
662
|
+
class AccountPrivileges(StrEnum):
|
|
663
|
+
"""The privileges of a copy account.
|
|
664
|
+
|
|
665
|
+
- ``all``: every privilege, with the grant option. On PostgreSQL, this is
|
|
666
|
+
a superuser. This is the default.
|
|
667
|
+
- ``read``: ``SELECT`` on the image's data, plus what the engine gives
|
|
668
|
+
every user.
|
|
669
|
+
"""
|
|
670
|
+
|
|
671
|
+
ALL = "all"
|
|
672
|
+
READ = "read"
|
|
673
|
+
|
|
674
|
+
|
|
675
|
+
class CopyAccount(_Model):
|
|
676
|
+
"""An account that every copy of a physical image carries, so consumers can log in over TCP."""
|
|
677
|
+
|
|
678
|
+
user: str = Field(min_length=1)
|
|
679
|
+
"""The account's user name. Must not be empty."""
|
|
680
|
+
password: Annotated[str, Field(min_length=1)] | SecretRef
|
|
681
|
+
"""The account's password: plain text, since copies hold no personal
|
|
682
|
+
data, or a secret reference."""
|
|
683
|
+
privileges: AccountPrivileges = AccountPrivileges.ALL
|
|
684
|
+
"""What the account may do: ``all`` (every privilege, with the grant
|
|
685
|
+
option) or ``read`` (``SELECT`` on the image's data)."""
|
|
686
|
+
|
|
687
|
+
|
|
688
|
+
class Package(_Model):
|
|
689
|
+
"""Which image formats to produce, and the database accounts built into physical images."""
|
|
690
|
+
|
|
691
|
+
formats: tuple[ImageFormat, ...] | None = Field(default=None, min_length=1)
|
|
692
|
+
"""The image formats to produce: ``physical``, ``logical`` or both. If
|
|
693
|
+
given, the list must not be empty. Defaults to every format the engine
|
|
694
|
+
supports. The ``--format`` option overrides it."""
|
|
695
|
+
accounts: tuple[CopyAccount, ...] = ()
|
|
696
|
+
"""Database accounts built into physical images, for consumers that serve
|
|
697
|
+
them with the engine's own image. None by default."""
|
|
698
|
+
|
|
699
|
+
|
|
700
|
+
class PiiScan(_Model):
|
|
701
|
+
"""Values the PII scan accepts on purpose."""
|
|
702
|
+
|
|
703
|
+
allow: dict[str, tuple[str, ...]] = Field(default_factory=dict[str, tuple[str, ...]])
|
|
704
|
+
"""``LIKE`` patterns of values the scan accepts, by column, such as
|
|
705
|
+
``users.email: ["%@company.com"]``. A value that a detector flags and no
|
|
706
|
+
pattern covers still fails verification."""
|
|
707
|
+
|
|
708
|
+
|
|
709
|
+
class Assertion(_Model):
|
|
710
|
+
"""A native query that must return no rows for the image to pass verification."""
|
|
711
|
+
|
|
712
|
+
name: str = Field(min_length=1)
|
|
713
|
+
"""The assertion's name, as the verification report shows it. Must not be
|
|
714
|
+
empty."""
|
|
715
|
+
sql: str = Field(min_length=1)
|
|
716
|
+
"""The query, in the engine's own language. Any row it returns fails
|
|
717
|
+
verification. Must not be empty."""
|
|
718
|
+
|
|
719
|
+
|
|
720
|
+
class Verify(_Model):
|
|
721
|
+
"""Verification settings, beyond the checks that always run."""
|
|
722
|
+
|
|
723
|
+
pii_scan: PiiScan = PiiScan()
|
|
724
|
+
"""Values the PII scan accepts on purpose, listed under ``allow``."""
|
|
725
|
+
assertions: tuple[Assertion, ...] = ()
|
|
726
|
+
"""Native queries that must return no rows."""
|
|
727
|
+
|
|
728
|
+
|
|
729
|
+
type AdapterSettings = Annotated[
|
|
730
|
+
dict[str, dict[str, JsonValue]],
|
|
731
|
+
Field(
|
|
732
|
+
description=(
|
|
733
|
+
"One adapter and its settings, as a mapping with a single key that names the "
|
|
734
|
+
"adapter, such as `{s3: {bucket: ...}}`. The adapter checks its own settings, "
|
|
735
|
+
"and its README lists them."
|
|
736
|
+
)
|
|
737
|
+
),
|
|
738
|
+
]
|
|
739
|
+
|
|
740
|
+
|
|
741
|
+
def _one_adapter(value: AdapterSettings) -> AdapterSettings:
|
|
742
|
+
if len(value) != 1:
|
|
743
|
+
message = "name exactly one adapter, as a mapping with a single key"
|
|
744
|
+
raise ValueError(message)
|
|
745
|
+
return value
|
|
746
|
+
|
|
747
|
+
|
|
748
|
+
class CosignSigning(_Model):
|
|
749
|
+
"""Signing with cosign.
|
|
750
|
+
|
|
751
|
+
Give exactly one of ``key``, to sign with a key pair, or ``keyless: true``,
|
|
752
|
+
to sign with the CI system's identity.
|
|
753
|
+
"""
|
|
754
|
+
|
|
755
|
+
key: SecretRef | None = None
|
|
756
|
+
"""The private key, in cosign's encrypted format, as a secret reference.
|
|
757
|
+
Its password comes from the ``COSIGN_PASSWORD`` environment variable."""
|
|
758
|
+
keyless: bool = False
|
|
759
|
+
"""Whether to sign without a key, through the CI system's identity token.
|
|
760
|
+
Only GitHub Actions jobs get one, so ``ci init`` refuses a keyless ``build``
|
|
761
|
+
job on other systems."""
|
|
762
|
+
transparency_log: bool = True
|
|
763
|
+
"""Whether to record signatures in the transparency log. Turn it off only
|
|
764
|
+
where the log cannot be reached."""
|
|
765
|
+
|
|
766
|
+
@model_validator(mode="after")
|
|
767
|
+
def _one_way(self) -> "CosignSigning":
|
|
768
|
+
if (self.key is None) != self.keyless:
|
|
769
|
+
message = "give exactly one of `key` or `keyless: true`"
|
|
770
|
+
raise ValueError(message)
|
|
771
|
+
return self
|
|
772
|
+
|
|
773
|
+
|
|
774
|
+
class Signing(_Model):
|
|
775
|
+
"""How ``store`` signs images."""
|
|
776
|
+
|
|
777
|
+
cosign: CosignSigning
|
|
778
|
+
"""Sign with cosign, using a key pair or the CI system's identity."""
|
|
779
|
+
|
|
780
|
+
|
|
781
|
+
class CosignTrust(_Model):
|
|
782
|
+
"""Which cosign signatures ``promote`` and ``fetch`` accept.
|
|
783
|
+
|
|
784
|
+
Give either ``public_key``, for key-pair signatures, or both ``identity``
|
|
785
|
+
and ``issuer``, for keyless signatures.
|
|
786
|
+
"""
|
|
787
|
+
|
|
788
|
+
public_key: SecretRef | None = None
|
|
789
|
+
"""For key-pair signatures: the public key that signatures must verify
|
|
790
|
+
against, as a secret reference."""
|
|
791
|
+
identity: str | None = None
|
|
792
|
+
"""For keyless signatures: the signer's certificate identity, matched
|
|
793
|
+
exactly. Give ``issuer`` with it."""
|
|
794
|
+
issuer: str | None = None
|
|
795
|
+
"""For keyless signatures: the OpenID Connect (OIDC) issuer, matched
|
|
796
|
+
exactly. Give ``identity`` with it."""
|
|
797
|
+
transparency_log: bool = True
|
|
798
|
+
"""Whether to require a transparency log entry. Turn it off only for
|
|
799
|
+
signatures made without one."""
|
|
800
|
+
|
|
801
|
+
@model_validator(mode="after")
|
|
802
|
+
def _one_way(self) -> "CosignTrust":
|
|
803
|
+
keyless = self.identity is not None and self.issuer is not None
|
|
804
|
+
partial = (self.identity is None) != (self.issuer is None)
|
|
805
|
+
if partial or (self.public_key is None) != keyless:
|
|
806
|
+
message = "give either `public_key`, or both `identity` and `issuer`"
|
|
807
|
+
raise ValueError(message)
|
|
808
|
+
return self
|
|
809
|
+
|
|
810
|
+
|
|
811
|
+
class Trust(_Model):
|
|
812
|
+
"""The signatures images must carry to cross into non-production."""
|
|
813
|
+
|
|
814
|
+
cosign: CosignTrust
|
|
815
|
+
"""Accept cosign signatures made with a given key or identity."""
|
|
816
|
+
|
|
817
|
+
|
|
818
|
+
class Promote(_Model):
|
|
819
|
+
"""Where ``promote`` copies verified images, and what it requires of them."""
|
|
820
|
+
|
|
821
|
+
to: tuple[AdapterSettings, ...] = Field(min_length=1)
|
|
822
|
+
"""The export stores, one adapter each, such as ``{filesystem: ...}`` or
|
|
823
|
+
``{s3: ...}``. At least one is needed. A filesystem store's ``mode``
|
|
824
|
+
(``"0640"`` by default) decides who can read the files, such as a web
|
|
825
|
+
server that serves them. Each store also gets an index of its images per
|
|
826
|
+
group, ``<spec>/<group>/index.json``. Stores that cannot list keys, like
|
|
827
|
+
``http``, are read through that index."""
|
|
828
|
+
channel: str = "latest"
|
|
829
|
+
"""The channel ``promote`` points at each image it copies to the export
|
|
830
|
+
stores. A channel name is 1 to 63 lowercase letters, digits, ``-`` or
|
|
831
|
+
``_``, starting with a letter or digit."""
|
|
832
|
+
strict: Strict = Strict()
|
|
833
|
+
"""The least strict level, per kind, that an image may have been built
|
|
834
|
+
with. ``promote`` refuses an image built with a lower level. By default,
|
|
835
|
+
``data: columns`` and ``warn`` for each kind of object."""
|
|
836
|
+
|
|
837
|
+
@field_validator("strict", mode="before")
|
|
838
|
+
@classmethod
|
|
839
|
+
def _strict(cls, value: object) -> object:
|
|
840
|
+
return _strict_mapping(value)
|
|
841
|
+
|
|
842
|
+
@field_validator("to")
|
|
843
|
+
@classmethod
|
|
844
|
+
def _stores(cls, value: tuple[AdapterSettings, ...]) -> tuple[AdapterSettings, ...]:
|
|
845
|
+
return tuple(_one_adapter(entry) for entry in value)
|
|
846
|
+
|
|
847
|
+
@field_validator("channel")
|
|
848
|
+
@classmethod
|
|
849
|
+
def _channel(cls, value: str) -> str:
|
|
850
|
+
return check_name("channel", value)
|
|
851
|
+
|
|
852
|
+
|
|
853
|
+
class Fetch(_Model):
|
|
854
|
+
"""Where ``fetch`` reads images from, and where it keeps them."""
|
|
855
|
+
|
|
856
|
+
model_config = ConfigDict(
|
|
857
|
+
strict=True,
|
|
858
|
+
frozen=True,
|
|
859
|
+
extra="forbid",
|
|
860
|
+
validate_by_name=True,
|
|
861
|
+
use_attribute_docstrings=True,
|
|
862
|
+
)
|
|
863
|
+
|
|
864
|
+
source: AdapterSettings = Field(alias="from")
|
|
865
|
+
"""The export store to read, as one adapter: ``{filesystem: ...}``,
|
|
866
|
+
``{s3: ...}`` or ``{http: ...}``. The ``http`` store reads from a web
|
|
867
|
+
server that serves the export store. It is read-only, and reads the index
|
|
868
|
+
that ``promote`` writes."""
|
|
869
|
+
staging: Path
|
|
870
|
+
"""The staging directory that ``fetch`` unpacks images into, for
|
|
871
|
+
``replicate`` to copy from."""
|
|
872
|
+
channel: str = "latest"
|
|
873
|
+
"""The export stores' channel to fetch. A channel name is 1 to 63
|
|
874
|
+
lowercase letters, digits, ``-`` or ``_``, starting with a letter or
|
|
875
|
+
digit."""
|
|
876
|
+
staging_channel: str = "active"
|
|
877
|
+
"""The channel in staging that ``fetch`` points at each new image.
|
|
878
|
+
``replicate`` copies from it, and ``activate`` moves it. It follows the
|
|
879
|
+
same naming rules as ``channel``."""
|
|
880
|
+
format: ImageFormat = ImageFormat.PHYSICAL
|
|
881
|
+
"""Which image format to fetch: ``physical`` or ``logical``."""
|
|
882
|
+
engine_version: str | None = None
|
|
883
|
+
"""Which compatibility line's images to fetch, such as ``8.4`` (not
|
|
884
|
+
``8.4.13``). Defaults to the newest line."""
|
|
885
|
+
keep: int = Field(default=3, ge=1)
|
|
886
|
+
"""How many generations staging keeps, so ``activate`` can roll back to
|
|
887
|
+
them. At least 1."""
|
|
888
|
+
|
|
889
|
+
@field_validator("source")
|
|
890
|
+
@classmethod
|
|
891
|
+
def _store(cls, value: AdapterSettings) -> AdapterSettings:
|
|
892
|
+
return _one_adapter(value)
|
|
893
|
+
|
|
894
|
+
@field_validator("channel", "staging_channel")
|
|
895
|
+
@classmethod
|
|
896
|
+
def _channels(cls, value: str) -> str:
|
|
897
|
+
return check_name("channel", value)
|
|
898
|
+
|
|
899
|
+
|
|
900
|
+
class ReplicateMode(StrEnum):
|
|
901
|
+
"""How ``replicate`` decides how many copies to make.
|
|
902
|
+
|
|
903
|
+
- ``pool``: keep a number of unclaimed copies of the active generation
|
|
904
|
+
ready. This is the default.
|
|
905
|
+
- ``on-demand``: make copies for a named requester.
|
|
906
|
+
"""
|
|
907
|
+
|
|
908
|
+
POOL = "pool"
|
|
909
|
+
ON_DEMAND = "on-demand"
|
|
910
|
+
|
|
911
|
+
|
|
912
|
+
class Replicate(_Model):
|
|
913
|
+
"""How copies are made from staging."""
|
|
914
|
+
|
|
915
|
+
using: AdapterSettings
|
|
916
|
+
"""The replicate adapter that makes the copies, such as
|
|
917
|
+
``{docker-volume: {...}}``. Its README lists its settings."""
|
|
918
|
+
mode: ReplicateMode = ReplicateMode.POOL
|
|
919
|
+
"""How ``replicate`` decides how many copies to make: ``pool`` or
|
|
920
|
+
``on-demand``."""
|
|
921
|
+
size: int = Field(default=2, ge=1)
|
|
922
|
+
"""In pool mode, how many unclaimed copies to keep ready. In on-demand
|
|
923
|
+
mode, how many copies each owner gets. At least 1."""
|
|
924
|
+
expires_hours: int = Field(default=24, ge=1)
|
|
925
|
+
"""How many hours an on-demand copy lives before ``release --expired``
|
|
926
|
+
removes it. At least 1."""
|
|
927
|
+
|
|
928
|
+
@field_validator("using")
|
|
929
|
+
@classmethod
|
|
930
|
+
def _adapter(cls, value: AdapterSettings) -> AdapterSettings:
|
|
931
|
+
return _one_adapter(value)
|
|
932
|
+
|
|
933
|
+
|
|
934
|
+
class Retention(_Model):
|
|
935
|
+
"""What ``prune`` keeps.
|
|
936
|
+
|
|
937
|
+
An image line is one image group's images for one engine version, such as
|
|
938
|
+
``postgres-18``. For each image line, ``prune`` keeps the newest ``keep``
|
|
939
|
+
generations, anything built within ``keep_days``, and whatever a channel
|
|
940
|
+
points at. It never removes a channel's target.
|
|
941
|
+
"""
|
|
942
|
+
|
|
943
|
+
keep: int = Field(default=3, ge=1)
|
|
944
|
+
"""How many of the newest generations each image line keeps. At least 1.
|
|
945
|
+
In staging, ``fetch.keep`` applies instead."""
|
|
946
|
+
keep_days: int = Field(default=7, ge=0)
|
|
947
|
+
"""Keep every generation built within this many days. 0 or more."""
|
|
948
|
+
keep_versions: int = Field(default=2, ge=1)
|
|
949
|
+
"""How many of a group's newest engine versions keep their generations,
|
|
950
|
+
counted for each engine apart, so a files line is never an old version of
|
|
951
|
+
the database's. Older versions keep only their channels' targets, and lose
|
|
952
|
+
their unclaimed pool copies. At least 1."""
|
|
953
|
+
|
|
954
|
+
|
|
955
|
+
class Secrets(_Model):
|
|
956
|
+
"""Secrets the run needs, by reference."""
|
|
957
|
+
|
|
958
|
+
anonymization_key: SecretRef | None = None
|
|
959
|
+
"""The key that seeds deterministic anonymization, as a secret reference.
|
|
960
|
+
Without it, Datadouble generates a random key for each generation."""
|
|
961
|
+
|
|
962
|
+
|
|
963
|
+
class NotifyOn(StrEnum):
|
|
964
|
+
"""The outcomes of a generated CI job that send a notification.
|
|
965
|
+
|
|
966
|
+
- ``failure``: the job failed.
|
|
967
|
+
- ``warning``: the job finished with warnings.
|
|
968
|
+
- ``recovery``: the job succeeded, and its previous run did not (it
|
|
969
|
+
failed, warned or was aborted).
|
|
970
|
+
|
|
971
|
+
``notify.when`` is ``[failure]`` by default.
|
|
972
|
+
"""
|
|
973
|
+
|
|
974
|
+
FAILURE = "failure"
|
|
975
|
+
WARNING = "warning"
|
|
976
|
+
RECOVERY = "recovery"
|
|
977
|
+
|
|
978
|
+
|
|
979
|
+
class WebhookFormat(StrEnum):
|
|
980
|
+
"""The JSON body a webhook receives.
|
|
981
|
+
|
|
982
|
+
- ``json``: every field (``spec``, ``job``, ``outcome``, ``recovered``,
|
|
983
|
+
``generation``, ``error``, ``run_url``) and a ``text`` line built from
|
|
984
|
+
them, for a receiver written for Datadouble.
|
|
985
|
+
- ``chat``: only ``{"text": ...}``, for chat incoming webhooks (Google
|
|
986
|
+
Chat, Slack, Mattermost, Rocket.Chat). Google Chat refuses any other
|
|
987
|
+
key, so it needs ``chat``.
|
|
988
|
+
|
|
989
|
+
``format`` is ``json`` by default.
|
|
990
|
+
"""
|
|
991
|
+
|
|
992
|
+
JSON = "json"
|
|
993
|
+
CHAT = "chat"
|
|
994
|
+
|
|
995
|
+
|
|
996
|
+
class Webhook(_Model):
|
|
997
|
+
"""A URL that Datadouble posts a JSON summary of the job's outcome to."""
|
|
998
|
+
|
|
999
|
+
url: SecretRef
|
|
1000
|
+
"""The webhook's URL, as a secret reference, since the URL usually carries
|
|
1001
|
+
its credential."""
|
|
1002
|
+
format: WebhookFormat = WebhookFormat.JSON
|
|
1003
|
+
"""The body to post: ``json`` (every field and a ``text`` line) or
|
|
1004
|
+
``chat`` (only ``text``, for chat incoming webhooks)."""
|
|
1005
|
+
|
|
1006
|
+
|
|
1007
|
+
class WebhookTarget(_Model):
|
|
1008
|
+
"""A webhook target, such as ``{webhook: {url: {env: ALERTS_WEBHOOK}}}``."""
|
|
1009
|
+
|
|
1010
|
+
webhook: Webhook
|
|
1011
|
+
"""The webhook to post to."""
|
|
1012
|
+
|
|
1013
|
+
|
|
1014
|
+
class Email(_Model):
|
|
1015
|
+
"""Mail sent by the CI system's own mechanism, where it has one."""
|
|
1016
|
+
|
|
1017
|
+
to: tuple[Annotated[str, Field(pattern=r"^[^@\s]+@[^@\s]+$")], ...] = Field(min_length=1)
|
|
1018
|
+
"""The addresses to mail. At least one is needed."""
|
|
1019
|
+
|
|
1020
|
+
|
|
1021
|
+
class EmailTarget(_Model):
|
|
1022
|
+
"""An email target, such as ``{email: {to: [data-team@example.com]}}``."""
|
|
1023
|
+
|
|
1024
|
+
email: Email
|
|
1025
|
+
"""The mail to send."""
|
|
1026
|
+
|
|
1027
|
+
|
|
1028
|
+
type NotifyTarget = Annotated[
|
|
1029
|
+
WebhookTarget | EmailTarget,
|
|
1030
|
+
Field(description="Where one notification goes: `{webhook: ...}` or `{email: ...}`."),
|
|
1031
|
+
]
|
|
1032
|
+
|
|
1033
|
+
|
|
1034
|
+
class Notify(_Model):
|
|
1035
|
+
"""Notifications for generated CI jobs that fail, warn or recover (decisions 125, 142).
|
|
1036
|
+
|
|
1037
|
+
Notifications live in the spec rather than in ``ci init``'s options, so
|
|
1038
|
+
generating the jobs again keeps them.
|
|
1039
|
+
"""
|
|
1040
|
+
|
|
1041
|
+
when: tuple[NotifyOn, ...] = Field(default=(NotifyOn.FAILURE,), min_length=1)
|
|
1042
|
+
"""The outcomes that send a notification: ``failure``, ``warning``,
|
|
1043
|
+
``recovery``, or any of them together. Defaults to ``[failure]``."""
|
|
1044
|
+
to: tuple[NotifyTarget, ...] = Field(min_length=1)
|
|
1045
|
+
"""Where notifications go, one target each: ``{webhook: ...}`` or
|
|
1046
|
+
``{email: ...}``. At least one is needed."""
|
|
1047
|
+
|
|
1048
|
+
def sends(self, outcome: str, *, recovered: bool = False) -> bool:
|
|
1049
|
+
"""Whether a job ending with ``outcome`` notifies; ``recovered`` for a recovery."""
|
|
1050
|
+
if recovered and NotifyOn.RECOVERY in self.when:
|
|
1051
|
+
return True
|
|
1052
|
+
return outcome in {str(kind) for kind in self.when}
|
|
1053
|
+
|
|
1054
|
+
@property
|
|
1055
|
+
def recovers(self) -> bool:
|
|
1056
|
+
"""Whether a webhook hears of recoveries, so jobs record their outcomes (decision 142)."""
|
|
1057
|
+
return NotifyOn.RECOVERY in self.when and bool(self.webhooks())
|
|
1058
|
+
|
|
1059
|
+
def webhooks(self) -> tuple[Webhook, ...]:
|
|
1060
|
+
"""The webhook targets, in order."""
|
|
1061
|
+
return tuple(t.webhook for t in self.to if isinstance(t, WebhookTarget))
|
|
1062
|
+
|
|
1063
|
+
def emails(self) -> tuple[str, ...]:
|
|
1064
|
+
"""Every address the email targets name, in order, without repeats."""
|
|
1065
|
+
found = [a for t in self.to if isinstance(t, EmailTarget) for a in t.email.to]
|
|
1066
|
+
return tuple(dict.fromkeys(found))
|
|
1067
|
+
|
|
1068
|
+
|
|
1069
|
+
class PathsFrom(_Model):
|
|
1070
|
+
"""A template that builds file paths from a table's columns.
|
|
1071
|
+
|
|
1072
|
+
For example, ``path: "documents/{customer_id}/{file_name}"`` builds a path
|
|
1073
|
+
from two columns. ``match``, if given, is a regular expression applied to
|
|
1074
|
+
the result, whose first group is the path. Use it for values such as URLs.
|
|
1075
|
+
"""
|
|
1076
|
+
|
|
1077
|
+
table: str
|
|
1078
|
+
"""The table whose selected rows hold the file paths."""
|
|
1079
|
+
path: str = Field(min_length=1)
|
|
1080
|
+
"""A template that builds a value from the row's columns, such as
|
|
1081
|
+
``documents/{customer_id}/{file_name}``. Without ``match``, the value is the
|
|
1082
|
+
path, relative to the tree's root. Must not be empty."""
|
|
1083
|
+
match: str | None = None
|
|
1084
|
+
"""A regular expression applied to the value ``path`` builds. Its first
|
|
1085
|
+
group is the path. Use it for values such as URLs."""
|
|
1086
|
+
|
|
1087
|
+
|
|
1088
|
+
FILES = EngineName("files")
|
|
1089
|
+
"""The engine that copies a ``files`` section's tree."""
|
|
1090
|
+
FILES_SOURCE = SourceName("files")
|
|
1091
|
+
"""The name of the ``files`` section's build's one source."""
|
|
1092
|
+
|
|
1093
|
+
|
|
1094
|
+
class Files(_Model):
|
|
1095
|
+
"""A file tree that the source's rows refer to, copied beside them (decision 97).
|
|
1096
|
+
|
|
1097
|
+
The ``files`` engine adapter reads the tree. Each top-level directory is a
|
|
1098
|
+
table, and ``select`` gives each one ``find`` tests. Every top-level
|
|
1099
|
+
directory must be selected or excluded.
|
|
1100
|
+
"""
|
|
1101
|
+
|
|
1102
|
+
connection: dict[str, JsonValue] = Field(default_factory=dict[str, JsonValue])
|
|
1103
|
+
"""Where the tree is and how to read it. The ``files`` adapter checks these
|
|
1104
|
+
settings."""
|
|
1105
|
+
select: dict[str, str] = Field(default_factory=dict[str, str])
|
|
1106
|
+
"""The ``find`` tests that choose each top-level directory's files, such as
|
|
1107
|
+
``-type f -mtime -30``."""
|
|
1108
|
+
exclude: tuple[str, ...] = ()
|
|
1109
|
+
"""Top-level directories to leave out."""
|
|
1110
|
+
paths_from: str | PathsFrom | None = None
|
|
1111
|
+
"""Which files the source's selected rows reference, relative to the
|
|
1112
|
+
tree's root. Either a ``table.column`` that holds paths, or a template
|
|
1113
|
+
with ``table``, ``path`` and optionally ``match``."""
|
|
1114
|
+
cleanup: tuple[str, ...] = ()
|
|
1115
|
+
"""Shell commands run in the root of the tree's working copy during
|
|
1116
|
+
``transform``, before the image is packaged and verified, such as one that
|
|
1117
|
+
removes EXIF data."""
|
|
1118
|
+
image: str | None = None
|
|
1119
|
+
"""The container image that the cleanup commands run in. Defaults to a
|
|
1120
|
+
Debian image."""
|
|
1121
|
+
|
|
1122
|
+
|
|
1123
|
+
class Spec(_Model):
|
|
1124
|
+
"""A complete spec, which describes one pipeline."""
|
|
1125
|
+
|
|
1126
|
+
model_config = ConfigDict(title="Datadouble spec")
|
|
1127
|
+
|
|
1128
|
+
name: SpecName
|
|
1129
|
+
"""The spec's name, the first part of every image's identity. It is 1 to
|
|
1130
|
+
63 lowercase letters, digits, ``-`` or ``_``, starting with a letter or
|
|
1131
|
+
digit."""
|
|
1132
|
+
sources: dict[SourceName, Source] = Field(min_length=1)
|
|
1133
|
+
"""The servers to copy from, by name. At least one is needed, and every
|
|
1134
|
+
source uses the same engine. All sources' databases go into one working
|
|
1135
|
+
server, so their names must not collide. Each source is read under its own
|
|
1136
|
+
snapshot. Source names follow the same rules as the spec's name."""
|
|
1137
|
+
exclude: tuple[str, ...] = ()
|
|
1138
|
+
"""Tables left out of every image, as globs matched from the right. For
|
|
1139
|
+
example, ``audit.*`` is every table in a namespace ``audit``, and
|
|
1140
|
+
``shop.*.*`` is every table in PostgreSQL's database ``shop``."""
|
|
1141
|
+
structure_only: tuple[str, ...] = ()
|
|
1142
|
+
"""Tables copied without their rows, as globs matched from the right."""
|
|
1143
|
+
case_sensitive: bool = False
|
|
1144
|
+
"""Whether table and column names match case-sensitively."""
|
|
1145
|
+
strict: Strict = Strict()
|
|
1146
|
+
"""How strict mode treats differences from the catalog lock, as a mapping
|
|
1147
|
+
of levels per kind. ``data`` takes ``off``, ``tables`` or ``columns``.
|
|
1148
|
+
``functions``, ``views``, ``triggers``, ``types``, ``sequences`` and
|
|
1149
|
+
``events`` take ``off``, ``warn`` or ``fail``. Kinds left out take their
|
|
1150
|
+
defaults."""
|
|
1151
|
+
subset: Subset = Subset()
|
|
1152
|
+
"""Which rows to copy: seeds, the references to follow, and what to do
|
|
1153
|
+
with the references not followed."""
|
|
1154
|
+
anonymize: dict[str, dict[str, Rule]] = Field(default_factory=dict[str, dict[str, Rule]])
|
|
1155
|
+
"""Anonymization rules, by table and then by column. Each rule uses one
|
|
1156
|
+
strategy: ``faker``, ``hash``, ``null``, ``format_preserving`` or
|
|
1157
|
+
``expression``."""
|
|
1158
|
+
hooks: Hooks = Hooks()
|
|
1159
|
+
"""Native scripts run before load and after transform."""
|
|
1160
|
+
files: Files | None = None
|
|
1161
|
+
"""A file tree copied with the rows, as a second source."""
|
|
1162
|
+
images: dict[GroupName, ImageGroup] = Field(
|
|
1163
|
+
default_factory=lambda: {DEFAULT_GROUP: ImageGroup(include=("*",))}
|
|
1164
|
+
)
|
|
1165
|
+
"""The images built from one extract, by group name. Defaults to one
|
|
1166
|
+
group, ``all``, that holds every table. Group names follow the same rules
|
|
1167
|
+
as the spec's name."""
|
|
1168
|
+
objects: tuple[ObjectRoot, ...] = ()
|
|
1169
|
+
"""Objects that code outside Datadouble expects in every image, such as
|
|
1170
|
+
``{view: reporting.daily}``. They join each image's closure."""
|
|
1171
|
+
package: Package = Package()
|
|
1172
|
+
"""The image formats to produce, and the database accounts built into physical images."""
|
|
1173
|
+
verify: Verify = Verify()
|
|
1174
|
+
"""Checks every image must pass. Each image must restore, its row counts
|
|
1175
|
+
and references must match, the PII scan must find nothing it doesn't
|
|
1176
|
+
allow, and every assertion must return no rows. This section sets the PII
|
|
1177
|
+
scan's allowed values and the assertions."""
|
|
1178
|
+
runtime: AdapterSettings | None = None
|
|
1179
|
+
"""Where engine software runs, from extract on: ``{docker: {...}}`` or
|
|
1180
|
+
``{kubernetes: {...}}``. Extract and the stages after it need it. The
|
|
1181
|
+
``kubernetes`` runtime reaches another cluster through ``kubeconfig``, a
|
|
1182
|
+
secret reference. It starts pods in the namespace given by ``namespace``.
|
|
1183
|
+
Without it, pods start where ``kubectl`` would put them: inside a cluster,
|
|
1184
|
+
the namespace of Datadouble's own pod, and otherwise the kubeconfig
|
|
1185
|
+
context's namespace."""
|
|
1186
|
+
store: tuple[dict[str, dict[str, JsonValue]], ...] = ()
|
|
1187
|
+
"""Where the build stores images, one adapter each: ``{filesystem: ...}`` or
|
|
1188
|
+
``{s3: ...}``. The filesystem store takes ``path``, a directory, and
|
|
1189
|
+
``mode``, an octal string that defaults to ``"0640"``. Every file it writes
|
|
1190
|
+
gets ``mode``, whatever the umask. Directories it creates get ``mode`` plus
|
|
1191
|
+
the search bit wherever it has the read bit (``0750`` for ``0640``). Modes
|
|
1192
|
+
that let anyone but the owner write, or that don't let the owner read and
|
|
1193
|
+
write, are refused."""
|
|
1194
|
+
signing: Signing | None = None
|
|
1195
|
+
"""How the build signs its images."""
|
|
1196
|
+
trust: Trust | None = None
|
|
1197
|
+
"""Which signatures ``promote`` and ``fetch`` accept."""
|
|
1198
|
+
promote: Promote | None = None
|
|
1199
|
+
"""The export stores that ``promote`` copies verified images to, and what
|
|
1200
|
+
it requires of them."""
|
|
1201
|
+
fetch: Fetch | None = None
|
|
1202
|
+
"""Where ``fetch`` reads promoted images, and the staging directory it
|
|
1203
|
+
fills."""
|
|
1204
|
+
replicate: Replicate | None = None
|
|
1205
|
+
"""How copies are made: the adapter, the mode (pool or on-demand), and how
|
|
1206
|
+
many."""
|
|
1207
|
+
announce: tuple[AdapterSettings, ...] = ()
|
|
1208
|
+
"""Where copies are announced to consumers, one adapter each:
|
|
1209
|
+
``{dotenv: ...}``, ``{ci-outputs: {}}``, ``{vault: ...}`` or
|
|
1210
|
+
``{k8s-secret: {}}``. The ``k8s-secret`` adapter writes Secrets in the
|
|
1211
|
+
namespace given by ``namespace``, and otherwise where ``kubectl`` would
|
|
1212
|
+
put them, as the ``kubernetes`` runtime does."""
|
|
1213
|
+
prune: Retention = Retention()
|
|
1214
|
+
"""What ``prune`` keeps: how many generations, for how many days, and how
|
|
1215
|
+
many engine versions."""
|
|
1216
|
+
secrets: Secrets = Secrets()
|
|
1217
|
+
"""Secrets the build needs, by reference."""
|
|
1218
|
+
notify: Notify | None = None
|
|
1219
|
+
"""Notifications for generated CI jobs that fail, warn or recover: webhooks and email."""
|
|
1220
|
+
|
|
1221
|
+
@property
|
|
1222
|
+
def engine(self) -> EngineName:
|
|
1223
|
+
"""The engine every source uses."""
|
|
1224
|
+
return next(iter(self.sources.values())).engine
|
|
1225
|
+
|
|
1226
|
+
@property
|
|
1227
|
+
def working(self) -> Source:
|
|
1228
|
+
"""The first source, whose ``image`` and ``server`` every source shares."""
|
|
1229
|
+
return next(iter(self.sources.values()))
|
|
1230
|
+
|
|
1231
|
+
@field_validator("sources")
|
|
1232
|
+
@classmethod
|
|
1233
|
+
def _sources(cls, value: dict[SourceName, Source]) -> dict[SourceName, Source]:
|
|
1234
|
+
for name in value:
|
|
1235
|
+
check_name("source name", name)
|
|
1236
|
+
first_name, first = next(iter(value.items()))
|
|
1237
|
+
for name, source in value.items():
|
|
1238
|
+
if source.engine != first.engine:
|
|
1239
|
+
message = (
|
|
1240
|
+
f"every source must use one engine: source {first_name} is {first.engine}"
|
|
1241
|
+
f" and source {name} is {source.engine}"
|
|
1242
|
+
)
|
|
1243
|
+
raise ValueError(message)
|
|
1244
|
+
for setting in ("image", "server"):
|
|
1245
|
+
if getattr(source, setting) != getattr(first, setting):
|
|
1246
|
+
message = (
|
|
1247
|
+
f"sources {first_name} and {name} give different `{setting}` settings;"
|
|
1248
|
+
" one working server holds every source, so give each the same one"
|
|
1249
|
+
)
|
|
1250
|
+
raise ValueError(message)
|
|
1251
|
+
return value
|
|
1252
|
+
|
|
1253
|
+
def files_spec(self) -> "Spec | None":
|
|
1254
|
+
"""The spec of the ``files`` section's build, sharing this one's images and storage."""
|
|
1255
|
+
if self.files is None:
|
|
1256
|
+
return None
|
|
1257
|
+
files = self.files
|
|
1258
|
+
return Spec(
|
|
1259
|
+
name=self.name,
|
|
1260
|
+
sources={
|
|
1261
|
+
FILES_SOURCE: Source(engine=FILES, connection=files.connection, image=files.image)
|
|
1262
|
+
},
|
|
1263
|
+
exclude=files.exclude,
|
|
1264
|
+
case_sensitive=self.case_sensitive,
|
|
1265
|
+
# Every top-level directory must be selected or excluded instead.
|
|
1266
|
+
strict=Strict(data=StrictLevel.OFF),
|
|
1267
|
+
subset=Subset(as_of=self.subset.as_of, seeds=files.select),
|
|
1268
|
+
hooks=Hooks(after_transform=tuple(TransformHook(sql=line) for line in files.cleanup)),
|
|
1269
|
+
# File trees have no objects for a group to declare.
|
|
1270
|
+
images={
|
|
1271
|
+
name: group.model_copy(update={"objects": ()})
|
|
1272
|
+
for name, group in self.images.items()
|
|
1273
|
+
},
|
|
1274
|
+
# Accounts belong to the source's physical images, not the files'.
|
|
1275
|
+
package=self.package.model_copy(update={"accounts": ()}),
|
|
1276
|
+
runtime=self.runtime,
|
|
1277
|
+
store=self.store,
|
|
1278
|
+
signing=self.signing,
|
|
1279
|
+
secrets=self.secrets,
|
|
1280
|
+
)
|
|
1281
|
+
|
|
1282
|
+
@field_validator("runtime")
|
|
1283
|
+
@classmethod
|
|
1284
|
+
def _runtime(cls, value: AdapterSettings | None) -> AdapterSettings | None:
|
|
1285
|
+
return None if value is None else _one_adapter(value)
|
|
1286
|
+
|
|
1287
|
+
@field_validator("announce")
|
|
1288
|
+
@classmethod
|
|
1289
|
+
def _announcers(cls, value: tuple[AdapterSettings, ...]) -> tuple[AdapterSettings, ...]:
|
|
1290
|
+
return tuple(_one_adapter(entry) for entry in value)
|
|
1291
|
+
|
|
1292
|
+
@field_validator("strict", mode="before")
|
|
1293
|
+
@classmethod
|
|
1294
|
+
def _strict(cls, value: object) -> object:
|
|
1295
|
+
return _strict_mapping(value)
|
|
1296
|
+
|
|
1297
|
+
@field_validator("name")
|
|
1298
|
+
@classmethod
|
|
1299
|
+
def _name(cls, value: SpecName) -> SpecName:
|
|
1300
|
+
return SpecName(check_name("spec name", value))
|
|
1301
|
+
|
|
1302
|
+
@field_validator("images")
|
|
1303
|
+
@classmethod
|
|
1304
|
+
def _groups(cls, value: dict[GroupName, ImageGroup]) -> dict[GroupName, ImageGroup]:
|
|
1305
|
+
if not value:
|
|
1306
|
+
message = "list at least one image group, or leave `images` out"
|
|
1307
|
+
raise ValueError(message)
|
|
1308
|
+
for name, group in value.items():
|
|
1309
|
+
check_name("image group", name)
|
|
1310
|
+
for required in group.requires:
|
|
1311
|
+
if required not in value:
|
|
1312
|
+
message = f"group {name!r} requires {required!r}, which is not defined"
|
|
1313
|
+
raise ValueError(message)
|
|
1314
|
+
return value
|
|
1315
|
+
|
|
1316
|
+
@field_validator("store")
|
|
1317
|
+
@classmethod
|
|
1318
|
+
def _stores(
|
|
1319
|
+
cls, value: tuple[dict[str, dict[str, JsonValue]], ...]
|
|
1320
|
+
) -> tuple[dict[str, dict[str, JsonValue]], ...]:
|
|
1321
|
+
for entry in value:
|
|
1322
|
+
if len(entry) != 1:
|
|
1323
|
+
message = "each store is a mapping with one key, the store kind"
|
|
1324
|
+
raise ValueError(message)
|
|
1325
|
+
return value
|
|
1326
|
+
|
|
1327
|
+
|
|
1328
|
+
def _plain(value: object) -> object:
|
|
1329
|
+
# YAML turns unquoted timestamps into datetimes; the models parse ISO text.
|
|
1330
|
+
if isinstance(value, dt.date):
|
|
1331
|
+
return value.isoformat()
|
|
1332
|
+
message = f"unsupported value {value!r}"
|
|
1333
|
+
raise TypeError(message)
|
|
1334
|
+
|
|
1335
|
+
|
|
1336
|
+
EXTENDS = "extends"
|
|
1337
|
+
"""The top-level key that names the specs a spec file extends."""
|
|
1338
|
+
|
|
1339
|
+
_DOCUMENT = TypeAdapter(JsonValue)
|
|
1340
|
+
|
|
1341
|
+
|
|
1342
|
+
def _document(text: str, origin: str) -> JsonValue:
|
|
1343
|
+
"""YAML or JSON text as plain JSON values."""
|
|
1344
|
+
try:
|
|
1345
|
+
raw: object = yaml.safe_load(text)
|
|
1346
|
+
except yaml.YAMLError as error:
|
|
1347
|
+
message = f"{origin} is not valid YAML or JSON: {error}"
|
|
1348
|
+
raise SpecError(message) from None
|
|
1349
|
+
try:
|
|
1350
|
+
return _DOCUMENT.validate_json(json.dumps(raw, default=_plain))
|
|
1351
|
+
except TypeError as error:
|
|
1352
|
+
message = f"{origin} holds a value that has no JSON form: {error}"
|
|
1353
|
+
raise SpecError(message) from None
|
|
1354
|
+
|
|
1355
|
+
|
|
1356
|
+
def _validated(document: JsonValue, origin: str) -> Spec:
|
|
1357
|
+
try:
|
|
1358
|
+
return Spec.model_validate_json(json.dumps(document))
|
|
1359
|
+
except ValidationError as error:
|
|
1360
|
+
details = tuple(
|
|
1361
|
+
(".".join(str(part) for part in problem["loc"]) or "(spec)", problem["msg"])
|
|
1362
|
+
for problem in error.errors(include_url=False)
|
|
1363
|
+
)
|
|
1364
|
+
message = f"{origin} does not match the spec schema: {error.error_count()} problem(s)"
|
|
1365
|
+
raise SpecError(message, details) from None
|
|
1366
|
+
|
|
1367
|
+
|
|
1368
|
+
def parse_spec(text: str, *, origin: str = "spec") -> Spec:
|
|
1369
|
+
"""Parse a spec from YAML or JSON text (JSON is valid YAML).
|
|
1370
|
+
|
|
1371
|
+
Text has no directory to find other files in, so a spec that extends
|
|
1372
|
+
others is refused here; :func:`read_spec` reads one from its file.
|
|
1373
|
+
"""
|
|
1374
|
+
document = _document(text, origin)
|
|
1375
|
+
if isinstance(document, dict) and EXTENDS in document:
|
|
1376
|
+
message = (
|
|
1377
|
+
f"{origin} extends other specs, which only a spec read from its file can do:"
|
|
1378
|
+
" their paths are relative to its directory"
|
|
1379
|
+
)
|
|
1380
|
+
raise SpecError(message)
|
|
1381
|
+
return _validated(document, origin)
|
|
1382
|
+
|
|
1383
|
+
|
|
1384
|
+
class SpecLayer(_Model):
|
|
1385
|
+
"""One file a spec was read from."""
|
|
1386
|
+
|
|
1387
|
+
path: PurePosixPath
|
|
1388
|
+
"""The file's path from the spec's directory, as written: symbolic links keep their names."""
|
|
1389
|
+
digest: FileDigest
|
|
1390
|
+
"""The SHA-256 of the file's bytes, as ``sha256:`` and the hex digest."""
|
|
1391
|
+
|
|
1392
|
+
|
|
1393
|
+
@dataclass(frozen=True, slots=True)
|
|
1394
|
+
class LoadedSpec:
|
|
1395
|
+
"""A spec read from its file, with every file it extends."""
|
|
1396
|
+
|
|
1397
|
+
spec: Spec
|
|
1398
|
+
layers: tuple[SpecLayer, ...]
|
|
1399
|
+
"""Every file the spec was read from, in the order they merged: the spec's own file last."""
|
|
1400
|
+
document: dict[str, JsonValue]
|
|
1401
|
+
"""The merged spec as written, before defaults, without ``extends``."""
|
|
1402
|
+
directory: Path
|
|
1403
|
+
"""The spec's directory, which every layer's path is relative to."""
|
|
1404
|
+
|
|
1405
|
+
|
|
1406
|
+
def merge_documents(base: dict[str, JsonValue], over: dict[str, JsonValue]) -> dict[str, JsonValue]:
|
|
1407
|
+
"""``over`` merged onto ``base``: mappings key by key, recursively; anything else replaces."""
|
|
1408
|
+
merged = dict(base)
|
|
1409
|
+
for key, value in over.items():
|
|
1410
|
+
earlier = merged.get(key)
|
|
1411
|
+
if isinstance(earlier, dict) and isinstance(value, dict):
|
|
1412
|
+
merged[key] = merge_documents(earlier, value)
|
|
1413
|
+
else:
|
|
1414
|
+
merged[key] = value
|
|
1415
|
+
return merged
|
|
1416
|
+
|
|
1417
|
+
|
|
1418
|
+
def _lexical(path: Path) -> Path:
|
|
1419
|
+
"""``path`` made absolute and normalized as written, without following symbolic links."""
|
|
1420
|
+
return Path(os.path.normpath(path.absolute()))
|
|
1421
|
+
|
|
1422
|
+
|
|
1423
|
+
@dataclass(frozen=True, slots=True)
|
|
1424
|
+
class _Layer:
|
|
1425
|
+
path: Path
|
|
1426
|
+
"""The file's lexical path: absolute, normalized, symbolic links not followed."""
|
|
1427
|
+
real: Path
|
|
1428
|
+
"""The file's real path, which identifies it however it is named."""
|
|
1429
|
+
|
|
1430
|
+
|
|
1431
|
+
@dataclass(frozen=True, slots=True)
|
|
1432
|
+
class _Placed:
|
|
1433
|
+
layer: SpecLayer
|
|
1434
|
+
document: dict[str, JsonValue]
|
|
1435
|
+
"""The file's own settings, without ``extends``."""
|
|
1436
|
+
|
|
1437
|
+
|
|
1438
|
+
class _Layers:
|
|
1439
|
+
"""Places a spec file and the files it extends in merge order: each after its parents.
|
|
1440
|
+
|
|
1441
|
+
Files are named by their lexical paths, so a symbolic link keeps its own
|
|
1442
|
+
name and a relative path in it is relative to the link's directory. A
|
|
1443
|
+
file is identified by its real path, so it is placed once, however many
|
|
1444
|
+
files extend it and by whatever names.
|
|
1445
|
+
"""
|
|
1446
|
+
|
|
1447
|
+
def __init__(self, directory: Path) -> None:
|
|
1448
|
+
self.directory = directory
|
|
1449
|
+
self.placed: dict[Path, _Placed] = {}
|
|
1450
|
+
|
|
1451
|
+
def relative(self, path: Path) -> PurePosixPath:
|
|
1452
|
+
return PurePosixPath(path.relative_to(self.directory).as_posix())
|
|
1453
|
+
|
|
1454
|
+
def parents(self, layer: _Layer, extends: JsonValue) -> tuple[_Layer, ...]:
|
|
1455
|
+
"""The files ``extends`` names, checked to be inside the spec's directory."""
|
|
1456
|
+
origin = self.relative(layer.path)
|
|
1457
|
+
listed = extends if isinstance(extends, list) else [extends]
|
|
1458
|
+
names = [name for name in listed if isinstance(name, str) and name]
|
|
1459
|
+
if len(names) != len(listed):
|
|
1460
|
+
message = f"{origin}: `{EXTENDS}` takes a path, or a list of paths, to other specs"
|
|
1461
|
+
raise SpecError(message)
|
|
1462
|
+
found: list[_Layer] = []
|
|
1463
|
+
for name in names:
|
|
1464
|
+
if Path(name).is_absolute():
|
|
1465
|
+
message = (
|
|
1466
|
+
f"{origin} extends {name}, an absolute path; give a path relative to {origin}"
|
|
1467
|
+
)
|
|
1468
|
+
raise SpecError(message)
|
|
1469
|
+
parent = _lexical(layer.path.parent / name)
|
|
1470
|
+
if not parent.is_relative_to(self.directory):
|
|
1471
|
+
message = (
|
|
1472
|
+
f"{origin} extends {name}, which is outside {self.directory}, the directory"
|
|
1473
|
+
" of the spec being read; the specs a spec extends live in its directory"
|
|
1474
|
+
)
|
|
1475
|
+
raise SpecError(message)
|
|
1476
|
+
found.append(_Layer(path=parent, real=parent.resolve()))
|
|
1477
|
+
return tuple(found)
|
|
1478
|
+
|
|
1479
|
+
def place(self, layer: _Layer, chain: tuple[_Layer, ...]) -> None:
|
|
1480
|
+
"""Place the file's parents, left to right, then the file, unless it is placed already."""
|
|
1481
|
+
reals = [step.real for step in chain]
|
|
1482
|
+
if layer.real in reals:
|
|
1483
|
+
steps = (*chain[reals.index(layer.real) :], layer)
|
|
1484
|
+
cycle = " -> ".join(str(self.relative(step.path)) for step in steps)
|
|
1485
|
+
message = f"specs extend each other in a cycle: {cycle}"
|
|
1486
|
+
raise SpecError(message)
|
|
1487
|
+
if layer.real in self.placed:
|
|
1488
|
+
return
|
|
1489
|
+
origin = self.relative(layer.path)
|
|
1490
|
+
try:
|
|
1491
|
+
data = layer.path.read_bytes()
|
|
1492
|
+
except OSError as error:
|
|
1493
|
+
message = f"cannot read {layer.path}: {error.strerror}"
|
|
1494
|
+
raise SpecError(message) from None
|
|
1495
|
+
try:
|
|
1496
|
+
text = data.decode("utf-8")
|
|
1497
|
+
except UnicodeDecodeError:
|
|
1498
|
+
message = f"{origin} is not UTF-8 text"
|
|
1499
|
+
raise SpecError(message) from None
|
|
1500
|
+
document = _document(text, str(origin))
|
|
1501
|
+
if document is None:
|
|
1502
|
+
document = {}
|
|
1503
|
+
if not isinstance(document, dict):
|
|
1504
|
+
message = f"{origin} is not a mapping of spec settings"
|
|
1505
|
+
raise SpecError(message)
|
|
1506
|
+
own = dict(document)
|
|
1507
|
+
if EXTENDS in own:
|
|
1508
|
+
for parent in self.parents(layer, own.pop(EXTENDS)):
|
|
1509
|
+
self.place(parent, (*chain, layer))
|
|
1510
|
+
digest = FileDigest("sha256:" + hashlib.sha256(data).hexdigest())
|
|
1511
|
+
self.placed[layer.real] = _Placed(SpecLayer(path=origin, digest=digest), own)
|
|
1512
|
+
|
|
1513
|
+
def merged(self) -> dict[str, JsonValue]:
|
|
1514
|
+
"""Every placed file's own settings, merged in the order they were placed."""
|
|
1515
|
+
merged: dict[str, JsonValue] = {}
|
|
1516
|
+
for placed in self.placed.values():
|
|
1517
|
+
merged = merge_documents(merged, placed.document)
|
|
1518
|
+
return merged
|
|
1519
|
+
|
|
1520
|
+
|
|
1521
|
+
def read_spec(path: Path) -> LoadedSpec:
|
|
1522
|
+
"""Read a spec file, merged with the specs it extends, and validate the result once.
|
|
1523
|
+
|
|
1524
|
+
Each file's ``extends`` names other spec files, by paths relative to that
|
|
1525
|
+
file. Every one must be inside the directory of ``path``, as written:
|
|
1526
|
+
paths are checked and recorded without following symbolic links. The
|
|
1527
|
+
files merge in one order, each file once and after all the files it
|
|
1528
|
+
extends, which come left to right: mappings merge key by key, and any
|
|
1529
|
+
other value replaces the one before it.
|
|
1530
|
+
"""
|
|
1531
|
+
lexical = _lexical(path)
|
|
1532
|
+
reader = _Layers(lexical.parent)
|
|
1533
|
+
spec_file = _Layer(path=lexical, real=lexical.resolve())
|
|
1534
|
+
reader.place(spec_file, ())
|
|
1535
|
+
document = reader.merged()
|
|
1536
|
+
layered = len(reader.placed) > 1
|
|
1537
|
+
origin = f"{path} with the specs it extends" if layered else str(path)
|
|
1538
|
+
spec = _validated(document, origin)
|
|
1539
|
+
taken = [
|
|
1540
|
+
str(placed.layer.path)
|
|
1541
|
+
for real, placed in reader.placed.items()
|
|
1542
|
+
if real != spec_file.real and placed.document.get("name") == spec.name
|
|
1543
|
+
]
|
|
1544
|
+
if taken:
|
|
1545
|
+
message = (
|
|
1546
|
+
f"{path} has the name {spec.name}, which {', '.join(taken)} also has; give it a"
|
|
1547
|
+
f" name of its own with `name`, so its images are not filed under {spec.name}"
|
|
1548
|
+
)
|
|
1549
|
+
raise SpecError(message)
|
|
1550
|
+
return LoadedSpec(
|
|
1551
|
+
spec=spec,
|
|
1552
|
+
layers=tuple(placed.layer for placed in reader.placed.values()),
|
|
1553
|
+
document=document,
|
|
1554
|
+
directory=reader.directory,
|
|
1555
|
+
)
|
|
1556
|
+
|
|
1557
|
+
|
|
1558
|
+
def load_spec(path: Path) -> Spec:
|
|
1559
|
+
"""Read and parse a spec file, merged with the specs it extends."""
|
|
1560
|
+
return read_spec(path).spec
|
|
1561
|
+
|
|
1562
|
+
|
|
1563
|
+
def spec_schema() -> dict[str, JsonValue]:
|
|
1564
|
+
"""The JSON Schema for specs."""
|
|
1565
|
+
schema: dict[str, JsonValue] = Spec.model_json_schema(mode="validation")
|
|
1566
|
+
schema["$schema"] = "https://json-schema.org/draft/2020-12/schema"
|
|
1567
|
+
# Read before validation, so it is not a field of the model.
|
|
1568
|
+
properties = _PROPERTIES.validate_python(schema["properties"])
|
|
1569
|
+
schema["properties"] = {EXTENDS: _EXTENDS_SCHEMA, **properties}
|
|
1570
|
+
return schema
|
|
1571
|
+
|
|
1572
|
+
|
|
1573
|
+
_PROPERTIES: TypeAdapter[dict[str, JsonValue]] = TypeAdapter(dict[str, JsonValue])
|
|
1574
|
+
|
|
1575
|
+
|
|
1576
|
+
_EXTENDS_SCHEMA: dict[str, JsonValue] = {
|
|
1577
|
+
"anyOf": [
|
|
1578
|
+
{"type": "string", "minLength": 1},
|
|
1579
|
+
{"type": "array", "items": {"type": "string", "minLength": 1}},
|
|
1580
|
+
],
|
|
1581
|
+
"title": "Extends",
|
|
1582
|
+
"description": (
|
|
1583
|
+
"Other spec files this one builds on, as a path or a list of paths relative to this"
|
|
1584
|
+
" file. Each must be inside the directory of the spec being run. Their settings merge"
|
|
1585
|
+
" left to right, then this file's: mappings merge key by key, and any other value,"
|
|
1586
|
+
" lists included, replaces the one before it. A file that several files extend merges"
|
|
1587
|
+
" once, before all of them. Only the merged spec is checked, and its `name` must differ"
|
|
1588
|
+
" from every name the other files give."
|
|
1589
|
+
),
|
|
1590
|
+
}
|