map-conform 0.1.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.
Files changed (79) hide show
  1. map_conform/__init__.py +5 -0
  2. map_conform/__main__.py +7 -0
  3. map_conform/batch/__init__.py +1 -0
  4. map_conform/batch/arrow.py +80 -0
  5. map_conform/batch/columnar.py +125 -0
  6. map_conform/batch/engine.py +191 -0
  7. map_conform/batch/files.py +207 -0
  8. map_conform/cli.py +460 -0
  9. map_conform/doctor.py +178 -0
  10. map_conform/errors.py +107 -0
  11. map_conform/expr/__init__.py +6 -0
  12. map_conform/expr/compiler.py +562 -0
  13. map_conform/expr/functions.py +542 -0
  14. map_conform/expr/sandbox.py +333 -0
  15. map_conform/expr/sdk.py +116 -0
  16. map_conform/map-conform-spec.schema.json +1204 -0
  17. map_conform/mapper.py +355 -0
  18. map_conform/metadata.py +73 -0
  19. map_conform/metrics.py +62 -0
  20. map_conform/naming/__init__.py +1 -0
  21. map_conform/naming/ascii-table.json +980 -0
  22. map_conform/naming/conform.py +262 -0
  23. map_conform/naming/flatten.py +148 -0
  24. map_conform/naming/nested.py +117 -0
  25. map_conform/naming/reserved/ansi.txt +369 -0
  26. map_conform/naming/reserved/duckdb.txt +114 -0
  27. map_conform/naming/reserved/postgres.txt +105 -0
  28. map_conform/naming/reserved/snowflake.txt +90 -0
  29. map_conform/naming/reserved.py +34 -0
  30. map_conform/naming/shape.py +96 -0
  31. map_conform/naming/streams.py +76 -0
  32. map_conform/naming/translit.py +170 -0
  33. map_conform/plan/__init__.py +1 -0
  34. map_conform/plan/chain.py +667 -0
  35. map_conform/plan/compile.py +551 -0
  36. map_conform/plan/lower.py +281 -0
  37. map_conform/plan/ops.py +336 -0
  38. map_conform/plan/row.py +212 -0
  39. map_conform/plan/vector.py +71 -0
  40. map_conform/rejects.py +92 -0
  41. map_conform/settings.py +157 -0
  42. map_conform/spec/__init__.py +1 -0
  43. map_conform/spec/_struct.py +483 -0
  44. map_conform/spec/bridge.py +109 -0
  45. map_conform/spec/check.py +380 -0
  46. map_conform/spec/errors.py +22 -0
  47. map_conform/spec/importer.py +87 -0
  48. map_conform/spec/jsonschema.py +54 -0
  49. map_conform/spec/load.py +357 -0
  50. map_conform/spec/model.py +473 -0
  51. map_conform/spec/reference.py +179 -0
  52. map_conform/spec/steps.py +297 -0
  53. map_conform/spec/stream_maps.py +233 -0
  54. map_conform/spec/zamboni.py +99 -0
  55. map_conform/transforms/__init__.py +1 -0
  56. map_conform/transforms/builtins.py +63 -0
  57. map_conform/transforms/casts.py +310 -0
  58. map_conform/transforms/fake.py +150 -0
  59. map_conform/transforms/nested.py +111 -0
  60. map_conform/transforms/numeric.py +318 -0
  61. map_conform/transforms/polars_vector.py +151 -0
  62. map_conform/transforms/privacy.py +220 -0
  63. map_conform/transforms/registry.py +116 -0
  64. map_conform/transforms/temporal.py +410 -0
  65. map_conform/transforms/text.py +249 -0
  66. map_conform/transforms/vector.py +386 -0
  67. map_conform/types/__init__.py +1 -0
  68. map_conform/types/canonical.py +255 -0
  69. map_conform/types/from_jsonschema.py +177 -0
  70. map_conform/types/jsontext.py +63 -0
  71. map_conform/types/to_arrow.py +52 -0
  72. map_conform/types/to_jsonschema.py +65 -0
  73. map_conform/types/wire.py +53 -0
  74. map_conform/udfs.py +327 -0
  75. map_conform-0.1.0.dist-info/METADATA +157 -0
  76. map_conform-0.1.0.dist-info/RECORD +79 -0
  77. map_conform-0.1.0.dist-info/WHEEL +4 -0
  78. map_conform-0.1.0.dist-info/entry_points.txt +2 -0
  79. map_conform-0.1.0.dist-info/licenses/LICENSE +201 -0
