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.
- map_conform/__init__.py +5 -0
- map_conform/__main__.py +7 -0
- map_conform/batch/__init__.py +1 -0
- map_conform/batch/arrow.py +80 -0
- map_conform/batch/columnar.py +125 -0
- map_conform/batch/engine.py +191 -0
- map_conform/batch/files.py +207 -0
- map_conform/cli.py +460 -0
- map_conform/doctor.py +178 -0
- map_conform/errors.py +107 -0
- map_conform/expr/__init__.py +6 -0
- map_conform/expr/compiler.py +562 -0
- map_conform/expr/functions.py +542 -0
- map_conform/expr/sandbox.py +333 -0
- map_conform/expr/sdk.py +116 -0
- map_conform/map-conform-spec.schema.json +1204 -0
- map_conform/mapper.py +355 -0
- map_conform/metadata.py +73 -0
- map_conform/metrics.py +62 -0
- map_conform/naming/__init__.py +1 -0
- map_conform/naming/ascii-table.json +980 -0
- map_conform/naming/conform.py +262 -0
- map_conform/naming/flatten.py +148 -0
- map_conform/naming/nested.py +117 -0
- map_conform/naming/reserved/ansi.txt +369 -0
- map_conform/naming/reserved/duckdb.txt +114 -0
- map_conform/naming/reserved/postgres.txt +105 -0
- map_conform/naming/reserved/snowflake.txt +90 -0
- map_conform/naming/reserved.py +34 -0
- map_conform/naming/shape.py +96 -0
- map_conform/naming/streams.py +76 -0
- map_conform/naming/translit.py +170 -0
- map_conform/plan/__init__.py +1 -0
- map_conform/plan/chain.py +667 -0
- map_conform/plan/compile.py +551 -0
- map_conform/plan/lower.py +281 -0
- map_conform/plan/ops.py +336 -0
- map_conform/plan/row.py +212 -0
- map_conform/plan/vector.py +71 -0
- map_conform/rejects.py +92 -0
- map_conform/settings.py +157 -0
- map_conform/spec/__init__.py +1 -0
- map_conform/spec/_struct.py +483 -0
- map_conform/spec/bridge.py +109 -0
- map_conform/spec/check.py +380 -0
- map_conform/spec/errors.py +22 -0
- map_conform/spec/importer.py +87 -0
- map_conform/spec/jsonschema.py +54 -0
- map_conform/spec/load.py +357 -0
- map_conform/spec/model.py +473 -0
- map_conform/spec/reference.py +179 -0
- map_conform/spec/steps.py +297 -0
- map_conform/spec/stream_maps.py +233 -0
- map_conform/spec/zamboni.py +99 -0
- map_conform/transforms/__init__.py +1 -0
- map_conform/transforms/builtins.py +63 -0
- map_conform/transforms/casts.py +310 -0
- map_conform/transforms/fake.py +150 -0
- map_conform/transforms/nested.py +111 -0
- map_conform/transforms/numeric.py +318 -0
- map_conform/transforms/polars_vector.py +151 -0
- map_conform/transforms/privacy.py +220 -0
- map_conform/transforms/registry.py +116 -0
- map_conform/transforms/temporal.py +410 -0
- map_conform/transforms/text.py +249 -0
- map_conform/transforms/vector.py +386 -0
- map_conform/types/__init__.py +1 -0
- map_conform/types/canonical.py +255 -0
- map_conform/types/from_jsonschema.py +177 -0
- map_conform/types/jsontext.py +63 -0
- map_conform/types/to_arrow.py +52 -0
- map_conform/types/to_jsonschema.py +65 -0
- map_conform/types/wire.py +53 -0
- map_conform/udfs.py +327 -0
- map_conform-0.1.0.dist-info/METADATA +157 -0
- map_conform-0.1.0.dist-info/RECORD +79 -0
- map_conform-0.1.0.dist-info/WHEEL +4 -0
- map_conform-0.1.0.dist-info/entry_points.txt +2 -0
- map_conform-0.1.0.dist-info/licenses/LICENSE +201 -0
map_conform/mapper.py
ADDED
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
"""The map-conform inline mapper.
|
|
2
|
+
|
|
3
|
+
At SCHEMA the mapper compiles a plan for each output stream of the tap stream; each RECORD is
|
|
4
|
+
conformed by the row executor. STATE passes through in order; ACTIVATE_VERSION is renamed to
|
|
5
|
+
the output streams. A BATCH message's files are conformed row by row and written out as new
|
|
6
|
+
BATCH files or as RECORDs (:mod:`map_conform.batch`).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import datetime as dt
|
|
12
|
+
import json
|
|
13
|
+
import sys
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import TYPE_CHECKING, Any, ClassVar
|
|
17
|
+
|
|
18
|
+
from singer_sdk.exceptions import ConfigValidationError
|
|
19
|
+
from singer_sdk.helpers.capabilities import PluginCapabilities
|
|
20
|
+
from singer_sdk.mapper_base import InlineMapper
|
|
21
|
+
from singer_sdk.singerlib.encoding.base import SingerMessageType
|
|
22
|
+
from singer_sdk.singerlib.encoding.simple import Message
|
|
23
|
+
|
|
24
|
+
from map_conform.batch.engine import BatchEngine
|
|
25
|
+
from map_conform.batch.files import BatchFileError
|
|
26
|
+
from map_conform.errors import RowRejected, ThresholdExceeded
|
|
27
|
+
from map_conform.metadata import Metadata, sdc_schema
|
|
28
|
+
from map_conform.metrics import StreamMetrics, write_metrics
|
|
29
|
+
from map_conform.plan.compile import compile_stream
|
|
30
|
+
from map_conform.plan.row import RowExecutor
|
|
31
|
+
from map_conform.rejects import RejectSink
|
|
32
|
+
from map_conform.settings import Settings, parse_settings, settings_jsonschema
|
|
33
|
+
from map_conform.spec._struct import Issues
|
|
34
|
+
from map_conform.spec.errors import SpecError
|
|
35
|
+
from map_conform.spec.load import load_spec, output_streams
|
|
36
|
+
from map_conform.spec.model import Defaults, Spec, parse_spec
|
|
37
|
+
from map_conform.spec.stream_maps import SDK_SETTINGS, translate
|
|
38
|
+
from map_conform.transforms.builtins import builtin_registry
|
|
39
|
+
from map_conform.udfs import load_udfs, registry_with
|
|
40
|
+
|
|
41
|
+
if sys.version_info >= (3, 12):
|
|
42
|
+
from typing import override
|
|
43
|
+
else:
|
|
44
|
+
from typing_extensions import override
|
|
45
|
+
|
|
46
|
+
if TYPE_CHECKING:
|
|
47
|
+
from collections.abc import Iterator
|
|
48
|
+
from pathlib import PurePath
|
|
49
|
+
|
|
50
|
+
from singer_sdk.helpers.capabilities import CapabilitiesEnum
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass(slots=True)
|
|
54
|
+
class RawMessage(Message):
|
|
55
|
+
"""A message written exactly as given.
|
|
56
|
+
|
|
57
|
+
The SDK message classes rebuild a message from the fields they model, which drops the
|
|
58
|
+
fields they do not and re-serialises others, such as ``time_extracted``. The mapper
|
|
59
|
+
builds the output dictionary itself and serialises that.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
payload: dict[str, Any] = field(default_factory=dict)
|
|
63
|
+
"""The message as decoded from the input line, ``type`` included."""
|
|
64
|
+
|
|
65
|
+
def __post_init__(self) -> None:
|
|
66
|
+
"""Take the message type from the payload."""
|
|
67
|
+
self.type = SingerMessageType(self.payload["type"])
|
|
68
|
+
|
|
69
|
+
@override
|
|
70
|
+
def to_dict(self) -> dict[str, Any]:
|
|
71
|
+
"""Return the message exactly as it was read.
|
|
72
|
+
|
|
73
|
+
Returns:
|
|
74
|
+
The decoded input message.
|
|
75
|
+
"""
|
|
76
|
+
return self.payload
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class MapConformMapper(InlineMapper):
|
|
80
|
+
"""Conform Singer streams so that targets receive clean data."""
|
|
81
|
+
|
|
82
|
+
name = "map-conform"
|
|
83
|
+
|
|
84
|
+
# SDK stream maps and flattening are accepted and translated into the spec (§15).
|
|
85
|
+
capabilities: ClassVar[list[CapabilitiesEnum]] = [
|
|
86
|
+
PluginCapabilities.ABOUT,
|
|
87
|
+
PluginCapabilities.STRUCTURED_LOGGING,
|
|
88
|
+
PluginCapabilities.STREAM_MAPS,
|
|
89
|
+
PluginCapabilities.FLATTENING,
|
|
90
|
+
]
|
|
91
|
+
|
|
92
|
+
config_jsonschema = settings_jsonschema()
|
|
93
|
+
|
|
94
|
+
def __init__(
|
|
95
|
+
self,
|
|
96
|
+
*,
|
|
97
|
+
config: dict | PurePath | str | list[PurePath | str] | None = None,
|
|
98
|
+
parse_env_config: bool = False,
|
|
99
|
+
validate_config: bool = True,
|
|
100
|
+
) -> None:
|
|
101
|
+
"""Validate the settings and load the conform spec, failing before any data flows.
|
|
102
|
+
|
|
103
|
+
Args:
|
|
104
|
+
config: Plugin config: a dict, or one or more JSON file paths.
|
|
105
|
+
parse_env_config: Also read settings from environment variables.
|
|
106
|
+
validate_config: Validate the config against ``config_jsonschema``.
|
|
107
|
+
|
|
108
|
+
Raises:
|
|
109
|
+
ConfigValidationError: if the settings or the spec are invalid; every problem is
|
|
110
|
+
listed with its path.
|
|
111
|
+
"""
|
|
112
|
+
super().__init__(
|
|
113
|
+
config=config,
|
|
114
|
+
parse_env_config=parse_env_config,
|
|
115
|
+
validate_config=validate_config,
|
|
116
|
+
)
|
|
117
|
+
self._started = dt.datetime.now(tz=dt.UTC)
|
|
118
|
+
self._metadata = Metadata(self._started)
|
|
119
|
+
self._executors: dict[str, list[RowExecutor]] = {}
|
|
120
|
+
self._rows: dict[str, int] = {}
|
|
121
|
+
self._metrics: dict[str, StreamMetrics] = {}
|
|
122
|
+
self._limits: dict[str, Defaults] = {}
|
|
123
|
+
self._rejects: RejectSink | None = None
|
|
124
|
+
self._run_id = self._started.strftime("%Y%m%dT%H%M%S%fZ")
|
|
125
|
+
try:
|
|
126
|
+
self.settings: Settings = parse_settings(self.config)
|
|
127
|
+
self.spec: Spec = self._load_spec(self.settings)
|
|
128
|
+
udfs = load_udfs(self.spec.udfs, allow_python_udfs=self.settings.allow_python_udfs)
|
|
129
|
+
self.registry = registry_with(builtin_registry(), udfs)
|
|
130
|
+
self._batches = BatchEngine(self.settings.batch_output, self._run_id, self._reject,
|
|
131
|
+
self._rows) # fmt: skip
|
|
132
|
+
except SpecError as exc:
|
|
133
|
+
raise ConfigValidationError(
|
|
134
|
+
f"Invalid {exc.source or 'configuration'}",
|
|
135
|
+
errors=[str(issue) for issue in exc.issues],
|
|
136
|
+
) from exc
|
|
137
|
+
|
|
138
|
+
def _load_spec(self, settings: Settings) -> Spec:
|
|
139
|
+
issues = Issues()
|
|
140
|
+
sdk = {name: getattr(settings, name) for name in SDK_SETTINGS}
|
|
141
|
+
base = translate(sdk, issues)
|
|
142
|
+
if issues:
|
|
143
|
+
raise SpecError(issues.items, "the stream_maps settings")
|
|
144
|
+
if base is not None and settings.stream_maps is not None:
|
|
145
|
+
self.logger.info(
|
|
146
|
+
"Translated %d SDK stream map(s) into the spec, with the compatibility "
|
|
147
|
+
"defaults (SDK column naming, stream names kept, no _sdc_* columns).",
|
|
148
|
+
len(settings.stream_maps),
|
|
149
|
+
)
|
|
150
|
+
if settings.spec_path is None and settings.spec is None and base is None:
|
|
151
|
+
self.logger.info("No spec_path or spec set; conforming with the default rules.")
|
|
152
|
+
return parse_spec({"version": 1}, "the default spec")
|
|
153
|
+
spec = load_spec(settings.spec_path, settings.spec, settings.spec_vars, base=base)
|
|
154
|
+
self.logger.info(
|
|
155
|
+
"Loaded the conform spec from %s (%d stream rule(s)).",
|
|
156
|
+
settings.spec_path or ("the spec setting" if settings.spec else "stream_maps"),
|
|
157
|
+
len(spec.streams),
|
|
158
|
+
)
|
|
159
|
+
return spec
|
|
160
|
+
|
|
161
|
+
@property
|
|
162
|
+
def expression_config(self) -> dict[str, Any]:
|
|
163
|
+
"""``config`` in expressions: stream_map_config, with spec_vars over it."""
|
|
164
|
+
return {**self.settings.stream_map_config, **self.settings.spec_vars}
|
|
165
|
+
|
|
166
|
+
# --- message handling ---------------------------------------------------------------
|
|
167
|
+
|
|
168
|
+
def _outputs(self, tap_stream: str) -> list[RowExecutor]:
|
|
169
|
+
executors = self._executors.get(tap_stream)
|
|
170
|
+
if executors is None:
|
|
171
|
+
msg = f"RECORD for stream {tap_stream!r} before its SCHEMA"
|
|
172
|
+
raise ValueError(msg)
|
|
173
|
+
return executors
|
|
174
|
+
|
|
175
|
+
@override
|
|
176
|
+
def map_schema_message(self, message_dict: dict) -> Iterator[RawMessage]:
|
|
177
|
+
"""Compile a plan for each output stream and emit its conformed SCHEMA.
|
|
178
|
+
|
|
179
|
+
Args:
|
|
180
|
+
message_dict: A SCHEMA message JSON dictionary.
|
|
181
|
+
|
|
182
|
+
Yields:
|
|
183
|
+
One conformed SCHEMA per output stream (none for a dropped stream).
|
|
184
|
+
|
|
185
|
+
Raises:
|
|
186
|
+
ConfigValidationError: if a plan does not compile; every problem has its path.
|
|
187
|
+
"""
|
|
188
|
+
tap_stream = message_dict["stream"]
|
|
189
|
+
executors: list[RowExecutor] = []
|
|
190
|
+
for resolved in output_streams(self.spec, tap_stream):
|
|
191
|
+
try:
|
|
192
|
+
plan = compile_stream(
|
|
193
|
+
self.spec,
|
|
194
|
+
resolved,
|
|
195
|
+
message_dict["schema"],
|
|
196
|
+
self.registry,
|
|
197
|
+
key_properties=tuple(message_dict.get("key_properties") or ()),
|
|
198
|
+
bookmark_properties=tuple(message_dict.get("bookmark_properties") or ()),
|
|
199
|
+
strict=self.settings.strict,
|
|
200
|
+
config=self.expression_config,
|
|
201
|
+
)
|
|
202
|
+
except SpecError as exc:
|
|
203
|
+
raise ConfigValidationError(
|
|
204
|
+
f"Invalid {exc.source}", errors=[str(i) for i in exc.issues]
|
|
205
|
+
) from exc
|
|
206
|
+
for note in plan.notes:
|
|
207
|
+
self.logger.info("Stream %r: %s", tap_stream, note)
|
|
208
|
+
metadata = self._metadata if resolved.settings.add_record_metadata else None
|
|
209
|
+
metrics = self._metrics.setdefault(plan.name, StreamMetrics())
|
|
210
|
+
self._limits[plan.name] = resolved.settings
|
|
211
|
+
executors.append(RowExecutor(plan, resolved.settings, metadata, metrics))
|
|
212
|
+
schema = dict(plan.schema)
|
|
213
|
+
if metadata is not None:
|
|
214
|
+
schema["properties"] = {**schema["properties"], **sdc_schema()}
|
|
215
|
+
out: dict[str, Any] = {
|
|
216
|
+
"type": "SCHEMA",
|
|
217
|
+
"stream": plan.name,
|
|
218
|
+
"schema": schema,
|
|
219
|
+
"key_properties": list(plan.key_properties),
|
|
220
|
+
}
|
|
221
|
+
if plan.bookmark_properties:
|
|
222
|
+
out["bookmark_properties"] = list(plan.bookmark_properties)
|
|
223
|
+
yield RawMessage(payload=out)
|
|
224
|
+
if not executors:
|
|
225
|
+
self.logger.info("Stream %r is dropped by the spec.", tap_stream)
|
|
226
|
+
self._executors[tap_stream] = executors
|
|
227
|
+
|
|
228
|
+
@override
|
|
229
|
+
def map_record_message(self, message_dict: dict) -> Iterator[RawMessage]:
|
|
230
|
+
"""Conform the record for each output stream.
|
|
231
|
+
|
|
232
|
+
Args:
|
|
233
|
+
message_dict: A RECORD message JSON dictionary.
|
|
234
|
+
|
|
235
|
+
Yields:
|
|
236
|
+
One conformed RECORD per output stream; ``version`` and ``time_extracted`` are
|
|
237
|
+
preserved.
|
|
238
|
+
"""
|
|
239
|
+
tap_stream = message_dict["stream"]
|
|
240
|
+
row = self._rows[tap_stream] = self._rows.get(tap_stream, 0) + 1
|
|
241
|
+
for executor in self._outputs(tap_stream):
|
|
242
|
+
try:
|
|
243
|
+
record = executor.run(message_dict["record"], message_dict, row)
|
|
244
|
+
except RowRejected as rejected:
|
|
245
|
+
self._reject(executor, rejected, message_dict["record"])
|
|
246
|
+
continue
|
|
247
|
+
if record is None: # dropped by the stream's filter
|
|
248
|
+
continue
|
|
249
|
+
executor.metrics.rows_out += 1
|
|
250
|
+
out: dict[str, Any] = {"type": "RECORD", "stream": executor.plan.name, "record": record}
|
|
251
|
+
for passed in ("version", "time_extracted"):
|
|
252
|
+
if passed in message_dict:
|
|
253
|
+
out[passed] = message_dict[passed]
|
|
254
|
+
yield RawMessage(payload=out)
|
|
255
|
+
|
|
256
|
+
def _reject(self, executor: RowExecutor, rejected: RowRejected, record: dict[str, Any]) -> None:
|
|
257
|
+
executor.metrics.rows_rejected += 1
|
|
258
|
+
if self._rejects is None:
|
|
259
|
+
storage = Path(self.settings.reject.storage)
|
|
260
|
+
self._rejects = RejectSink(storage, self.settings.reject.format, self._run_id)
|
|
261
|
+
self._rejects.write(executor.plan.name, rejected.error, record)
|
|
262
|
+
self.logger.warning("Rejected: %s", rejected.error)
|
|
263
|
+
|
|
264
|
+
def _close_rejects(self) -> None:
|
|
265
|
+
if self._rejects is None:
|
|
266
|
+
return
|
|
267
|
+
self._rejects.close()
|
|
268
|
+
for stream, path in self._rejects.paths.items():
|
|
269
|
+
self.logger.warning("Rejected rows of %r are in %s", stream, path)
|
|
270
|
+
|
|
271
|
+
def _check_thresholds(self) -> None:
|
|
272
|
+
"""Fail when a stream's reject or null rate is over its limit.
|
|
273
|
+
|
|
274
|
+
Raises:
|
|
275
|
+
ThresholdExceeded: naming the stream, the rate and the limit.
|
|
276
|
+
"""
|
|
277
|
+
for stream, metrics in self._metrics.items():
|
|
278
|
+
limits = self._limits[stream]
|
|
279
|
+
for label, count, limit in (
|
|
280
|
+
("rejected", metrics.rows_rejected, limits.max_reject_rate),
|
|
281
|
+
("nulled", metrics.rows_nulled, limits.max_null_rate),
|
|
282
|
+
):
|
|
283
|
+
if limit is not None and metrics.rate(count) > limit:
|
|
284
|
+
raise ThresholdExceeded(
|
|
285
|
+
stream,
|
|
286
|
+
what=label,
|
|
287
|
+
rate=metrics.rate(count),
|
|
288
|
+
limit=limit,
|
|
289
|
+
count=count,
|
|
290
|
+
rows=metrics.rows_in,
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
@override
|
|
294
|
+
def map_state_message(self, message_dict: dict) -> Iterator[RawMessage]:
|
|
295
|
+
"""Pass STATE through unchanged, in order.
|
|
296
|
+
|
|
297
|
+
Args:
|
|
298
|
+
message_dict: A STATE message JSON dictionary.
|
|
299
|
+
|
|
300
|
+
Yields:
|
|
301
|
+
The input message, after the rate thresholds are checked, so a target never
|
|
302
|
+
commits a bookmark past rows a bad source spoiled.
|
|
303
|
+
"""
|
|
304
|
+
try:
|
|
305
|
+
self._check_thresholds()
|
|
306
|
+
except ThresholdExceeded:
|
|
307
|
+
self._close_rejects()
|
|
308
|
+
raise
|
|
309
|
+
yield RawMessage(payload=message_dict)
|
|
310
|
+
|
|
311
|
+
@override
|
|
312
|
+
def process_endofpipe(self) -> None:
|
|
313
|
+
"""Check thresholds, close the reject sink, and report metrics."""
|
|
314
|
+
try:
|
|
315
|
+
self._check_thresholds()
|
|
316
|
+
finally:
|
|
317
|
+
self._close_rejects()
|
|
318
|
+
for stream, metrics in sorted(self._metrics.items()):
|
|
319
|
+
self.logger.info("Metrics for %r: %s", stream, json.dumps(metrics.to_dict()))
|
|
320
|
+
if self.settings.metrics_path:
|
|
321
|
+
write_metrics(self.settings.metrics_path, self._metrics)
|
|
322
|
+
|
|
323
|
+
@override
|
|
324
|
+
def map_activate_version_message(self, message_dict: dict) -> Iterator[RawMessage]:
|
|
325
|
+
"""Emit ACTIVATE_VERSION for each output stream of the tap stream.
|
|
326
|
+
|
|
327
|
+
Args:
|
|
328
|
+
message_dict: An ACTIVATE_VERSION message JSON dictionary.
|
|
329
|
+
|
|
330
|
+
Yields:
|
|
331
|
+
The message, renamed to each output stream.
|
|
332
|
+
"""
|
|
333
|
+
for executor in self._executors.get(message_dict["stream"], []):
|
|
334
|
+
yield RawMessage(payload={**message_dict, "stream": executor.plan.name})
|
|
335
|
+
|
|
336
|
+
@override
|
|
337
|
+
def map_batch_message(self, message_dict: dict) -> Iterator[RawMessage]:
|
|
338
|
+
"""Conform every row of the BATCH files, then write new files or RECORDs.
|
|
339
|
+
|
|
340
|
+
Args:
|
|
341
|
+
message_dict: A BATCH message JSON dictionary.
|
|
342
|
+
|
|
343
|
+
Yields:
|
|
344
|
+
BATCH messages for the conformed files (``batch_output.mode: batch``), or RECORD
|
|
345
|
+
messages (``record``).
|
|
346
|
+
|
|
347
|
+
Raises:
|
|
348
|
+
ConfigValidationError: for a manifest file that cannot be read.
|
|
349
|
+
"""
|
|
350
|
+
executors = self._outputs(message_dict["stream"])
|
|
351
|
+
try:
|
|
352
|
+
for out in self._batches.process(message_dict, executors):
|
|
353
|
+
yield RawMessage(payload=out)
|
|
354
|
+
except BatchFileError as exc:
|
|
355
|
+
raise ConfigValidationError(str(exc)) from exc
|
map_conform/metadata.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""The seven ``_sdc_*`` columns, exactly as the Singer SDK sets them (detailed design §11).
|
|
2
|
+
|
|
3
|
+
Names, schema and values match ``singer_sdk.sinks.core.Sink._add_sdc_metadata_to_record`` and
|
|
4
|
+
``_add_sdc_metadata_to_schema``, with one documented difference: ``_sdc_batched_at`` for
|
|
5
|
+
RECORD messages is the mapper's start time (the run is the batch), and the record's own
|
|
6
|
+
``_sdc_deleted_at`` is conformed to a UTC timestamp.
|
|
7
|
+
|
|
8
|
+
An SDK target strips these columns unless it sets ``add_record_metadata: true``.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import datetime as dt
|
|
14
|
+
import time
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from map_conform.errors import StepFailed
|
|
18
|
+
from map_conform.transforms.temporal import TemporalCast, localize, parse_temporal
|
|
19
|
+
|
|
20
|
+
SDC_PREFIX = "_sdc_"
|
|
21
|
+
TIMESTAMP_COLUMNS = ("_sdc_extracted_at", "_sdc_received_at", "_sdc_batched_at", "_sdc_deleted_at")
|
|
22
|
+
INTEGER_COLUMNS = ("_sdc_sequence", "_sdc_table_version", "_sdc_sync_started_at")
|
|
23
|
+
_DELETED_AT = TemporalCast(formats=("iso",))
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def sdc_schema() -> dict[str, dict[str, Any]]:
|
|
27
|
+
"""The ``_sdc_*`` property schemas, as the SDK writes them."""
|
|
28
|
+
properties: dict[str, dict[str, Any]] = {
|
|
29
|
+
column: {"type": ["null", "string"], "format": "date-time"} for column in TIMESTAMP_COLUMNS
|
|
30
|
+
}
|
|
31
|
+
properties.update({column: {"type": ["null", "integer"]} for column in INTEGER_COLUMNS})
|
|
32
|
+
return properties
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class Metadata:
|
|
36
|
+
"""Adds ``_sdc_*`` values to conformed records for one run."""
|
|
37
|
+
|
|
38
|
+
def __init__(self, started_at: dt.datetime | None = None) -> None:
|
|
39
|
+
"""Fix the run's start: ``_sdc_batched_at`` and ``_sdc_sync_started_at`` derive from it."""
|
|
40
|
+
start = started_at or dt.datetime.now(tz=dt.UTC)
|
|
41
|
+
self.batched_at = start.isoformat()
|
|
42
|
+
self.sync_started_at = int(start.timestamp() * 1000)
|
|
43
|
+
|
|
44
|
+
def add(
|
|
45
|
+
self,
|
|
46
|
+
record: dict[str, Any],
|
|
47
|
+
message: dict[str, Any],
|
|
48
|
+
deleted_at: object,
|
|
49
|
+
batched_at: str | None = None,
|
|
50
|
+
) -> None:
|
|
51
|
+
"""Set the seven columns on an output record; BATCH rows pass their file's time.
|
|
52
|
+
|
|
53
|
+
Raises:
|
|
54
|
+
StepFailed: if the source ``_sdc_deleted_at`` is not a timestamp.
|
|
55
|
+
"""
|
|
56
|
+
record["_sdc_extracted_at"] = message.get("time_extracted")
|
|
57
|
+
record["_sdc_received_at"] = dt.datetime.now(tz=dt.UTC).isoformat()
|
|
58
|
+
record["_sdc_batched_at"] = batched_at or self.batched_at
|
|
59
|
+
record["_sdc_deleted_at"] = conform_deleted_at(deleted_at)
|
|
60
|
+
record["_sdc_sequence"] = round(time.time() * 1000)
|
|
61
|
+
record["_sdc_table_version"] = message.get("version")
|
|
62
|
+
record["_sdc_sync_started_at"] = self.sync_started_at
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def conform_deleted_at(value: object) -> str | None:
|
|
66
|
+
"""A source ``_sdc_deleted_at`` as a UTC ISO timestamp, or None."""
|
|
67
|
+
if value is None or value == "":
|
|
68
|
+
return None
|
|
69
|
+
parsed = parse_temporal(value, _DELETED_AT)
|
|
70
|
+
if not isinstance(parsed, dt.datetime):
|
|
71
|
+
raise StepFailed(f"_sdc_deleted_at {value!r} is not a timestamp")
|
|
72
|
+
aware = parsed if parsed.tzinfo else localize(parsed, _DELETED_AT)
|
|
73
|
+
return aware.astimezone(dt.UTC).isoformat()
|
map_conform/metrics.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Per-stream counters (detailed design §13).
|
|
2
|
+
|
|
3
|
+
Counted per output stream: rows in and out, rejected rows, rows where ``on_error: null``
|
|
4
|
+
replaced a value, values kept raw (``keep``), and errors by (column, rule). They are logged
|
|
5
|
+
at the end of the run and, with ``metrics_path``, written as JSON.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
from collections import Counter
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass
|
|
18
|
+
class StreamMetrics:
|
|
19
|
+
"""Counters for one output stream."""
|
|
20
|
+
|
|
21
|
+
rows_in: int = 0
|
|
22
|
+
rows_out: int = 0
|
|
23
|
+
rows_rejected: int = 0
|
|
24
|
+
rows_nulled: int = 0
|
|
25
|
+
rows_filtered: int = 0
|
|
26
|
+
"""Rows the stream's filter dropped."""
|
|
27
|
+
values_kept: int = 0
|
|
28
|
+
members_dropped: Counter[tuple[str, str]] = field(default_factory=Counter)
|
|
29
|
+
"""Nested members a declared shape does not declare, by (column, member path)."""
|
|
30
|
+
errors: Counter[tuple[str, str]] = field(default_factory=Counter)
|
|
31
|
+
"""Failed values by (column, rule), whatever on_error did with them."""
|
|
32
|
+
|
|
33
|
+
def rate(self, count: int) -> float:
|
|
34
|
+
"""``count`` as a fraction of rows in."""
|
|
35
|
+
return count / self.rows_in if self.rows_in else 0.0
|
|
36
|
+
|
|
37
|
+
def to_dict(self) -> dict[str, Any]:
|
|
38
|
+
"""Plain data for the metrics file and log lines."""
|
|
39
|
+
return {
|
|
40
|
+
"rows_in": self.rows_in,
|
|
41
|
+
"rows_out": self.rows_out,
|
|
42
|
+
"rows_rejected": self.rows_rejected,
|
|
43
|
+
"rows_nulled": self.rows_nulled,
|
|
44
|
+
"rows_filtered": self.rows_filtered,
|
|
45
|
+
"values_kept": self.values_kept,
|
|
46
|
+
"members_dropped": [
|
|
47
|
+
{"column": column, "member": member, "count": count}
|
|
48
|
+
for (column, member), count in sorted(self.members_dropped.items())
|
|
49
|
+
],
|
|
50
|
+
"errors": [
|
|
51
|
+
{"column": column, "rule": rule, "count": count}
|
|
52
|
+
for (column, rule), count in sorted(self.errors.items())
|
|
53
|
+
],
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def write_metrics(path: str | Path, streams: dict[str, StreamMetrics]) -> None:
|
|
58
|
+
"""Write every stream's counters to ``path`` as JSON."""
|
|
59
|
+
target = Path(path)
|
|
60
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
61
|
+
document = {"streams": {name: m.to_dict() for name, m in sorted(streams.items())}}
|
|
62
|
+
target.write_text(json.dumps(document, indent=2) + "\n", encoding="utf-8")
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""The name conformer: conform column and stream names so every target accepts them."""
|