airbyte-source-iterable 1.0.2__tar.gz → 1.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. {airbyte_source_iterable-1.0.2 → airbyte_source_iterable-1.1.0}/PKG-INFO +1 -1
  2. {airbyte_source_iterable-1.0.2 → airbyte_source_iterable-1.1.0}/pyproject.toml +1 -1
  3. airbyte_source_iterable-1.1.0/source_iterable/components.py +122 -0
  4. {airbyte_source_iterable-1.0.2 → airbyte_source_iterable-1.1.0}/source_iterable/manifest.yaml +0 -59
  5. {airbyte_source_iterable-1.0.2 → airbyte_source_iterable-1.1.0}/source_iterable/source.py +2 -0
  6. {airbyte_source_iterable-1.0.2 → airbyte_source_iterable-1.1.0}/source_iterable/streams.py +218 -1
  7. airbyte_source_iterable-1.0.2/source_iterable/components.py +0 -126
  8. {airbyte_source_iterable-1.0.2 → airbyte_source_iterable-1.1.0}/.airbyte-pypi-readme.md +0 -0
  9. {airbyte_source_iterable-1.0.2 → airbyte_source_iterable-1.1.0}/source_iterable/__init__.py +0 -0
  10. {airbyte_source_iterable-1.0.2 → airbyte_source_iterable-1.1.0}/source_iterable/run.py +0 -0
  11. {airbyte_source_iterable-1.0.2 → airbyte_source_iterable-1.1.0}/source_iterable/schemas/campaigns.json +0 -0
  12. {airbyte_source_iterable-1.0.2 → airbyte_source_iterable-1.1.0}/source_iterable/schemas/campaigns_metrics.json +0 -0
  13. {airbyte_source_iterable-1.0.2 → airbyte_source_iterable-1.1.0}/source_iterable/schemas/channels.json +0 -0
  14. {airbyte_source_iterable-1.0.2 → airbyte_source_iterable-1.1.0}/source_iterable/schemas/email_bounce.json +0 -0
  15. {airbyte_source_iterable-1.0.2 → airbyte_source_iterable-1.1.0}/source_iterable/schemas/email_click.json +0 -0
  16. {airbyte_source_iterable-1.0.2 → airbyte_source_iterable-1.1.0}/source_iterable/schemas/email_complaint.json +0 -0
  17. {airbyte_source_iterable-1.0.2 → airbyte_source_iterable-1.1.0}/source_iterable/schemas/email_open.json +0 -0
  18. {airbyte_source_iterable-1.0.2 → airbyte_source_iterable-1.1.0}/source_iterable/schemas/email_send.json +0 -0
  19. {airbyte_source_iterable-1.0.2 → airbyte_source_iterable-1.1.0}/source_iterable/schemas/email_send_skip.json +0 -0
  20. {airbyte_source_iterable-1.0.2 → airbyte_source_iterable-1.1.0}/source_iterable/schemas/email_subscribe.json +0 -0
  21. {airbyte_source_iterable-1.0.2 → airbyte_source_iterable-1.1.0}/source_iterable/schemas/email_unsubscribe.json +0 -0
  22. {airbyte_source_iterable-1.0.2 → airbyte_source_iterable-1.1.0}/source_iterable/schemas/events.json +0 -0
  23. {airbyte_source_iterable-1.0.2 → airbyte_source_iterable-1.1.0}/source_iterable/schemas/list_users.json +0 -0
  24. {airbyte_source_iterable-1.0.2 → airbyte_source_iterable-1.1.0}/source_iterable/schemas/lists.json +0 -0
  25. {airbyte_source_iterable-1.0.2 → airbyte_source_iterable-1.1.0}/source_iterable/schemas/message_types.json +0 -0
  26. {airbyte_source_iterable-1.0.2 → airbyte_source_iterable-1.1.0}/source_iterable/schemas/metadata.json +0 -0
  27. {airbyte_source_iterable-1.0.2 → airbyte_source_iterable-1.1.0}/source_iterable/schemas/templates.json +0 -0
  28. {airbyte_source_iterable-1.0.2 → airbyte_source_iterable-1.1.0}/source_iterable/schemas/users.json +0 -0
  29. {airbyte_source_iterable-1.0.2 → airbyte_source_iterable-1.1.0}/source_iterable/slice_generators.py +0 -0
  30. {airbyte_source_iterable-1.0.2 → airbyte_source_iterable-1.1.0}/source_iterable/spec.json +0 -0
  31. {airbyte_source_iterable-1.0.2 → airbyte_source_iterable-1.1.0}/source_iterable/utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: airbyte-source-iterable
