-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsync_resources.py
More file actions
1404 lines (1209 loc) · 52.8 KB
/
sync_resources.py
File metadata and controls
1404 lines (1209 loc) · 52.8 KB
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
import json
import logging
from abc import ABC, abstractmethod
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field, replace
from decimal import Decimal
from typing import (
Any,
Callable,
Dict,
Generic,
List,
Literal,
Optional,
Tuple,
Type,
TypeVar,
cast,
)
import boto3
import pendulum
import requests
from requests.adapters import HTTPAdapter, Retry
logger = logging.getLogger()
logger.setLevel(logging.INFO)
s3_client = boto3.client("s3")
BASE_ORB_API_URL = "https://api.withorb.com/v1/"
DEFAULT_PAGE_SIZE = 20
MAX_PAGES_PER_SYNC = 10
## Only applies to costs
MIN_COSTS_START_TIME = pendulum.datetime(2023, 1, 1, 0, 0, 0, tz="UTC")
COSTS_TIMEFRAME_WINDOW = 10
GRACE_PERIOD_BUFFER_DAYS = 2
## Subscription Costs
SUBSCRIPTION_COSTS_PAGE_SIZE = DEFAULT_PAGE_SIZE
## Ledger Entries
LEDGER_ENTRIES_PAGE_SIZE = 300
## Customer Resource Events
CUSTOMER_RESOURCE_EVENTS_PAGE_SIZE = 200
CURRENT_STATE_VERSION = 4
REQUEST_TIMEOUT = 10
req_session = requests.Session()
retries = Retry(total=3, backoff_factor=0.1, status_forcelist=[429, 500, 502, 503, 504])
req_session.mount("https://", HTTPAdapter(max_retries=retries))
req_session.headers.update({"User-Agent": "Orb-Fivetran-Connector"})
class AbstractCursor(ABC):
@abstractmethod
def serialize(self) -> Dict[str, Any]:
...
@staticmethod
@abstractmethod
def deserialize(d: Dict[str, Any]) -> "AbstractCursor":
...
@staticmethod
@abstractmethod
def min() -> "AbstractCursor":
...
@abstractmethod
def pagination_exhausted(self) -> bool:
...
@dataclass(frozen=True)
class SimplePaginationCursor(AbstractCursor):
"""
This is a simple cursor that just keeps track of a pagination cursor string
but does not keep track of a minimum time like `Cursor` does. This is only used
when paginating slices for a nested resource.
"""
has_more: bool = True
current_cursor: Optional[str] = None
def serialize(self) -> Dict[str, Any]:
return {"has_more": self.has_more, "current_cursor": self.current_cursor}
@staticmethod
def deserialize(d: Dict[str, Any]) -> "SimplePaginationCursor":
return SimplePaginationCursor(
has_more=d["has_more"], current_cursor=d["current_cursor"]
)
@staticmethod
def min() -> "SimplePaginationCursor":
return SimplePaginationCursor(has_more=True, current_cursor=None)
def pagination_exhausted(self) -> bool:
return self.has_more is False
@dataclass(frozen=True)
class Cursor(AbstractCursor):
"""
When we paginate, we get results that are greater than
or equal to `min_time_cursor`. Since results are ordered
*newest* to *oldest*, the first page returned gives us the time
boundary of how to advance after pagination is exhausted
and we set this as `min_time_after_pagination_exhausted`, but
until we're still paging through this result set, we use
`min_time_cursor`.
"""
# Relate to "current" result set
min_time_cursor: pendulum.DateTime
maybe_pagination_cursor: Optional[str]
# This will become `min_time_cursor` after
# pagination is exhausted
min_time_after_pagination_exhausted: Optional[pendulum.DateTime] = None
def pagination_exhausted(self) -> bool:
return (
self.maybe_pagination_cursor is None
and self.min_time_after_pagination_exhausted is None
)
@staticmethod
def min() -> "Cursor":
return Cursor(
min_time_cursor=pendulum.from_timestamp(0),
maybe_pagination_cursor=None,
min_time_after_pagination_exhausted=None,
)
def with_updated_pagination_result(
self,
pagination_cursor: Optional[str],
max_time_in_page: Optional[pendulum.DateTime],
) -> "Cursor":
# No more pages left, and pagination is exhausted
if pagination_cursor is None:
return Cursor(
# We will set to `max_time_in_page` in the case that `min_time_after_pagination_exhausted` is None,
# which means that we only had a single page of results. If max_time_in_page is None, that means
# that there were no results so we want to maintain the `min_time_cursor`
min_time_cursor=self.min_time_after_pagination_exhausted
or max_time_in_page
or self.min_time_cursor,
maybe_pagination_cursor=None,
min_time_after_pagination_exhausted=None,
)
# We are paginating
elif pagination_cursor is not None:
# If we are paginating, there should be something in the current page,
# so max_time_in_page should be non-null
assert max_time_in_page is not None
return Cursor(
min_time_cursor=self.min_time_cursor,
maybe_pagination_cursor=pagination_cursor,
# If we don't already have a `min_time_after_pagination_exhausted`, then set this
# to the max time in this page, because that means this is the first page result
# Note that this assumes we're paginating *newest* to *oldest*
min_time_after_pagination_exhausted=self.min_time_after_pagination_exhausted
or max_time_in_page,
)
def serialize(self):
return {
"min_time_cursor": self.min_time_cursor.isoformat(),
"maybe_pagination_cursor": self.maybe_pagination_cursor,
"min_time_after_pagination_exhausted": self.min_time_after_pagination_exhausted.isoformat()
if self.min_time_after_pagination_exhausted
else None,
}
@staticmethod
def deserialize(serialized_state) -> "Cursor":
def maybe_parse_as_datetime(datetime_field) -> Optional[pendulum.DateTime]:
return (
cast(pendulum.DateTime, pendulum.parse(datetime_field))
if datetime_field is not None
else None
)
return Cursor(
min_time_cursor=pendulum.parse(serialized_state["min_time_cursor"]), # type: ignore
maybe_pagination_cursor=serialized_state["maybe_pagination_cursor"],
min_time_after_pagination_exhausted=maybe_parse_as_datetime(
serialized_state["min_time_after_pagination_exhausted"]
),
)
@dataclass
class CursorWithSlices(AbstractCursor):
"""
A wrapper around Cursor that allows us to store a cursor for each slice.
Used for Nested Streams.
"""
per_slice_cursor: Dict[str, Cursor]
# This is so that we can avoid fetching all slices in every invocation,
# so it's a cursor for the slice list itself (not a cursor for a slice)
# `CursorWithSlices` is fully exhausted when `slices_pagination_cursor` is None
# and each cursor in `per_slice_cursor` is exhausted
slices_pagination_cursor: SimplePaginationCursor
def cursor_for_slice(self, slice_id):
return self.per_slice_cursor.get(slice_id, Cursor.min())
def update_cursor_for_slice(self, slice_id, cursor):
self.per_slice_cursor[slice_id] = cursor
def update_slices_pagination_cursor(self, cursor):
self.slices_pagination_cursor = cursor
def all_current_slices_exhausted(self):
return all(
cursor.pagination_exhausted() for cursor in self.per_slice_cursor.values()
)
def pagination_exhausted(self) -> bool:
return self.slices_pagination_cursor.pagination_exhausted() and all(
self.cursor_for_slice(slice_id).pagination_exhausted()
for slice_id in self.per_slice_cursor.keys()
)
def serialize(self):
return {
"per_slice_cursor": {
slice_id: cursor.serialize()
for slice_id, cursor in self.per_slice_cursor.items()
},
"slices_pagination_cursor": self.slices_pagination_cursor.serialize(),
}
@staticmethod
def min() -> "CursorWithSlices":
return CursorWithSlices(
per_slice_cursor={}, slices_pagination_cursor=SimplePaginationCursor.min()
)
@staticmethod
def deserialize(serialized_state) -> "CursorWithSlices":
return CursorWithSlices(
per_slice_cursor={
slice_id: Cursor.deserialize(cursor)
for slice_id, cursor in serialized_state["per_slice_cursor"].items()
},
slices_pagination_cursor=SimplePaginationCursor.deserialize(
serialized_state["slices_pagination_cursor"]
),
)
@dataclass
class SubscriptionCostsCursor(AbstractCursor):
"""
A cursor for the SubscriptionCosts stream,
where we get costs for each timeframe across
all subscriptions.
The pagination strategy is to go through all subscriptions
for a given timeframe before advancing the timeframe. If we're
in the middle of paginating subscriptions, then
`current_subscriptions_pagination_cursor` will be non-None.
"""
current_timeframe_start: pendulum.DateTime
# The reason we store both start and end is so that we can
# keep the timeframe constant while we're still paginating subscriptions
# for this specific timeframe. We don't want later runs to have larger
# timeframes.
current_timeframe_end: pendulum.DateTime
current_subscriptions_pagination_cursor: Optional[str]
def serialize(self):
return {
"current_timeframe_start": self.current_timeframe_start.isoformat(),
"current_timeframe_end": self.current_timeframe_end.isoformat(),
"current_subscriptions_pagination_cursor": self.current_subscriptions_pagination_cursor,
}
@staticmethod
def deserialize(serialized_state) -> "SubscriptionCostsCursor":
current_timeframe_start_str = serialized_state["current_timeframe_start"]
current_timeframe_end_str = serialized_state["current_timeframe_end"]
return SubscriptionCostsCursor(
current_timeframe_start=pendulum.parse(
current_timeframe_start_str, tz="UTC"
),
current_timeframe_end=pendulum.parse(current_timeframe_end_str, tz="UTC"),
current_subscriptions_pagination_cursor=serialized_state[
"current_subscriptions_pagination_cursor"
],
)
@staticmethod
def calculate_end_time_from_start_time(
start_time: pendulum.DateTime,
) -> pendulum.DateTime:
return min(
start_time.add(days=COSTS_TIMEFRAME_WINDOW),
pendulum.now("UTC").subtract(days=GRACE_PERIOD_BUFFER_DAYS),
)
@staticmethod
def min() -> "SubscriptionCostsCursor":
return SubscriptionCostsCursor(
current_timeframe_start=MIN_COSTS_START_TIME,
current_timeframe_end=SubscriptionCostsCursor.calculate_end_time_from_start_time(
MIN_COSTS_START_TIME
),
current_subscriptions_pagination_cursor=None,
)
@staticmethod
def maybe_deserialize_state(state) -> "SubscriptionCostsCursor":
if state.get("subscription_costs"):
return SubscriptionCostsCursor.deserialize(state["subscription_costs"])
else:
return SubscriptionCostsCursor.min()
def advance_timeframe_bounds(self, timeframe_end):
assert self.current_subscriptions_pagination_cursor is None
self.current_timeframe_start = timeframe_end
self.current_timeframe_end = (
SubscriptionCostsCursor.calculate_end_time_from_start_time(
self.current_timeframe_start
)
)
def update_subscription_pagination_for_current_timeframe(
self, pagination_cursor: Optional[str]
):
"""
This advances which subscription we're on, while staying on the same timeframe.
"""
self.current_subscriptions_pagination_cursor = pagination_cursor
def mark_current_timeframe_exhausted(self):
self.current_subscriptions_pagination_cursor = None
def pagination_exhausted(self) -> bool:
"""
Pagination is exhausted if we no longer have a cursor for paginating.
"""
return self.current_subscriptions_pagination_cursor is None
T = TypeVar("T", bound=AbstractCursor)
class AbstractResourceFetchResponse(ABC, Generic[T]):
@abstractmethod
def all_resources(self):
pass
@abstractmethod
def get_updated_state(self) -> T:
pass
@staticmethod
@abstractmethod
def init_with_cursor(
cursor: T, resource_config
) -> "AbstractResourceFetchResponse[T]":
pass
class AbstractResourceFetcher(ABC, Generic[T]):
def __init__(self, secrets, resource_config):
self.resource_config = resource_config
self.secrets = secrets
@property
def auth_header(self):
orb_api_key = self.secrets.get("orb_api_key")
return {"Authorization": f"Bearer {orb_api_key}"}
@abstractmethod
def fetch_after_cursor(self, initial_cursor: T) -> AbstractResourceFetchResponse[T]:
pass
def fetch_all(
self, maybe_existing_state_cursor: T
) -> AbstractResourceFetchResponse[T]:
initial_cursor = (
maybe_existing_state_cursor
if maybe_existing_state_cursor is not None
else type(maybe_existing_state_cursor).min()
)
return self.fetch_after_cursor(initial_cursor)
def fetch_resources_from_path(
self,
path,
pagination_cursor: Optional[str] = None,
max_pages=MAX_PAGES_PER_SYNC,
) -> Tuple[List[Any], SimplePaginationCursor]:
"""
Exhaustively fetches resources from the passed in path. Note that
this needs to be called on every invocation of this sync, so
a very expensive parent resource will cause issues
"""
params = {
"limit": getattr(self.resource_config, "page_size", DEFAULT_PAGE_SIZE)
}
if pagination_cursor:
params["cursor"] = pagination_cursor
response_json = req_session.get(
BASE_ORB_API_URL + path,
headers=self.auth_header,
params=params,
).json()
resources = response_json["data"]
num_pages = 1
has_more = response_json["pagination_metadata"]["has_more"]
while has_more and num_pages < max_pages:
params["cursor"] = response_json["pagination_metadata"]["next_cursor"]
response_json = req_session.get(
BASE_ORB_API_URL + path,
headers=self.auth_header,
params=params,
).json()
resources.extend(response_json["data"])
num_pages += 1
has_more = response_json["pagination_metadata"]["has_more"]
return (
resources,
SimplePaginationCursor(
has_more=has_more,
current_cursor=response_json["pagination_metadata"]["next_cursor"],
),
)
@dataclass(frozen=True)
class BaseResourceConfig:
primary_key_list: List[str]
resultant_schema_key: str
maybe_fetcher_type: Optional[Type[AbstractResourceFetcher]]
page_size: int = field(default=DEFAULT_PAGE_SIZE, kw_only=True)
@dataclass(frozen=True)
class ResourceConfig(BaseResourceConfig):
api_path: str
# This determines what API field we use
# to store state in between syncs.
maybe_state_time_attribute: Optional[str]
fetch_strategy: Literal["direct_fetch", "resource_events"]
page_size: int = field(default=DEFAULT_PAGE_SIZE, kw_only=True)
@dataclass(frozen=True)
class NestedResourceConfig(BaseResourceConfig):
"""
Config for a nested resource, which is a resource that is nested under a parent resource
and cannot be paginated directly.
"""
# The path to a list of parent resources
all_slices_api_path: str
# The path to a single slice
single_slice_api_path: Callable[[str], str]
maybe_state_time_attribute: Optional[str]
page_size: int = field(default=DEFAULT_PAGE_SIZE, kw_only=True)
def slice_resource_config(self, slice_id: str) -> ResourceConfig:
"""
Returns a ResourceConfig for a single slice of this nested resource,
given the slice_id.
"""
return ResourceConfig(
api_path=self.single_slice_api_path(slice_id), # type:ignore
maybe_state_time_attribute=self.maybe_state_time_attribute,
resultant_schema_key=self.resultant_schema_key,
# Only support direct fetch for now for nested resources
fetch_strategy="direct_fetch",
primary_key_list=self.primary_key_list,
page_size=self.page_size,
maybe_fetcher_type=None,
)
def fetcher_for_resource_config(resource_config) -> Type[AbstractResourceFetcher]:
if resource_config.maybe_fetcher_type is not None:
return resource_config.maybe_fetcher_type
elif type(resource_config) == NestedResourceConfig:
return NestedResourceFetcher
elif resource_config.fetch_strategy == "direct_fetch":
return DirectResourceFetcher
else:
return ResourceEventBasedResourceFetcher
@dataclass
class FunctionState:
customer_cursor: AbstractCursor
plan_cursor: AbstractCursor
invoice_cursor: AbstractCursor
subscription_cursor: AbstractCursor
subscription_version_cursor: AbstractCursor
subscription_costs_cursor: AbstractCursor
credit_ledger_entry_cursor: AbstractCursor
def as_dict(self):
return {
"state_version": CURRENT_STATE_VERSION,
"customer": self.customer_cursor.serialize(),
"plan": self.plan_cursor.serialize(),
"invoice": self.invoice_cursor.serialize(),
"subscription": self.subscription_cursor.serialize(),
"subscription_version": self.subscription_version_cursor.serialize(),
"credit_ledger_entry": self.credit_ledger_entry_cursor.serialize(),
"subscription_costs": self.subscription_costs_cursor.serialize(),
}
@staticmethod
def from_serialized_state(state: Optional[Dict]):
if state is None or state.get("state_version") != CURRENT_STATE_VERSION:
logger.info("Discarding current state entirely.")
return FunctionState(
customer_cursor=Cursor.min(),
plan_cursor=Cursor.min(),
invoice_cursor=Cursor.min(),
subscription_cursor=Cursor.min(),
subscription_version_cursor=Cursor.min(),
credit_ledger_entry_cursor=CursorWithSlices.min(),
subscription_costs_cursor=SubscriptionCostsCursor.min(),
)
else:
def maybe_deserialize_resource_state(state: Dict, resource_name):
if state.get(resource_name) is not None:
return Cursor.deserialize(serialized_state=state[resource_name])
else:
return Cursor.min()
def maybe_deserialize_nested_resource_state(state: Dict, resource_name):
if state.get(resource_name) is not None:
return CursorWithSlices.deserialize(
serialized_state=state[resource_name]
)
else:
return CursorWithSlices.min()
return FunctionState(
customer_cursor=maybe_deserialize_resource_state(state, "customer"),
plan_cursor=maybe_deserialize_resource_state(state, "plan"),
invoice_cursor=maybe_deserialize_resource_state(state, "invoice"),
subscription_cursor=maybe_deserialize_resource_state(
state, "subscription"
),
subscription_version_cursor=maybe_deserialize_resource_state(
state, "subscription_version"
),
credit_ledger_entry_cursor=maybe_deserialize_nested_resource_state(
state, "credit_ledger_entry"
),
subscription_costs_cursor=SubscriptionCostsCursor.maybe_deserialize_state(
state
),
)
def state_cursor_for_resource(self, resource) -> AbstractCursor:
assert resource in RESOURCE_TO_RESOURCE_CONFIG.keys()
if resource == "customer":
return self.customer_cursor
elif resource == "plan":
return self.plan_cursor
elif resource == "subscription":
return self.subscription_cursor
elif resource == "issued_invoice":
return self.invoice_cursor
elif resource == "subscription_version":
return self.subscription_version_cursor
elif resource == "credit_ledger_entry":
return self.credit_ledger_entry_cursor
elif resource == "subscription_costs":
return self.subscription_costs_cursor
else:
raise Exception(f"Cannot get state for resource {resource}")
def set_for_resource(self, resource: str, cursor: AbstractCursor) -> None:
assert resource in RESOURCE_TO_RESOURCE_CONFIG.keys()
if resource == "subscription":
self.subscription_cursor = cursor
elif resource == "customer":
self.customer_cursor = cursor
elif resource == "plan":
self.plan_cursor = cursor
elif resource == "issued_invoice":
self.invoice_cursor = cursor
elif resource == "subscription_version":
self.subscription_version_cursor = cursor
elif resource == "credit_ledger_entry":
self.credit_ledger_entry_cursor = cursor
elif resource == "subscription_costs":
self.subscription_costs_cursor = cursor
else:
raise Exception(f"Cannot set state for resource {resource}")
@dataclass
class FivetranFunctionResponse:
state: FunctionState
insert: Dict = field(default_factory=dict)
schema: Dict = field(
default_factory=lambda: {
"customer": {
"primary_key": RESOURCE_TO_RESOURCE_CONFIG["customer"].primary_key_list
},
"plan": {
"primary_key": RESOURCE_TO_RESOURCE_CONFIG["plan"].primary_key_list
},
"invoice": {
"primary_key": RESOURCE_TO_RESOURCE_CONFIG[
"issued_invoice"
].primary_key_list
},
"subscription": {
"primary_key": RESOURCE_TO_RESOURCE_CONFIG[
"subscription"
].primary_key_list
},
"credit_ledger_entry": {
"primary_key": RESOURCE_TO_RESOURCE_CONFIG[
"credit_ledger_entry"
].primary_key_list
},
"subscription_costs": {
"primary_key": RESOURCE_TO_RESOURCE_CONFIG[
"subscription_costs"
].primary_key_list
},
# A subscription version is uniquely identified by a subscription ID and a
# start date given that the start date is in the past (which is the only resources
# we'll sync here.)
"subscription_version": {
"primary_key": RESOURCE_TO_RESOURCE_CONFIG[
"subscription_version"
].primary_key_list
},
}
)
has_more: bool = False
def as_dict(self, s3_sync=False):
if s3_sync:
return {
"state": self.state.as_dict(),
"schema": self.schema,
"hasMore": self.has_more,
}
else:
return {
"state": self.state.as_dict(),
"insert": self.insert,
"delete": {},
"schema": self.schema,
"hasMore": self.has_more,
}
def serialize_output_to_s3(self):
return {"insert": self.insert, "delete": {}}
@staticmethod
def test_response():
return FivetranFunctionResponse(
state=FunctionState.from_serialized_state(None),
insert={},
schema={},
has_more=False,
).as_dict()
@dataclass
class ResourceFetchResponse(AbstractResourceFetchResponse[Cursor]):
resource_id_to_resource: Dict[str, Any]
updated_state: Cursor
resource_config: ResourceConfig
def all_resources(self):
return list(self.resource_id_to_resource.values())
def add_resource(self, resource):
# Note that this first-write-wins behavior assumes that we're paginating
# *newest* to *oldest*
primary_key = ""
for element in self.resource_config.primary_key_list:
primary_key += resource[element]
if primary_key not in self.resource_id_to_resource.keys():
self.resource_id_to_resource[primary_key] = resource
@staticmethod
def init_with_cursor(
cursor: Cursor, resource_config: ResourceConfig
) -> "ResourceFetchResponse":
return ResourceFetchResponse(
resource_id_to_resource={},
updated_state=cursor,
resource_config=resource_config,
)
def get_updated_state(self) -> Cursor:
return self.updated_state
@dataclass
class NestedResourceFetchResponse(AbstractResourceFetchResponse[CursorWithSlices]):
slice_id_to_resource_fetch_response: Dict[str, ResourceFetchResponse]
updated_state: CursorWithSlices
nested_resource_config: NestedResourceConfig
@staticmethod
def init_with_cursor(
cursor: CursorWithSlices, resource_config: NestedResourceConfig
) -> "NestedResourceFetchResponse":
return NestedResourceFetchResponse(
slice_id_to_resource_fetch_response={},
updated_state=cursor,
nested_resource_config=resource_config,
)
def update_all_slices_cursor(self, cursor: SimplePaginationCursor):
self.updated_state.update_slices_pagination_cursor(cursor)
def add_response_for_slice(self, slice_id: str, response: ResourceFetchResponse):
self.slice_id_to_resource_fetch_response[slice_id] = response
self.updated_state.update_cursor_for_slice(slice_id, response.updated_state)
def all_resources(self):
for response in self.slice_id_to_resource_fetch_response.values():
yield from response.all_resources()
def top_level_slices_pagination_cursor(self):
return self.updated_state.slices_pagination_cursor
def get_updated_state(self) -> CursorWithSlices:
return self.updated_state
@dataclass
class PeriodicSubscriptionCost:
subscription_id: str
timeframe_start: str
timeframe_end: str
quantity: Decimal
subtotal: Decimal
total: Decimal
price_id: str
price_name: str
billable_metric_id: Optional[str]
grouped_costs_json: str
def serialize(self):
return {
"subscription_id": self.subscription_id,
"timeframe_start": self.timeframe_start,
"timeframe_end": self.timeframe_end,
"quantity": self.quantity,
"subtotal": self.subtotal,
"total": self.total,
"price_id": self.price_id,
"price": {
"id": self.price_id,
"name": self.price_name,
"billable_metric_id": self.billable_metric_id,
},
"grouped_costs_json": self.grouped_costs_json,
}
@dataclass
class SubscriptionCostsFetchResponse(
AbstractResourceFetchResponse[SubscriptionCostsCursor]
):
subscription_costs: List[PeriodicSubscriptionCost]
updated_state: SubscriptionCostsCursor
resource_config: ResourceConfig
def all_resources(self):
return [cost.serialize() for cost in self.subscription_costs]
def add_resource(self, resource):
self.subscription_costs.append(resource)
def update_cursor_state(
self,
subscriptions_cursor: SimplePaginationCursor,
timeframe_end: pendulum.DateTime,
):
if subscriptions_cursor.current_cursor is None:
self.updated_state.mark_current_timeframe_exhausted()
self.updated_state.advance_timeframe_bounds(timeframe_end=timeframe_end)
else:
self.updated_state.update_subscription_pagination_for_current_timeframe(
subscriptions_cursor.current_cursor
)
@staticmethod
def init_with_cursor(
cursor: SubscriptionCostsCursor, resource_config: ResourceConfig
) -> "SubscriptionCostsFetchResponse":
return SubscriptionCostsFetchResponse(
subscription_costs=[], updated_state=cursor, resource_config=resource_config
)
def get_updated_state(self) -> SubscriptionCostsCursor:
return self.updated_state
class DirectResourceFetcher(AbstractResourceFetcher[Cursor]):
"""
Used for resources that are not fetched via resource events
and are queried directly, such as SubscriptionVersion(s).
"""
def fetch_after_cursor(self, initial_cursor: Cursor) -> ResourceFetchResponse:
supports_incremental_syncs = (
self.resource_config.maybe_state_time_attribute is not None
)
"""
Fetches resources after the passed in cursor. Note that this will also attempt to paginate
up to MAX_PAGES_PER_SYNC times.
Since this is the `Direct` fetcher, it queries for resources directly based on a time attribute
of the resource.
"""
params: Dict[str, Any] = {"limit": self.resource_config.page_size}
def update_with_new_result_page(
response: ResourceFetchResponse,
) -> ResourceFetchResponse:
existing_cursor = response.updated_state
if self.resource_config.maybe_state_time_attribute is not None:
params[
f"{self.resource_config.maybe_state_time_attribute}[gte]"
] = existing_cursor.min_time_cursor.isoformat()
if existing_cursor.maybe_pagination_cursor is not None:
params["cursor"] = existing_cursor.maybe_pagination_cursor
response_json = req_session.get(
BASE_ORB_API_URL + self.resource_config.api_path,
headers=self.auth_header,
params=params,
).json()
resources = response_json["data"]
updated_pagination_cursor = (
response_json["pagination_metadata"]["next_cursor"]
if response_json["pagination_metadata"]["has_more"]
else None
)
if supports_incremental_syncs:
updated_response_cursor = existing_cursor.with_updated_pagination_result(
pagination_cursor=updated_pagination_cursor,
max_time_in_page=max(
map(
lambda resource: cast(
pendulum.DateTime,
pendulum.parse(
resource[
self.resource_config.maybe_state_time_attribute
]
),
),
resources,
),
default=None,
),
)
else:
assert existing_cursor.min_time_cursor == pendulum.from_timestamp(0)
assert existing_cursor.min_time_after_pagination_exhausted is None
updated_response_cursor = replace(
existing_cursor, maybe_pagination_cursor=updated_pagination_cursor
)
# Update passed in response with new resources
for resource in resources:
response.add_resource(resource)
response.updated_state = updated_response_cursor
return response
response = ResourceFetchResponse.init_with_cursor(
initial_cursor, resource_config=self.resource_config
)
updated_response = update_with_new_result_page(response)
num_pages_fetched = 1
# Fetch until there's nothing to paginate, or we've reached the max pages per sync
while not updated_response.updated_state.pagination_exhausted():
updated_response = update_with_new_result_page(response)
num_pages_fetched += 1
if num_pages_fetched == MAX_PAGES_PER_SYNC:
break
return updated_response
class NestedResourceFetcher(AbstractResourceFetcher[CursorWithSlices]):
"""
Used to fetch resources that require a full view of a parent
resource in order to be fetched. For example, to fetch all
Credit Ledger Entries, we need to first fetch all customers
"""
def fetch_slices(
self, pagination_cursor: Optional[str]
) -> Tuple[List[str], SimplePaginationCursor]:
all_slices_api_path = self.resource_config.all_slices_api_path
parent_resources, all_slices_cursor = self.fetch_resources_from_path(
all_slices_api_path, pagination_cursor=pagination_cursor
)
return (
list(map(lambda resource: resource["id"], parent_resources)),
all_slices_cursor,
)
def fetch_after_cursor(
self, initial_cursor: CursorWithSlices
) -> NestedResourceFetchResponse:
"""
Fetches all parent slices, and then for each of those slices, advances pagination
"""
logger.info(
f"Current number of slices: {len(initial_cursor.per_slice_cursor.keys())}"
)
response = NestedResourceFetchResponse.init_with_cursor(
initial_cursor, resource_config=self.resource_config
)
# If we haven't finished exhausting all slices, then don't try to fetch more slices.
paginating_existing_slices = False
if not response.get_updated_state().all_current_slices_exhausted():
logger.info(
"Continuing to fetch nested resources for the current set of slices..."
)
paginating_existing_slices = True
slice_ids = list(response.get_updated_state().per_slice_cursor.keys())
else:
# In the first invocation of this fetcher, we'll fetch some number of slices (falling into this block)
# and then in subsequent pagination invocations we'll exhaust them (falling into the above conditional).
# After the first set of slices is exhausted, we'll then fall into this block and fetch the rest of the slices.
# Finally, we'll want to start the whole cycle again... and at that point, pagination will be exhausted because
# we'll `all_current_slices_exhausted` and `has_more=False` on the top-level cursor.
logger.info("All current slices are exhausted; fetching more...")
slice_ids, all_slices_cursor = self.fetch_slices(
pagination_cursor=response.top_level_slices_pagination_cursor().current_cursor
)
if (
all_slices_cursor.current_cursor is None
and all_slices_cursor.has_more is False
):
logger.info(
"No more slices to fetch, so once this set of slices has been exhausted we'll start over..."
)
response.update_all_slices_cursor(all_slices_cursor)
slice_id_cursors = [
(slice_id, initial_cursor.cursor_for_slice(slice_id))
for slice_id in slice_ids
]
num_slices_fetched = 0
for slice_id, slice_cursor in slice_id_cursors:
if paginating_existing_slices and slice_cursor.pagination_exhausted():
# We can only skip exhausted slices when paginating_existing_slices, because we need to
# go past the min/existing cursor at least once to know whether pagination is exhausted
continue
# Only support direct fetchers for now
slice_resource_fetcher = DirectResourceFetcher(
self.secrets, self.resource_config.slice_resource_config(slice_id)
)
fetch_response: ResourceFetchResponse = (
slice_resource_fetcher.fetch_after_cursor(slice_cursor)
)
response.add_response_for_slice(slice_id, fetch_response)
num_slices_fetched += 1
logger.info(f"Fetched entries for {num_slices_fetched} slices")
return response
class ResourceEventBasedResourceFetcher(AbstractResourceFetcher[Cursor]):
def resource_event_resource_type_name(self):
return self.resource_config.resultant_schema_key
def resources_from_resource_event(self, event: Dict) -> List[Any]: