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,167 @@
|
|
|
1
|
+
"""Helpers for cursor-capable field sets and source cursor recommendations.
|
|
2
|
+
|
|
3
|
+
This module intentionally does not decide source-specific eligibility. A
|
|
4
|
+
connector with stronger type semantics than dlt's inference, such as MongoDB
|
|
5
|
+
with BSON types, should probe the source and pass the eligible field names in.
|
|
6
|
+
The shared utility owns only the common Supaflow metadata contract:
|
|
7
|
+
|
|
8
|
+
* ``cursor_capable`` means the user may select the field as a cursor.
|
|
9
|
+
* ``source_cursor_field=True`` is a sparse, single-field recommendation.
|
|
10
|
+
* Rejected dlt-inferred datetime fields may be demoted to STRING/text when the
|
|
11
|
+
connector knows the source type is not actually datetime-compatible.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import re
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from typing import Iterable, Sequence
|
|
18
|
+
|
|
19
|
+
from supaflow_python_sdk.field_capabilities import (
|
|
20
|
+
is_cursor_capable,
|
|
21
|
+
is_primary_key_capable,
|
|
22
|
+
)
|
|
23
|
+
from supaflow_python_sdk.models import SchemaFieldInfo
|
|
24
|
+
|
|
25
|
+
DATETIME_CURSOR_TYPES = frozenset({
|
|
26
|
+
"INSTANT",
|
|
27
|
+
"LOCALDATETIME",
|
|
28
|
+
"LOCALDATE",
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True)
|
|
33
|
+
class CursorRecommendationResult:
|
|
34
|
+
"""Result from applying cursor eligibility and recommendation metadata."""
|
|
35
|
+
|
|
36
|
+
recommended_name: str | None
|
|
37
|
+
eligible_names: frozenset[str]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
_UPDATE_PATTERNS = (
|
|
41
|
+
r"updat(e|ed|es|ing)?((_|-)?(at|time|date|on|ts|timestamp))?",
|
|
42
|
+
r"modif(y|ied|ication)?((_|-)?(at|time|date|on))?",
|
|
43
|
+
r"last(_|-)?modif(y|ied|ication)?((_|-)?(at|time|date|on|ts|timestamp))?",
|
|
44
|
+
r"lastmodified(date|time|timestamp)?",
|
|
45
|
+
r"last(_|-)?(change|modified|mod|update|edited)",
|
|
46
|
+
r"modified((_|-)?(at|time|date|on))?",
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
_CREATE_PATTERNS = (
|
|
50
|
+
r"creat(e|ed|ion)?((_|-)?(at|time|date|on|ts|timestamp))?",
|
|
51
|
+
r"insert(ed)?((_|-)?(at|time|date|on))?",
|
|
52
|
+
r"added((_|-)?(at|time|date|on))?",
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def apply_cursor_recommendation(
|
|
57
|
+
fields: list[SchemaFieldInfo],
|
|
58
|
+
*,
|
|
59
|
+
eligible_names: Iterable[str],
|
|
60
|
+
demote_rejected_datetime_to_string: bool = False,
|
|
61
|
+
demoted_original_data_type: str = "text",
|
|
62
|
+
cursor_types: Iterable[str] = DATETIME_CURSOR_TYPES,
|
|
63
|
+
) -> CursorRecommendationResult:
|
|
64
|
+
"""Apply cursor capability metadata and choose one recommendation.
|
|
65
|
+
|
|
66
|
+
``eligible_names`` is connector-owned. For Mongo, it is the set of dlt-
|
|
67
|
+
inferred datetime fields whose sampled BSON values are actually Dates. For
|
|
68
|
+
a connector whose inferred datetime types are already trustworthy, pass the
|
|
69
|
+
datetime field names directly.
|
|
70
|
+
|
|
71
|
+
The function mutates ``fields`` in place, matching the rest of the Python
|
|
72
|
+
SDK schema helpers.
|
|
73
|
+
"""
|
|
74
|
+
eligible = frozenset(name for name in eligible_names if name)
|
|
75
|
+
cursor_type_set = {t.upper() for t in cursor_types}
|
|
76
|
+
|
|
77
|
+
for field in fields:
|
|
78
|
+
field.source_cursor_field = None
|
|
79
|
+
|
|
80
|
+
canonical = (field.canonical_type or "").upper()
|
|
81
|
+
if canonical not in cursor_type_set:
|
|
82
|
+
continue
|
|
83
|
+
|
|
84
|
+
if field.name in eligible:
|
|
85
|
+
field.cursor_capable = True
|
|
86
|
+
if field.primary_key_capable is None:
|
|
87
|
+
field.primary_key_capable = is_primary_key_capable(
|
|
88
|
+
field.canonical_type,
|
|
89
|
+
)
|
|
90
|
+
continue
|
|
91
|
+
|
|
92
|
+
if demote_rejected_datetime_to_string:
|
|
93
|
+
field.canonical_type = "STRING"
|
|
94
|
+
field.original_data_type = demoted_original_data_type
|
|
95
|
+
field.cursor_capable = is_cursor_capable(field.canonical_type)
|
|
96
|
+
field.primary_key_capable = is_primary_key_capable(
|
|
97
|
+
field.canonical_type,
|
|
98
|
+
)
|
|
99
|
+
else:
|
|
100
|
+
field.cursor_capable = False
|
|
101
|
+
|
|
102
|
+
recommended = _choose_recommended_cursor(fields, eligible, cursor_type_set)
|
|
103
|
+
if recommended is not None:
|
|
104
|
+
recommended.source_cursor_field = True
|
|
105
|
+
|
|
106
|
+
return CursorRecommendationResult(
|
|
107
|
+
recommended_name=recommended.name if recommended is not None else None,
|
|
108
|
+
eligible_names=eligible,
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _choose_recommended_cursor(
|
|
113
|
+
fields: Sequence[SchemaFieldInfo],
|
|
114
|
+
eligible_names: frozenset[str],
|
|
115
|
+
cursor_types: set[str],
|
|
116
|
+
) -> SchemaFieldInfo | None:
|
|
117
|
+
best_score: tuple[int, int] | None = None
|
|
118
|
+
best_field: SchemaFieldInfo | None = None
|
|
119
|
+
for idx, field in enumerate(fields):
|
|
120
|
+
if field.name not in eligible_names:
|
|
121
|
+
continue
|
|
122
|
+
if (field.canonical_type or "").upper() not in cursor_types:
|
|
123
|
+
continue
|
|
124
|
+
if field.cursor_capable is False:
|
|
125
|
+
continue
|
|
126
|
+
|
|
127
|
+
# Higher score wins. For equal scores, earlier source field order wins
|
|
128
|
+
# to keep schema output stable under repeated refreshes.
|
|
129
|
+
score = (_cursor_field_score(field), -idx)
|
|
130
|
+
if best_score is None or score > best_score:
|
|
131
|
+
best_score = score
|
|
132
|
+
best_field = field
|
|
133
|
+
|
|
134
|
+
return best_field
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _cursor_field_score(field: SchemaFieldInfo) -> int:
|
|
138
|
+
name = (field.name or "").lower()
|
|
139
|
+
score = 0
|
|
140
|
+
|
|
141
|
+
if name == "systemmodstamp":
|
|
142
|
+
score += 50
|
|
143
|
+
elif name in {"updated_at", "updatedat"}:
|
|
144
|
+
score += 48
|
|
145
|
+
elif name == "lastmodifieddate":
|
|
146
|
+
score += 45
|
|
147
|
+
elif _matches_any_pattern(name, _UPDATE_PATTERNS):
|
|
148
|
+
score += 30
|
|
149
|
+
elif _matches_any_pattern(name, _CREATE_PATTERNS):
|
|
150
|
+
score += 20
|
|
151
|
+
elif name == "_supa_synced":
|
|
152
|
+
score += 15
|
|
153
|
+
|
|
154
|
+
canonical = (field.canonical_type or "").upper()
|
|
155
|
+
if canonical in {"INSTANT", "LOCALDATETIME"}:
|
|
156
|
+
score += 25
|
|
157
|
+
elif canonical == "LOCALDATE":
|
|
158
|
+
score += 20
|
|
159
|
+
|
|
160
|
+
if field.source_primary_key is True:
|
|
161
|
+
score += 15
|
|
162
|
+
|
|
163
|
+
return score
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _matches_any_pattern(value: str, patterns: Iterable[str]) -> bool:
|
|
167
|
+
return any(re.search(pattern, value) for pattern in patterns)
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from enum import Enum
|
|
5
|
+
from typing import Any, Never
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class ErrorType(str, Enum):
|
|
9
|
+
"""Enumeration of all recognized connector error categories.
|
|
10
|
+
|
|
11
|
+
Inherits from ``str`` so values can be compared directly to string
|
|
12
|
+
literals and serialized without special handling.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
CONNECTION = "CONNECTION"
|
|
16
|
+
AUTH = "AUTH"
|
|
17
|
+
CONFIGURATION = "CONFIGURATION"
|
|
18
|
+
VALIDATION = "VALIDATION"
|
|
19
|
+
IO = "IO"
|
|
20
|
+
TIMEOUT = "TIMEOUT"
|
|
21
|
+
CANCELLED = "CANCELLED"
|
|
22
|
+
RATE_LIMIT = "RATE_LIMIT"
|
|
23
|
+
UNSUPPORTED = "UNSUPPORTED"
|
|
24
|
+
PERMANENT_FAILURE = "PERMANENT_FAILURE"
|
|
25
|
+
DEPENDENCY = "DEPENDENCY"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class ConnectorError:
|
|
30
|
+
"""Structured error payload carried by :class:`ConnectorException`.
|
|
31
|
+
|
|
32
|
+
Attributes:
|
|
33
|
+
type: Category of the failure (see :class:`ErrorType`).
|
|
34
|
+
message: Human-readable description of the failure.
|
|
35
|
+
retryable: Whether the operation can be safely retried.
|
|
36
|
+
code: Optional short machine-readable error code (e.g. ``"HTTP_429"``).
|
|
37
|
+
details: Optional free-form key/value context for diagnostics.
|
|
38
|
+
stack_trace: Optional captured stack trace string.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
type: ErrorType
|
|
42
|
+
message: str
|
|
43
|
+
retryable: bool = False
|
|
44
|
+
code: str | None = None
|
|
45
|
+
details: dict[str, Any] | None = None
|
|
46
|
+
stack_trace: str | None = None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class ConnectorException(Exception):
|
|
50
|
+
"""Exception raised by connectors to signal a structured failure.
|
|
51
|
+
|
|
52
|
+
Always carries a :class:`ConnectorError` instance so callers can
|
|
53
|
+
inspect the error category, retryability, and any extra context
|
|
54
|
+
without string-parsing the message.
|
|
55
|
+
|
|
56
|
+
Example::
|
|
57
|
+
|
|
58
|
+
try:
|
|
59
|
+
connect()
|
|
60
|
+
except ConnectorException as exc:
|
|
61
|
+
if exc.error.retryable:
|
|
62
|
+
schedule_retry()
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
def __init__(self, error: ConnectorError) -> None:
|
|
66
|
+
self.error = error
|
|
67
|
+
super().__init__(error.message)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def fail(
|
|
71
|
+
error_type: ErrorType,
|
|
72
|
+
message: str,
|
|
73
|
+
*,
|
|
74
|
+
retryable: bool = False,
|
|
75
|
+
code: str | None = None,
|
|
76
|
+
**details: Any,
|
|
77
|
+
) -> Never:
|
|
78
|
+
"""Raise a :class:`ConnectorException` with a single call.
|
|
79
|
+
|
|
80
|
+
Keyword arguments beyond ``retryable`` and ``code`` are collected into
|
|
81
|
+
the ``details`` dict. If no extra keyword arguments are supplied,
|
|
82
|
+
``details`` is set to ``None`` rather than an empty dict.
|
|
83
|
+
|
|
84
|
+
Example::
|
|
85
|
+
|
|
86
|
+
fail(
|
|
87
|
+
ErrorType.CONFIGURATION,
|
|
88
|
+
"batch_size must be a positive integer",
|
|
89
|
+
field="batch_size",
|
|
90
|
+
got=value,
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
Args:
|
|
94
|
+
error_type: Category of the failure.
|
|
95
|
+
message: Human-readable description.
|
|
96
|
+
retryable: Whether the caller may retry the operation.
|
|
97
|
+
code: Optional short machine-readable error code.
|
|
98
|
+
**details: Additional key/value context stored in
|
|
99
|
+
:attr:`ConnectorError.details`.
|
|
100
|
+
|
|
101
|
+
Raises:
|
|
102
|
+
ConnectorException: Always.
|
|
103
|
+
"""
|
|
104
|
+
raise ConnectorException(
|
|
105
|
+
ConnectorError(
|
|
106
|
+
type=error_type,
|
|
107
|
+
message=message,
|
|
108
|
+
retryable=retryable,
|
|
109
|
+
code=code,
|
|
110
|
+
details=details if details else None,
|
|
111
|
+
)
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
@dataclass
|
|
116
|
+
class Warning:
|
|
117
|
+
"""Non-fatal advisory issued during connector execution.
|
|
118
|
+
|
|
119
|
+
Warnings do not interrupt pipeline processing; they are collected and
|
|
120
|
+
surfaced in the job summary.
|
|
121
|
+
|
|
122
|
+
Attributes:
|
|
123
|
+
code: Short machine-readable warning code (e.g. ``"NULL_SKIP"``).
|
|
124
|
+
message: Human-readable description of the condition.
|
|
125
|
+
details: Optional free-form key/value context.
|
|
126
|
+
"""
|
|
127
|
+
|
|
128
|
+
code: str
|
|
129
|
+
message: str
|
|
130
|
+
details: dict[str, Any] | None = None
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Python port of FieldCapabilityUtil.
|
|
2
|
+
|
|
3
|
+
Determines field-level capability flags (cursor_capable, primary_key_capable)
|
|
4
|
+
based on canonical type. Connectors may override these defaults.
|
|
5
|
+
|
|
6
|
+
Mirrors: io.supaflow.core.model.metadata.FieldCapabilityUtil
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from supaflow_python_sdk.models import SchemaObjectInfo
|
|
11
|
+
|
|
12
|
+
_CURSOR_CAPABLE_TYPES = {"INSTANT", "LOCALDATETIME", "LOCALDATE"}
|
|
13
|
+
|
|
14
|
+
_PRIMARY_KEY_INCAPABLE_TYPES = {"BOOLEAN", "BINARY", "XML", "JSON"}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def is_cursor_capable(canonical_type: str | None) -> bool:
|
|
18
|
+
"""Whether a field type can serve as an incremental cursor.
|
|
19
|
+
|
|
20
|
+
Strict: only timestamp types qualify by default.
|
|
21
|
+
Returns True for None (backward compat with legacy metadata).
|
|
22
|
+
"""
|
|
23
|
+
if canonical_type is None:
|
|
24
|
+
return True
|
|
25
|
+
return canonical_type.upper() in _CURSOR_CAPABLE_TYPES
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def is_primary_key_capable(canonical_type: str | None) -> bool:
|
|
29
|
+
"""Whether a field type can serve as a primary key.
|
|
30
|
+
|
|
31
|
+
Most types qualify except BOOLEAN, BINARY, XML, JSON.
|
|
32
|
+
Returns True for None (backward compat).
|
|
33
|
+
"""
|
|
34
|
+
if canonical_type is None:
|
|
35
|
+
return True
|
|
36
|
+
return canonical_type.upper() not in _PRIMARY_KEY_INCAPABLE_TYPES
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def apply_field_capabilities(obj: SchemaObjectInfo) -> None:
|
|
40
|
+
"""Apply cursor_capable and primary_key_capable to all fields when not already set.
|
|
41
|
+
|
|
42
|
+
Call this after building fields as a safety net. Pre-set values are preserved.
|
|
43
|
+
"""
|
|
44
|
+
if not obj.fields:
|
|
45
|
+
return
|
|
46
|
+
for field in obj.fields:
|
|
47
|
+
if field.cursor_capable is None:
|
|
48
|
+
field.cursor_capable = is_cursor_capable(field.canonical_type)
|
|
49
|
+
if field.primary_key_capable is None:
|
|
50
|
+
field.primary_key_capable = is_primary_key_capable(field.canonical_type)
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import glob
|
|
4
|
+
import os
|
|
5
|
+
import sys
|
|
6
|
+
from datetime import datetime, timezone
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from supaflow_python_sdk.errors import ErrorType, fail
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def check_cancelled(cancel_path: str | None) -> None:
|
|
13
|
+
"""Check cancel marker and raise CANCELLED if present.
|
|
14
|
+
|
|
15
|
+
Call this in long-running loops (e.g., per CSV file during stage) to
|
|
16
|
+
allow the platform to interrupt in-progress connector work gracefully.
|
|
17
|
+
|
|
18
|
+
Args:
|
|
19
|
+
cancel_path: Filesystem path to the cancel marker file, or ``None``
|
|
20
|
+
(or empty string) to skip the check entirely.
|
|
21
|
+
|
|
22
|
+
Raises:
|
|
23
|
+
ConnectorException: With ``ErrorType.CANCELLED`` if the marker file
|
|
24
|
+
exists at ``cancel_path``.
|
|
25
|
+
"""
|
|
26
|
+
if cancel_path and Path(cancel_path).exists():
|
|
27
|
+
fail(ErrorType.CANCELLED, "Operation cancelled by platform")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def discover_csv_files(data_path: str, pattern: str | None = None) -> list[str]:
|
|
31
|
+
"""Find and sort data files in the staging directory.
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
data_path: Directory to search for files.
|
|
35
|
+
pattern: Glob pattern to match filenames against. Defaults to the
|
|
36
|
+
staged CSV contract, ``"success_part_*.csv.gz"``, with fallback
|
|
37
|
+
to legacy ``"success_part_*.csv"`` files.
|
|
38
|
+
|
|
39
|
+
Returns:
|
|
40
|
+
Sorted list of absolute file paths matching *pattern* inside
|
|
41
|
+
*data_path*. Returns an empty list when no files match.
|
|
42
|
+
"""
|
|
43
|
+
if pattern is None:
|
|
44
|
+
compressed = sorted(glob.glob(os.path.join(data_path, "success_part_*.csv.gz")))
|
|
45
|
+
if compressed:
|
|
46
|
+
return compressed
|
|
47
|
+
return sorted(glob.glob(os.path.join(data_path, "success_part_*.csv")))
|
|
48
|
+
return sorted(glob.glob(os.path.join(data_path, pattern)))
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _log(level: str, message: str, context: dict) -> None:
|
|
52
|
+
"""Write a structured log line to stderr.
|
|
53
|
+
|
|
54
|
+
The platform routes stderr output from connector subprocesses into the
|
|
55
|
+
job log, so writing here is the correct way for connectors to emit
|
|
56
|
+
diagnostic messages.
|
|
57
|
+
|
|
58
|
+
Args:
|
|
59
|
+
level: Log level label (``"INFO"``, ``"WARN"``, or ``"ERROR"``).
|
|
60
|
+
message: Human-readable log message.
|
|
61
|
+
context: Optional key/value context pairs to append to the line.
|
|
62
|
+
"""
|
|
63
|
+
ts = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
|
64
|
+
parts = [f"[{ts}] [{level}] {message}"]
|
|
65
|
+
if context:
|
|
66
|
+
ctx_str = " ".join(f"{k}={v}" for k, v in context.items())
|
|
67
|
+
parts.append(ctx_str)
|
|
68
|
+
print(" ".join(parts), file=sys.stderr, flush=True)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def log_info(message: str, **context) -> None:
|
|
72
|
+
"""Emit an INFO-level structured log line to stderr.
|
|
73
|
+
|
|
74
|
+
Args:
|
|
75
|
+
message: Human-readable log message.
|
|
76
|
+
**context: Optional key/value context pairs appended to the line.
|
|
77
|
+
"""
|
|
78
|
+
_log("INFO", message, context)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def log_warn(message: str, **context) -> None:
|
|
82
|
+
"""Emit a WARN-level structured log line to stderr.
|
|
83
|
+
|
|
84
|
+
Args:
|
|
85
|
+
message: Human-readable log message.
|
|
86
|
+
**context: Optional key/value context pairs appended to the line.
|
|
87
|
+
"""
|
|
88
|
+
_log("WARN", message, context)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def log_error(message: str, **context) -> None:
|
|
92
|
+
"""Emit an ERROR-level structured log line to stderr.
|
|
93
|
+
|
|
94
|
+
Args:
|
|
95
|
+
message: Human-readable log message.
|
|
96
|
+
**context: Optional key/value context pairs appended to the line.
|
|
97
|
+
"""
|
|
98
|
+
_log("ERROR", message, context)
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""Versioned SDK contract consumed by the agent-owned connector host.
|
|
2
|
+
|
|
3
|
+
The host runs against each connector's pinned SDK. Keep its imports here so SDK
|
|
4
|
+
implementation changes do not expand that cross-version contract accidentally.
|
|
5
|
+
These are the existing types, codecs and emitters, not alternate implementations.
|
|
6
|
+
Wire protocol and stage-format negotiation have separate version contracts.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import dataclasses
|
|
11
|
+
from importlib.resources import files
|
|
12
|
+
import json
|
|
13
|
+
|
|
14
|
+
from . import models as _models
|
|
15
|
+
from . import write_plan as _write_plan
|
|
16
|
+
from ._precision_json import JsonNumber, dumps as json_dumps, loads as json_loads
|
|
17
|
+
from .csv_record_emitter import CsvRecordEmitter
|
|
18
|
+
from .errors import ConnectorError, ConnectorException, ErrorType, Warning, fail
|
|
19
|
+
from .helpers import check_cancelled
|
|
20
|
+
from .job_context import JobContext
|
|
21
|
+
from .jsonl_record_emitter import JsonlRecordEmitter
|
|
22
|
+
from .models import MetadataField, ProgressUpdatePolicy, ReadResult, SyncStateResponse
|
|
23
|
+
from .native_mapped_jsonl_record_emitter import NativeMappedJsonlRecordEmitter
|
|
24
|
+
from .schema_compliance import validate_schema_response
|
|
25
|
+
from .source import (
|
|
26
|
+
CheckpointEmitter,
|
|
27
|
+
ChildContextWriter,
|
|
28
|
+
ParentContextReader,
|
|
29
|
+
ProgressReporter,
|
|
30
|
+
ProgressStatus,
|
|
31
|
+
RecordEmitResult,
|
|
32
|
+
RecordEmitter,
|
|
33
|
+
)
|
|
34
|
+
from .supa_id import supa_id_debug_enabled
|
|
35
|
+
from .write_plan import RecordFieldBinding, RecordWritePlan, SystemFieldBinding
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
# Data can also be inspected in an uninstalled, hash-verified SDK wheel. Keep
|
|
39
|
+
# the host's live declarations and the producer's view on the same source.
|
|
40
|
+
_COMPATIBILITY = json.loads(files(__package__).joinpath("compatibility.json").read_text("utf-8"))
|
|
41
|
+
HOST_API_VERSION = _COMPATIBILITY["hostApiVersion"]
|
|
42
|
+
|
|
43
|
+
_REQUEST_TYPES = {
|
|
44
|
+
"init": _models.InitRequest,
|
|
45
|
+
"stage": _models.StageRequest,
|
|
46
|
+
"load": _models.LoadRequest,
|
|
47
|
+
"map_target_object": _models.MapTargetObjectRequest,
|
|
48
|
+
"schema": _models.SchemaRequest,
|
|
49
|
+
"read": _models.ReadRequest,
|
|
50
|
+
"supports_direct_remote_load": _models.ReadRequest,
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def request_type_for(operation: str) -> type | None:
|
|
55
|
+
"""Return the SDK's request class, or None for an unknown operation."""
|
|
56
|
+
return _REQUEST_TYPES.get(operation)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def wire_dataclass_types() -> dict[str, type]:
|
|
60
|
+
"""Return SDK-owned nested wire types without exposing module internals.
|
|
61
|
+
|
|
62
|
+
The host may extend its local lookup; each call returns a fresh dictionary.
|
|
63
|
+
Preserve the legacy models/write-plan registry, including Warning, while
|
|
64
|
+
letting future SDKs move their implementations behind this function.
|
|
65
|
+
"""
|
|
66
|
+
return {
|
|
67
|
+
name: value
|
|
68
|
+
for module in (_models, _write_plan)
|
|
69
|
+
for name, value in vars(module).items()
|
|
70
|
+
if isinstance(value, type) and dataclasses.is_dataclass(value)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def stage_format_versions() -> dict[str, tuple[int, ...]]:
|
|
75
|
+
"""Declare stage file-format versions produced by this pinned SDK.
|
|
76
|
+
|
|
77
|
+
MAPPED_JSONL consumes rows already enriched by the dlt adapter;
|
|
78
|
+
NATIVE_MAPPED_JSONL enriches source-shaped BaseConnector rows itself.
|
|
79
|
+
The mode selects the producer path, not an independent version namespace.
|
|
80
|
+
Both JSONL modes share JSONL's file-format versions and Java readers;
|
|
81
|
+
CSV has its own file-format versions. Version 1 names the existing bytes:
|
|
82
|
+
two-header CSV and mapped, typed JSONL records, respectively.
|
|
83
|
+
Host API v1 constructors produce one fixed file version per mode; each
|
|
84
|
+
tuple therefore has one entry. Keep the list shape for a future host API
|
|
85
|
+
that can explicitly construct several versions, without adding that now.
|
|
86
|
+
This declaration does not enable deployment flags or select a format.
|
|
87
|
+
"""
|
|
88
|
+
return {mode: tuple(versions)
|
|
89
|
+
for mode, versions in _COMPATIBILITY["stageFormatVersions"].items()}
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
__all__ = [
|
|
93
|
+
"HOST_API_VERSION", "request_type_for", "wire_dataclass_types", "stage_format_versions",
|
|
94
|
+
"ConnectorError", "ConnectorException", "ErrorType", "Warning", "fail",
|
|
95
|
+
"JobContext", "check_cancelled", "validate_schema_response", "supa_id_debug_enabled",
|
|
96
|
+
"JsonNumber", "json_dumps", "json_loads",
|
|
97
|
+
"MetadataField", "ProgressUpdatePolicy", "ReadResult", "SyncStateResponse",
|
|
98
|
+
"RecordFieldBinding", "RecordWritePlan", "SystemFieldBinding",
|
|
99
|
+
"CheckpointEmitter", "ChildContextWriter", "ParentContextReader",
|
|
100
|
+
"ProgressReporter", "ProgressStatus", "RecordEmitResult", "RecordEmitter",
|
|
101
|
+
"CsvRecordEmitter", "JsonlRecordEmitter", "NativeMappedJsonlRecordEmitter",
|
|
102
|
+
]
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Public capability for job-scoped JSON snapshots.
|
|
2
|
+
|
|
3
|
+
Hosts supply the implementation. Connector code does not need to know about
|
|
4
|
+
transport descriptors, filesystem paths, locks or the private runtime package.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from collections.abc import Callable
|
|
9
|
+
from typing import Any, Protocol
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class JobContext(Protocol):
|
|
13
|
+
"""The existing snapshot operation, independent of its storage mechanism."""
|
|
14
|
+
|
|
15
|
+
def get_or_create_json(
|
|
16
|
+
self,
|
|
17
|
+
namespace: str,
|
|
18
|
+
key: str,
|
|
19
|
+
loader: Callable[[], Any],
|
|
20
|
+
*,
|
|
21
|
+
validator: Callable[[Any], None] | None = None,
|
|
22
|
+
) -> Any:
|
|
23
|
+
"""Return a stored snapshot or load, validate and store a JSON value.
|
|
24
|
+
|
|
25
|
+
Loader failures propagate to the caller. Validation and persistence
|
|
26
|
+
behavior belong to the supplied implementation.
|
|
27
|
+
"""
|
|
28
|
+
...
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class _JobContextCarrier:
|
|
32
|
+
"""Host-owned capability, excluded from dataclass constructors and wire data.
|
|
33
|
+
|
|
34
|
+
Kept outside dataclass fields so serializers cannot traverse the runtime
|
|
35
|
+
implementation. Hosts assign the instance attribute after deserialization.
|
|
36
|
+
Shallow copies preserve it; data-only reconstruction must forward it.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
job_context: JobContext | None = None
|