supaflow-python-sdk 1.0.74__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.
- supaflow_python_sdk/__init__.py +150 -0
- supaflow_python_sdk/_definition_validation.py +220 -0
- supaflow_python_sdk/_legacy_manifest.py +89 -0
- supaflow_python_sdk/_legacy_naming.py +50 -0
- supaflow_python_sdk/_precision_json.py +74 -0
- supaflow_python_sdk/base_connector.py +146 -0
- supaflow_python_sdk/capabilities.py +74 -0
- supaflow_python_sdk/catalog_naming.py +189 -0
- supaflow_python_sdk/child_settings.py +44 -0
- supaflow_python_sdk/compatibility.json +10 -0
- supaflow_python_sdk/connector_definition.py +279 -0
- supaflow_python_sdk/connector_fixture.py +13 -0
- supaflow_python_sdk/connector_identity.py +55 -0
- supaflow_python_sdk/connector_property.py +97 -0
- supaflow_python_sdk/connector_resource.py +388 -0
- supaflow_python_sdk/csv_record_emitter.py +288 -0
- supaflow_python_sdk/cursor_candidates.py +167 -0
- supaflow_python_sdk/errors.py +130 -0
- supaflow_python_sdk/field_capabilities.py +50 -0
- supaflow_python_sdk/helpers.py +98 -0
- supaflow_python_sdk/host_api.py +102 -0
- supaflow_python_sdk/job_context.py +39 -0
- supaflow_python_sdk/jsonl_record_emitter.py +727 -0
- supaflow_python_sdk/keyless_object_handling.py +19 -0
- supaflow_python_sdk/models.py +1052 -0
- supaflow_python_sdk/naming.py +267 -0
- supaflow_python_sdk/native_mapped_jsonl_record_emitter.py +180 -0
- supaflow_python_sdk/oauth.py +399 -0
- supaflow_python_sdk/openapi_schema_builder.py +778 -0
- supaflow_python_sdk/property_rules.py +27 -0
- supaflow_python_sdk/py.typed +0 -0
- supaflow_python_sdk/resource_options.py +9 -0
- supaflow_python_sdk/schema_compliance.py +481 -0
- supaflow_python_sdk/source.py +165 -0
- supaflow_python_sdk/source_namespace.py +325 -0
- supaflow_python_sdk/supa_id.py +422 -0
- supaflow_python_sdk/temporal_stage_value.py +136 -0
- supaflow_python_sdk/type_inference.py +583 -0
- supaflow_python_sdk/ui.py +45 -0
- supaflow_python_sdk/write_plan.py +112 -0
- supaflow_python_sdk-1.0.74.dist-info/METADATA +80 -0
- supaflow_python_sdk-1.0.74.dist-info/RECORD +44 -0
- supaflow_python_sdk-1.0.74.dist-info/WHEEL +5 -0
- supaflow_python_sdk-1.0.74.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
"""Framework-neutral resource metadata with deprecated adapter-field compatibility."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from typing import Any, Mapping, Sequence
|
|
6
|
+
|
|
7
|
+
from supaflow_python_sdk.resource_options import ResourceAdapterOptions
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True)
|
|
11
|
+
class ConnectorResource:
|
|
12
|
+
"""Declarative definition for one exposed Supaflow object."""
|
|
13
|
+
|
|
14
|
+
name: str
|
|
15
|
+
mode: str
|
|
16
|
+
primary_key: str | list[str] | None = "id"
|
|
17
|
+
cursor_field: str | None = None
|
|
18
|
+
source_name: str | None = None
|
|
19
|
+
static_fields: Sequence[tuple[str, str]] = ()
|
|
20
|
+
description: str | None = None
|
|
21
|
+
schema_strategy: str = "static_with_probe_fill"
|
|
22
|
+
"""How schema discovery merges declared ``static_fields`` with types
|
|
23
|
+
inferred from a live sample of records.
|
|
24
|
+
|
|
25
|
+
Values:
|
|
26
|
+
|
|
27
|
+
* ``"static_with_probe_fill"`` (default) -- declared types are
|
|
28
|
+
authoritative. Probe contributes only novel field names the static
|
|
29
|
+
schema does not know about. Prevents costly schema flap when a
|
|
30
|
+
small probe sample mis-infers a type the OpenAPI spec got right
|
|
31
|
+
(e.g., ISO-8601 ``created_at`` inferred as ``text`` but declared
|
|
32
|
+
as ``timestamp``). Best for connectors with a stable, high-quality
|
|
33
|
+
OpenAPI spec; drift between spec and API surfaces as a loud first-
|
|
34
|
+
sync mismatch rather than being silently papered over.
|
|
35
|
+
|
|
36
|
+
* ``"probe_with_static_fallback"`` -- probe wins on name collisions;
|
|
37
|
+
static only fills in fields probe never observed. Retained for
|
|
38
|
+
connectors that intentionally want sample-driven types to
|
|
39
|
+
override the declared schema (e.g., when the OpenAPI spec is
|
|
40
|
+
known to drift from the live API). Normalize-backed discovery rejects
|
|
41
|
+
this strategy when its dlt source supplies business-column hints on the
|
|
42
|
+
resource, a preloaded schema, or a root static table variant: dlt does not
|
|
43
|
+
retain whether a hinted column was observed and may coerce sampled values
|
|
44
|
+
before schema publication, so probe-first precedence would not be
|
|
45
|
+
sample-driven.
|
|
46
|
+
|
|
47
|
+
* anything else (e.g., ``"static_only"``) -- skip probe entirely
|
|
48
|
+
and return static_fields verbatim. Useful when the schema is
|
|
49
|
+
fully declared and probe would add nothing.
|
|
50
|
+
"""
|
|
51
|
+
envelope_prefix: str | None = None
|
|
52
|
+
"""Top-level envelope key to hoist to the record root before normalize.
|
|
53
|
+
|
|
54
|
+
Many REST APIs wrap records in a single envelope key whose contents
|
|
55
|
+
are the business payload (Jira's ``fields``, Stripe's ``data``, HubSpot's
|
|
56
|
+
``properties``). Setting ``envelope_prefix`` causes the framework to
|
|
57
|
+
register an ``add_map`` transformation on the resource that hoists the
|
|
58
|
+
envelope dict's keys to the root of each record during extract.
|
|
59
|
+
|
|
60
|
+
The hoist is applied before dlt normalize sees the record, so all
|
|
61
|
+
downstream column and child-table names reflect the post-hoist shape.
|
|
62
|
+
For Jira ``issues`` with ``envelope_prefix="fields"``, dlt produces
|
|
63
|
+
columns like ``status__name`` instead of ``fields__status__name`` and
|
|
64
|
+
child tables like ``issues__components`` instead of
|
|
65
|
+
``issues__fields__components``.
|
|
66
|
+
|
|
67
|
+
Collision check: the framework asserts at extract time that the
|
|
68
|
+
envelope dict's keys do not collide with existing root keys. If they
|
|
69
|
+
do, it raises ``ConnectorException(VALIDATION_ERROR)`` with the colliding
|
|
70
|
+
key names. Failing hard prevents silent data loss.
|
|
71
|
+
"""
|
|
72
|
+
excluded_normalized_tables: tuple[str, ...] = ()
|
|
73
|
+
"""Exact-match names of normalized tables to drop at schema-discovery
|
|
74
|
+
time.
|
|
75
|
+
|
|
76
|
+
Applied after dlt's normalize produces its default_schema.data_tables()
|
|
77
|
+
but before SchemaObjectInfo construction. Names must match the
|
|
78
|
+
post-envelope-hoist table layout (i.e., what dlt actually writes to
|
|
79
|
+
the filesystem destination). For Jira issues, excluding
|
|
80
|
+
``issues__operations__link_groups`` also transitively drops its
|
|
81
|
+
descendant ``issues__operations__link_groups__links`` -- the framework
|
|
82
|
+
computes the transitive closure automatically so connector authors
|
|
83
|
+
need not enumerate every leaf.
|
|
84
|
+
|
|
85
|
+
No pattern matching in 1.6a; add if a future connector needs it.
|
|
86
|
+
"""
|
|
87
|
+
propagation: Mapping[str, Any] | None = None
|
|
88
|
+
"""Per-resource business FK propagation config, mirroring dlt's native
|
|
89
|
+
RelationalNormalizerConfigPropagation shape.
|
|
90
|
+
|
|
91
|
+
When set, the framework applies this config to the source's schema
|
|
92
|
+
via RelationalNormalizer.update_normalizer_config() before extract
|
|
93
|
+
runs. Values project parent row columns onto descendant rows during
|
|
94
|
+
normalize, using dlt's built-in mechanism.
|
|
95
|
+
|
|
96
|
+
Shape:
|
|
97
|
+
{
|
|
98
|
+
"root": {parent_col: propagated_col, ...},
|
|
99
|
+
"tables": {sub_table_name: {parent_col: propagated_col, ...}, ...},
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
The framework does not wrap or validate this config; the shape must
|
|
103
|
+
match what dlt's own RelationalNormalizerConfigPropagation TypedDict
|
|
104
|
+
accepts (see dlt/common/normalizers/json/typing.py). Malformed configs
|
|
105
|
+
fail at pipeline-setup time during the framework's
|
|
106
|
+
update_normalizer_config() call.
|
|
107
|
+
"""
|
|
108
|
+
incremental_strategy_override: str | None = None
|
|
109
|
+
"""Override the default incremental strategy derived from ``mode``.
|
|
110
|
+
|
|
111
|
+
When set to ``"CONNECTOR_MANAGED"``, the resource is still incremental
|
|
112
|
+
(``mode="incremental"``) but the connector manages cursor advancement
|
|
113
|
+
via ``_build_sync_response`` instead of dlt's ``Incremental`` state
|
|
114
|
+
injection. The framework suppresses ``source_cursor_field`` in schema
|
|
115
|
+
discovery and skips ``StateInjectableContext`` at read time.
|
|
116
|
+
"""
|
|
117
|
+
bounded_cursor_window: bool = False
|
|
118
|
+
"""Use a bounded ``[start, cutoff)`` window instead of dlt's stateful
|
|
119
|
+
Incremental.last_value tracking.
|
|
120
|
+
|
|
121
|
+
Compatible with ``COLUMN_CURSOR`` -- the resource keeps that
|
|
122
|
+
incremental strategy, schema discovery still surfaces
|
|
123
|
+
``source_cursor_field`` (the UI/catalog continue to treat the
|
|
124
|
+
resource as column-cursor), and ``_create_source`` is expected to
|
|
125
|
+
apply ``dlt.sources.incremental(cursor_field, initial_value=...,
|
|
126
|
+
end_value=..., range_start="closed", range_end="open")`` so the
|
|
127
|
+
upstream source emits an SQL upper bound.
|
|
128
|
+
|
|
129
|
+
Runtime behavior the framework provides for bounded resources:
|
|
130
|
+
|
|
131
|
+
1. Read fails with ``CONFIGURATION`` when ``SyncStateRequest`` lacks
|
|
132
|
+
``cutoff_time``. A bounded incremental sync without a cutoff
|
|
133
|
+
would silently scan the full source on every run.
|
|
134
|
+
2. ``_coerce_effective_start(resource, raw_string)`` is called once
|
|
135
|
+
before ``_create_source`` to convert the persisted cursor string
|
|
136
|
+
to the typed form dlt's ``Incremental.initial_value`` expects.
|
|
137
|
+
Default hook is identity; connectors with typed cursors
|
|
138
|
+
(datetime / date) override it.
|
|
139
|
+
3. ``_coerce_cutoff_value(resource, raw_string)`` is called once
|
|
140
|
+
before ``_create_source`` to convert ``cutoff_time`` to the typed
|
|
141
|
+
form dlt's ``Incremental.end_value`` expects. Default identity.
|
|
142
|
+
4. No ``StateInjectableContext`` is set up -- dlt's
|
|
143
|
+
``Incremental.last_value`` writeback is intentionally unused.
|
|
144
|
+
After ``pipeline.run`` the framework persists the applied
|
|
145
|
+
cutoff (typed) via :func:`build_cutoff_sync_response` so the
|
|
146
|
+
next run's lower bound is exactly the previous run's open
|
|
147
|
+
upper bound. Equal-cursor duplication is eliminated by window
|
|
148
|
+
math, so ``custom_state.incremental_boundary`` (dlt
|
|
149
|
+
``unique_hashes``) is intentionally not populated.
|
|
150
|
+
|
|
151
|
+
Mutually exclusive with ``incremental_strategy_override="CONNECTOR_MANAGED"``:
|
|
152
|
+
``DltResourceSpec.__post_init__`` raises ``ValueError`` when both
|
|
153
|
+
are set, because bounded is a ``COLUMN_CURSOR`` runtime mode and
|
|
154
|
+
CONNECTOR_MANAGED already owns cursor advancement via
|
|
155
|
+
``_build_sync_response``. The combination would mix bounded-style
|
|
156
|
+
cutoff coercion on entry with the connector-managed sync-response
|
|
157
|
+
on exit. Spec-time also rejects bounded without ``cursor_field``
|
|
158
|
+
and bounded on ``mode="full_refresh"``.
|
|
159
|
+
|
|
160
|
+
Default False (legacy behavior unchanged).
|
|
161
|
+
"""
|
|
162
|
+
windowed_replace: bool = False
|
|
163
|
+
"""Opt this object into windowed-replace loading.
|
|
164
|
+
|
|
165
|
+
Stamped into ``SchemaObjectInfo.custom_attributes`` as
|
|
166
|
+
``supaflow_windowed_replace`` so the Java loader deletes the
|
|
167
|
+
connector-reported applied read window (half-open
|
|
168
|
+
``[start_inclusive, end_exclusive)``) inside the merge transaction
|
|
169
|
+
immediately before MERGE. Requires an incremental resource with a
|
|
170
|
+
``cursor_field``; the connector must report
|
|
171
|
+
``SyncStateResponse.applied_read_window`` (e.g. via
|
|
172
|
+
``build_cutoff_sync_response(..., applied_read_window=...)``) for the
|
|
173
|
+
delete to fire. Rows that vanish from a re-read window (invalidated
|
|
174
|
+
clicks, privacy-thresholded report dimensions) are removed instead of
|
|
175
|
+
surviving MERGE forever.
|
|
176
|
+
"""
|
|
177
|
+
child_primary_keys: Mapping[str, str | list[str]] | None = None
|
|
178
|
+
"""Per-child-table primary key declaration for _supa_id computation.
|
|
179
|
+
|
|
180
|
+
Maps fully-qualified child table name (POST-envelope-hoist, i.e., what
|
|
181
|
+
dlt normalize actually emits) to the PK field name (or list of field
|
|
182
|
+
names for composite keys). When the root resource declares
|
|
183
|
+
``envelope_prefix="fields"``, the hoist is applied before normalize,
|
|
184
|
+
so child tables are ``issues__components``, ``issues__changelog__histories``,
|
|
185
|
+
etc. -- NOT ``issues__fields__components``. Mismatched names silently
|
|
186
|
+
fall through to Case B at emit time.
|
|
187
|
+
|
|
188
|
+
Drives the emit-time decision between:
|
|
189
|
+
- Case A (entry present): child _supa_id = hash(parent_supa_id + child_pk)
|
|
190
|
+
- Case B (entry absent): child _supa_id = hash(parent_supa_id + list_idx + content)
|
|
191
|
+
|
|
192
|
+
At read time Java also sends
|
|
193
|
+
``ReadRequest.child_context_infos[n].context_fields``. Those
|
|
194
|
+
``primary_key`` flags mean the same thing as root request metadata: the
|
|
195
|
+
orchestrator's effective business key after user selection and discovery
|
|
196
|
+
defaults are merged. The child hash path therefore prefers that request
|
|
197
|
+
carrier so wizard/API PK overrides apply to children too, and uses this
|
|
198
|
+
map only when the request carries no effective child PK.
|
|
199
|
+
|
|
200
|
+
``_supa_id`` is an internal merge pseudokey. If it appears as discovery
|
|
201
|
+
``source_primary_key`` or effective ``primary_key`` in either root or
|
|
202
|
+
child metadata, the upstream metadata is polluted; fix the
|
|
203
|
+
discovery/selection/merge carrier instead of special-casing the hash
|
|
204
|
+
primitive.
|
|
205
|
+
|
|
206
|
+
On roots (Phase 1 onwards) ``source_primary_key`` IS used: it marks
|
|
207
|
+
the connector's declared business key for the wizard's pre-selection
|
|
208
|
+
while ``_supa_id`` is no longer flagged.
|
|
209
|
+
"""
|
|
210
|
+
primary_key_locked: bool = False
|
|
211
|
+
"""Whether the connector asserts authority over the root primary key.
|
|
212
|
+
|
|
213
|
+
When False (the default), ``primary_key`` is used as the hash input for
|
|
214
|
+
``_supa_id`` computation but is NOT surfaced to the UI as a locked
|
|
215
|
+
selection. The framework treats it as a reasonable default that the
|
|
216
|
+
user may override.
|
|
217
|
+
|
|
218
|
+
When True, the connector explicitly claims that ``primary_key`` is the
|
|
219
|
+
stable business identifier for this resource. Set this only when the
|
|
220
|
+
source API guarantees key stability across syncs.
|
|
221
|
+
|
|
222
|
+
Declared here for API completeness. Not yet read by any runtime code at
|
|
223
|
+
this commit -- consumption is wired in later Phase-1 tasks (the
|
|
224
|
+
``build_object_info(primary_key=...)`` call sites and the schema-
|
|
225
|
+
discovery PK-stamping logic). Connector authors may opt in early.
|
|
226
|
+
|
|
227
|
+
Changing the default to True for existing connectors is a breaking
|
|
228
|
+
change once the consuming code lands: it alters the ``_supa_id`` lock
|
|
229
|
+
state surfaced to downstream consumers. Add deliberately.
|
|
230
|
+
"""
|
|
231
|
+
child_primary_keys_locked: Mapping[str, bool] | None = None
|
|
232
|
+
"""Per-child-table authority flags, parallel to ``child_primary_keys``.
|
|
233
|
+
|
|
234
|
+
Maps the same fully-qualified child table names used in
|
|
235
|
+
``child_primary_keys`` to a boolean indicating whether the connector
|
|
236
|
+
asserts authority over that child's PK. Absent entries default to
|
|
237
|
+
False (unlocked).
|
|
238
|
+
|
|
239
|
+
Declared now for API completeness. Not consumed in Phase 1 -- Phase 2
|
|
240
|
+
will wire it into schema-discovery output. Connector authors may opt in
|
|
241
|
+
early; nothing reads this field until Phase 2 ships.
|
|
242
|
+
"""
|
|
243
|
+
|
|
244
|
+
path_segments: tuple[str, ...] | None = None
|
|
245
|
+
"""v11: structural object-routing identity for the resource.
|
|
246
|
+
|
|
247
|
+
Under ``DltConnectorSpec.preserve_original_names=True`` this MUST
|
|
248
|
+
be non-empty -- it is the structured form of the resource's
|
|
249
|
+
source-side name (the dlt resource name). For ordinary root
|
|
250
|
+
resources whose name is a single source identifier (Jira's
|
|
251
|
+
``"issues"``, Stripe's ``"customer"``), this is a 1-tuple
|
|
252
|
+
``("issues",)``. MongoDB-style internal aliases that pack a
|
|
253
|
+
multi-component FQN into a single dlt resource name (e.g.,
|
|
254
|
+
``"sales__orders"``) also use a 1-tuple containing the aliased
|
|
255
|
+
string -- the alias is a single dlt-side identifier even if the
|
|
256
|
+
Supaflow-facing FQN decomposes differently.
|
|
257
|
+
|
|
258
|
+
Independent of ``obj.name`` / ``obj.catalog`` / ``obj.schema``
|
|
259
|
+
(display identity) and the dlt-internal joined form (private,
|
|
260
|
+
derived). See
|
|
261
|
+
docs/superpowers/specs/2026-05-11-dlt-original-source-names-b2-closure-design.md
|
|
262
|
+
§4.1 and §4.5.
|
|
263
|
+
|
|
264
|
+
Validated at the connector spec's ``__post_init__`` so the
|
|
265
|
+
requirement is enforced exactly when ``preserve_original_names``
|
|
266
|
+
flips on; resources outside the new contract may leave it None.
|
|
267
|
+
"""
|
|
268
|
+
|
|
269
|
+
cursor_field_path_segments: tuple[str, ...] | None = None
|
|
270
|
+
"""v11: structural cursor-field identity (§4.3).
|
|
271
|
+
|
|
272
|
+
Required (non-empty) when ``cursor_field`` is set under
|
|
273
|
+
``preserve_original_names=True``. For atomic cursors (every
|
|
274
|
+
in-scope connector today), this is a 1-tuple matching
|
|
275
|
+
``cursor_field``. For a nested cursor like ``profile.updated_at``
|
|
276
|
+
flowing through dlt normalize with object flattening, it would
|
|
277
|
+
be ``("profile", "updated_at")`` while ``cursor_field`` is the
|
|
278
|
+
external display form ``"profile__updated_at"``.
|
|
279
|
+
|
|
280
|
+
Consistency invariant (enforced at connector spec
|
|
281
|
+
construction): ``to_external_joined_path(self, preserve=True)``
|
|
282
|
+
MUST equal ``cursor_field``. Catches author typos at spec time.
|
|
283
|
+
|
|
284
|
+
Independent of cursor display identity (``cursor_field``) and the
|
|
285
|
+
dlt-internal cursor name (private, derived via
|
|
286
|
+
``to_dlt_internal_name`` -- the shape dlt's
|
|
287
|
+
``Incremental.cursor_path`` consumes).
|
|
288
|
+
"""
|
|
289
|
+
|
|
290
|
+
primary_key_path_segments: list[tuple[str, ...]] | None = None
|
|
291
|
+
"""v11 (closure design): structural primary-key identity (§4.4).
|
|
292
|
+
|
|
293
|
+
Required (non-empty) when ``primary_key`` is set under
|
|
294
|
+
``preserve_original_names=True``. One tuple per PK column.
|
|
295
|
+
|
|
296
|
+
Author shapes:
|
|
297
|
+
|
|
298
|
+
- Atomic at root (``primary_key=("id",)``):
|
|
299
|
+
``primary_key_path_segments=[("id",)]``.
|
|
300
|
+
- Composite atomic (``primary_key=("id", "key")``):
|
|
301
|
+
``primary_key_path_segments=[("id",), ("key",)]``.
|
|
302
|
+
- Nested composite (Jira workflows;
|
|
303
|
+
``primary_key=["id__entity_id", "id__name"]``):
|
|
304
|
+
``primary_key_path_segments=[("id", "entity_id"), ("id", "name")]``.
|
|
305
|
+
|
|
306
|
+
Consistency invariant (enforced at connector spec
|
|
307
|
+
construction): for each column ``i``,
|
|
308
|
+
``to_external_joined_path(primary_key_path_segments[i],
|
|
309
|
+
preserve=True) == primary_key[i]``. Catches author typos like
|
|
310
|
+
declaring ``primary_key=["id__entity_id"]`` while writing
|
|
311
|
+
``primary_key_path_segments=[("id", "entity")]``.
|
|
312
|
+
|
|
313
|
+
The framework derives the dlt-internal PK column form via
|
|
314
|
+
``to_dlt_internal_name`` per segment-tuple (the ``▶``-joined
|
|
315
|
+
shape dlt's resource-level dedup expects when the connector has
|
|
316
|
+
opted into ``SupaflowNamingConvention``).
|
|
317
|
+
"""
|
|
318
|
+
|
|
319
|
+
adapter_options: ResourceAdapterOptions | None = field(default=None, kw_only=True)
|
|
320
|
+
|
|
321
|
+
@property
|
|
322
|
+
def is_incremental(self) -> bool:
|
|
323
|
+
return self.mode == "incremental"
|
|
324
|
+
|
|
325
|
+
@property
|
|
326
|
+
def incremental_strategy(self) -> str:
|
|
327
|
+
if self.incremental_strategy_override:
|
|
328
|
+
return self.incremental_strategy_override
|
|
329
|
+
return "COLUMN_CURSOR" if self.is_incremental else "UNSUPPORTED"
|
|
330
|
+
|
|
331
|
+
@property
|
|
332
|
+
def is_connector_managed(self) -> bool:
|
|
333
|
+
return self.incremental_strategy == "CONNECTOR_MANAGED"
|
|
334
|
+
|
|
335
|
+
def state_source_name(self) -> str:
|
|
336
|
+
if self.source_name:
|
|
337
|
+
return self.source_name
|
|
338
|
+
return self.name
|
|
339
|
+
|
|
340
|
+
def __post_init__(self) -> None:
|
|
341
|
+
if self.adapter_options is not None:
|
|
342
|
+
if not isinstance(self.adapter_options, ResourceAdapterOptions):
|
|
343
|
+
raise TypeError("The dlt adapter requires DltResourceOptions")
|
|
344
|
+
self.adapter_options._apply_legacy_fields(self)
|
|
345
|
+
# ``bounded_cursor_window`` is a runtime mode that builds on
|
|
346
|
+
# top of ``COLUMN_CURSOR``. Combinations that produce split
|
|
347
|
+
# semantics across the framework's incremental-state setup
|
|
348
|
+
# (entry) and sync-response (exit) branches must be rejected
|
|
349
|
+
# at spec construction, before the resource is ever read.
|
|
350
|
+
if self.bounded_cursor_window:
|
|
351
|
+
if not self.is_incremental:
|
|
352
|
+
raise ValueError(
|
|
353
|
+
f"DltResourceSpec(name={self.name!r}): "
|
|
354
|
+
f"bounded_cursor_window=True requires "
|
|
355
|
+
f"mode='incremental' (got mode={self.mode!r}). "
|
|
356
|
+
f"A bounded [start, cutoff) window is only "
|
|
357
|
+
f"meaningful for incremental reads."
|
|
358
|
+
)
|
|
359
|
+
if not self.cursor_field:
|
|
360
|
+
raise ValueError(
|
|
361
|
+
f"DltResourceSpec(name={self.name!r}): "
|
|
362
|
+
f"bounded_cursor_window=True requires a non-empty "
|
|
363
|
+
f"cursor_field so the framework can apply "
|
|
364
|
+
f"dlt.sources.incremental(...) and persist the "
|
|
365
|
+
f"applied cutoff under that field name."
|
|
366
|
+
)
|
|
367
|
+
if self.is_connector_managed:
|
|
368
|
+
raise ValueError(
|
|
369
|
+
f"DltResourceSpec(name={self.name!r}): "
|
|
370
|
+
f"bounded_cursor_window=True is incompatible with "
|
|
371
|
+
f"incremental_strategy_override="
|
|
372
|
+
f"{self.incremental_strategy_override!r}. Bounded "
|
|
373
|
+
f"is a COLUMN_CURSOR runtime mode -- "
|
|
374
|
+
f"CONNECTOR_MANAGED resources already own their "
|
|
375
|
+
f"cursor advancement via _build_sync_response, "
|
|
376
|
+
f"and accepting both would mix bounded-style "
|
|
377
|
+
f"cutoff coercion on entry with "
|
|
378
|
+
f"connector-managed sync-response on exit. Pick "
|
|
379
|
+
f"one strategy."
|
|
380
|
+
)
|
|
381
|
+
if self.windowed_replace and (
|
|
382
|
+
not self.is_incremental or not self.cursor_field
|
|
383
|
+
):
|
|
384
|
+
raise ValueError(
|
|
385
|
+
f"DltResourceSpec(name={self.name!r}): "
|
|
386
|
+
f"windowed_replace=True requires "
|
|
387
|
+
f"an incremental resource with cursor_field set"
|
|
388
|
+
)
|
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
"""CSV chunk emitter matching Java ChunkedOutputStream contract.
|
|
2
|
+
|
|
3
|
+
SDK-owned production transport for the host and testkit.
|
|
4
|
+
Connector authors emit through RecordEmitter; the host constructs this pinned
|
|
5
|
+
implementation without changing the selected staging format.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import base64
|
|
10
|
+
import datetime as _dt
|
|
11
|
+
import decimal as _decimal
|
|
12
|
+
import gzip
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import uuid as _uuid
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from supaflow_python_sdk.models import MetadataField
|
|
19
|
+
from supaflow_python_sdk.source import RecordEmitter, RecordEmitResult
|
|
20
|
+
from supaflow_python_sdk.write_plan import RecordWritePlan
|
|
21
|
+
from supaflow_python_sdk.temporal_stage_value import (
|
|
22
|
+
encode_temporal_stage_value,
|
|
23
|
+
validate_max_fractional_second_digits,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _json_default(obj: Any) -> Any:
|
|
28
|
+
"""Encode types stdlib json.dumps does not natively support.
|
|
29
|
+
|
|
30
|
+
Connectors emit nested dict/list values containing types produced by
|
|
31
|
+
BSON, dlt, and pymongo conversions (pendulum.DateTime, uuid.UUID,
|
|
32
|
+
bson.Binary, decimal.Decimal, ...). Without this fallback,
|
|
33
|
+
json.dumps raises "Object of type X is not JSON serializable" and
|
|
34
|
+
aborts the whole read. The first reported case was the MongoDB
|
|
35
|
+
source's pendulum.DateTime values nested in `tomatoes.lastUpdated`
|
|
36
|
+
(sample_mflix.embedded_movies); pendulum.DateTime subclasses
|
|
37
|
+
datetime.datetime so the datetime branch covers it.
|
|
38
|
+
|
|
39
|
+
Note that datetime.datetime must be checked before datetime.date
|
|
40
|
+
because datetime.datetime is itself a subclass of datetime.date.
|
|
41
|
+
"""
|
|
42
|
+
if isinstance(obj, (_dt.datetime, _dt.date, _dt.time)):
|
|
43
|
+
return obj.isoformat()
|
|
44
|
+
if isinstance(obj, _dt.timedelta):
|
|
45
|
+
return obj.total_seconds()
|
|
46
|
+
if isinstance(obj, _decimal.Decimal):
|
|
47
|
+
return str(obj)
|
|
48
|
+
if isinstance(obj, _uuid.UUID):
|
|
49
|
+
return str(obj)
|
|
50
|
+
if isinstance(obj, (bytes, bytearray, memoryview)):
|
|
51
|
+
return base64.b64encode(bytes(obj)).decode("ascii")
|
|
52
|
+
if isinstance(obj, (set, frozenset)):
|
|
53
|
+
return list(obj)
|
|
54
|
+
return str(obj)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _stringify_value(value: Any) -> str:
|
|
58
|
+
"""Convert one non-null CSV value using the same scalar encoders as JSON."""
|
|
59
|
+
if isinstance(value, (dict, list)):
|
|
60
|
+
return json.dumps(value, ensure_ascii=False, default=_json_default)
|
|
61
|
+
|
|
62
|
+
encoded = _json_default(value)
|
|
63
|
+
if isinstance(encoded, (dict, list)):
|
|
64
|
+
return json.dumps(encoded, ensure_ascii=False, default=_json_default)
|
|
65
|
+
return str(encoded)
|
|
66
|
+
|
|
67
|
+
# Minimum chunk size: 1MB (matches Java ChunkedOutputStream.MINIMUM_CHUNK_SIZE)
|
|
68
|
+
_MIN_CHUNK_SIZE = 1024 * 1024
|
|
69
|
+
# Default chunk size: 100MB (matches Java ChunkedOutputStream.Builder default)
|
|
70
|
+
_DEFAULT_CHUNK_SIZE = 100 * 1024 * 1024
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class CsvRecordEmitter(RecordEmitter):
|
|
74
|
+
"""Writes records as chunked CSV matching the Java CSV contract exactly.
|
|
75
|
+
|
|
76
|
+
- Byte-based chunk rotation (not record-count)
|
|
77
|
+
- Configurable header rows prepended to every chunk
|
|
78
|
+
(2 = field names + data types, 1 = field names, 0 = none)
|
|
79
|
+
- CSV encoding matching CsvWriter.encode()
|
|
80
|
+
- File naming: success_part_{index}.csv.gz
|
|
81
|
+
- fsync on file and directory after each chunk
|
|
82
|
+
"""
|
|
83
|
+
|
|
84
|
+
def __init__(
|
|
85
|
+
self,
|
|
86
|
+
output_dir: str,
|
|
87
|
+
fields: list[MetadataField],
|
|
88
|
+
csv_format: dict[str, Any] | None = None,
|
|
89
|
+
chunk_size: int = _DEFAULT_CHUNK_SIZE,
|
|
90
|
+
plan: RecordWritePlan | None = None,
|
|
91
|
+
):
|
|
92
|
+
csv_format = csv_format or {}
|
|
93
|
+
self._output_dir = output_dir
|
|
94
|
+
self._fields = fields
|
|
95
|
+
self._chunk_size = max(chunk_size, _MIN_CHUNK_SIZE)
|
|
96
|
+
self._delimiter = csv_format.get("fieldDelimiter", ",")
|
|
97
|
+
self._quote = csv_format.get("fieldOptionallyEnclosedBy", '"')
|
|
98
|
+
self._null_marker = csv_format.get("nullMarker", "\\N")
|
|
99
|
+
self._header_rows = self._normalize_header_rows(csv_format.get("headerRows", 2))
|
|
100
|
+
declared_precision = csv_format.get("maxFractionalSecondDigits")
|
|
101
|
+
if declared_precision is not None:
|
|
102
|
+
if isinstance(declared_precision, bool) or not isinstance(
|
|
103
|
+
declared_precision, int
|
|
104
|
+
):
|
|
105
|
+
raise ValueError(
|
|
106
|
+
"CSV maxFractionalSecondDigits must be an integer, got "
|
|
107
|
+
f"{declared_precision!r}"
|
|
108
|
+
)
|
|
109
|
+
plan_precision = (
|
|
110
|
+
plan.max_fractional_second_digits if plan is not None else None
|
|
111
|
+
)
|
|
112
|
+
validate_max_fractional_second_digits(declared_precision)
|
|
113
|
+
validate_max_fractional_second_digits(plan_precision)
|
|
114
|
+
if declared_precision is not None and plan_precision is None:
|
|
115
|
+
raise ValueError(
|
|
116
|
+
"CSV destination declares maxFractionalSecondDigits="
|
|
117
|
+
f"{declared_precision} but the emitter received no write-plan "
|
|
118
|
+
"precision policy"
|
|
119
|
+
)
|
|
120
|
+
if (
|
|
121
|
+
declared_precision is not None
|
|
122
|
+
and declared_precision != plan_precision
|
|
123
|
+
):
|
|
124
|
+
raise ValueError(
|
|
125
|
+
"CSV temporal precision policy mismatch: destination declared "
|
|
126
|
+
f"{declared_precision} but write plan contains {plan_precision}"
|
|
127
|
+
)
|
|
128
|
+
self._max_fractional_second_digits = plan_precision
|
|
129
|
+
self._target_types_by_source_name = {
|
|
130
|
+
binding.source_name: getattr(
|
|
131
|
+
binding.target_field, "canonical_type", None
|
|
132
|
+
)
|
|
133
|
+
for binding in (plan.fields if plan is not None else [])
|
|
134
|
+
if binding.source_name and binding.target_field is not None
|
|
135
|
+
}
|
|
136
|
+
self._header_bytes = self._build_header()
|
|
137
|
+
self._chunk_index = 0
|
|
138
|
+
self._current_chunk = bytearray()
|
|
139
|
+
self._records_emitted = 0
|
|
140
|
+
self._total_bytes_written = 0
|
|
141
|
+
self._closed = False
|
|
142
|
+
|
|
143
|
+
@staticmethod
|
|
144
|
+
def _normalize_header_rows(value: Any) -> int:
|
|
145
|
+
try:
|
|
146
|
+
rows = int(value)
|
|
147
|
+
except (TypeError, ValueError):
|
|
148
|
+
return 2
|
|
149
|
+
if rows <= 0:
|
|
150
|
+
return 0
|
|
151
|
+
if rows == 1:
|
|
152
|
+
return 1
|
|
153
|
+
return 2
|
|
154
|
+
|
|
155
|
+
def _build_header(self) -> bytes:
|
|
156
|
+
"""Build CSV header bytes based on the configured header row count."""
|
|
157
|
+
if self._header_rows == 0:
|
|
158
|
+
return b""
|
|
159
|
+
|
|
160
|
+
names = [f.name for f in self._fields]
|
|
161
|
+
row1 = self._encode_csv_line(names)
|
|
162
|
+
if self._header_rows == 1:
|
|
163
|
+
return (row1 + "\n").encode("utf-8")
|
|
164
|
+
|
|
165
|
+
types = [
|
|
166
|
+
f.original_data_type if f.original_data_type else f.canonical_type
|
|
167
|
+
for f in self._fields
|
|
168
|
+
]
|
|
169
|
+
row2 = self._encode_csv_line(types)
|
|
170
|
+
return (row1 + "\n" + row2 + "\n").encode("utf-8")
|
|
171
|
+
|
|
172
|
+
def _encode_field(self, value: str) -> str:
|
|
173
|
+
"""Encode a single CSV field matching Java CsvWriter.encode()."""
|
|
174
|
+
d = self._delimiter
|
|
175
|
+
q = self._quote
|
|
176
|
+
needs_quote = False
|
|
177
|
+
|
|
178
|
+
# Replace \r with \n (Java CsvWriter behavior)
|
|
179
|
+
if "\r" in value:
|
|
180
|
+
value = value.replace("\r", "\n")
|
|
181
|
+
needs_quote = True
|
|
182
|
+
|
|
183
|
+
if d in value:
|
|
184
|
+
needs_quote = True
|
|
185
|
+
if q in value:
|
|
186
|
+
# Double the quote character
|
|
187
|
+
value = value.replace(q, q + q)
|
|
188
|
+
needs_quote = True
|
|
189
|
+
if "\n" in value:
|
|
190
|
+
needs_quote = True
|
|
191
|
+
if value and (value[0] == " " or value[-1] == " "):
|
|
192
|
+
needs_quote = True
|
|
193
|
+
|
|
194
|
+
if needs_quote:
|
|
195
|
+
return q + value + q
|
|
196
|
+
return value
|
|
197
|
+
|
|
198
|
+
def _encode_csv_line(self, values: list[str]) -> str:
|
|
199
|
+
"""Encode a list of values as a single CSV line (no trailing newline)."""
|
|
200
|
+
return self._delimiter.join(self._encode_field(v) for v in values)
|
|
201
|
+
|
|
202
|
+
def emit(self, record: dict[str, Any]) -> None:
|
|
203
|
+
"""Emit a single record as a CSV line."""
|
|
204
|
+
if self._closed:
|
|
205
|
+
raise RuntimeError("Cannot emit after close")
|
|
206
|
+
|
|
207
|
+
values = []
|
|
208
|
+
remap_legacy = self._null_marker != "\\N"
|
|
209
|
+
for field in self._fields:
|
|
210
|
+
v = record.get(field.name)
|
|
211
|
+
if v is None:
|
|
212
|
+
values.append(self._null_marker)
|
|
213
|
+
elif (
|
|
214
|
+
isinstance(v, str) and v == ""
|
|
215
|
+
and getattr(field, "canonical_type", "STRING") not in {"STRING", "BINARY"}
|
|
216
|
+
):
|
|
217
|
+
# Empty Base64 represents zero bytes, distinct from SQL NULL.
|
|
218
|
+
values.append(self._null_marker)
|
|
219
|
+
elif remap_legacy and isinstance(v, str) and v == "\\N":
|
|
220
|
+
values.append(self._null_marker)
|
|
221
|
+
else:
|
|
222
|
+
target_type = self._target_types_by_source_name.get(
|
|
223
|
+
field.name, getattr(field, "canonical_type", None)
|
|
224
|
+
)
|
|
225
|
+
staged_value = encode_temporal_stage_value(
|
|
226
|
+
v, target_type, self._max_fractional_second_digits
|
|
227
|
+
)
|
|
228
|
+
values.append(_stringify_value(staged_value))
|
|
229
|
+
|
|
230
|
+
line = self._encode_csv_line(values) + "\n"
|
|
231
|
+
line_bytes = line.encode("utf-8")
|
|
232
|
+
self._current_chunk.extend(line_bytes)
|
|
233
|
+
self._records_emitted += 1
|
|
234
|
+
|
|
235
|
+
# Byte-based rotation check after complete record
|
|
236
|
+
if len(self._current_chunk) >= self._chunk_size:
|
|
237
|
+
self._flush_chunk()
|
|
238
|
+
|
|
239
|
+
def complete(self) -> RecordEmitResult:
|
|
240
|
+
"""Flush remaining data and return statistics."""
|
|
241
|
+
if self._current_chunk:
|
|
242
|
+
self._flush_chunk()
|
|
243
|
+
return RecordEmitResult(
|
|
244
|
+
records_emitted=self._records_emitted,
|
|
245
|
+
bytes_written=self._total_bytes_written,
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
def close(self) -> None:
|
|
249
|
+
"""Flush and release resources."""
|
|
250
|
+
if not self._closed:
|
|
251
|
+
if self._current_chunk:
|
|
252
|
+
self._flush_chunk()
|
|
253
|
+
self._closed = True
|
|
254
|
+
|
|
255
|
+
@property
|
|
256
|
+
def closed(self) -> bool:
|
|
257
|
+
return self._closed
|
|
258
|
+
|
|
259
|
+
@property
|
|
260
|
+
def output_dir(self) -> str:
|
|
261
|
+
"""Public read-only access to the directory this emitter writes to."""
|
|
262
|
+
return self._output_dir
|
|
263
|
+
|
|
264
|
+
def _flush_chunk(self) -> None:
|
|
265
|
+
"""Write current chunk with header prepended."""
|
|
266
|
+
if not self._current_chunk:
|
|
267
|
+
return
|
|
268
|
+
|
|
269
|
+
data = bytes(self._header_bytes) + bytes(self._current_chunk)
|
|
270
|
+
os.makedirs(self._output_dir, exist_ok=True)
|
|
271
|
+
path = os.path.join(self._output_dir, f"success_part_{self._chunk_index}.csv.gz")
|
|
272
|
+
|
|
273
|
+
with open(path, "wb") as f:
|
|
274
|
+
with gzip.GzipFile(fileobj=f, mode="wb", mtime=0) as gz:
|
|
275
|
+
gz.write(data)
|
|
276
|
+
f.flush()
|
|
277
|
+
os.fsync(f.fileno())
|
|
278
|
+
|
|
279
|
+
# fsync parent directory for metadata durability
|
|
280
|
+
dir_fd = os.open(self._output_dir, os.O_RDONLY)
|
|
281
|
+
try:
|
|
282
|
+
os.fsync(dir_fd)
|
|
283
|
+
finally:
|
|
284
|
+
os.close(dir_fd)
|
|
285
|
+
|
|
286
|
+
self._total_bytes_written += os.path.getsize(path)
|
|
287
|
+
self._chunk_index += 1
|
|
288
|
+
self._current_chunk = bytearray()
|