3
- Version: 1.0.2
3
+ Version: 1.1.0
4
4
  Summary: Source implementation for Iterable.
5
5
  Home-page: https://airbyte.com
6
6
  License: ELv2
@@ -3,7 +3,7 @@ requires = [ "poetry-core>=1.0.0",]
3
3
  build-backend = "poetry.core.masonry.api"
4
4
 
5
5
  [tool.poetry]
6
- version = "1.0.2"
6
+ version = "1.1.0"
7
7
  name = "airbyte-source-iterable"
8
8
  description = "Source implementation for Iterable."
9
9
  authors = [ "Airbyte <contact@airbyte.io>",]
@@ -0,0 +1,122 @@
1
+ #
2
+ # Copyright (c) 2023 Airbyte, Inc., all rights reserved.
3
+ #
4
+
5
+ from dataclasses import dataclass
6
+ from datetime import datetime
7
+ from typing import Any, Dict, Iterable, Mapping
8
+
9
+ import requests
10
+
11
+ from airbyte_cdk.sources.declarative.extractors.dpath_extractor import DpathExtractor
12
+
13
+
14
+ @dataclass
15
+ class EventsRecordExtractor(DpathExtractor):
16
+ common_fields = ("itblInternal", "_type", "createdAt", "email")
17
+
18
+ def extract_records(self, response: requests.Response) -> Iterable[Mapping[str, Any]]:
19
+ jsonl_records = super().extract_records(response=response)
20
+ for record_dict in jsonl_records:
21
+ record_dict_common_fields = {}
22
+ for field in self.common_fields:
23
+ record_dict_common_fields[field] = record_dict.pop(field, None)
24
+ yield {**record_dict_common_fields, "data": record_dict}
25
+
26
+
27
+ # Fields documented by Iterable as managed or used for sending messages.
28
+ # Reference: https://support.iterable.com/hc/en-us/articles/217744303
29
+ STANDARD_USER_FIELDS = frozenset(
30
+ {
31
+ # Unique identifiers
32
+ "email",
33
+ "userId",
34
+ # Managed by Iterable
35
+ "emailListIds",
36
+ "itblUserId",
37
+ "knownLitigatorFilter",
38
+ "profileUpdatedAt",
39
+ "receivedSMSDisclaimer",
40
+ "signupDate",
41
+ "signupSource",
42
+ "subscribedMessageTypeIds",
43
+ "unsubscribedChannelIds",
44
+ "unsubscribedMessageTypeIds",
45
+ "userListIds",
46
+ # Geolocation fields populated by Iterable from the user's IP
47
+ "city",
48
+ "region",
49
+ # Fields used for sending messages
50
+ "country",
51
+ "devices",
52
+ "ip",
53
+ "locale",
54
+ "phoneNumber",
55
+ "profile",
56
+ "timeZone",
57
+ "whatsAppPhoneNumber",
58
+ # Iterable-internal fields (the export returns them as flat dotted keys)
59
+ "itblInternal.emailDomain",
60
+ "itblInternal.phoneCountry",
61
+ "itblInternal.phoneType",
62
+ "itblInternal.documentCreatedAt",
63
+ "itblInternal.documentUpdatedAt",
64
+ "itblInternal.isUnknownUser",
65
+ "itblDS.brandAffinityLabel",
66
+ "itblDS.predictiveGoals",
67
+ }
68
+ )
69
+
70
+ # The export API emits these as space-separated timestamps ("2021-04-14 16:52:31 +00:00")
71
+ # while the schema declares format: date-time (RFC3339); normalize so typed destinations
72
+ # do not null the values into _airbyte_meta.changes.
73
+ USER_TIMESTAMP_FIELDS = (
74
+ "signupDate",
75
+ "profileUpdatedAt",
76
+ "itblInternal.documentCreatedAt",
77
+ "itblInternal.documentUpdatedAt",
78
+ )
79
+ _USER_TIMESTAMP_FORMATS = (
80
+ "%Y-%m-%d %H:%M:%S %z",
81
+ "%Y-%m-%dT%H:%M:%S%z",
82
+ "%Y-%m-%d %H:%M:%S.%f %z",
83
+ "%Y-%m-%dT%H:%M:%S.%f%z",
84
+ )
85
+
86
+
87
+ def normalize_user_timestamp(value: Any) -> Any:
88
+ """Rewrite Iterable's space-separated timestamps to RFC 3339. Other values pass through."""
89
+ if not isinstance(value, str):
90
+ return value
91
+ for fmt in _USER_TIMESTAMP_FORMATS:
92
+ try:
93
+ return datetime.strptime(value, fmt).isoformat()
94
+ except ValueError:
95
+ continue
96
+ return value
97
+
98
+
99
+ def standardize_user_record(record: Mapping[str, Any]) -> Dict[str, Any]:
100
+ """Keep the fields Iterable manages at the top level and move everything else under `data`.
101
+
102
+ Standard fields are those documented at:
103
+ https://support.iterable.com/hc/en-us/articles/217744303-User-Profile-Fields-Used-by-Iterable
104
+
105
+ The Iterable export API flattens nested objects into dotted keys (e.g.
106
+ `itblInternal.emailDomain`), so Iterable-internal fields are listed in their flat
107
+ dotted form. Keys not listed here - including Iterable-internal dotted keys that
108
+ are not declared in the stream schema - are routed into `data` so destinations
109
+ that materialize only declared fields never drop them.
110
+ """
111
+ standard: Dict[str, Any] = {}
112
+ data: Dict[str, Any] = {}
113
+ for key, value in record.items():
114
+ if key in STANDARD_USER_FIELDS:
115
+ standard[key] = value
116
+ else:
117
+ data[key] = value
118
+ for field in USER_TIMESTAMP_FIELDS:
119
+ if field in standard:
120
+ standard[field] = normalize_user_timestamp(standard[field])
121
+ standard["data"] = data
122
+ return standard
@@ -300,65 +300,6 @@ streams:
300
300
  - results
