continuo-python-runtime 0.13.0__py3-none-any.whl → 0.15.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.
@@ -8,7 +8,8 @@ import sys
8
8
  from importlib import metadata
9
9
  from pathlib import Path
10
10
 
11
- from continuo_python_runtime.contract.loader import load_contract_dir
11
+ from continuo_python_runtime.contract.loader import load_contract_dir, load_contract_docs
12
+ from continuo_python_runtime.contract.ontology_check import check_project
12
13
  from continuo_python_runtime.contract.pack import (
13
14
  PACKAGE_SOURCE_USAGE,
14
15
  build_bundle,
@@ -57,6 +58,18 @@ def main(argv: list[str] | None = None) -> int:
57
58
  )
58
59
  validate_parser.add_argument("contract_dir", help="Path to contract directory")
59
60
  validate_parser.add_argument("--dialect", default=None, help=dialect_help)
61
+ validate_parser.add_argument(
62
+ "--project",
63
+ default=None,
64
+ help="The project the contracts belong to: a contract whose `project` property "
65
+ "names another project is refused",
66
+ )
67
+ validate_parser.add_argument(
68
+ "--ontology",
69
+ default=None,
70
+ help="The company's ontology file (needs --project): check every contract "
71
+ "against it, as a release does",
72
+ )
60
73
 
61
74
  # pack subcommand
62
75
  pack_parser = subparsers.add_parser(
@@ -68,12 +81,12 @@ def main(argv: list[str] | None = None) -> int:
68
81
  ),
69
82
  )
70
83
  pack_parser.add_argument("contract_dir", help="Path to contract directory")
71
- pack_parser.add_argument("--service", required=True, help="Service name")
84
+ pack_parser.add_argument("--project", required=True, help="Project name")
72
85
  pack_parser.add_argument("--repo-root", required=True, help="Repository root path")
73
86
  pack_parser.add_argument(
74
87
  "--image",
75
88
  default=None,
76
- help="Image the service runs; its package list is read with "
89
+ help="Image the project runs; its package list is read with "
77
90
  "`docker run --entrypoint continuo-runtime <image> packages`",
78
91
  )
79
92
  pack_parser.add_argument(
@@ -120,16 +133,23 @@ def main(argv: list[str] | None = None) -> int:
120
133
  )
121
134
 
122
135
  args = parser.parse_args(argv)
136
+ if args.command == "validate" and args.ontology is not None and args.project is None:
137
+ validate_parser.error("--ontology needs --project")
123
138
  if args.command == "pack" and (args.image is None) == (args.image_packages is None):
124
139
  pack_parser.error(PACKAGE_SOURCE_USAGE)
125
140
 
126
141
  try:
127
142
  if args.command == "validate":
128
- return cmd_validate(args.contract_dir, args.dialect)
143
+ return cmd_validate(
144
+ args.contract_dir,
145
+ args.dialect,
146
+ project=args.project,
147
+ ontology=args.ontology,
148
+ )
129
149
  elif args.command == "pack":
