-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathmodel_to_component_factory.py
2179 lines (2039 loc) · 92.8 KB
/
model_to_component_factory.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
#
# Copyright (c) 2023 Airbyte, Inc., all rights reserved.
#
from __future__ import annotations
import datetime
import importlib
import inspect
import re
from functools import partial
from typing import (
Any,
Callable,
Dict,
List,
Mapping,
MutableMapping,
Optional,
Tuple,
Type,
Union,
get_args,
get_origin,
get_type_hints,
)
from airbyte_cdk.models import FailureType, Level
from airbyte_cdk.sources.connector_state_manager import ConnectorStateManager
from airbyte_cdk.sources.declarative.async_job.job_orchestrator import AsyncJobOrchestrator
from airbyte_cdk.sources.declarative.async_job.job_tracker import JobTracker
from airbyte_cdk.sources.declarative.async_job.repository import AsyncJobRepository
from airbyte_cdk.sources.declarative.async_job.status import AsyncJobStatus
from airbyte_cdk.sources.declarative.auth import DeclarativeOauth2Authenticator, JwtAuthenticator
from airbyte_cdk.sources.declarative.auth.declarative_authenticator import (
DeclarativeAuthenticator,
NoAuth,
)
from airbyte_cdk.sources.declarative.auth.jwt import JwtAlgorithm
from airbyte_cdk.sources.declarative.auth.oauth import (
DeclarativeSingleUseRefreshTokenOauth2Authenticator,
)
from airbyte_cdk.sources.declarative.auth.selective_authenticator import SelectiveAuthenticator
from airbyte_cdk.sources.declarative.auth.token import (
ApiKeyAuthenticator,
BasicHttpAuthenticator,
BearerAuthenticator,
LegacySessionTokenAuthenticator,
)
from airbyte_cdk.sources.declarative.auth.token_provider import (
InterpolatedStringTokenProvider,
SessionTokenProvider,
TokenProvider,
)
from airbyte_cdk.sources.declarative.checks import CheckStream
from airbyte_cdk.sources.declarative.concurrency_level import ConcurrencyLevel
from airbyte_cdk.sources.declarative.datetime import MinMaxDatetime
from airbyte_cdk.sources.declarative.declarative_stream import DeclarativeStream
from airbyte_cdk.sources.declarative.decoders import (
Decoder,
GzipJsonDecoder,
IterableDecoder,
JsonDecoder,
JsonlDecoder,
PaginationDecoderDecorator,
XmlDecoder,
)
from airbyte_cdk.sources.declarative.extractors import (
DpathExtractor,
RecordFilter,
RecordSelector,
ResponseToFileExtractor,
)
from airbyte_cdk.sources.declarative.extractors.record_filter import (
ClientSideIncrementalRecordFilterDecorator,
)
from airbyte_cdk.sources.declarative.extractors.record_selector import (
SCHEMA_TRANSFORMER_TYPE_MAPPING,
)
from airbyte_cdk.sources.declarative.incremental import (
ChildPartitionResumableFullRefreshCursor,
CursorFactory,
DatetimeBasedCursor,
DeclarativeCursor,
GlobalSubstreamCursor,
PerPartitionCursor,
PerPartitionWithGlobalCursor,
ResumableFullRefreshCursor,
)
from airbyte_cdk.sources.declarative.interpolation import InterpolatedString
from airbyte_cdk.sources.declarative.interpolation.interpolated_mapping import InterpolatedMapping
from airbyte_cdk.sources.declarative.migrations.legacy_to_per_partition_state_migration import (
LegacyToPerPartitionStateMigration,
)
from airbyte_cdk.sources.declarative.models import CustomStateMigration
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
AddedFieldDefinition as AddedFieldDefinitionModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
AddFields as AddFieldsModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
ApiKeyAuthenticator as ApiKeyAuthenticatorModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
AsyncJobStatusMap as AsyncJobStatusMapModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
AsyncRetriever as AsyncRetrieverModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
BasicHttpAuthenticator as BasicHttpAuthenticatorModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
BearerAuthenticator as BearerAuthenticatorModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
CheckStream as CheckStreamModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
CompositeErrorHandler as CompositeErrorHandlerModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
ConcurrencyLevel as ConcurrencyLevelModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
ConstantBackoffStrategy as ConstantBackoffStrategyModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
CursorPagination as CursorPaginationModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
CustomAuthenticator as CustomAuthenticatorModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
CustomBackoffStrategy as CustomBackoffStrategyModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
CustomDecoder as CustomDecoderModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
CustomErrorHandler as CustomErrorHandlerModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
CustomIncrementalSync as CustomIncrementalSyncModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
CustomPaginationStrategy as CustomPaginationStrategyModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
CustomPartitionRouter as CustomPartitionRouterModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
CustomRecordExtractor as CustomRecordExtractorModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
CustomRecordFilter as CustomRecordFilterModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
CustomRequester as CustomRequesterModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
CustomRetriever as CustomRetrieverModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
CustomSchemaLoader as CustomSchemaLoader,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
CustomTransformation as CustomTransformationModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
DatetimeBasedCursor as DatetimeBasedCursorModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
DeclarativeStream as DeclarativeStreamModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
DefaultErrorHandler as DefaultErrorHandlerModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
DefaultPaginator as DefaultPaginatorModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
DpathExtractor as DpathExtractorModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
ExponentialBackoffStrategy as ExponentialBackoffStrategyModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
GzipJsonDecoder as GzipJsonDecoderModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
HttpRequester as HttpRequesterModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
HttpResponseFilter as HttpResponseFilterModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
InlineSchemaLoader as InlineSchemaLoaderModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
IterableDecoder as IterableDecoderModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
JsonDecoder as JsonDecoderModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
JsonFileSchemaLoader as JsonFileSchemaLoaderModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
JsonlDecoder as JsonlDecoderModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
JwtAuthenticator as JwtAuthenticatorModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
JwtHeaders as JwtHeadersModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
JwtPayload as JwtPayloadModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
KeysToLower as KeysToLowerModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
LegacySessionTokenAuthenticator as LegacySessionTokenAuthenticatorModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
LegacyToPerPartitionStateMigration as LegacyToPerPartitionStateMigrationModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
ListPartitionRouter as ListPartitionRouterModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
MinMaxDatetime as MinMaxDatetimeModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
NoAuth as NoAuthModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
NoPagination as NoPaginationModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
OAuthAuthenticator as OAuthAuthenticatorModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
OffsetIncrement as OffsetIncrementModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
PageIncrement as PageIncrementModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
ParentStreamConfig as ParentStreamConfigModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
RecordFilter as RecordFilterModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
RecordSelector as RecordSelectorModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
RemoveFields as RemoveFieldsModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
RequestOption as RequestOptionModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
RequestPath as RequestPathModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
SelectiveAuthenticator as SelectiveAuthenticatorModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
SessionTokenAuthenticator as SessionTokenAuthenticatorModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
SimpleRetriever as SimpleRetrieverModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import Spec as SpecModel
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
SubstreamPartitionRouter as SubstreamPartitionRouterModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import ValueType
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
WaitTimeFromHeader as WaitTimeFromHeaderModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
WaitUntilTimeFromHeader as WaitUntilTimeFromHeaderModel,
)
from airbyte_cdk.sources.declarative.models.declarative_component_schema import (
XmlDecoder as XmlDecoderModel,
)
from airbyte_cdk.sources.declarative.partition_routers import (
CartesianProductStreamSlicer,
ListPartitionRouter,
SinglePartitionRouter,
SubstreamPartitionRouter,
)
from airbyte_cdk.sources.declarative.partition_routers.substream_partition_router import (
ParentStreamConfig,
)
from airbyte_cdk.sources.declarative.requesters import HttpRequester, RequestOption
from airbyte_cdk.sources.declarative.requesters.error_handlers import (
CompositeErrorHandler,
DefaultErrorHandler,
HttpResponseFilter,
)
from airbyte_cdk.sources.declarative.requesters.error_handlers.backoff_strategies import (
ConstantBackoffStrategy,
ExponentialBackoffStrategy,
WaitTimeFromHeaderBackoffStrategy,
WaitUntilTimeFromHeaderBackoffStrategy,
)
from airbyte_cdk.sources.declarative.requesters.http_job_repository import AsyncHttpJobRepository
from airbyte_cdk.sources.declarative.requesters.paginators import (
DefaultPaginator,
NoPagination,
PaginatorTestReadDecorator,
)
from airbyte_cdk.sources.declarative.requesters.paginators.strategies import (
CursorPaginationStrategy,
CursorStopCondition,
OffsetIncrement,
PageIncrement,
StopConditionPaginationStrategyDecorator,
)
from airbyte_cdk.sources.declarative.requesters.request_option import RequestOptionType
from airbyte_cdk.sources.declarative.requesters.request_options import (
DatetimeBasedRequestOptionsProvider,
DefaultRequestOptionsProvider,
InterpolatedRequestOptionsProvider,
RequestOptionsProvider,
)
from airbyte_cdk.sources.declarative.requesters.request_path import RequestPath
from airbyte_cdk.sources.declarative.requesters.requester import HttpMethod
from airbyte_cdk.sources.declarative.retrievers import (
AsyncRetriever,
SimpleRetriever,
SimpleRetrieverTestReadDecorator,
)
from airbyte_cdk.sources.declarative.schema import (
DefaultSchemaLoader,
InlineSchemaLoader,
JsonFileSchemaLoader,
)
from airbyte_cdk.sources.declarative.spec import Spec
from airbyte_cdk.sources.declarative.stream_slicers import StreamSlicer
from airbyte_cdk.sources.declarative.transformations import (
AddFields,
RecordTransformation,
RemoveFields,
)
from airbyte_cdk.sources.declarative.transformations.add_fields import AddedFieldDefinition
from airbyte_cdk.sources.declarative.transformations.keys_to_lower_transformation import (
KeysToLowerTransformation,
)
from airbyte_cdk.sources.message import (
InMemoryMessageRepository,
LogAppenderMessageRepositoryDecorator,
MessageRepository,
)
from airbyte_cdk.sources.streams.concurrent.cursor import ConcurrentCursor, CursorField
from airbyte_cdk.sources.streams.concurrent.state_converters.datetime_stream_state_converter import (
CustomFormatConcurrentStreamStateConverter,
DateTimeStreamStateConverter,
)
from airbyte_cdk.sources.streams.http.error_handlers.response_models import ResponseAction
from airbyte_cdk.sources.types import Config
from airbyte_cdk.sources.utils.transform import TransformConfig, TypeTransformer
from isodate import parse_duration
from pydantic.v1 import BaseModel
ComponentDefinition = Mapping[str, Any]
class ModelToComponentFactory:
EPOCH_DATETIME_FORMAT = "%s"
def __init__(
self,
limit_pages_fetched_per_slice: Optional[int] = None,
limit_slices_fetched: Optional[int] = None,
emit_connector_builder_messages: bool = False,
disable_retries: bool = False,
disable_cache: bool = False,
message_repository: Optional[MessageRepository] = None,
):
self._init_mappings()
self._limit_pages_fetched_per_slice = limit_pages_fetched_per_slice
self._limit_slices_fetched = limit_slices_fetched
self._emit_connector_builder_messages = emit_connector_builder_messages
self._disable_retries = disable_retries
self._disable_cache = disable_cache
self._message_repository = message_repository or InMemoryMessageRepository( # type: ignore
self._evaluate_log_level(emit_connector_builder_messages)
)
def _init_mappings(self) -> None:
self.PYDANTIC_MODEL_TO_CONSTRUCTOR: Mapping[Type[BaseModel], Callable[..., Any]] = {
AddedFieldDefinitionModel: self.create_added_field_definition,
AddFieldsModel: self.create_add_fields,
ApiKeyAuthenticatorModel: self.create_api_key_authenticator,
BasicHttpAuthenticatorModel: self.create_basic_http_authenticator,
BearerAuthenticatorModel: self.create_bearer_authenticator,
CheckStreamModel: self.create_check_stream,
CompositeErrorHandlerModel: self.create_composite_error_handler,
ConcurrencyLevelModel: self.create_concurrency_level,
ConstantBackoffStrategyModel: self.create_constant_backoff_strategy,
CursorPaginationModel: self.create_cursor_pagination,
CustomAuthenticatorModel: self.create_custom_component,
CustomBackoffStrategyModel: self.create_custom_component,
CustomDecoderModel: self.create_custom_component,
CustomErrorHandlerModel: self.create_custom_component,
CustomIncrementalSyncModel: self.create_custom_component,
CustomRecordExtractorModel: self.create_custom_component,
CustomRecordFilterModel: self.create_custom_component,
CustomRequesterModel: self.create_custom_component,
CustomRetrieverModel: self.create_custom_component,
CustomSchemaLoader: self.create_custom_component,
CustomStateMigration: self.create_custom_component,
CustomPaginationStrategyModel: self.create_custom_component,
CustomPartitionRouterModel: self.create_custom_component,
CustomTransformationModel: self.create_custom_component,
DatetimeBasedCursorModel: self.create_datetime_based_cursor,
DeclarativeStreamModel: self.create_declarative_stream,
DefaultErrorHandlerModel: self.create_default_error_handler,
DefaultPaginatorModel: self.create_default_paginator,
DpathExtractorModel: self.create_dpath_extractor,
ExponentialBackoffStrategyModel: self.create_exponential_backoff_strategy,
SessionTokenAuthenticatorModel: self.create_session_token_authenticator,
HttpRequesterModel: self.create_http_requester,
HttpResponseFilterModel: self.create_http_response_filter,
InlineSchemaLoaderModel: self.create_inline_schema_loader,
JsonDecoderModel: self.create_json_decoder,
JsonlDecoderModel: self.create_jsonl_decoder,
GzipJsonDecoderModel: self.create_gzipjson_decoder,
KeysToLowerModel: self.create_keys_to_lower_transformation,
IterableDecoderModel: self.create_iterable_decoder,
XmlDecoderModel: self.create_xml_decoder,
JsonFileSchemaLoaderModel: self.create_json_file_schema_loader,
JwtAuthenticatorModel: self.create_jwt_authenticator,
LegacyToPerPartitionStateMigrationModel: self.create_legacy_to_per_partition_state_migration,
ListPartitionRouterModel: self.create_list_partition_router,
MinMaxDatetimeModel: self.create_min_max_datetime,
NoAuthModel: self.create_no_auth,
NoPaginationModel: self.create_no_pagination,
OAuthAuthenticatorModel: self.create_oauth_authenticator,
OffsetIncrementModel: self.create_offset_increment,
PageIncrementModel: self.create_page_increment,
ParentStreamConfigModel: self.create_parent_stream_config,
RecordFilterModel: self.create_record_filter,
RecordSelectorModel: self.create_record_selector,
RemoveFieldsModel: self.create_remove_fields,
RequestPathModel: self.create_request_path,
RequestOptionModel: self.create_request_option,
LegacySessionTokenAuthenticatorModel: self.create_legacy_session_token_authenticator,
SelectiveAuthenticatorModel: self.create_selective_authenticator,
SimpleRetrieverModel: self.create_simple_retriever,
SpecModel: self.create_spec,
SubstreamPartitionRouterModel: self.create_substream_partition_router,
WaitTimeFromHeaderModel: self.create_wait_time_from_header,
WaitUntilTimeFromHeaderModel: self.create_wait_until_time_from_header,
AsyncRetrieverModel: self.create_async_retriever,
}
# Needed for the case where we need to perform a second parse on the fields of a custom component
self.TYPE_NAME_TO_MODEL = {cls.__name__: cls for cls in self.PYDANTIC_MODEL_TO_CONSTRUCTOR}
def create_component(
self,
model_type: Type[BaseModel],
component_definition: ComponentDefinition,
config: Config,
**kwargs: Any,
) -> Any:
"""
Takes a given Pydantic model type and Mapping representing a component definition and creates a declarative component and
subcomponents which will be used at runtime. This is done by first parsing the mapping into a Pydantic model and then creating
creating declarative components from that model.
:param model_type: The type of declarative component that is being initialized
:param component_definition: The mapping that represents a declarative component
:param config: The connector config that is provided by the customer
:return: The declarative component to be used at runtime
"""
component_type = component_definition.get("type")
if component_definition.get("type") != model_type.__name__:
raise ValueError(
f"Expected manifest component of type {model_type.__name__}, but received {component_type} instead"
)
declarative_component_model = model_type.parse_obj(component_definition)
if not isinstance(declarative_component_model, model_type):
raise ValueError(
f"Expected {model_type.__name__} component, but received {declarative_component_model.__class__.__name__}"
)
return self._create_component_from_model(
model=declarative_component_model, config=config, **kwargs
)
def _create_component_from_model(self, model: BaseModel, config: Config, **kwargs: Any) -> Any:
if model.__class__ not in self.PYDANTIC_MODEL_TO_CONSTRUCTOR:
raise ValueError(
f"{model.__class__} with attributes {model} is not a valid component type"
)
component_constructor = self.PYDANTIC_MODEL_TO_CONSTRUCTOR.get(model.__class__)
if not component_constructor:
raise ValueError(f"Could not find constructor for {model.__class__}")
return component_constructor(model=model, config=config, **kwargs)
@staticmethod
def create_added_field_definition(
model: AddedFieldDefinitionModel, config: Config, **kwargs: Any
) -> AddedFieldDefinition:
interpolated_value = InterpolatedString.create(
model.value, parameters=model.parameters or {}
)
return AddedFieldDefinition(
path=model.path,
value=interpolated_value,
value_type=ModelToComponentFactory._json_schema_type_name_to_type(model.value_type),
parameters=model.parameters or {},
)
def create_add_fields(self, model: AddFieldsModel, config: Config, **kwargs: Any) -> AddFields:
added_field_definitions = [
self._create_component_from_model(
model=added_field_definition_model,
value_type=ModelToComponentFactory._json_schema_type_name_to_type(
added_field_definition_model.value_type
),
config=config,
)
for added_field_definition_model in model.fields
]
return AddFields(fields=added_field_definitions, parameters=model.parameters or {})
def create_keys_to_lower_transformation(
self, model: KeysToLowerModel, config: Config, **kwargs: Any
) -> KeysToLowerTransformation:
return KeysToLowerTransformation()
@staticmethod
def _json_schema_type_name_to_type(value_type: Optional[ValueType]) -> Optional[Type[Any]]:
if not value_type:
return None
names_to_types = {
ValueType.string: str,
ValueType.number: float,
ValueType.integer: int,
ValueType.boolean: bool,
}
return names_to_types[value_type]
@staticmethod
def create_api_key_authenticator(
model: ApiKeyAuthenticatorModel,
config: Config,
token_provider: Optional[TokenProvider] = None,
**kwargs: Any,
) -> ApiKeyAuthenticator:
if model.inject_into is None and model.header is None:
raise ValueError(
"Expected either inject_into or header to be set for ApiKeyAuthenticator"
)
if model.inject_into is not None and model.header is not None:
raise ValueError(
"inject_into and header cannot be set both for ApiKeyAuthenticator - remove the deprecated header option"
)
if token_provider is not None and model.api_token != "":
raise ValueError(
"If token_provider is set, api_token is ignored and has to be set to empty string."
)
request_option = (
RequestOption(
inject_into=RequestOptionType(model.inject_into.inject_into.value),
field_name=model.inject_into.field_name,
parameters=model.parameters or {},
)
if model.inject_into
else RequestOption(
inject_into=RequestOptionType.header,
field_name=model.header or "",
parameters=model.parameters or {},
)
)
return ApiKeyAuthenticator(
token_provider=(
token_provider
if token_provider is not None
else InterpolatedStringTokenProvider(
api_token=model.api_token or "",
config=config,
parameters=model.parameters or {},
)
),
request_option=request_option,
config=config,
parameters=model.parameters or {},
)
def create_legacy_to_per_partition_state_migration(
self,
model: LegacyToPerPartitionStateMigrationModel,
config: Mapping[str, Any],
declarative_stream: DeclarativeStreamModel,
) -> LegacyToPerPartitionStateMigration:
retriever = declarative_stream.retriever
if not isinstance(retriever, SimpleRetrieverModel):
raise ValueError(
f"LegacyToPerPartitionStateMigrations can only be applied on a DeclarativeStream with a SimpleRetriever. Got {type(retriever)}"
)
partition_router = retriever.partition_router
if not isinstance(
partition_router, (SubstreamPartitionRouterModel, CustomPartitionRouterModel)
):
raise ValueError(
f"LegacyToPerPartitionStateMigrations can only be applied on a SimpleRetriever with a Substream partition router. Got {type(partition_router)}"
)
if not hasattr(partition_router, "parent_stream_configs"):
raise ValueError(
"LegacyToPerPartitionStateMigrations can only be applied with a parent stream configuration."
)
return LegacyToPerPartitionStateMigration(
declarative_stream.retriever.partition_router,
declarative_stream.incremental_sync,
config,
declarative_stream.parameters,
) # type: ignore # The retriever type was already checked
def create_session_token_authenticator(
self, model: SessionTokenAuthenticatorModel, config: Config, name: str, **kwargs: Any
) -> Union[ApiKeyAuthenticator, BearerAuthenticator]:
decoder = (
self._create_component_from_model(model=model.decoder, config=config)
if model.decoder
else JsonDecoder(parameters={})
)
login_requester = self._create_component_from_model(
model=model.login_requester,
config=config,
name=f"{name}_login_requester",
decoder=decoder,
)
token_provider = SessionTokenProvider(
login_requester=login_requester,
session_token_path=model.session_token_path,
expiration_duration=parse_duration(model.expiration_duration)
if model.expiration_duration
else None,
parameters=model.parameters or {},
message_repository=self._message_repository,
decoder=decoder,
)
if model.request_authentication.type == "Bearer":
return ModelToComponentFactory.create_bearer_authenticator(
BearerAuthenticatorModel(type="BearerAuthenticator", api_token=""), # type: ignore # $parameters has a default value
config,
token_provider=token_provider, # type: ignore # $parameters defaults to None
)
else:
return ModelToComponentFactory.create_api_key_authenticator(
ApiKeyAuthenticatorModel(
type="ApiKeyAuthenticator",
api_token="",
inject_into=model.request_authentication.inject_into,
), # type: ignore # $parameters and headers default to None
config=config,
token_provider=token_provider,
)
@staticmethod
def create_basic_http_authenticator(
model: BasicHttpAuthenticatorModel, config: Config, **kwargs: Any
) -> BasicHttpAuthenticator:
return BasicHttpAuthenticator(
password=model.password or "",
username=model.username,
config=config,
parameters=model.parameters or {},
)
@staticmethod
def create_bearer_authenticator(
model: BearerAuthenticatorModel,
config: Config,
token_provider: Optional[TokenProvider] = None,
**kwargs: Any,
) -> BearerAuthenticator:
if token_provider is not None and model.api_token != "":
raise ValueError(
"If token_provider is set, api_token is ignored and has to be set to empty string."
)
return BearerAuthenticator(
token_provider=(
token_provider
if token_provider is not None
else InterpolatedStringTokenProvider(
api_token=model.api_token or "",
config=config,
parameters=model.parameters or {},
)
),
config=config,
parameters=model.parameters or {},
)
@staticmethod
def create_check_stream(model: CheckStreamModel, config: Config, **kwargs: Any) -> CheckStream:
return CheckStream(stream_names=model.stream_names, parameters={})
def create_composite_error_handler(
self, model: CompositeErrorHandlerModel, config: Config, **kwargs: Any
) -> CompositeErrorHandler:
error_handlers = [
self._create_component_from_model(model=error_handler_model, config=config)
for error_handler_model in model.error_handlers
]
return CompositeErrorHandler(
error_handlers=error_handlers, parameters=model.parameters or {}
)
@staticmethod
def create_concurrency_level(
model: ConcurrencyLevelModel, config: Config, **kwargs: Any
) -> ConcurrencyLevel:
return ConcurrencyLevel(
default_concurrency=model.default_concurrency,
max_concurrency=model.max_concurrency,
config=config,
parameters={},
)
def create_concurrent_cursor_from_datetime_based_cursor(
self,
state_manager: ConnectorStateManager,
model_type: Type[BaseModel],
component_definition: ComponentDefinition,
stream_name: str,
stream_namespace: Optional[str],
config: Config,
stream_state: MutableMapping[str, Any],
**kwargs: Any,
) -> Tuple[ConcurrentCursor, DateTimeStreamStateConverter]:
component_type = component_definition.get("type")
if component_definition.get("type") != model_type.__name__:
raise ValueError(
f"Expected manifest component of type {model_type.__name__}, but received {component_type} instead"
)
datetime_based_cursor_model = model_type.parse_obj(component_definition)
if not isinstance(datetime_based_cursor_model, DatetimeBasedCursorModel):
raise ValueError(
f"Expected {model_type.__name__} component, but received {datetime_based_cursor_model.__class__.__name__}"
)
interpolated_cursor_field = InterpolatedString.create(
datetime_based_cursor_model.cursor_field,
parameters=datetime_based_cursor_model.parameters or {},
)
cursor_field = CursorField(interpolated_cursor_field.eval(config=config))
interpolated_partition_field_start = InterpolatedString.create(
datetime_based_cursor_model.partition_field_start or "start_time",
parameters=datetime_based_cursor_model.parameters or {},
)
interpolated_partition_field_end = InterpolatedString.create(
datetime_based_cursor_model.partition_field_end or "end_time",
parameters=datetime_based_cursor_model.parameters or {},
)
slice_boundary_fields = (
interpolated_partition_field_start.eval(config=config),
interpolated_partition_field_end.eval(config=config),
)
datetime_format = datetime_based_cursor_model.datetime_format
cursor_granularity = (
parse_duration(datetime_based_cursor_model.cursor_granularity)
if datetime_based_cursor_model.cursor_granularity
else None
)
lookback_window = None
interpolated_lookback_window = (
InterpolatedString.create(
datetime_based_cursor_model.lookback_window,
parameters=datetime_based_cursor_model.parameters or {},
)
if datetime_based_cursor_model.lookback_window
else None
)
if interpolated_lookback_window:
evaluated_lookback_window = interpolated_lookback_window.eval(config=config)
if evaluated_lookback_window:
lookback_window = parse_duration(evaluated_lookback_window)
connector_state_converter: DateTimeStreamStateConverter
connector_state_converter = CustomFormatConcurrentStreamStateConverter(
datetime_format=datetime_format,
input_datetime_formats=datetime_based_cursor_model.cursor_datetime_formats,
is_sequential_state=True,
cursor_granularity=cursor_granularity,
# type: ignore # Having issues w/ inspection for GapType and CursorValueType as shown in existing tests. Confirmed functionality is working in practice
)
start_date_runtime_value: Union[InterpolatedString, str, MinMaxDatetime]
if isinstance(datetime_based_cursor_model.start_datetime, MinMaxDatetimeModel):
start_date_runtime_value = self.create_min_max_datetime(
model=datetime_based_cursor_model.start_datetime, config=config
)
else:
start_date_runtime_value = datetime_based_cursor_model.start_datetime
end_date_runtime_value: Optional[Union[InterpolatedString, str, MinMaxDatetime]]
if isinstance(datetime_based_cursor_model.end_datetime, MinMaxDatetimeModel):
end_date_runtime_value = self.create_min_max_datetime(
model=datetime_based_cursor_model.end_datetime, config=config
)
else:
end_date_runtime_value = datetime_based_cursor_model.end_datetime
interpolated_start_date = MinMaxDatetime.create(
interpolated_string_or_min_max_datetime=start_date_runtime_value,
parameters=datetime_based_cursor_model.parameters,
)
interpolated_end_date = (
None
if not end_date_runtime_value
else MinMaxDatetime.create(
end_date_runtime_value, datetime_based_cursor_model.parameters
)
)
# If datetime format is not specified then start/end datetime should inherit it from the stream slicer
if not interpolated_start_date.datetime_format:
interpolated_start_date.datetime_format = datetime_format
if interpolated_end_date and not interpolated_end_date.datetime_format:
interpolated_end_date.datetime_format = datetime_format
start_date = interpolated_start_date.get_datetime(config=config)
end_date_provider = (
partial(interpolated_end_date.get_datetime, config)
if interpolated_end_date
else connector_state_converter.get_end_provider()
)
if (
datetime_based_cursor_model.step and not datetime_based_cursor_model.cursor_granularity
) or (
not datetime_based_cursor_model.step and datetime_based_cursor_model.cursor_granularity
):
raise ValueError(
f"If step is defined, cursor_granularity should be as well and vice-versa. "
f"Right now, step is `{datetime_based_cursor_model.step}` and cursor_granularity is `{datetime_based_cursor_model.cursor_granularity}`"
)
# When step is not defined, default to a step size from the starting date to the present moment
step_length = datetime.timedelta.max
interpolated_step = (
InterpolatedString.create(
datetime_based_cursor_model.step,
parameters=datetime_based_cursor_model.parameters or {},
)
if datetime_based_cursor_model.step
else None
)
if interpolated_step:
evaluated_step = interpolated_step.eval(config)
if evaluated_step:
step_length = parse_duration(evaluated_step)
return (
ConcurrentCursor(
stream_name=stream_name,
stream_namespace=stream_namespace,
stream_state=stream_state,
message_repository=self._message_repository, # type: ignore # message_repository is always instantiated with a value by factory
connector_state_manager=state_manager,
connector_state_converter=connector_state_converter,
cursor_field=cursor_field,
slice_boundary_fields=slice_boundary_fields,
start=start_date, # type: ignore # Having issues w/ inspection for GapType and CursorValueType as shown in existing tests. Confirmed functionality is working in practice
end_provider=end_date_provider, # type: ignore # Having issues w/ inspection for GapType and CursorValueType as shown in existing tests. Confirmed functionality is working in practice
lookback_window=lookback_window,
slice_range=step_length,
cursor_granularity=cursor_granularity,
),
connector_state_converter,
)
@staticmethod
def create_constant_backoff_strategy(
model: ConstantBackoffStrategyModel, config: Config, **kwargs: Any
) -> ConstantBackoffStrategy:
return ConstantBackoffStrategy(
backoff_time_in_seconds=model.backoff_time_in_seconds,
config=config,
parameters=model.parameters or {},
)
def create_cursor_pagination(
self, model: CursorPaginationModel, config: Config, decoder: Decoder, **kwargs: Any
) -> CursorPaginationStrategy:
if isinstance(decoder, PaginationDecoderDecorator):
if not isinstance(decoder.decoder, (JsonDecoder, XmlDecoder)):
raise ValueError(
f"Provided decoder of {type(decoder.decoder)=} is not supported. Please set JsonDecoder or XmlDecoder instead."
)
decoder_to_use = decoder
else:
if not isinstance(decoder, (JsonDecoder, XmlDecoder)):
raise ValueError(
f"Provided decoder of {type(decoder)=} is not supported. Please set JsonDecoder or XmlDecoder instead."
)
decoder_to_use = PaginationDecoderDecorator(decoder=decoder)
return CursorPaginationStrategy(
cursor_value=model.cursor_value,
decoder=decoder_to_use,
page_size=model.page_size,
stop_condition=model.stop_condition,
config=config,
parameters=model.parameters or {},
)
def create_custom_component(self, model: Any, config: Config, **kwargs: Any) -> Any:
"""
Generically creates a custom component based on the model type and a class_name reference to the custom Python class being
instantiated. Only the model's additional properties that match the custom class definition are passed to the constructor
:param model: The Pydantic model of the custom component being created
:param config: The custom defined connector config
:return: The declarative component built from the Pydantic model to be used at runtime
"""
custom_component_class = self._get_class_from_fully_qualified_class_name(model.class_name)
component_fields = get_type_hints(custom_component_class)
model_args = model.dict()
model_args["config"] = config
# There are cases where a parent component will pass arguments to a child component via kwargs. When there are field collisions
# we defer to these arguments over the component's definition
for key, arg in kwargs.items():
model_args[key] = arg
# Pydantic is unable to parse a custom component's fields that are subcomponents into models because their fields and types are not
# defined in the schema. The fields and types are defined within the Python class implementation. Pydantic can only parse down to
# the custom component and this code performs a second parse to convert the sub-fields first into models, then declarative components
for model_field, model_value in model_args.items():
# If a custom component field doesn't have a type set, we try to use the type hints to infer the type
if (
isinstance(model_value, dict)
and "type" not in model_value
and model_field in component_fields
):
derived_type = self._derive_component_type_from_type_hints(
component_fields.get(model_field)
)
if derived_type:
model_value["type"] = derived_type
if self._is_component(model_value):
model_args[model_field] = self._create_nested_component(
model, model_field, model_value, config
)
elif isinstance(model_value, list):
vals = []
for v in model_value:
if isinstance(v, dict) and "type" not in v and model_field in component_fields:
derived_type = self._derive_component_type_from_type_hints(
component_fields.get(model_field)
)
if derived_type:
v["type"] = derived_type
if self._is_component(v):
vals.append(self._create_nested_component(model, model_field, v, config))
else:
vals.append(v)
model_args[model_field] = vals
kwargs = {
class_field: model_args[class_field]
for class_field in component_fields.keys()
if class_field in model_args
}
return custom_component_class(**kwargs)
@staticmethod
def _get_class_from_fully_qualified_class_name(full_qualified_class_name: str) -> Any:
split = full_qualified_class_name.split(".")
module = ".".join(split[:-1])