|
37 | 37 | from dataclasses import asdict, dataclass |
38 | 38 | from enum import Enum |
39 | 39 | from functools import lru_cache |
40 | | -from typing import TYPE_CHECKING, Any |
| 40 | +from pathlib import Path |
| 41 | +from typing import TYPE_CHECKING, Any, cast |
41 | 42 |
|
42 | 43 | import requests |
43 | 44 | import ulid |
| 45 | +import yaml |
44 | 46 |
|
45 | 47 | from airbyte import exceptions as exc |
46 | 48 | from airbyte._util import meta |
|
52 | 54 | from airbyte.sources.base import Source |
53 | 55 |
|
54 | 56 |
|
| 57 | +DEBUG = True |
| 58 | +"""Enable debug mode for telemetry code.""" |
| 59 | + |
| 60 | + |
55 | 61 | HASH_SEED = "PyAirbyte:" |
56 | 62 | """Additional seed for randomizing one-way hashed strings.""" |
57 | 63 |
|
|
73 | 79 | DO_NOT_TRACK = "DO_NOT_TRACK" |
74 | 80 | """Environment variable to opt-out of telemetry.""" |
75 | 81 |
|
| 82 | +_ENV_ANALYTICS_ID = "AIRBYTE_ANALYTICS_ID" # Allows user to override the anonymous user ID |
| 83 | +_ANALYTICS_FILE = Path.home() / ".airbyte" / "analytics.yml" |
| 84 | +_ANALYTICS_ID: str | bool | None = None |
| 85 | + |
| 86 | + |
| 87 | +def _setup_analytics() -> str | bool: |
| 88 | + """Set up the analytics file if it doesn't exist. |
| 89 | +
|
| 90 | + Return the anonymous user ID or False if the user has opted out. |
| 91 | + """ |
| 92 | + anonymous_user_id: str | None = None |
| 93 | + issues: list[str] = [] |
| 94 | + |
| 95 | + if os.environ.get(DO_NOT_TRACK): |
| 96 | + # User has opted out of tracking. |
| 97 | + return False |
| 98 | + |
| 99 | + if _ENV_ANALYTICS_ID in os.environ: |
| 100 | + # If the user has chosen to override their analytics ID, use that value and |
| 101 | + # remember it for future invocations. |
| 102 | + anonymous_user_id = os.environ[_ENV_ANALYTICS_ID] |
| 103 | + |
| 104 | + if not _ANALYTICS_FILE.exists(): |
| 105 | + # This is a one-time message to inform the user that we are tracking anonymous usage stats. |
| 106 | + print( |
| 107 | + "Anonymous usage reporting is enabled. For more information or to opt out, please" |
| 108 | + " see https://docs.airbyte.io/pyairbyte/anonymized-usage-statistics" |
| 109 | + ) |
| 110 | + |
| 111 | + if _ANALYTICS_FILE.exists(): |
| 112 | + analytics_text = _ANALYTICS_FILE.read_text() |
| 113 | + try: |
| 114 | + analytics: dict = yaml.safe_load(analytics_text) |
| 115 | + except Exception as ex: |
| 116 | + issues += f"File appears corrupted. Error was: {ex!s}" |
| 117 | + |
| 118 | + if analytics and "anonymous_user_id" in analytics: |
| 119 | + # The analytics ID was successfully located. |
| 120 | + if not anonymous_user_id: |
| 121 | + return analytics["anonymous_user_id"] |
| 122 | + |
| 123 | + if anonymous_user_id == analytics["anonymous_user_id"]: |
| 124 | + # Values match, no need to update the file. |
| 125 | + return analytics["anonymous_user_id"] |
| 126 | + |
| 127 | + issues.append("Provided analytics ID did not match the file. Rewriting the file.") |
| 128 | + print( |
| 129 | + f"Received a user-provided analytics ID override in the '{_ENV_ANALYTICS_ID}' " |
| 130 | + "environment variable." |
| 131 | + ) |
| 132 | + |
| 133 | + # File is missing, incomplete, or stale. Create a new one. |
| 134 | + anonymous_user_id = anonymous_user_id or str(ulid.ULID()) |
| 135 | + try: |
| 136 | + _ANALYTICS_FILE.parent.mkdir(exist_ok=True, parents=True) |
| 137 | + _ANALYTICS_FILE.write_text( |
| 138 | + "# This file is used by PyAirbyte to track anonymous usage statistics.\n" |
| 139 | + "# For more information or to opt out, please see\n" |
| 140 | + "# - https://docs.airbyte.com/operator-guides/telemetry\n" |
| 141 | + f"anonymous_user_id: {anonymous_user_id}\n" |
| 142 | + ) |
| 143 | + except Exception: |
| 144 | + # Failed to create the analytics file. Likely due to a read-only filesystem. |
| 145 | + issues.append("Failed to write the analytics file. Check filesystem permissions.") |
| 146 | + pass |
| 147 | + |
| 148 | + if DEBUG and issues: |
| 149 | + nl = "\n" |
| 150 | + print(f"One or more issues occurred when configuring usage tracking:\n{nl.join(issues)}") |
| 151 | + |
| 152 | + return anonymous_user_id |
| 153 | + |
| 154 | + |
| 155 | +def _get_analytics_id() -> str | None: |
| 156 | + result: str | bool | None = _ANALYTICS_ID |
| 157 | + if result is None: |
| 158 | + result = _setup_analytics() |
| 159 | + |
| 160 | + if result is False: |
| 161 | + return None |
| 162 | + |
| 163 | + return cast(str, result) |
| 164 | + |
| 165 | + |
| 166 | +_ANALYTICS_ID = _get_analytics_id() |
| 167 | + |
76 | 168 |
|
77 | 169 | class SyncState(str, Enum): |
78 | 170 | STARTED = "started" |
@@ -174,7 +266,7 @@ def send_telemetry( |
174 | 266 | "https://api.segment.io/v1/track", |
175 | 267 | auth=(PYAIRBYTE_APP_TRACKING_KEY, ""), |
176 | 268 | json={ |
177 | | - "anonymousId": "airbyte-lib-user", |
| 269 | + "anonymousId": _get_analytics_id(), |
178 | 270 | "event": "sync", |
179 | 271 | "properties": payload_props, |
180 | 272 | "timestamp": datetime.datetime.utcnow().isoformat(), # noqa: DTZ003 |
|
0 commit comments