map_conform/cli.py ADDED
@@ -0,0 +1,460 @@
1
+ """The ``map-conform`` command.
2
+
3
+ Meltano runs the mapper as ``map-conform --config ... [--about]``; those arguments go to the
4
+ Singer SDK's CLI unchanged. Tool subcommands (``map-conform spec ...``) are handled here.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import dataclasses
10
+ import json
11
+ import sys
12
+ from pathlib import Path
13
+ from typing import TYPE_CHECKING, Any
14
+
15
+ import click
16
+ import yaml
17
+
18
+ from map_conform.doctor import check_project
19
+ from map_conform.expr.functions import FUNCTIONS
20
+ from map_conform.mapper import MapConformMapper
21
+ from map_conform.plan.compile import compile_stream, plan_report
22
+ from map_conform.spec.bridge import draft_from_catalog, export_columns
23
+ from map_conform.spec.check import CatalogStream, check_spec, explain, read_catalog
24
+ from map_conform.spec.errors import SpecError
25
+ from map_conform.spec.importer import import_stream_maps
26
+ from map_conform.spec.jsonschema import render
27
+ from map_conform.spec.load import load_spec, output_streams
28
+ from map_conform.spec.zamboni import namespace_of, read_table_config, write_table_config
29
+ from map_conform.transforms.builtins import builtin_registry
30
+ from map_conform.udfs import load_udfs, registry_with
31
+
32
+ if TYPE_CHECKING:
33
+ from map_conform.spec.model import Spec
34
+ from map_conform.transforms.registry import Registry, Transform
35
+
36
+ TOOL_COMMANDS = frozenset({"spec", "functions", "doctor"})
37
+
38
+
39
+ @click.group(name="map-conform")
40
+ def tools() -> None:
41
+ """map-conform tools. Run without a subcommand, map-conform is the Singer mapper."""
42
+
43
+
44
+ @tools.group()
45
+ def spec() -> None:
46
+ """Work with conform spec files."""
47
+
48
+
49
+ @spec.command(name="schema")
50
+ def spec_schema() -> None:
51
+ """Print the conform spec's JSON Schema."""
52
+ click.echo(render(), nl=False)
53
+
54
+
55
+ _SPEC_ARG = click.argument("spec_path", metavar="SPEC", type=click.Path(dir_okay=False))
56
+ _CATALOG = click.option(
57
+ "--catalog",
58
+ type=click.Path(exists=True, dir_okay=False),
59
+ help="A Singer catalog to check the spec against.",
60
+ )
61
+ _ZAMBONI = click.option(
62
+ "--zamboni",
63
+ type=click.Path(exists=True, dir_okay=False),
64
+ help="A Zamboni table-config (version 2) whose columns give the types.",
65
+ )
66
+ _NAMESPACE = click.option(
67
+ "--namespace", help="The Zamboni namespace, when the table-config has several."
68
+ )
69
+ _VARS = click.option(
70
+ "--var",
71
+ "variables",
72
+ multiple=True,
73
+ metavar="NAME=VALUE",
74
+ help="A spec variable for ${NAME}; repeatable.",
75
+ )
76
+
77
+
78
+ def _spec_vars(variables: tuple[str, ...]) -> dict[str, Any]:
79
+ spec_vars: dict[str, Any] = {}
80
+ for item in variables:
81
+ name, sep, value = item.partition("=")
82
+ if not sep or not name:
83
+ raise click.BadParameter(f"{item!r} is not NAME=VALUE", param_hint="--var")
84
+ spec_vars[name] = value
85
+ return spec_vars
86
+
87
+
88
+ def _load(
89
+ spec_path: str, variables: tuple[str, ...], catalog_path: str | None
90
+ ) -> tuple[Spec, list[CatalogStream] | None]:
91
+ """Load the spec (and catalog), or print every problem and exit 1."""
92
+ spec_vars = _spec_vars(variables)
93
+ try:
94
+ spec = load_spec(spec_path, spec_vars=spec_vars)
95
+ catalog = read_catalog(catalog_path) if catalog_path else None
96
+ except SpecError as exc:
97
+ click.echo(f"{exc.source}: {len(exc.issues)} problem(s)", err=True)
98
+ for issue in exc.issues:
99
+ click.echo(f" {issue}", err=True)
100
+ sys.exit(1)
101
+ return spec, catalog
102
+
103
+
104
+ @spec.command(name="validate")
105
+ @_SPEC_ARG
106
+ @_CATALOG
107
+ @_VARS
108
+ @click.option("--strict", is_flag=True, help="Treat warnings as errors.")
109
+ def spec_validate(
110
+ spec_path: str, catalog: str | None, variables: tuple[str, ...], *, strict: bool
111
+ ) -> None:
112
+ """Parse SPEC strictly and report every problem with its path.
113
+
114
+ With --catalog, also check it against the catalog's streams: output names, column
115
+ references, explicit names, collisions, key properties and undeclared columns.
116
+ """
117
+ loaded, streams = _load(spec_path, variables, catalog)
118
+ findings = check_spec(loaded, streams)
119
+ for finding in findings:
120
+ click.echo(str(finding), err=True)
121
+ errors = [f for f in findings if f.severity == "error" or strict]
122
+ if errors:
123
+ click.echo(f"{spec_path}: {len(errors)} problem(s)", err=True)
124
+ sys.exit(1)
125
+ checked = f", checked against {len(streams)} catalog stream(s)" if streams else ""
126
+ click.echo(f"{spec_path}: valid ({len(loaded.streams)} stream rule(s){checked})")
127
+
128
+
129
+ @spec.command(name="import")
130
+ @click.option(
131
+ "--stream-maps",
132
+ "config_path",
133
+ type=click.Path(exists=True, dir_okay=False),
134
+ help="A plugin config (JSON) with SDK stream_maps and flattening settings.",
135
+ )
136
+ @_CATALOG
137
+ @_ZAMBONI
138
+ @_NAMESPACE
139
+ @click.option(
140
+ "-o", "--output", type=click.Path(dir_okay=False), help="Write the spec here, not stdout."
141
+ )
142
+ def spec_import(
143
+ config_path: str | None,
144
+ catalog: str | None,
145
+ zamboni: str | None,
146
+ namespace: str | None,
147
+ output: str | None,
148
+ ) -> None:
149
+ """Draft a spec from a catalog (and Zamboni columns), or convert SDK stream_maps.
150
+
151
+ With --stream-maps, the SDK settings become a native spec, and --catalog makes the types
152
+ the SDK takes from tap properties explicit. Without it, --catalog drafts a spec with an
153
+ explicit canonical type for every property, taken from --zamboni's columns where given.
154
+ """
155
+ if config_path is None and catalog is None:
156
+ raise click.UsageError("give --catalog CATALOG.json, --stream-maps CONFIG.json, or both")
157
+ if zamboni is not None and (config_path is not None or catalog is None):
158
+ raise click.UsageError(
159
+ "--zamboni drafts from a --catalog; it does not apply to stream maps"
160
+ )
161
+ try:
162
+ streams = read_catalog(catalog) if catalog else None
163
+ if config_path is not None:
164
+ config = json.loads(Path(config_path).read_text(encoding="utf-8"))
165
+ native, notes = import_stream_maps(config, streams)
166
+ else:
167
+ assert streams is not None # noqa: S101 -- checked above
168
+ document = read_table_config(zamboni) if zamboni else None
169
+ space = namespace_of(document, namespace, zamboni) if document and zamboni else None
170
+ native, notes = draft_from_catalog(streams, document, space)
171
+ except (OSError, json.JSONDecodeError) as exc:
172
+ raise click.ClickException(f"cannot read {config_path}: {exc}") from exc
173
+ except SpecError as exc:
174
+ click.echo(f"{exc.source}: {len(exc.issues)} problem(s)", err=True)
175
+ for issue in exc.issues:
176
+ click.echo(f" {issue}", err=True)
177
+ sys.exit(1)
178
+ text = yaml.safe_dump(native, sort_keys=False, allow_unicode=True, width=100)
179
+ if output:
180
+ Path(output).write_text(text, encoding="utf-8")
181
+ else:
182
+ click.echo(text, nl=False)
183
+ for note in notes:
184
+ click.echo(f"note: {note}", err=True)
185
+
186
+
187
+ @spec.command(name="export")
188
+ @_SPEC_ARG
189
+ @click.option(
190
+ "--zamboni",
191
+ "zamboni",
192
+ required=True,
193
+ type=click.Path(exists=True, dir_okay=False),
194
+ help="The Zamboni table-config (version 2) whose columns to fill.",
195
+ )
196
+ @click.option(
197
+ "--catalog",
198
+ required=True,
199
+ type=click.Path(exists=True, dir_okay=False),
200
+ help="The Singer catalog to compile each stream against.",
201
+ )
202
+ @_NAMESPACE
203
+ @_VARS
204
+ @click.option(
205
+ "-o", "--output", type=click.Path(dir_okay=False), help="Write here instead of in place."
206
+ )
207
+ def spec_export( # noqa: PLR0913 -- one parameter per option
208
+ spec_path: str,
209
+ *,
210
+ zamboni: str,
211
+ catalog: str,
212
+ namespace: str | None,
213
+ variables: tuple[str, ...],
214
+ output: str | None,
215
+ ) -> None:
216
+ """Write each output stream's canonical column types into Zamboni table-config columns."""
217
+ loaded, streams = _load(spec_path, variables, catalog)
218
+ assert streams is not None # noqa: S101 -- --catalog is required
219
+ try:
220
+ document = read_table_config(zamboni)
221
+ space = namespace_of(document, namespace, zamboni)
222
+ registry = _registry(loaded, allow_python_udfs=False)
223
+ written = export_columns(
224
+ loaded, streams, document, space, registry=registry, config=_spec_vars(variables)
225
+ )
226
+ except SpecError as exc:
227
+ click.echo(f"{exc.source}: {len(exc.issues)} problem(s)", err=True)
228
+ for issue in exc.issues:
229
+ click.echo(f" {issue}", err=True)
230
+ sys.exit(1)
231
+ write_table_config(document, output or zamboni)
232
+ click.echo(f"{output or zamboni}: columns written for {', '.join(written) or 'no table'}")
233
+
234
+
235
+ @spec.command(name="explain")
236
+ @_SPEC_ARG
237
+ @click.option("--stream", "tap_stream", required=True, help="The tap stream to explain.")
238
+ @_CATALOG
239
+ @_VARS
240
+ @click.option("--json", "as_json", is_flag=True, help="Print the report as JSON.")
241
+ @click.option(
242
+ "--allow-python-udfs",
243
+ is_flag=True,
244
+ help="Import the spec's module-path UDFs, as the allow_python_udfs setting does.",
245
+ )
246
+ def spec_explain( # noqa: PLR0913 -- one parameter per option
247
+ spec_path: str,
248
+ tap_stream: str,
249
+ catalog: str | None,
250
+ variables: tuple[str, ...],
251
+ *,
252
+ as_json: bool,
253
+ allow_python_udfs: bool,
254
+ ) -> None:
255
+ """Show what SPEC does to one tap stream: rules matched, output names, columns."""
256
+ loaded, streams = _load(spec_path, variables, catalog)
257
+ report = explain(loaded, tap_stream, streams)
258
+ entry = next((s for s in streams or [] if s.name == tap_stream), None)
259
+ if entry is not None:
260
+ try:
261
+ registry = _registry(loaded, allow_python_udfs=allow_python_udfs)
262
+ except SpecError as exc:
263
+ report["findings"].extend(str(i) for i in exc.issues)
264
+ else:
265
+ _add_plans(loaded, entry, report, _spec_vars(variables), registry)
266
+ if as_json:
267
+ click.echo(json.dumps(report, indent=2, ensure_ascii=False))
268
+ else:
269
+ click.echo(_render_explain(report))
270
+ if report["findings"]:
271
+ sys.exit(1)
272
+
273
+
274
+ def _registry(loaded: Spec | None, *, allow_python_udfs: bool) -> Registry:
275
+ """The builtins plus installed UDFs (and the spec's, when allowed)."""
276
+ spec_udfs = loaded.udfs if loaded is not None else {}
277
+ udfs = load_udfs(spec_udfs, allow_python_udfs=allow_python_udfs)
278
+ return registry_with(builtin_registry(), udfs)
279
+
280
+
281
+ def _add_plans(
282
+ loaded: Spec,
283
+ entry: CatalogStream,
284
+ report: dict[str, Any],
285
+ config: dict[str, Any],
286
+ registry: Registry,
287
+ ) -> None:
288
+ """Compile each output stream against the catalog schema and add the plan."""
289
+ schema = {"type": "object", "properties": dict(entry.properties)}
290
+ for output, resolved in zip(report["outputs"], output_streams(loaded, entry.name), strict=True):
291
+ try:
292
+ plan = compile_stream(
293
+ loaded,
294
+ resolved,
295
+ schema,
296
+ registry,
297
+ key_properties=entry.key_properties,
298
+ config=config,
299
+ )
300
+ except SpecError as exc:
301
+ report["findings"].extend(str(i) for i in exc.issues)
302
+ continue
303
+ output["plan"] = plan_report(plan)
304
+
305
+
306
+ def _render_plan(plan: dict[str, Any]) -> list[str]:
307
+ lines = [" plan:"]
308
+ for column in plan["columns"]:
309
+ flags = "" if column["nullable"] else " not null"
310
+ lines.append(
311
+ f" {column['name']}: {column['type']}{flags}, on_error {column['on_error']}"
312
+ )
313
+ lines.append(f" steps: {' -> '.join(column['steps'])}")
314
+ if "default" in column:
315
+ lines.append(f" default: {column['default']}")
316
+ if "enum" in column:
317
+ lines.append(f" enum: {', '.join(column['enum'])}")
318
+ if "reads" in column:
319
+ lines.append(f" reads: {', '.join(column['reads'])}")
320
+ if "filter" in plan:
321
+ lines.append(f" filter: {plan['filter']}")
322
+ return lines
323
+
324
+
325
+ def _render_column(column: dict[str, Any]) -> list[str]:
326
+ source = ", ".join(column["source"] or ["(derived)"])
327
+ kind = column["type"] or (f"tap {column['tap_type']}" if column["tap_type"] else "?")
328
+ extra = "" if column["declared"] else " [undeclared]"
329
+ lines = [f" {source} -> {column['name']} {kind}{extra}"]
330
+ if "expr" in column:
331
+ lines.append(f" expr: {column['expr']}")
332
+ if "transform" in column:
333
+ lines.append(f" transform: {json.dumps(column['transform'], ensure_ascii=False)}")
334
+ lines.extend(f" note: {note}" for note in column.get("notes", []))
335
+ return lines
336
+
337
+
338
+ def _render_explain(report: dict[str, Any]) -> str:
339
+ lines = [f"tap stream: {report['tap_stream']}"]
340
+ if report["in_catalog"] is False:
341
+ lines.append(" (not in the catalog: only the spec's columns are known)")
342
+ lines.append(f"rules matched: {', '.join(report['matched']) or '(none: defaults)'}")
343
+ if report.get("dropped"):
344
+ lines.append("dropped: no output stream")
345
+ for output in report["outputs"]:
346
+ lines.append("")
347
+ origin = f" (from streams key {output['key']!r})" if output["key"] else ""
348
+ lines.append(f"output stream: {output['name']}{origin}")
349
+ if output["key_properties"]:
350
+ lines.append(f" key properties: {', '.join(output['key_properties'])}")
351
+ if output["filter"]:
352
+ lines.append(f" filter: {output['filter']}")
353
+ if output["settings"]:
354
+ lines.append(f" overrides: {json.dumps(output['settings'], ensure_ascii=False)}")
355
+ lines.append(" columns:")
356
+ for column in output["columns"]:
357
+ lines.extend(_render_column(column))
358
+ if "plan" in output:
359
+ lines.extend(_render_plan(output["plan"]))
360
+ if report["findings"]:
361
+ lines.append("")
362
+ lines.extend(f"problem: {f}" for f in report["findings"])
363
+ return "\n".join(lines)
364
+
365
+
366
+ @tools.command(name="doctor")
367
+ @click.option(
368
+ "--meltano-yml",
369
+ "meltano_yml",
370
+ default="meltano.yml",
371
+ show_default=True,
372
+ type=click.Path(dir_okay=False),
373
+ help="The Meltano project file.",
374
+ )
375
+ @click.option("--strict", is_flag=True, help="Treat warnings as errors.")
376
+ def doctor(meltano_yml: str, *, strict: bool) -> None:
377
+ """Check a Meltano project's use of map-conform: settings, spec, UDFs, targets' metadata."""
378
+ findings = check_project(meltano_yml)
379
+ for finding in findings:
380
+ click.echo(str(finding), err=finding.severity != "note")
381
+ failing = [f for f in findings if f.severity == "error" or (strict and f.severity == "warning")]
382
+ if failing:
383
+ click.echo(f"{meltano_yml}: {len(failing)} problem(s)", err=True)
384
+ sys.exit(1)
385
+ click.echo(f"{meltano_yml}: no problems found")
386
+
387
+
388
+ @tools.command(name="functions")
389
+ @click.option("--json", "as_json", is_flag=True, help="Machine-readable output.")
390
+ def functions(*, as_json: bool) -> None:
391
+ """List the builtin steps and the functions expressions can call."""
392
+ report = functions_report()
393
+ if as_json:
394
+ click.echo(json.dumps(report, indent=2))
395
+ return
396
+ lines = ["Builtin steps:"]
397
+ for step in report["steps"]:
398
+ flags = (" [vectorised]" if step["vectorised"] else "") + (" [udf]" if step["udf"] else "")
399
+ lines.append(f" {step['name']}({step['signature']}){flags}")
400
+ if step["doc"]:
401
+ lines.append(f" {step['doc']}")
402
+ lines.append(f" cast: one of {', '.join(report['casts'])}")
403
+ group = None
404
+ for fn in report["functions"]:
405
+ if fn["group"] != group:
406
+ group = fn["group"]
407
+ lines.extend(["", f"Expression functions: {group}"])
408
+ lines.append(f" {fn['signature']}")
409
+ lines.append(f" {fn['doc']}")
410
+ click.echo("\n".join(lines))
411
+
412
+
413
+ def functions_report() -> dict[str, Any]:
414
+ """Builtin steps (and installed UDFs), cast targets and expression functions."""
415
+ registry = _registry(None, allow_python_udfs=False)
416
+ groups = ("predicates", "coercion", "temporal", "text", "numeric", "misc", "python", "modules")
417
+ ordered = sorted(FUNCTIONS.values(), key=lambda f: (groups.index(f.group), f.name))
418
+ builtins = builtin_registry().names()
419
+ return {
420
+ "steps": [
421
+ {**_step_report(t), "udf": name not in builtins}
422
+ for name, t in sorted(registry.names().items())
423
+ ],
424
+ "casts": sorted(registry.casts),
425
+ "functions": [
426
+ {"name": f.name, "group": f.group, "signature": f.signature, "doc": f.doc}
427
+ for f in ordered
428
+ ],
429
+ }
430
+
431
+
432
+ def _step_report(transform: Transform) -> dict[str, Any]:
433
+ params = [
434
+ f"{f.name}={f.default!r}" if _shown_default(f.default) else f.name
435
+ for f in dataclasses.fields(transform.kwargs)
436
+ ]
437
+ return {
438
+ "name": transform.name,
439
+ "signature": ", ".join(params),
440
+ "positional": transform.positional,
441
+ "accepts": sorted(transform.accepts),
442
+ "vectorised": transform.vectorised,
443
+ "doc": transform.doc,
444
+ }
445
+
446
+
447
+ def _shown_default(default: object) -> bool:
448
+ """Whether a kwarg's default is a real value (not missing, not an internal sentinel)."""
449
+ return default is not dataclasses.MISSING and isinstance(
450
+ default, (str, int, float, bool, tuple, type(None))
451
+ )
452
+
453
+
454
+ def main(argv: list[str] | None = None) -> None:
455
+ """Dispatch to a tool subcommand, or run the mapper."""
456
+ args = sys.argv[1:] if argv is None else argv
457
+ if args and args[0] in TOOL_COMMANDS:
458
+ tools.main(args=args, prog_name="map-conform")
459
+ else:
460
+ MapConformMapper.cli.main(args=args, prog_name="map-conform")
map_conform/doctor.py ADDED
@@ -0,0 +1,178 @@
1
+ """``map-conform doctor``: check a Meltano project's use of map-conform (WBS 9.3).
2
+
3
+ For each map-conform mapper in ``meltano.yml`` and each of its mappings (the mapping's
4
+ config over the plugin's), the doctor checks:
5
+
6
+ 1. the settings are valid;
7
+ 2. ``spec_path`` exists (relative to the project) and the spec, with any ``stream_maps``,
8
+ loads without problems;
9
+ 3. UDF opt-in: spec ``udfs`` given as module paths need ``allow_python_udfs: true``; the
10
+ setting without such UDFs is noted;
11
+ 4. ``_sdc_*`` columns: when the mapping adds them (``add_record_metadata``, in the settings
12
+ or anywhere in the spec), every loader that runs after it in a job must set
13
+ ``add_record_metadata: true``, or an SDK target strips them. With no job using the
14
+ mapping, every loader is checked.
15
+
16
+ Config set only through environment variables is not visible here; a finding says so.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import sys
22
+ from dataclasses import dataclass
23
+ from pathlib import Path
24
+ from typing import Any, Literal
25
+
26
+ import yaml
27
+
28
+ if sys.version_info >= (3, 12):
29
+ from typing import override
30
+ else:
31
+ from typing_extensions import override
32
+
33
+ from map_conform.settings import parse_settings
34
+ from map_conform.spec._struct import Issues
35
+ from map_conform.spec.errors import SpecError
36
+ from map_conform.spec.load import deep_merge, load_spec
37
+ from map_conform.spec.stream_maps import SDK_SETTINGS, translate
38
+
39
+ Severity = Literal["error", "warning", "note"]
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class Finding:
44
+ """One problem or remark."""
45
+
46
+ severity: Severity
47
+ where: str
48
+ message: str
49
+
50
+ @override
51
+ def __str__(self) -> str:
52
+ """``error: plugins.mappers.map-conform: ...``."""
53
+ return f"{self.severity}: {self.where}: {self.message}"
54
+
55
+
56
+ def _is_map_conform(plugin: dict[str, Any]) -> bool:
57
+ return (
58
+ plugin.get("name") == "map-conform"
59
+ or plugin.get("namespace") == "map_conform"
60
+ or plugin.get("executable") == "map-conform"
61
+ or "map-conform" in str(plugin.get("pip_url", ""))
62
+ or plugin.get("inherit_from") == "map-conform"
63
+ )
64
+
65
+
66
+ def _plugins(project: dict[str, Any], kind: str) -> dict[str, dict[str, Any]]:
67
+ return {p["name"]: p for p in (project.get("plugins") or {}).get(kind) or [] if "name" in p}
68
+
69
+
70
+ def _loader_config(loaders: dict[str, dict[str, Any]], name: str) -> dict[str, Any]:
71
+ """A loader's config, over its ``inherit_from`` parent's."""
72
+ plugin = loaders.get(name) or {}
73
+ parent = plugin.get("inherit_from")
74
+ base = _loader_config(loaders, parent) if parent and parent != name else {}
75
+ merged = deep_merge(base, plugin.get("config") or {})
76
+ return merged if isinstance(merged, dict) else {}
77
+
78
+
79
+ def _following_loaders(
80
+ project: dict[str, Any], mapping: str, loaders: dict[str, dict[str, Any]]
81
+ ) -> list[str]:
82
+ """Loaders that run after the mapping in any job's task."""
83
+ found: list[str] = []
84
+ for job in project.get("jobs") or []:
85
+ for task in job.get("tasks") or []:
86
+ steps = task.split() if isinstance(task, str) else [s for t in task for s in t.split()]
87
+ if mapping not in steps:
88
+ continue
89
+ later = steps[steps.index(mapping) + 1 :]
90
+ found.extend(s for s in later if s in loaders and s not in found)
91
+ return found
92
+
93
+
94
+ def _adds_metadata(config: dict[str, Any], spec_doc: Any) -> bool: # noqa: ANN401 -- a Spec
95
+ if config.get("add_record_metadata"):
96
+ return True
97
+ if spec_doc is None:
98
+ return False
99
+ if spec_doc.defaults.add_record_metadata:
100
+ return True
101
+ return any(rules.raw.get("add_record_metadata") for rules in spec_doc.streams.values())
102
+
103
+
104
+ def check_project(path: str | Path) -> list[Finding]:
105
+ """Every finding for the project at ``path`` (a meltano.yml)."""
106
+ file = Path(path)
107
+ try:
108
+ project = yaml.safe_load(file.read_text(encoding="utf-8")) or {}
109
+ except (OSError, yaml.YAMLError) as exc:
110
+ return [Finding("error", str(file), f"cannot read the project: {exc}")]
111
+ mappers = {n: p for n, p in _plugins(project, "mappers").items() if _is_map_conform(p)}
112
+ if not mappers:
113
+ return [Finding("warning", str(file), "no map-conform mapper in plugins.mappers")]
114
+ loaders = _plugins(project, "loaders")
115
+ findings: list[Finding] = []
116
+ for name, plugin in mappers.items():
117
+ mappings = plugin.get("mappings") or [{"name": name, "config": {}}]
118
+ for mapping in mappings:
119
+ where = f"plugins.mappers.{name}.mappings.{mapping.get('name', name)}"
120
+ merged = deep_merge(plugin.get("config") or {}, mapping.get("config") or {})
121
+ config = merged if isinstance(merged, dict) else {}
122
+ name_of = str(mapping.get("name", name))
123
+ findings.extend(
124
+ _check_mapping(file.parent, project, loaders, where=where, mapping=name_of,
125
+ config=config)
126
+ ) # fmt: skip
127
+ return findings
128
+
129
+
130
+ def _check_mapping( # noqa: PLR0913 -- the mapping and its project
131
+ root: Path,
132
+ project: dict[str, Any],
133
+ loaders: dict[str, dict[str, Any]],
134
+ *,
135
+ where: str,
136
+ mapping: str,
137
+ config: dict[str, Any],
138
+ ) -> list[Finding]:
139
+ findings: list[Finding] = []
140
+ try:
141
+ settings = parse_settings(config)
142
+ except SpecError as exc:
143
+ return [Finding("error", where, f"invalid setting: {i}") for i in exc.issues]
144
+ spec = None
145
+ spec_path = settings.spec_path
146
+ if spec_path is not None and not (root / spec_path).is_file():
147
+ findings.append(
148
+ Finding("error", f"{where}.config.spec_path", f"{spec_path!r} does not exist")
149
+ )
150
+ spec_path = None
151
+ issues = Issues()
152
+ base = translate({k: getattr(settings, k) for k in SDK_SETTINGS}, issues)
153
+ findings.extend(Finding("error", where, str(i)) for i in issues.items)
154
+ if spec_path is not None or settings.spec is not None or base is not None:
155
+ try:
156
+ spec = load_spec(root / spec_path if spec_path else None, settings.spec,
157
+ settings.spec_vars, base=base) # fmt: skip
158
+ except SpecError as exc:
159
+ findings.extend(Finding("error", f"{where} (spec)", str(i)) for i in exc.issues)
160
+ if spec is not None and spec.udfs and not settings.allow_python_udfs:
161
+ findings.append(Finding("error", f"{where}.config", "the spec has module-path udfs; "
162
+ "set allow_python_udfs: true to allow them")) # fmt: skip
163
+ if settings.allow_python_udfs and (spec is None or not spec.udfs):
164
+ findings.append(Finding("note", f"{where}.config.allow_python_udfs",
165
+ "set, but the spec has no module-path udfs")) # fmt: skip
166
+ if _adds_metadata(config, spec):
167
+ targets = _following_loaders(project, mapping, loaders) or list(loaders)
168
+ message = (
169
+ f"{mapping} adds _sdc_* columns, but this target does not set "
170
+ "add_record_metadata: true, so an SDK target strips them (unless it is set in "
171
+ "the environment)"
172
+ )
173
+ findings.extend(
174
+ Finding("error", f"plugins.loaders.{loader}.config", message)
175
+ for loader in targets
176
+ if not _loader_config(loaders, loader).get("add_record_metadata")
177
+ )
178
+ return findings