130
150
  return cmd_pack(
131
151
  args.contract_dir,
132
- args.service,
152
+ args.project,
133
153
  args.repo_root,
134
154
  args.out,
135
155
  image=args.image,
@@ -158,15 +178,67 @@ def main(argv: list[str] | None = None) -> int:
158
178
  return 0
159
179
 
160
180
 
161
- def cmd_validate(contract_dir: str, dialect: str | None = None) -> int:
162
- """Validate contracts in a directory."""
163
- load_contract_dir(Path(contract_dir), dialect=dialect)
164
- return 0
181
+ _FINDING_LEVELS = {"error": logging.ERROR, "warning": logging.WARNING, "info": logging.INFO}
182
+
183
+
184
+ def cmd_validate(
185
+ contract_dir: str,
186
+ dialect: str | None = None,
187
+ *,
188
+ project: str | None = None,
189
+ ontology: str | None = None,
190
+ ) -> int:
191
+ """Validate contracts in a directory.
192
+
193
+ With no ``project``, every contract is checked as a contract of any project
194
+ and nothing is logged. With a ``project``, a contract whose ``project``
195
+ property names another one is refused too, as ``pack`` refuses it.
196
+
197
+ With an ``ontology`` file (which needs the ``project``), each contract is
198
+ then checked against it by the per-project rules of continuo-contracts.
199
+ Each finding is logged at its level, ERROR for an error, WARNING for a
200
+ warning and INFO for information, as ``<severity> [<rule>] <subject>:
201
+ <message>``, in the order the library returns them, followed by one INFO
202
+ line counting the three. Any error makes the exit code 1. An ontology file
203
+ that cannot be read, is not an ontology or is refused by the library's
204
+ ``ontology`` rule is one ERROR line and exit 1, before any finding. Nothing
205
+ goes to stdout.
206
+ """
207
+ if project is None:
208
+ load_contract_dir(Path(contract_dir), dialect=dialect)
209
+ return 0
210
+ loaded = load_contract_docs(Path(contract_dir), dialect=dialect, project=project)
211
+ if ontology is None:
212
+ return 0
213
+
214
+ findings = check_project(
215
+ [doc for _, doc in loaded], project=project, ontology_path=Path(ontology)
216
+ )
217
+ for finding in findings:
218
+ logger.log(
219
+ _FINDING_LEVELS[finding.severity],
220
+ "%s [%s] %s: %s",
221
+ finding.severity,
222
+ finding.rule,
223
+ finding.subject,
224
+ finding.message,
225
+ )
226
+ counts = {severity: 0 for severity in _FINDING_LEVELS}
227
+ for finding in findings:
228
+ counts[finding.severity] += 1
229
+ logger.info(
230
+ "%d error(s), %d warning(s), %d info: %s",
231
+ counts["error"],
232
+ counts["warning"],
233
+ counts["info"],
234
+ project,
235
+ )
236
+ return 1 if counts["error"] else 0
165
237
 
166
238
 
167
239
  def cmd_pack(
168
240
  contract_dir: str,
169
- service: str,
241
+ project: str,
170
242
  repo_root: str,
171
243
  out: str,
172
244
  *,
@@ -183,7 +255,7 @@ def cmd_pack(
183
255
  packages = image_packages_from(
184
256
  image=image, image_packages=None if image_packages is None else Path(image_packages)
185
257
  )
186
- doc = build_bundle(Path(contract_dir), Path(repo_root), service, packages, dialect=dialect)
258
+ doc = build_bundle(Path(contract_dir), Path(repo_root), project, packages, dialect=dialect)
187
259
  write_bundle(doc, Path(out))
188
260
  return 0
189
261
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  A contracts folder holds one ODCS v3.2.0 contract per node, in a file named
4
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
5
+ project share a table name. continuo-contracts reads each file strictly, checks
6
6
  it and maps it to its ``PythonNode``; the runtime then applies the rules it
7
7
  keeps for itself and builds its :class:`~continuo_python_runtime.contract.model
8
8
  .Node`. Every refusal is a :class:`ContractError` that names the file.
@@ -129,15 +129,22 @@ def issue_lines(file: Path | str, issues: Iterable[object]) -> list[str]:
129
129
 
130
130
 
131
131
  def node_from_contract(
132
- doc: Mapping[str, Any], file: Path, *, dialect: str | None, check_reads: bool
132
+ doc: Mapping[str, Any],
133
+ file: Path,
134
+ *,
135
+ dialect: str | None,
136
+ check_reads: bool,
137
+ project: str | None = None,
133
138
  ) -> Node:
134
139
  """Check the ODCS contract ``doc``, read from ``file``, and build its :class:`Node`.
135
140
 
136
141
  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.
142
+ (``validate_python_contract``, of which only the base name of ``file``
143
+ counts for the file-name rule). With a ``project`` it also refuses a
144
+ contract whose authored ``project`` property names another project; with
145
+ none, that property is not compared. When it finds issues they become one
146
+ :class:`ContractError` with one :func:`issue_lines` line per issue, and
147
+ nothing else runs.
141
148
 
142
149
  The runtime's own rules follow, each naming ``file`` and the relation:
143
150
  the kind's reads rule (:mod:`~continuo_python_runtime.contract.kinds`),
@@ -155,7 +162,7 @@ def node_from_contract(
155
162
  ``required``), ``extra_columns``, ``config``, ``secret_ref``,
156
163
  ``mode_type``, the key when the node upserts and the assets.
157
164
  """
158
- issues = validate_python_contract(doc, path=str(file), service=None)
165
+ issues = validate_python_contract(doc, path=str(file), project=project)
159
166
  if issues:
160
167
  raise ContractError("\n".join(issue_lines(file, issues)))
161
168
  python = node_from_odcs(doc)
@@ -225,6 +232,27 @@ def load_contract_dir(
225
232
  ) -> list[Node]:
226
233
  """Load and check every ``*.odcs.yaml`` contract in ``path``, in file-name order.
227
234
 
235
+ The nodes, as :func:`load_contract_docs` loads them with no project. Every
236
+ refusal and every rule are described there.
237
+ """
238
+ return [node for node, _ in load_contract_docs(path, dialect=dialect, check_reads=check_reads)]
239
+
240
+
241
+ def load_contract_docs(
242
+ path: Path,
243
+ *,
244
+ dialect: str | None = None,
245
+ check_reads: bool = True,
246
+ project: str | None = None,
247
+ ) -> list[tuple[Node, Mapping[str, Any]]]:
248
+ """Load and check every ``*.odcs.yaml`` contract in ``path``, in file-name order.
249
+
250
+ Each node comes with the document it was built from, the one read from its
251
+ file and checked, so a caller that needs the documents does not read the
252
+ files again. ``project``, when given, is the project the contracts belong
253
+ to: continuo-contracts then refuses a contract whose authored ``project``
254
+ property names another one, as :func:`node_from_contract` says.
255
+
228
256
  Any other file whose name ends in ``.yml`` or ``.yaml``, in any case
229
257
  (``legacy.YML``, ``t.odcs.YAML``, ``t.odcs.yml``), is refused: one
230
258
  :class:`ContractError` names every such file, one line each, with how to
@@ -256,7 +284,8 @@ def load_contract_dir(
256
284
  instead of blaming a valid read.
257
285
 
258
286
  Raises ``ContractError`` for an unknown ``dialect``, a file in another
259
- format, a folder with no contract, a contract that is refused, and two
287
+ format, a folder with no contract, a contract that is refused (one that
288
+ names another project than ``project``, when given, included), and two
260
289
  files that declare the same ``<schema>.<table>``, compared in lower case.
261
290
  """
262
291
  if dialect is not None:
@@ -282,11 +311,13 @@ def load_contract_dir(
282
311
  if not files:
283
312
  raise ContractError(f"no contract files found in {path}")
284
313
 
285
- nodes: list[Node] = []
314
+ loaded: list[tuple[Node, Mapping[str, Any]]] = []
286
315
  relation_files: dict[str, Path] = {}
287
316
  for file in files:
288
317
  doc = parse_contract(read_contract_text(file), file)
289
- node = node_from_contract(doc, file, dialect=dialect, check_reads=check_reads)
318
+ node = node_from_contract(
319
+ doc, file, dialect=dialect, check_reads=check_reads, project=project
320
+ )
290
321
  # Relations are compared in lower case, as continuo compares them: a
291
322
  # warehouse folds the case of an unquoted name, so two contracts whose
292
323
  # tables differ only in case would build one table.
@@ -297,5 +328,5 @@ def load_contract_dir(
297
328
  f"duplicate node {node.relation} (in {existing} and {file})"
298
329
  )
299
330
  relation_files[key] = file
300
- nodes.append(node)
301
- return nodes
331
+ loaded.append((node, doc))
332
+ return loaded
@@ -0,0 +1,89 @@
1
+ """Check a Python project's contracts against the company's ontology file.
2
+
3
+ ``continuo-runtime validate --project <name> --ontology <file>`` runs the
4
+ per-project rules of continuo-contracts over the contracts of one project:
5
+ each contract is stored as a release stores it, filled with what the
6
+ ontology knows and checked, so a team sees in its own CI what a release says
7
+ about its bindings. The rules read contracts against an ontology file that the
8
+ library's own ``ontology`` rule accepts, so a file that rule refuses stops the
9
+ check before any contract is read, as it does in the library's dbt check. This
10
+ is the only module of the runtime that imports the library's ontology modules.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from collections.abc import Mapping, Sequence
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ from continuo_contracts import ontology
20
+ from continuo_contracts.contract import normalise_python
21
+ from continuo_contracts.errors import ContractsError, OntologyError
22
+ from continuo_contracts.ontology_check import (
23
+ PER_PROJECT_RULES,
24
+ Finding,
25
+ check,
26
+ ontology_findings,
27
+ )
28
+
29
+ from continuo_python_runtime.errors import ContractError
30
+
31
+
32
+ def _read_ontology(ontology_path: Path) -> ontology.Ontology:
33
+ """Return the ontology the file ``ontology_path`` holds.
34
+
35
+ Raises ``ContractError``, with the message ``<file>: <reason>``, for a file
36
+ that cannot be read (missing, a folder, no permission), one that is not
37
+ UTF-8 text and one the library does not accept as an ontology, whose
38
+ reason is the library's own message. The ``ontology`` rule, which can
39
+ refuse a file that loads, is run by :func:`check_project`.
40
+ """
41
+ try:
42
+ text = ontology_path.read_bytes().decode("utf-8")
43
+ except OSError as exc:
44
+ raise ContractError(f"{ontology_path}: {exc.strerror or exc}") from None
45
+ except UnicodeDecodeError as exc:
46
+ raise ContractError(f"{ontology_path}: the file is not UTF-8 text ({exc})") from None
47
+ try:
48
+ return ontology.load(text)
49
+ except OntologyError as exc:
50
+ raise ContractError(f"{ontology_path}: {exc}") from None
51
+
52
+
53
+ def check_project(
54
+ docs: Sequence[Mapping[str, Any]], *, project: str, ontology_path: Path
55
+ ) -> list[Finding]:
56
+ """Return the findings of the per-project rules over ``docs``, the contracts of ``project``.
57
+
58
+ ``docs`` are contract documents that continuo-contracts already accepted as
59
+ a Python contract; none is changed. The ontology file is read first, and
60
+ the library's ``ontology`` rule runs over it alone. Each document then goes
61
+ through ``normalise_python`` as the contract of ``project`` that reads
62
+ nothing the ontology tracks, then through ``ontology.resolve``, and the
63
+ rules ``contract``, ``coverage``, ``quality`` and ``privacy`` run over all
64
+ of them. The findings come as the library returns them, sorted. A
65
+ ``project`` the ontology does not declare gets the library's one
66
+ information finding and one warning for each contract that writes a
67
+ binding.
68
+
69
+ Raises ``ContractError`` when ``ontology_path`` cannot be read or is not an
70
+ ontology (see :func:`_read_ontology`), when the ``ontology`` rule finds an
71
+ error in the file, whatever ``project`` is (the message is ``<file>: the
72
+ ontology file has <n> error(s): run continuo-contracts ontology check
73
+ <file>``, and no contract is read against the file), and when ``project``
74
+ is blank. Findings of the ``ontology`` rule that are not errors do not stop
75
+ the check.
76
+ """
77
+ loaded = _read_ontology(ontology_path)
78
+ broken = sum(finding.severity == "error" for finding in ontology_findings(loaded))
79
+ if broken:
80
+ raise ContractError(
81
+ f"{ontology_path}: the ontology file has {broken} error(s): "
82
+ f"run continuo-contracts ontology check {ontology_path}"
83
+ )
84
+ try:
85
+ stored = [normalise_python(doc, project=project, reads=[]) for doc in docs]
86
+ except ContractsError as exc:
87
+ raise ContractError(str(exc)) from None
88
+ resolved = [ontology.resolve(contract, loaded) for contract in stored]
89
+ return check(loaded, resolved, rules=PER_PROJECT_RULES)
@@ -1,12 +1,12 @@
1
- """``continuo-runtime pack``: the bundle of a service's ODCS contracts.
1
+ """``continuo-runtime pack``: the bundle of a project's ODCS contracts.
2
2
 
3
- A service's CI packs the contracts of its ``contracts/`` folder into one
3
+ A project's CI packs the contracts of its ``contracts/`` folder into one
4
4
  ``odcs-bundle.json`` and uploads it with the release. The bundle is UTF-8 JSON,
5
5
  written by :func:`write_bundle` as ``json.dumps(doc, sort_keys=True, indent=2,
6
6
  ensure_ascii=False)`` and a newline, and holds::
7
7
 
8
8
  {"bundle_version": 1,
9
- "service": <service>,
9
+ "project": <project>,
10
10
  "producer": {"continuo_python_runtime": <version>, "continuo_contracts": <version>},
11
11
  "image_packages": {<name>: <version>},
12
12
  "nodes": [{"path": <repo path of the contract file>,
@@ -18,7 +18,7 @@ ensure_ascii=False)`` and a newline, and holds::
18
18
  are the two parts :func:`~continuo_python_runtime.hashing.hash_parts` computes from
19
19
  the files of the repository; the third part, the config hash, is computed from the
20
20
  contract text by whoever reads the bundle. ``image_packages`` is the package list of
21
- the image the service runs, read from that image, never from the environment ``pack``
21
+ the image the project runs, read from that image, never from the environment ``pack``
22
22
  runs in.
23
23
  """
24
24
 
@@ -51,7 +51,7 @@ from continuo_python_runtime.lint import lint_source
51
51
  BUNDLE_VERSION = 1
52
52
 
53
53
  PACKAGE_SOURCE_USAGE = (
54
- "pack records the package list of the image the service runs: give exactly one of "
54
+ "pack records the package list of the image the project runs: give exactly one of "
55
55
  "--image <ref> (read from the image) or --image-packages <file> "
56
56
  "(a JSON object of package name to version)"
57
57
  )
@@ -155,7 +155,7 @@ def _repo_path(file: Path, repo_root: Path) -> str:
155
155
  def build_bundle(
156
156
  contract_dir: Path,
157
157
  repo_root: Path,
158
- service: str,
158
+ project: str,
159
159
  image_packages: Mapping[str, str],
160
160
  *,
161
161
  dialect: str | None = None,
@@ -165,7 +165,7 @@ def build_bundle(
165
165
  The contracts are loaded as :func:`~continuo_python_runtime.contract.loader
166
166
  .load_contract_dir` loads them, every read checked under ``dialect`` (``None``
167
167
  is sqlglot's dialect-neutral parser). Each contract is then checked once more
168
- against ``service`` by continuo-contracts, as the release does: one
168
+ against ``project`` by continuo-contracts, as the release does: one
169
169
  ``ContractError`` lists every issue of every file, one line each, naming the
170
170
  file by its path below ``repo_root``.
171
171
 
@@ -183,7 +183,7 @@ def build_bundle(
183
183
  files = [(node, _repo_path(node.path, repo_root), read_contract_text(node.path)) for node in nodes]
184
184
  issues: list[str] = []
185
185
  for _, path, text in files:
186
- found = validate_python_contract(parse_contract(text, path), path=path, service=service)
186
+ found = validate_python_contract(parse_contract(text, path), path=path, project=project)
187
187
  issues.extend(issue_lines(path, found))
188
188
  if issues:
189
189
  raise ContractError("\n".join(issues))
@@ -205,7 +205,7 @@ def build_bundle(
205
205
 
206
206
  return {
207
207
  "bundle_version": BUNDLE_VERSION,
208
- "service": service,
208
+ "project": project,
209
209
  "producer": {
210
210
  "continuo_python_runtime": metadata.version("continuo-python-runtime"),
211
211
  "continuo_contracts": metadata.version("continuo-contracts"),
@@ -1,7 +1,7 @@
1
1
  """The distributions installed in the running Python environment.
2
2
 
3
3
  ``continuo-runtime packages`` prints them, so that a producer bundle records exactly
4
- what the image its service runs holds.
4
+ what the image its project runs holds.
5
5
  """
6
6
 
7
7
  import logging