301
301
  partition_router: []
302
302
  primary_key: []
303
- - name: users
304
- type: DeclarativeStream
305
- retriever:
306
- type: SimpleRetriever
307
- decoder:
308
- type: JsonlDecoder
309
- paginator:
310
- type: NoPagination
311
- requester:
312
- path: export/data.json
313
- type: HttpRequester
314
- url_base: "{{ 'https://api.eu.iterable.com/api/' if config.get('region', 'US') == 'EU' else 'https://api.iterable.com/api/' }}"
315
- http_method: GET
316
- authenticator:
317
- type: ApiKeyAuthenticator
318
- api_token: "{{ config['api_key'] }}"
319
- inject_into:
320
- type: RequestOption
321
- field_name: Api-Key
322
- inject_into: header
323
- request_headers: {}
324
- request_body_json: {}
325
- request_parameters:
326
- stream: "True"
327
- dataTypeName: user
328
- record_selector:
329
- type: RecordSelector
330
- extractor:
331
- class_name: source_iterable.components.UsersRecordExtractor
332
- field_path: []
333
- partition_router: []
334
- primary_key: []
335
- incremental_sync:
336
- step: P90D
337
- type: DatetimeBasedCursor
338
- cursor_field: profileUpdatedAt
339
- end_datetime:
340
- type: MinMaxDatetime
341
- datetime: "{{ config['end_date'] if config['end_date'] else now_utc().strftime('%Y-%m-%dT%H:%M:%SZ') }}"
342
- datetime_format: "%Y-%m-%dT%H:%M:%SZ"
343
- start_datetime:
344
- type: MinMaxDatetime
345
- datetime: "{{ config['start_date'] }}"
346
- datetime_format: "%Y-%m-%dT%H:%M:%SZ"
347
- datetime_format: "%Y-%m-%d %H:%M:%S"
348
- end_time_option:
349
- type: RequestOption
350
- field_name: endDateTime
351
- inject_into: request_parameter
352
- start_time_option:
353
- type: RequestOption
354
- field_name: startDateTime
355
- inject_into: request_parameter
356
- cursor_granularity: PT1S
357
- cursor_datetime_formats:
358
- - "%Y-%m-%d %H:%M:%S %z"
359
- - "%Y-%m-%dT%H:%M:%S%z"
360
- - "%Y-%m-%d %H:%M:%S.%f %z"
361
- - "%Y-%m-%dT%H:%M:%S.%f%z"
362
303
  - name: events
