-
Notifications
You must be signed in to change notification settings - Fork 70
/
core.py
1450 lines (1172 loc) · 50 KB
/
core.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Stream abstract class."""
from __future__ import annotations
import abc
import copy
import datetime
import json
import typing as t
from os import PathLike
from pathlib import Path
from types import MappingProxyType
import singer_sdk._singerlib as singer
from singer_sdk import metrics
from singer_sdk.batch import Batcher
from singer_sdk.exceptions import (
AbortedSyncFailedException,
AbortedSyncPausedException,
InvalidReplicationKeyException,
InvalidStreamSortException,
MaxRecordsLimitException,
)
from singer_sdk.helpers._batch import (
BaseBatchFileEncoding,
BatchConfig,
SDKBatchMessage,
)
from singer_sdk.helpers._catalog import pop_deselected_record_properties
from singer_sdk.helpers._compat import datetime_fromisoformat
from singer_sdk.helpers._flattening import get_flattening_options
from singer_sdk.helpers._state import (
finalize_state_progress_markers,
get_starting_replication_value,
get_state_partitions_list,
get_writeable_state_dict,
increment_state,
is_state_non_resumable,
log_sort_error,
reset_state_progress_markers,
write_replication_key_signpost,
write_starting_replication_value,
)
from singer_sdk.helpers._typing import (
TypeConformanceLevel,
conform_record_data_types,
is_datetime_type,
)
from singer_sdk.helpers._util import utc_now
from singer_sdk.mapper import RemoveRecordTransform, SameRecordTransform, StreamMap
if t.TYPE_CHECKING:
import logging
from singer_sdk.helpers import types
from singer_sdk.helpers._compat import Traversable
from singer_sdk.tap_base import Tap
# Replication methods
REPLICATION_FULL_TABLE = "FULL_TABLE"
REPLICATION_INCREMENTAL = "INCREMENTAL"
REPLICATION_LOG_BASED = "LOG_BASED"
class Stream(metaclass=abc.ABCMeta): # noqa: PLR0904
"""Abstract base class for tap streams.
:ivar context: Stream partition or context dictionary.
.. versionadded:: 0.39.0
The ``context`` attribute.
"""
STATE_MSG_FREQUENCY = 10000
"""Number of records between state messages."""
ABORT_AT_RECORD_COUNT: int | None = None
"""
If set, raise `MaxRecordsLimitException` if the limit is exceeded.
"""
TYPE_CONFORMANCE_LEVEL = TypeConformanceLevel.RECURSIVE
"""Type conformance level for this stream.
Field types in the schema are used to convert record field values to the correct
type.
Available options are:
- ``TypeConformanceLevel.NONE``: No conformance is performed.
- ``TypeConformanceLevel.RECURSIVE``: Conformance is performed recursively through
all nested levels in the record.
- ``TypeConformanceLevel.ROOT_ONLY``: Conformance is performed only on the
root level.
"""
# Used for nested stream relationships
parent_stream_type: type[Stream] | None = None
"""Parent stream type for this stream. If this stream is a child stream, this should
be set to the parent stream class.
"""
ignore_parent_replication_key: bool = False
selected_by_default: bool = True
"""Whether this stream is selected by default in the catalog."""
def __init__(
self,
tap: Tap,
schema: str | PathLike | dict[str, t.Any] | singer.Schema | None = None,
name: str | None = None,
) -> None:
"""Init tap stream.
Args:
tap: Singer Tap this stream belongs to.
schema: JSON schema for records in this stream.
name: Name of this stream.
Raises:
ValueError: TODO
FileNotFoundError: TODO
"""
if name:
self.name: str = name
if not self.name:
msg = "Missing argument or class variable 'name'."
raise ValueError(msg)
self.logger: logging.Logger = tap.logger.getChild(self.name)
self.metrics_logger = tap.metrics_logger
self.tap_name: str = tap.name
self.context: types.Context | None = None
self._config: dict = dict(tap.config)
self._tap = tap
self._tap_state = tap.state
self._tap_input_catalog: singer.Catalog | None = None
self._stream_maps: list[StreamMap] | None = None
self.forced_replication_method: str | None = None
self._replication_key: str | None = None
self._primary_keys: t.Sequence[str] | None = None
self._state_partitioning_keys: list[str] | None = None
self._schema_filepath: Path | Traversable | None = None
self._metadata: singer.MetadataMapping | None = None
self._mask: singer.SelectionMask | None = None
self._schema: dict
self._is_state_flushed: bool = True
self._last_emitted_state: dict | None = None
self._sync_costs: dict[str, int] = {}
self.child_streams: list[Stream] = []
if schema:
if isinstance(schema, (PathLike, str)):
if not Path(schema).is_file():
msg = f"Could not find schema file '{self.schema_filepath}'."
raise FileNotFoundError(msg)
self._schema_filepath = Path(schema)
elif isinstance(schema, dict):
self._schema = schema
elif isinstance(schema, singer.Schema):
self._schema = schema.to_dict()
else:
msg = f"Unexpected type {type(schema).__name__} for arg 'schema'." # type: ignore[unreachable]
raise ValueError(msg)
if self.schema_filepath:
self._schema = json.loads(self.schema_filepath.read_text())
if not self.schema:
msg = (
f"Could not initialize schema for stream '{self.name}'. A valid schema "
"object or filepath was not provided."
)
raise ValueError(msg)
@property
def stream_maps(self) -> list[StreamMap]:
"""Get stream transformation maps.
The 0th item is the primary stream map. List should not be empty.
Returns:
A list of one or more map transformations for this stream.
"""
if self._stream_maps:
return self._stream_maps
if self._tap.mapper: # type: ignore[truthy-bool]
self._stream_maps = self._tap.mapper.stream_maps[self.name]
self.logger.info(
"Tap has custom mapper. Using %d provided map(s).",
len(self.stream_maps),
)
else:
self.logger.info(
"No custom mapper provided for '%s'. Using SameRecordTransform.",
self.name,
)
self._stream_maps = [
SameRecordTransform(
stream_alias=self.name,
raw_schema=self.schema,
key_properties=self.primary_keys,
flattening_options=get_flattening_options(self.config),
),
]
return self._stream_maps
@property
def is_timestamp_replication_key(self) -> bool:
"""Check is replication key is a timestamp.
Developers can override to `True` in order to force this value, although this
should not be required in most use cases since the type can generally be
accurately detected from the JSON Schema.
Returns:
True if the stream uses a timestamp-based replication key.
Raises:
InvalidReplicationKeyException: If the schema does not contain the
replication key.
"""
if not self.replication_key:
return False
type_dict = self.schema.get("properties", {}).get(self.replication_key)
if type_dict is None:
msg = f"Field '{self.replication_key}' is not in schema for stream '{self.name}'" # noqa: E501
raise InvalidReplicationKeyException(msg)
return is_datetime_type(type_dict)
def get_starting_replication_key_value(
self,
context: types.Context | None,
) -> t.Any | None: # noqa: ANN401
"""Get starting replication key.
Will return the value of the stream's replication key when `--state` is passed.
If no prior state exists, will return `None`.
Developers should use this method to seed incremental processing for
non-datetime replication keys. For datetime and date replication keys, use
:meth:`~singer_sdk.Stream.get_starting_timestamp()`
Args:
context: Stream partition or context dictionary.
Returns:
Starting replication value.
.. note::
This method requires :attr:`~singer_sdk.Stream.replication_key` to be set
to a non-null value, indicating the stream should be synced incrementally.
"""
state = self.get_context_state(context)
return (
get_starting_replication_value(state)
if self.replication_method != REPLICATION_FULL_TABLE
else None
)
def get_starting_timestamp(
self,
context: types.Context | None,
) -> datetime.datetime | None:
"""Get starting replication timestamp.
Will return the value of the stream's replication key when `--state` is passed.
If no state exists, will return `start_date` if set, or `None` if neither
the stream state nor `start_date` is set.
Developers should use this method to seed incremental processing for date
and datetime replication keys. For non-datetime replication keys, use
:meth:`~singer_sdk.Stream.get_starting_replication_key_value()`
.. note::
This method requires :attr:`~singer_sdk.Stream.replication_key` to be set
to a non-null value, indicating the stream should be synced incrementally.
Args:
context: Stream partition or context dictionary.
Returns:
`start_date` from config, or state value if using timestamp replication.
Raises:
ValueError: If the replication value is not a valid timestamp.
"""
value = self.get_starting_replication_key_value(context)
if value is None:
return None
if not self.is_timestamp_replication_key:
msg = f"The replication key {self.replication_key} is not of timestamp type"
raise ValueError(msg)
result = datetime_fromisoformat(value)
return result if result.tzinfo else result.replace(tzinfo=datetime.timezone.utc)
@property
def selected(self) -> bool:
"""Check if stream is selected.
Returns:
True if the stream is selected.
"""
return self.mask.get((), True)
@selected.setter
def selected(self, value: bool | None) -> None:
"""Set stream selection.
Args:
value: True if the stream is selected.
"""
self.metadata.root.selected = value
self._mask = self.metadata.resolve_selection()
@t.final
@property
def has_selected_descendents(self) -> bool:
"""Check descendents.
Returns:
True if any child streams are selected, recursively.
"""
return any(
child.selected or child.has_selected_descendents
for child in self.child_streams or []
)
@t.final
@property
def descendent_streams(self) -> list[Stream]:
"""Get child streams.
Returns:
A list of all children, recursively.
"""
result: list[Stream] = [*self.child_streams]
for child in self.child_streams:
result += child.descendent_streams or []
return result
def _write_replication_key_signpost(
self,
context: types.Context | None,
value: datetime.datetime | str | int | float,
) -> None:
"""Write the signpost value, if available.
Args:
context: Stream partition or context dictionary.
value: TODO
"""
if not value:
return
state = self.get_context_state(context)
write_replication_key_signpost(state, value)
def _parse_datetime(self, value: str) -> datetime.datetime: # noqa: PLR6301
"""Parse a datetime string.
Args:
value: The datetime string.
Returns:
The parsed datetime, timezone-aware preferred.
"""
result = datetime_fromisoformat(value)
# Ensure datetime is timezone-aware
if not result.tzinfo:
result = result.replace(tzinfo=datetime.timezone.utc)
return result
def compare_start_date(self, value: str, start_date_value: str) -> str:
"""Compare a bookmark value to a start date and return the most recent value.
If the replication key is a datetime-formatted string, this method will parse
the value and compare it to the start date. Otherwise, the bookmark value is
returned.
If the tap uses a non-datetime replication key (e.g. an UNIX timestamp), the
developer is encouraged to override this method to provide custom logic for
comparing the bookmark value to the start date.
Args:
value: The replication key value.
start_date_value: The start date value from the config.
Returns:
The most recent value between the bookmark and start date.
"""
if self.is_timestamp_replication_key:
return max(value, start_date_value, key=self._parse_datetime)
return value
def _write_starting_replication_value(self, context: types.Context | None) -> None:
"""Write the starting replication value, if available.
Args:
context: Stream partition or context dictionary.
"""
value = None
state = self.get_context_state(context)
if self.replication_key:
replication_key_value = state.get("replication_key_value")
if replication_key_value and self.replication_key == state.get(
"replication_key",
):
value = replication_key_value
# Use start_date if it is more recent than the replication_key state
start_date_value: str | None = self.config.get("start_date")
if start_date_value:
if not value:
value = start_date_value
else:
value = self.compare_start_date(value, start_date_value)
write_starting_replication_value(state, value)
def get_replication_key_signpost(
self,
context: types.Context | None, # noqa: ARG002
) -> datetime.datetime | t.Any | None: # noqa: ANN401
"""Get the replication signpost.
For timestamp-based replication keys, this defaults to `utc_now()`. For
non-timestamp replication keys, default to `None`. For consistency in subsequent
calls, the value will be frozen (cached) at its initially called state, per
partition argument if applicable.
Developers may optionally override this method in advanced use cases such
as unsorted incremental streams or complex hierarchical stream scenarios.
For more info: :doc:`/implementation/state`
Args:
context: Stream partition or context dictionary.
Returns:
Max allowable bookmark value for this stream's replication key.
"""
return utc_now() if self.is_timestamp_replication_key else None
@property
def schema_filepath(self) -> Path | Traversable | None:
"""Get path to schema file.
Returns:
Path to a schema file for the stream or `None` if n/a.
"""
return self._schema_filepath
@property
def schema(self) -> dict:
"""Get schema.
Returns:
JSON Schema dictionary for this stream.
"""
return self._schema
@property
def primary_keys(self) -> t.Sequence[str] | None:
"""Get primary keys.
Returns:
A list of primary key(s) for the stream.
"""
return self._primary_keys or []
@primary_keys.setter
def primary_keys(self, new_value: t.Sequence[str] | None) -> None:
"""Set primary key(s) for the stream.
Args:
new_value: TODO
"""
self._primary_keys = new_value
@property
def state_partitioning_keys(self) -> list[str] | None:
"""Get state partition keys.
If not set, a default partitioning will be inherited from the stream's context.
If an empty list is set (`[]`), state will be held in one bookmark per stream.
Returns:
Partition keys for the stream state bookmarks.
"""
return self._state_partitioning_keys
@state_partitioning_keys.setter
def state_partitioning_keys(self, new_value: list[str] | None) -> None:
"""Set partition keys for the stream state bookmarks.
If not set, a default partitioning will be inherited from the stream's context.
If an empty list is set (`[]`), state will be held in one bookmark per stream.
Args:
new_value: the new list of keys
"""
self._state_partitioning_keys = new_value
@property
def replication_key(self) -> str | None:
"""Get replication key.
Returns:
Replication key for the stream.
"""
return self._replication_key or None
@replication_key.setter
def replication_key(self, new_value: str | None) -> None:
"""Set replication key for the stream.
Args:
new_value: TODO
"""
self._replication_key = new_value
@property
def is_sorted(self) -> bool:
"""Expect stream to be sorted.
When `True`, incremental streams will attempt to resume if unexpectedly
interrupted.
Returns:
`True` if stream is sorted. Defaults to `False`.
"""
return False
@property
def check_sorted(self) -> bool:
"""Check if stream is sorted.
This setting enables additional checks which may trigger
`InvalidStreamSortException` if records are found which are unsorted.
Returns:
`True` if sorting is checked. Defaults to `True`.
"""
return True
@property
def metadata(self) -> singer.MetadataMapping:
"""Get stream metadata.
Metadata attributes (`inclusion`, `selected`, etc.) are part of the Singer spec.
Metadata from an input catalog will override standard metadata.
Returns:
A mapping from property breadcrumbs to metadata objects.
"""
if self._metadata is not None:
return self._metadata
if self._tap_input_catalog:
catalog_entry = self._tap_input_catalog.get_stream(self.tap_stream_id)
if catalog_entry:
self._metadata = catalog_entry.metadata
return self._metadata
self._metadata = singer.MetadataMapping.get_standard_metadata(
schema=self.schema,
replication_method=self.forced_replication_method,
key_properties=self.primary_keys or [],
valid_replication_keys=(
[self.replication_key] if self.replication_key else None
),
schema_name=None,
selected_by_default=self.selected_by_default,
)
# If there's no input catalog, select all streams
self._metadata.root.selected = (
self._tap_input_catalog is None and self.selected_by_default
)
return self._metadata
@property
def _singer_catalog_entry(self) -> singer.CatalogEntry:
"""Return catalog entry as specified by the Singer catalog spec.
Returns:
TODO
"""
return singer.CatalogEntry(
tap_stream_id=self.tap_stream_id,
stream=self.name,
schema=singer.Schema.from_dict(self.schema),
metadata=self.metadata,
key_properties=self.primary_keys or [],
replication_key=self.replication_key,
replication_method=self.replication_method,
is_view=None,
database=None,
table=None,
row_count=None,
stream_alias=None,
)
@property
def _singer_catalog(self) -> singer.Catalog:
"""TODO.
Returns:
TODO
"""
return singer.Catalog([(self.tap_stream_id, self._singer_catalog_entry)])
@property
def config(self) -> t.Mapping[str, t.Any]:
"""Get stream configuration.
Returns:
A frozen (read-only) config dictionary map.
"""
return MappingProxyType(self._config)
@property
def tap_stream_id(self) -> str:
"""Return a unique stream ID.
Default implementations will return `self.name` but this behavior may be
overridden if required by the developer.
Returns:
Unique stream ID.
"""
return self.name
@property
def replication_method(self) -> str:
"""Get replication method.
Returns:
Replication method to be used for this stream.
"""
if self.forced_replication_method:
return str(self.forced_replication_method)
if self.replication_key:
return REPLICATION_INCREMENTAL
return REPLICATION_FULL_TABLE
# State properties:
@property
def tap_state(self) -> dict:
"""Return a writeable state dict for the entire tap.
Note: This dictionary is shared (and writable) across all streams.
This method is internal to the SDK and should not need to be overridden.
Developers may access this property but this is not recommended except in
advanced use cases. Instead, developers should access the latest stream
replication key values using :meth:`~singer_sdk.Stream.get_starting_timestamp()`
for timestamp keys, or
:meth:`~singer_sdk.Stream.get_starting_replication_key_value()` for
non-timestamp keys.
Returns:
A writeable state dict for the entire tap.
"""
return self._tap_state
def get_context_state(self, context: types.Context | None) -> dict:
"""Return a writable state dict for the given context.
Gives a partitioned context state if applicable; else returns stream state.
A blank state will be created in none exists.
This method is internal to the SDK and should not need to be overridden.
Developers may access this property but this is not recommended except in
advanced use cases. Instead, developers should access the latest stream
replication key values using
:meth:`~singer_sdk.Stream.get_starting_timestamp()` for timestamp keys, or
:meth:`~singer_sdk.Stream.get_starting_replication_key_value()` for
non-timestamp keys.
Partition level may be overridden by
:attr:`~singer_sdk.Stream.state_partitioning_keys` if set.
Args:
context: Stream partition or context dictionary.
Returns:
A partitioned context state if applicable; else returns stream state.
A blank state will be created in none exists.
"""
state_partition_context = self._get_state_partition_context(context)
if state_partition_context:
return get_writeable_state_dict(
self.tap_state,
self.name,
state_partition_context=state_partition_context,
)
return self.stream_state
@property
def stream_state(self) -> dict:
"""Get writable state.
This method is internal to the SDK and should not need to be overridden.
Developers may access this property but this is not recommended except in
advanced use cases. Instead, developers should access the latest stream
replication key values using :meth:`~singer_sdk.Stream.get_starting_timestamp()`
for timestamp keys, or
:meth:`~singer_sdk.Stream.get_starting_replication_key_value()` for
non-timestamp keys.
A blank state entry will be created if one doesn't already exist.
Returns:
A writable state dict for this stream.
"""
return get_writeable_state_dict(self.tap_state, self.name)
# Partitions
@property
def partitions(self) -> list[dict] | None:
"""Get stream partitions.
Developers may override this property to provide a default partitions list.
By default, this method returns a list of any partitions which are already
defined in state, otherwise None.
Returns:
A list of partition key dicts (if applicable), otherwise `None`.
"""
result: list[dict] = [
partition_state["context"]
for partition_state in (
get_state_partitions_list(self.tap_state, self.name) or []
)
]
return result or None
# Private bookmarking methods
def _increment_stream_state(
self,
latest_record: types.Record,
*,
context: types.Context | None = None,
) -> None:
"""Update state of stream or partition with data from the provided record.
Raises `InvalidStreamSortException` is `self.is_sorted = True` and unsorted data
is detected.
Note: The default implementation does not advance any bookmarks unless
`self.replication_method == 'INCREMENTAL'.
Args:
latest_record: TODO
context: Stream partition or context dictionary.
Raises:
ValueError: TODO
"""
# This also creates a state entry if one does not yet exist:
state_dict = self.get_context_state(context)
# Advance state bookmark values if applicable
if latest_record and self.replication_method == REPLICATION_INCREMENTAL:
if not self.replication_key:
msg = (
f"Could not detect replication key for '{self.name}' "
f"stream(replication method={self.replication_method})"
)
raise ValueError(msg)
treat_as_sorted = self.is_sorted
if not treat_as_sorted and self.state_partitioning_keys is not None:
# Streams with custom state partitioning are not resumable.
treat_as_sorted = False
increment_state(
state_dict,
replication_key=self.replication_key,
latest_record=latest_record,
is_sorted=treat_as_sorted,
check_sorted=self.check_sorted,
)
# Private message authoring methods:
def _write_state_message(self) -> None:
"""Write out a STATE message with the latest state."""
if (not self._is_state_flushed) and (
self.tap_state != self._last_emitted_state
):
self._tap.write_message(singer.StateMessage(value=self.tap_state))
self._last_emitted_state = copy.deepcopy(self.tap_state)
self._is_state_flushed = True
def _generate_schema_messages(
self,
) -> t.Generator[singer.SchemaMessage, None, None]:
"""Generate schema messages from stream maps.
Yields:
Schema message objects.
"""
bookmark_keys = [self.replication_key] if self.replication_key else None
for stream_map in self.stream_maps:
if isinstance(stream_map, RemoveRecordTransform):
# Don't emit schema if the stream's records are all ignored.
continue
yield singer.SchemaMessage(
stream_map.stream_alias,
stream_map.transformed_schema,
stream_map.transformed_key_properties,
bookmark_keys,
)
def _write_schema_message(self) -> None:
"""Write out a SCHEMA message with the stream schema."""
for schema_message in self._generate_schema_messages():
self._tap.write_message(schema_message)
@property
def mask(self) -> singer.SelectionMask:
"""Get a boolean mask for stream and property selection.
Returns:
A mapping of breadcrumbs to boolean values, representing stream and field
selection.
"""
if self._mask is None:
self._mask = self.metadata.resolve_selection()
return self._mask
def _generate_record_messages(
self,
record: types.Record,
) -> t.Generator[singer.RecordMessage, None, None]:
"""Write out a RECORD message.
Args:
record: A single stream record.
Yields:
Record message objects.
"""
pop_deselected_record_properties(record, self.schema, self.mask)
record = conform_record_data_types(
stream_name=self.name,
record=record,
schema=self.schema,
level=self.TYPE_CONFORMANCE_LEVEL,
logger=self.logger,
)
for stream_map in self.stream_maps:
mapped_record = stream_map.transform(record)
# Emit record if not filtered
if mapped_record is not None:
yield singer.RecordMessage(
stream=stream_map.stream_alias,
record=mapped_record,
version=None,
time_extracted=utc_now(),
)
def _generate_batch_messages(
self,
encoding: BaseBatchFileEncoding,
manifest: list[str],
) -> t.Generator[SDKBatchMessage, None, None]:
"""Write out a BATCH message.
Args:
encoding: The encoding to use for the batch.
manifest: A list of filenames for the batch.
Yields:
Batch message objects.
"""
for stream_map in self.stream_maps:
yield SDKBatchMessage(
stream=stream_map.stream_alias,
encoding=encoding,
manifest=manifest,
)
def _write_record_message(self, record: types.Record) -> None:
"""Write out a RECORD message.
Args:
record: A single stream record.
"""
for record_message in self._generate_record_messages(record):
self._tap.write_message(record_message)
self._is_state_flushed = False
def _write_batch_message(
self,
encoding: BaseBatchFileEncoding,
manifest: list[str],
) -> None:
"""Write out a BATCH message.
Args:
encoding: The encoding to use for the batch.
manifest: A list of filenames for the batch.
"""
for batch_message in self._generate_batch_messages(encoding, manifest):
self._tap.write_message(batch_message)
self._is_state_flushed = False
def _log_metric(self, point: metrics.Point) -> None:
"""Log a single measurement.
Args:
point: A single measurement value.
"""
metrics.log(self.metrics_logger, point=point)
def log_sync_costs(self) -> None:
"""Log a summary of Sync costs.
The costs are calculated via `calculate_sync_cost`.
This method can be overridden to log results in a custom
format. It is only called once at the end of the life of
the stream.
"""
if len(self._sync_costs) > 0:
msg = f"Total Sync costs for stream {self.name}: {self._sync_costs}"
self.logger.info(msg)
def _check_max_record_limit(self, current_record_index: int) -> None:
"""Raise an exception if dry run record limit exceeded.
Raised if we find dry run record limit exceeded,
aka `current_record_index > self.ABORT_AT_RECORD_COUNT - 1`.
Args:
current_record_index: The zero-based index of the current record.
"""
if (
self.ABORT_AT_RECORD_COUNT is not None
and current_record_index > self.ABORT_AT_RECORD_COUNT - 1
):
self._abort_sync(
abort_reason=MaxRecordsLimitException(
"Stream prematurely aborted due to the stream's max dry run "
f"record limit ({self.ABORT_AT_RECORD_COUNT}) being reached.",
),
)
def _abort_sync(self, abort_reason: Exception) -> None:
"""Handle a sync operation being aborted.
This method will attempt to close out the sync operation as gracefully as
possible - for instance, if a max runtime or record count is reached. This can
also be called for `SIGTERM` and KeyboardInterrupt events.
If a state message is pending, we will attempt to write it to STDOUT before
shutting down.
If the stream can reach a valid resumable state, then we will raise
`AbortedSyncPausedException`. Otherwise, `AbortedSyncFailedException` will be
raised.
Args:
abort_reason: The exception that triggered the sync to be aborted.
Raises:
AbortedSyncFailedException: Raised if sync could not reach a valid state.
AbortedSyncPausedException: Raised if sync was able to be transitioned into
a valid state without data loss or corruption.
"""
self._write_state_message() # Write out state message if pending.
if self.replication_method == "FULL_TABLE":
msg = "Sync operation aborted for stream in 'FULL_TABLE' replication mode."
raise AbortedSyncFailedException(msg) from abort_reason
if is_state_non_resumable(self.stream_state):
msg = "Sync operation aborted and state is not in a resumable state."