continuo-python-runtime 0.12.0__py3-none-any.whl → 0.13.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- continuo_python_runtime/cli.py +102 -37
- continuo_python_runtime/content_check.py +4 -4
- continuo_python_runtime/contract/kinds.py +37 -29
- continuo_python_runtime/contract/loader.py +207 -439
- continuo_python_runtime/contract/model.py +12 -6
- continuo_python_runtime/contract/pack.py +299 -0
- continuo_python_runtime/contract/paths.py +1 -1
- continuo_python_runtime/contract/read_tables.py +85 -0
- continuo_python_runtime/harness.py +14 -5
- continuo_python_runtime/hashing.py +23 -40
- continuo_python_runtime/packages.py +56 -0
- {continuo_python_runtime-0.12.0.dist-info → continuo_python_runtime-0.13.0.dist-info}/METADATA +191 -119
- {continuo_python_runtime-0.12.0.dist-info → continuo_python_runtime-0.13.0.dist-info}/RECORD +17 -16
- continuo_python_runtime/contract/merge.py +0 -178
- continuo_python_runtime/contract/secret_ref.py +0 -31
- {continuo_python_runtime-0.12.0.dist-info → continuo_python_runtime-0.13.0.dist-info}/WHEEL +0 -0
- {continuo_python_runtime-0.12.0.dist-info → continuo_python_runtime-0.13.0.dist-info}/entry_points.txt +0 -0
- {continuo_python_runtime-0.12.0.dist-info → continuo_python_runtime-0.13.0.dist-info}/licenses/LICENSE +0 -0
- {continuo_python_runtime-0.12.0.dist-info → continuo_python_runtime-0.13.0.dist-info}/licenses/NOTICE +0 -0
|
@@ -1,120 +1,71 @@
|
|
|
1
|
-
"""
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
.
|
|
5
|
-
|
|
1
|
+
"""The contract loader: one ODCS contract per node.
|
|
2
|
+
|
|
3
|
+
A contracts folder holds one ODCS v3.2.0 contract per node, in a file named
|
|
4
|
+
``<table>.odcs.yaml``, or ``<schema>.<table>.odcs.yaml`` when two nodes of one
|
|
5
|
+
service share a table name. continuo-contracts reads each file strictly, checks
|
|
6
|
+
it and maps it to its ``PythonNode``; the runtime then applies the rules it
|
|
7
|
+
keeps for itself and builds its :class:`~continuo_python_runtime.contract.model
|
|
8
|
+
.Node`. Every refusal is a :class:`ContractError` that names the file.
|
|
6
9
|
"""
|
|
7
10
|
|
|
8
11
|
from __future__ import annotations
|
|
9
12
|
|
|
10
|
-
import
|
|
11
|
-
from pathlib import Path
|
|
13
|
+
from collections.abc import Iterable, Mapping
|
|
14
|
+
from pathlib import Path
|
|
12
15
|
from typing import Any
|
|
13
16
|
|
|
14
|
-
import
|
|
17
|
+
from continuo_contracts import yaml_strict
|
|
18
|
+
from continuo_contracts.errors import StrictYamlError
|
|
19
|
+
from continuo_contracts.python import PythonNode, node_from_odcs
|
|
20
|
+
from continuo_contracts.validate import validate_python_contract
|
|
21
|
+
from continuo_contracts.vocabulary import continuo_values
|
|
15
22
|
from sqlglot import Dialect
|
|
16
23
|
|
|
17
|
-
from continuo_python_runtime.contract.kinds import
|
|
18
|
-
from continuo_python_runtime.contract.model import
|
|
19
|
-
CRITICALITIES,
|
|
20
|
-
DEFAULT_KIND,
|
|
21
|
-
DEFAULT_MODE_TYPE,
|
|
22
|
-
EXTRA_COLUMNS_POLICIES,
|
|
23
|
-
MODE_TYPES,
|
|
24
|
-
Column,
|
|
25
|
-
Node,
|
|
26
|
-
)
|
|
27
|
-
from continuo_python_runtime.contract.secret_ref import validate_secret_ref
|
|
24
|
+
from continuo_python_runtime.contract.kinds import rules_for
|
|
25
|
+
from continuo_python_runtime.contract.model import Column, Node
|
|
28
26
|
from continuo_python_runtime.errors import ContractError
|
|
29
|
-
from continuo_python_runtime.types import parse_sql_type
|
|
30
|
-
|
|
31
|
-
_ALLOWED_KEYS = {
|
|
32
|
-
"schema",
|
|
33
|
-
"table",
|
|
34
|
-
"description",
|
|
35
|
-
"owner",
|
|
36
|
-
"schedule",
|
|
37
|
-
"criticality",
|
|
38
|
-
"kind",
|
|
39
|
-
"script",
|
|
40
|
-
"extra_columns",
|
|
41
|
-
"reads",
|
|
42
|
-
"output_columns",
|
|
43
|
-
"config",
|
|
44
|
-
"content_hash",
|
|
45
|
-
"secret_ref",
|
|
46
|
-
"mode_type",
|
|
47
|
-
"primary_key",
|
|
48
|
-
"timeout_minutes",
|
|
49
|
-
"assets",
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
# Bounds of a node's declared task timeout, in minutes (one minute to one week).
|
|
53
|
-
MIN_TIMEOUT_MINUTES = 1
|
|
54
|
-
MAX_TIMEOUT_MINUTES = 10_080
|
|
55
|
-
|
|
56
|
-
_REQUIRED_STRING_FIELDS = ("schema", "table", "owner", "schedule")
|
|
57
|
-
|
|
58
|
-
_ALLOWED_OUTPUT_COLUMN_KEYS = {"name", "type", "nullable"}
|
|
59
|
-
|
|
60
27
|
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
raise ContractError(f"duplicate key {key!r} at {key_node.start_mark}")
|
|
73
|
-
seen.add(key)
|
|
74
|
-
return yaml.SafeLoader.construct_mapping(loader, node, deep=deep)
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
_StrictLoader.add_constructor(
|
|
78
|
-
yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, _strict_construct_mapping
|
|
28
|
+
CONTRACT_SUFFIX = ".odcs.yaml"
|
|
29
|
+
# The endings of a YAML file's name, compared in lower case: any file that ends
|
|
30
|
+
# in one of them and not exactly in CONTRACT_SUFFIX is refused.
|
|
31
|
+
_YAML_SUFFIXES = (".yml", ".yaml")
|
|
32
|
+
|
|
33
|
+
# Where a refused file's author finds how to convert it: the refusal is read in
|
|
34
|
+
# the CI of the domain team that owns the repository, which does not hold this
|
|
35
|
+
# repository's docs.
|
|
36
|
+
_CONVERSION_GUIDE = (
|
|
37
|
+
"https://github.com/carolsimone/continuo-python-runtime/blob/main/"
|
|
38
|
+
"docs/boundary-contract.md#converting-a-contract-file"
|
|
79
39
|
)
|
|
80
40
|
|
|
81
|
-
|
|
82
|
-
def _node_label(raw: dict[str, Any], source: str) -> str:
|
|
83
|
-
"""Build a `source (schema.table)`-style label for error messages."""
|
|
84
|
-
schema = raw.get("schema")
|
|
85
|
-
table = raw.get("table")
|
|
86
|
-
if isinstance(schema, str) and schema and isinstance(table, str) and table:
|
|
87
|
-
return f"{source} ({schema}.{table})"
|
|
88
|
-
return source
|
|
89
|
-
|
|
90
|
-
|
|
91
41
|
_JSON_SCALARS = (str, int, float, bool, type(None))
|
|
92
42
|
|
|
43
|
+
# What a document that is not a mapping is, as the words of a message.
|
|
44
|
+
_DOCUMENT_KINDS = {
|
|
45
|
+
list: "a list",
|
|
46
|
+
str: "a string",
|
|
47
|
+
bool: "a boolean",
|
|
48
|
+
int: "a number",
|
|
49
|
+
float: "a number",
|
|
50
|
+
}
|
|
51
|
+
|
|
93
52
|
|
|
94
53
|
def _validate_config(raw: Any, label: str) -> dict[str, Any]:
|
|
95
|
-
"""Validate the node's physical-layout
|
|
96
|
-
|
|
97
|
-
The engine's adapter
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
every dict/list container currently being descended into; a container is
|
|
110
|
-
added just before recursing into its items and discarded right after, so
|
|
111
|
-
re-entering one still on the stack is a genuine back-edge (a cycle), while
|
|
112
|
-
the *same* container reached twice at sibling positions — a legal DAG,
|
|
113
|
-
e.g. one list aliased under two different keys — is not: its first visit
|
|
114
|
-
finishes (and is discarded) before the second begins.
|
|
54
|
+
"""Validate the node's physical-layout ``config`` as a JSON-shaped mapping.
|
|
55
|
+
|
|
56
|
+
The engine's adapter, not this loader, owns the vocabulary, so the only
|
|
57
|
+
rules here are the ones the hash and the adapters need: it is a mapping,
|
|
58
|
+
every key at every level is a string, and every value is a JSON scalar, a
|
|
59
|
+
list or a mapping. A contract file always passes, since ``yaml_strict``
|
|
60
|
+
reads nothing else; a document built in code can hold a key that is not a
|
|
61
|
+
string, a value JSON cannot write or a container that contains itself, and
|
|
62
|
+
each is refused here, naming the node.
|
|
63
|
+
|
|
64
|
+
``active`` holds the ``id()`` of every dict or list being descended into:
|
|
65
|
+
a container is added just before its items are checked and discarded right
|
|
66
|
+
after, so meeting one that is still in ``active`` is a cycle, while one
|
|
67
|
+
container reached twice at sibling positions is not.
|
|
115
68
|
"""
|
|
116
|
-
if raw is None:
|
|
117
|
-
return {}
|
|
118
69
|
if not isinstance(raw, dict):
|
|
119
70
|
raise ContractError(f"{label}: 'config' must be a mapping")
|
|
120
71
|
|
|
@@ -151,339 +102,162 @@ def _validate_config(raw: Any, label: str) -> dict[str, Any]:
|
|
|
151
102
|
return raw
|
|
152
103
|
|
|
153
104
|
|
|
154
|
-
def
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
``replace`` would look enforced when it is not. Names keep their order,
|
|
161
|
-
which is what the wire entry carries. Each must be spelled exactly as an
|
|
162
|
-
output column (postgres quotes identifiers, so ``Rate_Date`` is not
|
|
163
|
-
``rate_date``) declared ``nullable: false``, because a NULL key never
|
|
164
|
-
matches an existing row. Repeats are refused case-insensitively too, so a
|
|
165
|
-
key cannot name two columns that differ only in case. A floating-point
|
|
166
|
-
column is refused as well: the warehouse treats ``0.0`` and ``-0.0`` as
|
|
167
|
-
one key, so ``ensure_unique_key`` would reject the rows at write time --
|
|
168
|
-
failing here instead keeps an unwritable upsert out of the contract.
|
|
105
|
+
def _upsert_key(python: PythonNode, label: str) -> tuple[str, ...]:
|
|
106
|
+
"""Return the key the harness upserts on: the node's key when it upserts, else none.
|
|
107
|
+
|
|
108
|
+
On a replace or append node a key only describes the table. The names of
|
|
109
|
+
an upsert key are compared case-insensitively too, so a key cannot name
|
|
110
|
+
two columns that differ only in case.
|
|
169
111
|
"""
|
|
170
|
-
if mode_type != "upsert":
|
|
171
|
-
if "primary_key" in raw:
|
|
172
|
-
raise ContractError(
|
|
173
|
-
f"{label}: 'primary_key' is only allowed when mode_type is upsert "
|
|
174
|
-
f"(got {mode_type})"
|
|
175
|
-
)
|
|
112
|
+
if python.mode_type != "upsert":
|
|
176
113
|
return ()
|
|
177
|
-
if "primary_key" not in raw:
|
|
178
|
-
raise ContractError(f"{label}: 'primary_key' is required when mode_type is upsert")
|
|
179
|
-
raw_key = raw["primary_key"]
|
|
180
|
-
if not isinstance(raw_key, list) or not raw_key:
|
|
181
|
-
raise ContractError(
|
|
182
|
-
f"{label}: 'primary_key' must be a non-empty list of output column names"
|
|
183
|
-
)
|
|
184
|
-
by_name = {column.name: column for column in columns}
|
|
185
114
|
seen: set[str] = set()
|
|
186
|
-
for name in
|
|
187
|
-
|
|
188
|
-
raise ContractError(
|
|
189
|
-
f"{label}: 'primary_key' entry {name!r} must be a non-empty string"
|
|
190
|
-
)
|
|
191
|
-
folded = name.lower() # same folding as continuo's parser
|
|
115
|
+
for name in python.primary_key:
|
|
116
|
+
folded = name.lower()
|
|
192
117
|
if folded in seen:
|
|
193
118
|
raise ContractError(
|
|
194
|
-
f"{label}:
|
|
119
|
+
f"{label}: the upsert key names {name!r} more than once "
|
|
195
120
|
"(names are compared case-insensitively)"
|
|
196
121
|
)
|
|
197
122
|
seen.add(folded)
|
|
198
|
-
|
|
199
|
-
if column is None:
|
|
200
|
-
raise ContractError(
|
|
201
|
-
f"{label}: 'primary_key' column {name!r} is not in output_columns"
|
|
202
|
-
)
|
|
203
|
-
if column.nullable:
|
|
204
|
-
raise ContractError(
|
|
205
|
-
f"{label}: 'primary_key' column {name!r} must be declared nullable: false"
|
|
206
|
-
)
|
|
207
|
-
if parse_sql_type(column.type).base == "DOUBLE_PRECISION":
|
|
208
|
-
raise ContractError(
|
|
209
|
-
f"{label}: 'primary_key' column {name!r} is floating-point "
|
|
210
|
-
f"({column.type}); a floating-point column cannot be a primary key"
|
|
211
|
-
)
|
|
212
|
-
return tuple(raw_key)
|
|
213
|
-
|
|
123
|
+
return tuple(python.primary_key)
|
|
214
124
|
|
|
215
|
-
_DRIVE_PATH = re.compile(r"^[A-Za-z]:")
|
|
216
125
|
|
|
126
|
+
def issue_lines(file: Path | str, issues: Iterable[object]) -> list[str]:
|
|
127
|
+
"""One line per issue of the contract in ``file``, ``f"{file}: {issue}"``."""
|
|
128
|
+
return [f"{file}: {issue}" for issue in issues]
|
|
217
129
|
|
|
218
|
-
def _validate_assets(
|
|
219
|
-
raw: dict[str, Any], rules: KindRules, kind: str, label: str
|
|
220
|
-
) -> tuple[str, ...]:
|
|
221
|
-
"""Validate ``assets``: repo-relative paths of the files a script reads.
|
|
222
130
|
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
root and without a ``..`` segment; it is normalised (``./data//ref.json``
|
|
226
|
-
is ``data/ref.json``) and keeps its declared position. A repeat after
|
|
227
|
-
normalising is refused. Whether the file exists is checked where a
|
|
228
|
-
repository root is known.
|
|
229
|
-
"""
|
|
230
|
-
if "assets" not in raw:
|
|
231
|
-
return ()
|
|
232
|
-
if not rules.assets_allowed:
|
|
233
|
-
raise ContractError(
|
|
234
|
-
f"{label}: 'assets' is not allowed for kind {kind} (it has no script to read files)"
|
|
235
|
-
)
|
|
236
|
-
raw_assets = raw["assets"]
|
|
237
|
-
if not isinstance(raw_assets, list):
|
|
238
|
-
raise ContractError(f"{label}: 'assets' must be a list of repository-relative paths")
|
|
239
|
-
assets: list[str] = []
|
|
240
|
-
for entry in raw_assets:
|
|
241
|
-
if not isinstance(entry, str) or not entry.strip():
|
|
242
|
-
raise ContractError(f"{label}: 'assets' entry {entry!r} must be a non-empty string")
|
|
243
|
-
if "\\" in entry:
|
|
244
|
-
raise ContractError(f"{label}: 'assets' entry {entry!r} must use forward slashes")
|
|
245
|
-
path = PurePosixPath(entry)
|
|
246
|
-
if path.is_absolute() or _DRIVE_PATH.match(entry):
|
|
247
|
-
raise ContractError(
|
|
248
|
-
f"{label}: 'assets' entry {entry!r} must be relative to the repository root"
|
|
249
|
-
)
|
|
250
|
-
if ".." in path.parts:
|
|
251
|
-
raise ContractError(f"{label}: 'assets' entry {entry!r} must not contain '..'")
|
|
252
|
-
normalised = path.as_posix()
|
|
253
|
-
if normalised == ".":
|
|
254
|
-
raise ContractError(f"{label}: 'assets' entry {entry!r} must name a file")
|
|
255
|
-
if normalised in assets:
|
|
256
|
-
raise ContractError(f"{label}: 'assets' names {normalised!r} more than once")
|
|
257
|
-
assets.append(normalised)
|
|
258
|
-
return tuple(assets)
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
def parse_node(
|
|
262
|
-
raw: dict[str, Any],
|
|
263
|
-
source: str,
|
|
264
|
-
*,
|
|
265
|
-
dialect: str | None = None,
|
|
266
|
-
check_reads: bool = True,
|
|
131
|
+
def node_from_contract(
|
|
132
|
+
doc: Mapping[str, Any], file: Path, *, dialect: str | None, check_reads: bool
|
|
267
133
|
) -> Node:
|
|
268
|
-
"""
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
``
|
|
272
|
-
|
|
273
|
-
:func
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
``
|
|
277
|
-
the
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
134
|
+
"""Check the ODCS contract ``doc``, read from ``file``, and build its :class:`Node`.
|
|
135
|
+
|
|
136
|
+
continuo-contracts checks the contract first
|
|
137
|
+
(``validate_python_contract``, with no service, of which only the base
|
|
138
|
+
name of ``file`` counts for the file-name rule). When it finds issues they
|
|
139
|
+
become one :class:`ContractError` with one :func:`issue_lines` line per
|
|
140
|
+
issue, and nothing else runs.
|
|
141
|
+
|
|
142
|
+
The runtime's own rules follow, each naming ``file`` and the relation:
|
|
143
|
+
the kind's reads rule (:mod:`~continuo_python_runtime.contract.kinds`),
|
|
144
|
+
which, unless ``check_reads`` is false, parses each read of a python-node
|
|
145
|
+
as one read query under ``dialect`` and refuses a read that names a table
|
|
146
|
+
without its schema (a reference to a CTE in scope excepted); the shape of ``config``;
|
|
147
|
+
and the case-insensitive uniqueness of an upsert key's names.
|
|
148
|
+
|
|
149
|
+
The node takes ``owner`` from ``team.name``, ``description`` from
|
|
150
|
+
``description.purpose`` (``""`` when absent), and ``schedule``,
|
|
151
|
+
``criticality`` and ``timeout_minutes`` (``None`` when absent) from the
|
|
152
|
+
contract's ``continuo`` custom properties. Every other field is the
|
|
153
|
+
library's ``PythonNode``, kept as ``python``: the kind as the library
|
|
154
|
+
reads it, the script, the reads, the columns (nullable unless
|
|
155
|
+
``required``), ``extra_columns``, ``config``, ``secret_ref``,
|
|
156
|
+
``mode_type``, the key when the node upserts and the assets.
|
|
283
157
|
"""
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
if unknown:
|
|
293
|
-
raise ContractError(f"{label}: unknown key(s) {sorted(unknown)}")
|
|
294
|
-
|
|
295
|
-
kind = raw.get("kind", DEFAULT_KIND)
|
|
296
|
-
rules = rules_for(kind, label)
|
|
297
|
-
|
|
298
|
-
for field in _REQUIRED_STRING_FIELDS:
|
|
299
|
-
value = raw.get(field)
|
|
300
|
-
if not isinstance(value, str) or not value.strip():
|
|
301
|
-
raise ContractError(
|
|
302
|
-
f"{label}: required field '{field}' must be a non-empty string"
|
|
303
|
-
)
|
|
304
|
-
|
|
305
|
-
schema = raw["schema"]
|
|
306
|
-
table = raw["table"]
|
|
307
|
-
owner = raw["owner"]
|
|
308
|
-
schedule = raw["schedule"]
|
|
309
|
-
|
|
310
|
-
if rules.script_required:
|
|
311
|
-
raw_script = raw.get("script")
|
|
312
|
-
if not isinstance(raw_script, str) or not raw_script.strip():
|
|
313
|
-
raise ContractError(
|
|
314
|
-
f"{label}: required field 'script' must be a non-empty string"
|
|
315
|
-
)
|
|
316
|
-
script = raw_script
|
|
317
|
-
else:
|
|
318
|
-
if "script" in raw:
|
|
319
|
-
raise ContractError(
|
|
320
|
-
f"{label}: 'script' is forbidden for kind {kind} "
|
|
321
|
-
"(it is a contract-only kind)"
|
|
322
|
-
)
|
|
323
|
-
script = ""
|
|
324
|
-
|
|
325
|
-
criticality = raw.get("criticality")
|
|
326
|
-
if not isinstance(criticality, str) or criticality not in CRITICALITIES:
|
|
327
|
-
raise ContractError(
|
|
328
|
-
f"{label}: 'criticality' must be one of {sorted(CRITICALITIES)}, got {criticality!r}"
|
|
329
|
-
)
|
|
330
|
-
|
|
331
|
-
extra_columns = raw.get("extra_columns", "raise")
|
|
332
|
-
if (
|
|
333
|
-
not isinstance(extra_columns, str)
|
|
334
|
-
or extra_columns not in EXTRA_COLUMNS_POLICIES
|
|
335
|
-
):
|
|
336
|
-
raise ContractError(
|
|
337
|
-
f"{label}: 'extra_columns' must be one of {sorted(EXTRA_COLUMNS_POLICIES)}, "
|
|
338
|
-
f"got {extra_columns!r}"
|
|
339
|
-
)
|
|
340
|
-
|
|
341
|
-
reads = rules.reads.validate(
|
|
342
|
-
raw.get("reads"), label, dialect=dialect, check_reads=check_reads
|
|
158
|
+
issues = validate_python_contract(doc, path=str(file), service=None)
|
|
159
|
+
if issues:
|
|
160
|
+
raise ContractError("\n".join(issue_lines(file, issues)))
|
|
161
|
+
python = node_from_odcs(doc)
|
|
162
|
+
label = f"{file} ({python.relation})"
|
|
163
|
+
|
|
164
|
+
reads = rules_for(python.kind, label).reads.validate(
|
|
165
|
+
dict(python.reads), label, dialect=dialect, check_reads=check_reads
|
|
343
166
|
)
|
|
167
|
+
config = _validate_config(python.config, label)
|
|
168
|
+
primary_key = _upsert_key(python, label)
|
|
344
169
|
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
if not rules.secret_allowed:
|
|
348
|
-
raise ContractError(f"{label}: 'secret_ref' is not allowed for kind {kind}")
|
|
349
|
-
secret_ref = validate_secret_ref(raw["secret_ref"], label)
|
|
350
|
-
|
|
351
|
-
timeout_minutes = raw.get("timeout_minutes")
|
|
352
|
-
if "timeout_minutes" in raw and (
|
|
353
|
-
type(timeout_minutes) is not int
|
|
354
|
-
or not MIN_TIMEOUT_MINUTES <= timeout_minutes <= MAX_TIMEOUT_MINUTES
|
|
355
|
-
):
|
|
356
|
-
raise ContractError(
|
|
357
|
-
f"{label}: 'timeout_minutes' must be an integer between "
|
|
358
|
-
f"{MIN_TIMEOUT_MINUTES} and {MAX_TIMEOUT_MINUTES}, got {timeout_minutes!r}"
|
|
359
|
-
)
|
|
360
|
-
|
|
361
|
-
mode_type = raw.get("mode_type", DEFAULT_MODE_TYPE)
|
|
362
|
-
if not isinstance(mode_type, str) or mode_type not in MODE_TYPES:
|
|
363
|
-
raise ContractError(
|
|
364
|
-
f"{label}: 'mode_type' must be one of {sorted(MODE_TYPES)}, got {mode_type!r}"
|
|
365
|
-
)
|
|
366
|
-
if mode_type not in rules.mode_types:
|
|
367
|
-
raise ContractError(
|
|
368
|
-
f"{label}: 'mode_type' {mode_type!r} is not allowed for kind {kind!r} "
|
|
369
|
-
f"(allowed: {sorted(rules.mode_types)})"
|
|
370
|
-
)
|
|
371
|
-
|
|
372
|
-
raw_columns = raw.get("output_columns")
|
|
373
|
-
if not isinstance(raw_columns, list) or not raw_columns:
|
|
374
|
-
raise ContractError(f"{label}: 'output_columns' must be a non-empty list")
|
|
375
|
-
|
|
376
|
-
seen_names: set[str] = set()
|
|
377
|
-
columns: list[Column] = []
|
|
378
|
-
for entry in raw_columns:
|
|
379
|
-
if not isinstance(entry, dict):
|
|
380
|
-
raise ContractError(
|
|
381
|
-
f"{label}: each 'output_columns' entry must be a mapping, got {entry!r}"
|
|
382
|
-
)
|
|
383
|
-
unknown_col_keys = set(entry) - _ALLOWED_OUTPUT_COLUMN_KEYS
|
|
384
|
-
if unknown_col_keys:
|
|
385
|
-
raise ContractError(
|
|
386
|
-
f"{label}: output column has unknown key(s) {sorted(unknown_col_keys)}"
|
|
387
|
-
)
|
|
388
|
-
name = entry.get("name")
|
|
389
|
-
if not isinstance(name, str) or not name.strip():
|
|
390
|
-
raise ContractError(f"{label}: output column missing non-empty 'name'")
|
|
391
|
-
col_type = entry.get("type")
|
|
392
|
-
if not isinstance(col_type, str):
|
|
393
|
-
raise ContractError(
|
|
394
|
-
f"{label}: output column '{name}' has unsupported 'type' {col_type!r}"
|
|
395
|
-
)
|
|
396
|
-
try:
|
|
397
|
-
parse_sql_type(col_type)
|
|
398
|
-
except ContractError as e:
|
|
399
|
-
raise ContractError(
|
|
400
|
-
f"{label}: output column '{name}' has unsupported {str(e)}"
|
|
401
|
-
) from e
|
|
402
|
-
nullable = entry.get("nullable", True)
|
|
403
|
-
if not isinstance(nullable, bool):
|
|
404
|
-
raise ContractError(
|
|
405
|
-
f"{label}: output column '{name}' has non-boolean 'nullable' {nullable!r}"
|
|
406
|
-
)
|
|
407
|
-
if name in seen_names:
|
|
408
|
-
raise ContractError(f"{label}: duplicate column '{name}' in output_columns")
|
|
409
|
-
seen_names.add(name)
|
|
410
|
-
columns.append(Column(name=name, type=col_type, nullable=nullable))
|
|
411
|
-
|
|
412
|
-
primary_key = _validate_primary_key(raw, mode_type, columns, label)
|
|
413
|
-
assets = _validate_assets(raw, rules, kind, label)
|
|
414
|
-
|
|
415
|
-
description = raw.get("description", "")
|
|
416
|
-
if not isinstance(description, str):
|
|
417
|
-
raise ContractError(f"{label}: 'description' must be a string")
|
|
418
|
-
|
|
419
|
-
config = _validate_config(raw.get("config"), label)
|
|
420
|
-
|
|
421
|
-
content_hash = raw.get("content_hash")
|
|
422
|
-
if content_hash is not None and not isinstance(content_hash, str):
|
|
423
|
-
raise ContractError(f"{label}: 'content_hash' must be a string")
|
|
424
|
-
|
|
170
|
+
values = continuo_values(doc.get("customProperties"))
|
|
171
|
+
description = doc.get("description", {}).get("purpose", "")
|
|
425
172
|
return Node(
|
|
426
|
-
schema=schema,
|
|
427
|
-
table=table,
|
|
428
|
-
owner=
|
|
429
|
-
schedule=schedule,
|
|
430
|
-
criticality=criticality,
|
|
431
|
-
script=script,
|
|
173
|
+
schema=python.schema,
|
|
174
|
+
table=python.table,
|
|
175
|
+
owner=doc["team"]["name"],
|
|
176
|
+
schedule=values["schedule"],
|
|
177
|
+
criticality=values["criticality"],
|
|
178
|
+
script=python.script,
|
|
432
179
|
reads=reads,
|
|
433
|
-
output_columns=tuple(
|
|
180
|
+
output_columns=tuple(
|
|
181
|
+
Column(name=column.name, type=column.type, nullable=column.nullable)
|
|
182
|
+
for column in python.output_columns
|
|
183
|
+
),
|
|
184
|
+
python=python,
|
|
185
|
+
path=file,
|
|
434
186
|
description=description,
|
|
435
|
-
extra_columns=extra_columns,
|
|
187
|
+
extra_columns=python.extra_columns,
|
|
436
188
|
config=config,
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
mode_type=mode_type,
|
|
189
|
+
kind=python.kind,
|
|
190
|
+
secret_ref=python.secret_ref,
|
|
191
|
+
mode_type=python.mode_type,
|
|
441
192
|
primary_key=primary_key,
|
|
442
|
-
timeout_minutes=
|
|
443
|
-
assets=assets,
|
|
193
|
+
timeout_minutes=values.get("timeoutMinutes"),
|
|
194
|
+
assets=tuple(python.assets),
|
|
444
195
|
)
|
|
445
196
|
|
|
446
197
|
|
|
198
|
+
def read_contract_text(file: Path) -> str:
|
|
199
|
+
"""Return the text of the contract ``file`` exactly as written, line endings included."""
|
|
200
|
+
try:
|
|
201
|
+
return file.read_bytes().decode("utf-8")
|
|
202
|
+
except UnicodeDecodeError as exc:
|
|
203
|
+
raise ContractError(f"{file}: the file is not UTF-8 text ({exc})") from None
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def parse_contract(text: str, file: Path | str) -> Mapping[str, Any]:
|
|
207
|
+
"""Return the document of the contract ``text``, read strictly by continuo-contracts.
|
|
208
|
+
|
|
209
|
+
``file`` is only the name the refusals carry.
|
|
210
|
+
"""
|
|
211
|
+
try:
|
|
212
|
+
doc = yaml_strict.load(text)
|
|
213
|
+
except StrictYamlError as exc:
|
|
214
|
+
raise ContractError(f"{file}: {exc}") from None
|
|
215
|
+
if not isinstance(doc, Mapping):
|
|
216
|
+
holds = "nothing" if doc is None else _DOCUMENT_KINDS.get(type(doc), type(doc).__name__)
|
|
217
|
+
raise ContractError(
|
|
218
|
+
f"{file}: a contract file holds one ODCS contract, a mapping; this one holds {holds}"
|
|
219
|
+
)
|
|
220
|
+
return doc
|
|
221
|
+
|
|
222
|
+
|
|
447
223
|
def load_contract_dir(
|
|
448
224
|
path: Path, *, dialect: str | None = None, check_reads: bool = True
|
|
449
225
|
) -> list[Node]:
|
|
450
|
-
"""Load and
|
|
451
|
-
|
|
452
|
-
``
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
226
|
+
"""Load and check every ``*.odcs.yaml`` contract in ``path``, in file-name order.
|
|
227
|
+
|
|
228
|
+
Any other file whose name ends in ``.yml`` or ``.yaml``, in any case
|
|
229
|
+
(``legacy.YML``, ``t.odcs.YAML``, ``t.odcs.yml``), is refused: one
|
|
230
|
+
:class:`ContractError` names every such file, one line each, with how to
|
|
231
|
+
convert it. An image pairs a runtime with its contracts, so a contract in
|
|
232
|
+
another format is a mistake, never a node to skip. Files with any other
|
|
233
|
+
extension are not read.
|
|
234
|
+
|
|
235
|
+
``check_reads=False`` skips only the checks of the reads of a python-node:
|
|
236
|
+
that each parses as one read query and that each names its tables with
|
|
237
|
+
their schemas. Every other rule of :func:`node_from_contract` and every
|
|
238
|
+
rule here (the dialect name, the duplicate relations, the empty folder)
|
|
239
|
+
still runs. The harness
|
|
457
240
|
(:func:`~continuo_python_runtime.harness.run_node`) passes it, because
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
- CI already
|
|
462
|
-
|
|
463
|
-
parser
|
|
464
|
-
- The
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
the per-read ``ensure_single_read`` call matters: an unrecognized
|
|
479
|
-
dialect name (e.g. a typo'd ``--dialect POSTGRES`` instead of
|
|
480
|
-
``postgres``) raises the same bare ``ValueError`` a genuinely
|
|
481
|
-
unparseable read would, and would otherwise be misreported as a
|
|
482
|
-
rejected read instead of a bad flag -- blaming an innocent, valid read.
|
|
483
|
-
|
|
484
|
-
Raises `ContractError` if ``dialect`` is not a sqlglot dialect name, if
|
|
485
|
-
no nodes are found, if any file's document is malformed, or if two nodes
|
|
486
|
-
across files share the same `(schema, table)`.
|
|
241
|
+
checking the reads again at container start can only disagree with the
|
|
242
|
+
checks already passed, never catch a new problem:
|
|
243
|
+
|
|
244
|
+
- CI already checked the reads (``continuo-runtime validate``) under the
|
|
245
|
+
repository's ``--dialect``, and continuo checked them again with its own
|
|
246
|
+
parser before promoting the release.
|
|
247
|
+
- The harness has no ``--dialect`` of its own, so it would parse with
|
|
248
|
+
sqlglot's dialect-neutral grammar, which refuses ordinary postgres such
|
|
249
|
+
as ``a ~ 'x'`` that parses under ``--dialect postgres``.
|
|
250
|
+
- Nothing at run time reads the parse: ``ctx.read`` finds a read by name
|
|
251
|
+
and hands its SQL to the adapter as written.
|
|
252
|
+
|
|
253
|
+
``dialect`` is checked once, before any file is read: sqlglot raises the
|
|
254
|
+
same ``ValueError`` for an unknown dialect name as for a read it cannot
|
|
255
|
+
parse, so a typo such as ``--dialect POSTGRES`` is reported as a bad flag
|
|
256
|
+
instead of blaming a valid read.
|
|
257
|
+
|
|
258
|
+
Raises ``ContractError`` for an unknown ``dialect``, a file in another
|
|
259
|
+
format, a folder with no contract, a contract that is refused, and two
|
|
260
|
+
files that declare the same ``<schema>.<table>``, compared in lower case.
|
|
487
261
|
"""
|
|
488
262
|
if dialect is not None:
|
|
489
263
|
try:
|
|
@@ -491,43 +265,37 @@ def load_contract_dir(
|
|
|
491
265
|
except ValueError as exc:
|
|
492
266
|
raise ContractError(f"unknown --dialect {dialect!r}: {exc}") from exc
|
|
493
267
|
|
|
494
|
-
|
|
268
|
+
entries = sorted(path.iterdir()) if path.is_dir() else []
|
|
269
|
+
yaml_files = [
|
|
270
|
+
entry for entry in entries if entry.name.lower().endswith(_YAML_SUFFIXES)
|
|
271
|
+
]
|
|
272
|
+
files = [entry for entry in yaml_files if entry.name.endswith(CONTRACT_SUFFIX)]
|
|
273
|
+
others = [entry for entry in yaml_files if not entry.name.endswith(CONTRACT_SUFFIX)]
|
|
274
|
+
if others:
|
|
275
|
+
raise ContractError(
|
|
276
|
+
"\n".join(
|
|
277
|
+
f"{other}: runtime 0.13.0 reads only ODCS contracts named "
|
|
278
|
+
f"<table>.odcs.yaml; convert this file ({_CONVERSION_GUIDE})"
|
|
279
|
+
for other in others
|
|
280
|
+
)
|
|
281
|
+
)
|
|
282
|
+
if not files:
|
|
283
|
+
raise ContractError(f"no contract files found in {path}")
|
|
495
284
|
|
|
496
285
|
nodes: list[Node] = []
|
|
497
|
-
|
|
498
|
-
|
|
286
|
+
relation_files: dict[str, Path] = {}
|
|
499
287
|
for file in files:
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
if
|
|
508
|
-
document = {}
|
|
509
|
-
if not isinstance(document, dict):
|
|
288
|
+
doc = parse_contract(read_contract_text(file), file)
|
|
289
|
+
node = node_from_contract(doc, file, dialect=dialect, check_reads=check_reads)
|
|
290
|
+
# Relations are compared in lower case, as continuo compares them: a
|
|
291
|
+
# warehouse folds the case of an unquoted name, so two contracts whose
|
|
292
|
+
# tables differ only in case would build one table.
|
|
293
|
+
key = node.relation.lower()
|
|
294
|
+
existing = relation_files.get(key)
|
|
295
|
+
if existing is not None:
|
|
510
296
|
raise ContractError(
|
|
511
|
-
f"{
|
|
512
|
-
f"got {type(document).__name__}"
|
|
297
|
+
f"duplicate node {node.relation} (in {existing} and {file})"
|
|
513
298
|
)
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
raise ContractError(f"{file.name}: 'nodes' must be a list")
|
|
517
|
-
|
|
518
|
-
for raw_node in raw_nodes:
|
|
519
|
-
node = parse_node(
|
|
520
|
-
raw_node, file.name, dialect=dialect, check_reads=check_reads
|
|
521
|
-
)
|
|
522
|
-
existing_source = relation_sources.get(node.relation)
|
|
523
|
-
if existing_source is not None:
|
|
524
|
-
raise ContractError(
|
|
525
|
-
f"duplicate node {node.relation} (in {existing_source} and {file.name})"
|
|
526
|
-
)
|
|
527
|
-
relation_sources[node.relation] = file.name
|
|
528
|
-
nodes.append(node)
|
|
529
|
-
|
|
530
|
-
if not nodes:
|
|
531
|
-
raise ContractError(f"no contract files found in {path}")
|
|
532
|
-
|
|
299
|
+
relation_files[key] = file
|
|
300
|
+
nodes.append(node)
|
|
533
301
|
return nodes
|