363
304
  primary_key: []
364
305
  retriever:
@@ -42,6 +42,7 @@ from .streams import (
42
42
  SmsSendSkip,
43
43
  SmsUsageInfo,
44
44
  Templates,
45
+ Users,
45
46
  WebPushClick,
46
47
  WebPushSend,
47
48
  WebPushSendSkip,
@@ -78,6 +79,7 @@ class SourceIterable(YamlDeclarativeSource):
78
79
  [
79
80
  CampaignsMetrics(authenticator=authenticator, region=region, **campaigns_date_range),
80
81
  Templates(authenticator=authenticator, region=region, **date_range),
82
+ Users(authenticator=authenticator, region=region, **date_range),
81
83
  EmailBounce(authenticator=authenticator, region=region, **date_range),
82
84
  EmailClick(authenticator=authenticator, region=region, **date_range),
83
85
  EmailComplaint(authenticator=authenticator, region=region, **date_range),
@@ -3,10 +3,13 @@
3
3
  #
4
4
 
5
5
  import csv
6
+ import gzip
6
7
  import json
8
+ import time
7
9
  from abc import ABC, abstractmethod
8
10
  from io import StringIO
9
11
  from typing import Any, Dict, Iterable, List, Mapping, MutableMapping, Optional, Union
12
+ from urllib.parse import urlsplit
10
13
 
11
14
  import pendulum
12
15
  import requests
@@ -21,6 +24,7 @@ from airbyte_cdk.sources.streams.core import CheckpointMixin, package_name_from_
21
24
  from airbyte_cdk.sources.streams.http import HttpStream
22
25
  from airbyte_cdk.sources.streams.http.exceptions import DefaultBackoffException, UserDefinedBackoffException
23
26
  from airbyte_cdk.sources.utils.schema_helpers import ResourceSchemaLoader
27
+ from source_iterable.components import standardize_user_record
24
28
  from source_iterable.slice_generators import AdjustableSliceGenerator, RangeSliceGenerator, StreamSlice
25
29
  from source_iterable.utils import dateutil_parse
26
30
 
@@ -267,7 +271,7 @@ class IterableExportStream(IterableStream, CheckpointMixin, ABC):
267
271
  stream_state = stream_state or {}
268
272
  start_datetime = self._start_date
269
273
  if stream_state.get(self.cursor_field):
270
- start_datetime = pendulum.parse(stream_state[self.cursor_field])
274
+ start_datetime = self._field_to_datetime(stream_state[self.cursor_field])
271
275
  return start_datetime
272
276
 
273
277
  def _get_effective_end_date(self) -> DateTime:
@@ -626,6 +630,219 @@ class HostedUnsubscribeClick(IterableExportEventsStreamAdjustableRange):
626
630
  data_field = "hostedUnsubscribeClick"
627
631
 
628
632
 
633
+ class _ExportTruncated(Exception):
634
+ """An export job exceeded Iterable's 100 GB export limit; carries the job id."""
635
+
636
+
637
+ class Users(IterableExportStreamRanged):
638
+ """
639
+ Exports user profiles through Iterable's asynchronous Export API instead of the synchronous
640
+ `GET /api/export/data.json` call, which Iterable closes before a large user export finishes.
641
+
642
+ For every 90-day slice the stream starts an export job (`POST /api/export/start`), polls
643
+ `GET /api/export/{jobId}/files` until the job completes, pages through the files the job
644
+ produced and downloads each one. The files hold one JSON object per line. Every record goes
645
+ through `standardize_user_record`, so the stream keeps the record shape of version 1.0.0:
646
+ fields Iterable manages stay at the top level, everything else lands under `data`.
647
+
648
+ Iterable allows one start or poll request per second per organization and runs four exports
649
+ at a time; extra jobs queue. Download URLs expire after 30 minutes, so the remaining
650
+ files are listed again once a page is older than `download_url_max_age_seconds`. An export
651
+ over Iterable's 100 GB limit is truncated; its window is split in half and exported again.
652
+ Details: https://api.iterable.com/api/docs#export_startExport
653
+ """
654
+
655
+ data_field = "user"
656
+ cursor_field = "profileUpdatedAt"
657
+ http_method = "POST"
658
+
659
+ poll_interval_seconds = 15
660
+ max_wait_seconds = 4 * 60 * 60
661
+ download_attempts = 3
662
+ download_url_max_age_seconds = 20 * 60
663
+ export_timestamp_format = "%Y-%m-%d %H:%M:%S"
664
+
665
+ def path(self, **kwargs) -> str:
666
+ return "export/start"
667
+
668
+ def request_params(self, **kwargs) -> MutableMapping[str, Any]:
669
+ # The export window travels in the JSON body, not in the query string.
670
+ return {}
671
+
672
+ def request_body_json(
673
+ self,
674
+ stream_state: Optional[Mapping[str, Any]] = None,
675
+ stream_slice: Optional[StreamSlice] = None,
676
+ next_page_token: Optional[Mapping[str, Any]] = None,
677
+ ) -> Optional[Mapping[str, Any]]:
678
+ return {
679
+ "outputFormat": "application/x-json-stream",
680
+ "dataTypeName": self.data_field,
681
+ "startDateTime": stream_slice.start_date.strftime(self.export_timestamp_format),
682
+ "endDateTime": stream_slice.end_date.strftime(self.export_timestamp_format),
683
+ }
684
+
685
+ def read_records(
686
+ self,
687
+ sync_mode: SyncMode,
688
+ cursor_field: List[str] = None,
689
+ stream_slice: Mapping[str, Any] = None,
690
+ stream_state: Mapping[str, Any] = None,
691
+ ) -> Iterable[Mapping[str, Any]]:
692
+ # Same checkpoint rules as IterableExportStream.read_records, but the cursor stays a string
693
+ # in the emitted record (RFC 3339 after standardization) and is only parsed for comparison.
694
+ if not hasattr(self, "_sync_start_cursor"):
695
+ initial_state = getattr(self, "_state", None) or {}
696
+ state_value = initial_state.get(self.cursor_field)
697
+ self._sync_start_cursor = self._field_to_datetime(state_value) if state_value else None
698
+ # The wait budget runs from the last record emitted, not per job: the platform's heartbeat only counts
699
+ # records and state, and a truncated job followed by its halves emits nothing in between.
700
+ self._quiet_since = time.monotonic()
701
+ for record in self._read_window(sync_mode, cursor_field, stream_slice, stream_state):
702
+ cursor_value = record.get(self.cursor_field)
703
+ if cursor_value is None:
704
+ self._quiet_since = time.monotonic()
705
+ yield record
706
+ continue
707
+ cursor_datetime = self._field_to_datetime(cursor_value)
708
+ current_state = getattr(self, "_state", None) or {}
709
+ self.state = self._get_updated_state(current_state, {self.cursor_field: cursor_datetime})
710
+ if self._sync_start_cursor is not None and cursor_datetime <= self._sync_start_cursor:
711
+ continue
712
+ self._quiet_since = time.monotonic()
713
+ yield record
714
+
715
+ def _read_window(
716
+ self, sync_mode: SyncMode, cursor_field: List[str], stream_slice: StreamSlice, stream_state: Mapping[str, Any]
717
+ ) -> Iterable[Mapping[str, Any]]:
718
+ try:
719
+ yield from super(IterableExportStream, self).read_records(
720
+ sync_mode, cursor_field=cursor_field, stream_slice=stream_slice, stream_state=stream_state
721
+ )
722
+ except _ExportTruncated as truncated:
723
+ # Raised before any file of the job is read, so no record of this window was emitted yet.
724
+ start, end = stream_slice.start_date, stream_slice.end_date
725
+ if (end - start).total_seconds() < 2:
726
+ raise AirbyteTracedException(
727
+ message=(
728
+ f"Iterable truncated export job {truncated} for the users stream: the profiles updated between {start} and "
729
+ f"{end} exceed Iterable's 100 GB export limit, and the window cannot be split further. Contact Iterable "
730
+ "support, or deselect the users stream to sync the other streams."
731
+ ),
732
+ internal_message=f"export job {truncated} truncated for a window under 2 seconds",
733
+ failure_type=FailureType.system_error,
734
+ )
735
+ middle = start + (end - start) / 2
736
+ self.logger.warning(f"Iterable truncated export job {truncated} (over 100 GB); exporting {start} to {end} in two halves.")
737
+ for half in (StreamSlice(start, middle), StreamSlice(middle, end)):
738
+ yield from self._read_window(sync_mode, cursor_field, half, stream_state)
739
+
740
+ def parse_response(self, response: requests.Response, **kwargs) -> Iterable[Mapping]:
741
+ job_id = response.json()["jobId"]
742
+ self.logger.info(f"Started Iterable export job {job_id} for the users stream")
743
+ for file_url in self._wait_for_export_files(job_id):
744
+ yield from self._read_export_file(file_url)
745
+
746
+ def _poll_export(self, job_id: Any, start_after: Optional[str] = None) -> Mapping[str, Any]:
747
+ _, response = self._http_client.send_request(
748
+ http_method="GET",
749
+ url=f"{self.url_base}export/{job_id}/files",
750
+ request_kwargs={"timeout": (60, 300)},
751
+ params={"startAfter": start_after} if start_after else None,
752
+ dedupe_query_params=True,
753
+ )
754
+ # IterableStream.should_retry gives up after three GenericError responses per slice; count them per poll.
755
+ self._slice_retry = 0
756
+ return response.json()
757
+
758
+ def _cancel_export(self, job_id: Any) -> None:
759
+ """Best effort: a job left behind keeps one of the organization's four export slots."""
760
+ try:
761
+ requests.delete(f"{self.url_base}export/{job_id}", auth=self._cred, timeout=(60, 300))
762
+ except requests.RequestException as error:
763
+ self.logger.warning(f"Could not cancel Iterable export job {job_id}: {error}")
764
+
765
+ def _wait_for_export_files(self, job_id: Any) -> Iterable[str]:
766
+ """Poll the job until it completes, then yield the download URL of every file it produced."""
767
+ deadline = self._quiet_since + self.max_wait_seconds
768
+ status = self._poll_export(job_id)
769
+ # A running job can go back to enqueued when Iterable restarts it; it keeps its progress.
770
+ while status.get("jobState") in ("enqueued", "running"):
771
+ if time.monotonic() >= deadline:
772
+ self._cancel_export(job_id)
773
+ raise AirbyteTracedException(
774
+ message=(
775
+ f"Iterable export job {job_id} for the users stream did not finish within "
776
+ f"{self.max_wait_seconds} seconds of the last record read. Retry the sync; Iterable runs four "
777
+ "exports at a time and queues the rest."
778
+ ),
779
+ internal_message=f"job {job_id} still {status.get('jobState')} after {self.max_wait_seconds}s",
780
+ failure_type=FailureType.transient_error,
781
+ )
782
+ time.sleep(self.poll_interval_seconds)
783
+ status = self._poll_export(job_id)
784
+ if status.get("jobState") != "completed":
785
+ raise AirbyteTracedException(
786
+ message=f"Iterable export job {job_id} for the users stream ended in state '{status.get('jobState')}'. Retry the sync.",
787
+ internal_message=f"export job {job_id}: {status}",
788
+ failure_type=FailureType.transient_error,
789
+ )
790
+ if status.get("exportTruncated"):
791
+ raise _ExportTruncated(job_id)
792
+ files = status.get("files") or []
793
+ listed_at = time.monotonic()
794
+ while files:
795
+ export_file = files.pop(0)
796
+ yield export_file["url"]
797
+ # List again after the last file read when the page is used up or its URLs near expiry.
798
+ if not files or time.monotonic() - listed_at > self.download_url_max_age_seconds:
799
+ files = self._poll_export(job_id, start_after=export_file["file"]).get("files") or []
800
+ listed_at = time.monotonic()
801
+
802
+ def _download_export_file(self, url: str) -> requests.Response:
803
+ """Fetch a file through its pre-signed URL. The API key must not be sent to the file host."""
804
+ last_error: Optional[Exception] = None
805
+ for attempt in range(1, self.download_attempts + 1):
806
+ try:
807
+ response = requests.get(url, timeout=(60, 300), headers={"Accept-Encoding": "identity"})
808
+ if response.status_code == 429 or response.status_code >= 500:
809
+ last_error = HTTPError(f"HTTP {response.status_code} while downloading an export file", response=response)
810
+ elif not response.ok:
811
+ raise AirbyteTracedException(
812
+ message=(
813
+ f"Iterable's file host refused a users export file (HTTP {response.status_code}). "
814
+ "Its download link may have expired. Retry the sync."
815
+ ),
816
+ internal_message=f"export file download returned HTTP {response.status_code}",
817
+ failure_type=FailureType.transient_error,
818
+ )
819
+ else:
820
+ return response
821
+ except (requests.ConnectionError, requests.Timeout) as error:
822
+ last_error = error
823
+ if attempt < self.download_attempts:
824
+ time.sleep(self.retry_factor * attempt)
825
+ # The query string of a pre-signed URL is a credential; keep it out of the error.
826
+ error, signature = str(last_error), urlsplit(url).query
827
+ raise AirbyteTracedException(
828
+ message=f"Could not download an Iterable users export file after {self.download_attempts} attempts.",
829
+ internal_message=error.replace(signature, "<signature>") if signature else error,
830
+ failure_type=FailureType.transient_error,
831
+ )
832
+
833
+ def _read_export_file(self, url: str) -> Iterable[Mapping[str, Any]]:
834
+ # Iterable caps each export file at 10 MB, so a file is read whole. Compressed files are
835
+ # recognized by the gzip magic bytes rather than by name or header.
836
+ content = self._download_export_file(url).content
837
+ if content[:2] == b"\x1f\x8b":
838
+ content = gzip.decompress(content)
839
+ for line in content.splitlines():
840
+ line = line.strip()
841
+ if not line:
842
+ continue
843
+ yield standardize_user_record(json.loads(line))
844
+
845
+
629
846
  class Templates(IterableExportStreamRanged):
630
847
  data_field = "templates"
631
848
  template_types = ["Base", "Blast", "Triggered", "Workflow"]
@@ -1,126 +0,0 @@
1
- #
2
- # Copyright (c) 2023 Airbyte, Inc., all rights reserved.
3
- #
4
-
5
- from dataclasses import dataclass
6
- from datetime import datetime
7
- from typing import Any, Iterable, Mapping
8
-
9
- import requests
10
-
11
- from airbyte_cdk.sources.declarative.extractors.dpath_extractor import DpathExtractor
12
-
13
-
14
- @dataclass
15
- class EventsRecordExtractor(DpathExtractor):
16
- common_fields = ("itblInternal", "_type", "createdAt", "email")
17
-
18
- def extract_records(self, response: requests.Response) -> Iterable[Mapping[str, Any]]:
19
- jsonl_records = super().extract_records(response=response)
20
- for record_dict in jsonl_records:
21
- record_dict_common_fields = {}
22
- for field in self.common_fields:
23
- record_dict_common_fields[field] = record_dict.pop(field, None)
24
- yield {**record_dict_common_fields, "data": record_dict}
25
-
26
-
27
- @dataclass
28
- class UsersRecordExtractor(DpathExtractor):
29
- """Extracts user records, keeping standard Iterable-managed fields at the top level
30
- and placing all custom/tenant-specific dataFields into a generic `data` object.
31
-
32
- Standard fields are those documented at:
33
- https://support.iterable.com/hc/en-us/articles/217744303-User-Profile-Fields-Used-by-Iterable
34
-
35
- The Iterable export API flattens nested objects into dotted keys (e.g.
36
- `itblInternal.emailDomain`), so Iterable-internal fields are listed in their flat
37
- dotted form. Keys not listed here - including Iterable-internal dotted keys that
38
- are not declared in the stream schema - are routed into `data` so destinations
39
- that materialize only declared fields never drop them.
40
- """
41
-
42
- # Fields documented by Iterable as managed or used for sending messages.
43
- # Reference: https://support.iterable.com/hc/en-us/articles/217744303
44
- STANDARD_FIELDS = frozenset(
45
- {
46
- # Unique identifiers
47
- "email",
48
- "userId",
49
- # Managed by Iterable
50
- "emailListIds",
51
- "itblUserId",
52
- "knownLitigatorFilter",
53
- "profileUpdatedAt",
54
- "receivedSMSDisclaimer",
55
- "signupDate",
56
- "signupSource",
57
- "subscribedMessageTypeIds",
58
- "unsubscribedChannelIds",
59
- "unsubscribedMessageTypeIds",
60
- "userListIds",
61
- # Geolocation fields populated by Iterable from the user's IP
62
- "city",
63
- "region",
64
- # Fields used for sending messages
65
- "country",
66
- "devices",
67
- "ip",
68
- "locale",
69
- "phoneNumber",
70
- "profile",
71
- "timeZone",
72
- "whatsAppPhoneNumber",
73
- # Iterable-internal fields (the export returns them as flat dotted keys)
74
- "itblInternal.emailDomain",
75
- "itblInternal.phoneCountry",
76
- "itblInternal.phoneType",
77
- "itblInternal.documentCreatedAt",
78
- "itblInternal.documentUpdatedAt",
79
- "itblInternal.isUnknownUser",
80
- "itblDS.brandAffinityLabel",
81
- "itblDS.predictiveGoals",
82
- }
83
- )
84
-
85
- # The export API emits these as space-separated timestamps ("2021-04-14 16:52:31 +00:00")
86
- # while the schema declares format: date-time (RFC3339); normalize so typed destinations
87
- # do not null the values into _airbyte_meta.changes.
88
- TIMESTAMP_FIELDS = (
89
- "signupDate",
90
- "profileUpdatedAt",
91
- "itblInternal.documentCreatedAt",
92
- "itblInternal.documentUpdatedAt",
93
- )
94
- _TIMESTAMP_FORMATS = (
95
- "%Y-%m-%d %H:%M:%S %z",
96
- "%Y-%m-%dT%H:%M:%S%z",
97
- "%Y-%m-%d %H:%M:%S.%f %z",
98
- "%Y-%m-%dT%H:%M:%S.%f%z",
99
- )
100
-
101
- @classmethod
102
- def _normalize_timestamp(cls, value: Any) -> Any:
103
- if not isinstance(value, str):
104
- return value
105
- for fmt in cls._TIMESTAMP_FORMATS:
106
- try:
107
- return datetime.strptime(value, fmt).isoformat()
108
- except ValueError:
109
- continue
110
- return value
111
-
112
- def extract_records(self, response: requests.Response) -> Iterable[Mapping[str, Any]]:
113
- jsonl_records = super().extract_records(response=response)
114
- for record_dict in jsonl_records:
115
- standard: dict[str, Any] = {}
116
- data: dict[str, Any] = {}
117
- for key, value in record_dict.items():
118
- if key in self.STANDARD_FIELDS:
119
- standard[key] = value
120
- else:
121
- data[key] = value
122
- for field in self.TIMESTAMP_FIELDS:
123
- if field in standard:
124
- standard[field] = self._normalize_timestamp(standard[field])
125
- standard["data"] = data
126
- yield standard