traqio 0.1.0__py3-none-any.whl
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.
- traqio/__init__.py +58 -0
- traqio/_client.py +762 -0
- traqio/_version.py +1 -0
- traqio/py.typed +0 -0
- traqio-0.1.0.dist-info/METADATA +277 -0
- traqio-0.1.0.dist-info/RECORD +8 -0
- traqio-0.1.0.dist-info/WHEEL +4 -0
- traqio-0.1.0.dist-info/licenses/LICENSE +21 -0
traqio/__init__.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""Traqio server SDK for Python — the server half of Traqio's web SDK.
|
|
2
|
+
|
|
3
|
+
The browser half (``@traqio/web``) keeps the trackID, the ad click id the visitor
|
|
4
|
+
landed with. The conversion that counts — a sign-up, a purchase — happens on your
|
|
5
|
+
backend, where the user id is known: this package reports it, with the trackID, and
|
|
6
|
+
Traqio ties the two together. It authenticates with a SECRET server key, which is
|
|
7
|
+
what allows a conversion to be tied to a click: keep it on the server.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from ._client import (
|
|
11
|
+
SOURCE_COOKIE,
|
|
12
|
+
TRACK_ID_COOKIE,
|
|
13
|
+
AnalyticsResult,
|
|
14
|
+
Attribution,
|
|
15
|
+
Result,
|
|
16
|
+
Traqio,
|
|
17
|
+
TraqioError,
|
|
18
|
+
clean_event_name,
|
|
19
|
+
clean_group_key,
|
|
20
|
+
clean_group_type,
|
|
21
|
+
clean_groups,
|
|
22
|
+
clean_props,
|
|
23
|
+
clean_traits,
|
|
24
|
+
exposure_props,
|
|
25
|
+
hash_email,
|
|
26
|
+
parse_source_cookie,
|
|
27
|
+
source_from_cookie_header,
|
|
28
|
+
source_from_request,
|
|
29
|
+
track_id_from_cookie_header,
|
|
30
|
+
track_id_from_request,
|
|
31
|
+
web_context_from_request,
|
|
32
|
+
)
|
|
33
|
+
from ._version import __version__
|
|
34
|
+
|
|
35
|
+
__all__ = [
|
|
36
|
+
"SOURCE_COOKIE",
|
|
37
|
+
"TRACK_ID_COOKIE",
|
|
38
|
+
"AnalyticsResult",
|
|
39
|
+
"Attribution",
|
|
40
|
+
"Result",
|
|
41
|
+
"Traqio",
|
|
42
|
+
"TraqioError",
|
|
43
|
+
"__version__",
|
|
44
|
+
"clean_event_name",
|
|
45
|
+
"clean_group_key",
|
|
46
|
+
"clean_group_type",
|
|
47
|
+
"clean_groups",
|
|
48
|
+
"clean_props",
|
|
49
|
+
"clean_traits",
|
|
50
|
+
"exposure_props",
|
|
51
|
+
"hash_email",
|
|
52
|
+
"parse_source_cookie",
|
|
53
|
+
"source_from_cookie_header",
|
|
54
|
+
"source_from_request",
|
|
55
|
+
"track_id_from_cookie_header",
|
|
56
|
+
"track_id_from_request",
|
|
57
|
+
"web_context_from_request",
|
|
58
|
+
]
|
traqio/_client.py
ADDED
|
@@ -0,0 +1,762 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
import time
|
|
8
|
+
import urllib.error
|
|
9
|
+
import urllib.request
|
|
10
|
+
import math
|
|
11
|
+
import re
|
|
12
|
+
import uuid
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
from datetime import datetime, timezone
|
|
15
|
+
from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Tuple, Union
|
|
16
|
+
from urllib.parse import parse_qsl, unquote
|
|
17
|
+
|
|
18
|
+
from ._version import __version__
|
|
19
|
+
|
|
20
|
+
#: The cookie ``@traqio/web`` writes on your registrable domain, holding the trackID.
|
|
21
|
+
TRACK_ID_COOKIE = "traq_click"
|
|
22
|
+
|
|
23
|
+
#: The cookie ``@traqio/web`` writes next to it, holding where the visitor came from
|
|
24
|
+
#: when no Traqio link brought them: the landing's ``utm_*``, ``gclid`` / ``fbclid`` /
|
|
25
|
+
#: ``ttclid``, the referring site's host — as a query string.
|
|
26
|
+
SOURCE_COOKIE = "traq_src"
|
|
27
|
+
|
|
28
|
+
#: ``(query-string parameter, API field)`` — the only fields Traqio reads in a source.
|
|
29
|
+
_SOURCE_FIELDS: Tuple[Tuple[str, str], ...] = (
|
|
30
|
+
("utm_source", "utmSource"),
|
|
31
|
+
("utm_medium", "utmMedium"),
|
|
32
|
+
("utm_campaign", "utmCampaign"),
|
|
33
|
+
("utm_content", "utmContent"),
|
|
34
|
+
("utm_term", "utmTerm"),
|
|
35
|
+
("referrer", "referrer"),
|
|
36
|
+
("gclid", "gclid"),
|
|
37
|
+
("fbclid", "fbclid"),
|
|
38
|
+
("ttclid", "ttclid"),
|
|
39
|
+
)
|
|
40
|
+
_MAX_SOURCE_VALUE = 200
|
|
41
|
+
|
|
42
|
+
_DEFAULT_ENDPOINT = "https://api.traqio.app"
|
|
43
|
+
_SECRET_PREFIX = "tq_sk_"
|
|
44
|
+
|
|
45
|
+
#: ``(url, headers, body, timeout_seconds) -> (status, body)``. Raises ``OSError`` (or
|
|
46
|
+
#: ``urllib.error.URLError``) when there is no HTTP answer at all.
|
|
47
|
+
Transport = Callable[[str, Dict[str, str], bytes, float], Tuple[int, bytes]]
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class TraqioError(Exception):
|
|
51
|
+
"""A refused call (4xx, never retried) or one that kept failing (5xx, 429, network).
|
|
52
|
+
|
|
53
|
+
``status`` is the HTTP status, or ``None`` for a network error or a timeout;
|
|
54
|
+
``body`` is the API's decoded JSON answer, when there was one.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
def __init__(self, message: str, status: Optional[int] = None, body: Any = None) -> None:
|
|
58
|
+
super().__init__(message)
|
|
59
|
+
self.status = status
|
|
60
|
+
self.body = body
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass(frozen=True)
|
|
64
|
+
class Attribution:
|
|
65
|
+
"""Who gets the credit for a user: the last click before their sign-up — or organic."""
|
|
66
|
+
|
|
67
|
+
#: ``deterministic`` when a click won, ``organic`` otherwise.
|
|
68
|
+
type: str
|
|
69
|
+
#: ``meta``, ``tiktok``, ``google``… or ``organic``.
|
|
70
|
+
network: str
|
|
71
|
+
campaign_id: Optional[str]
|
|
72
|
+
adset_id: Optional[str]
|
|
73
|
+
ad_id: Optional[str]
|
|
74
|
+
|
|
75
|
+
@classmethod
|
|
76
|
+
def from_dict(cls, data: Mapping[str, Any]) -> "Attribution":
|
|
77
|
+
return cls(
|
|
78
|
+
type=str(data.get("type") or "organic"),
|
|
79
|
+
network=str(data.get("network") or "organic"),
|
|
80
|
+
campaign_id=data.get("campaignId"),
|
|
81
|
+
adset_id=data.get("adsetId"),
|
|
82
|
+
ad_id=data.get("adId"),
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@dataclass(frozen=True)
|
|
87
|
+
class Result:
|
|
88
|
+
"""What Traqio answered.
|
|
89
|
+
|
|
90
|
+
``track_id`` says what happened to the trackID, when the call carried one:
|
|
91
|
+
``matched`` (tied to this user — a retry answers ``matched`` again), ``unknown``
|
|
92
|
+
(no click of this product has that id), ``expired`` (older than the attribution
|
|
93
|
+
window), ``claimed`` (another user, or an app install, already owns that click),
|
|
94
|
+
``refused`` (the click failed an anti-fraud rule).
|
|
95
|
+
"""
|
|
96
|
+
|
|
97
|
+
#: Events recorded by this call.
|
|
98
|
+
accepted: int
|
|
99
|
+
#: Events Traqio already had (same eventId or same transactionId).
|
|
100
|
+
duplicates: int
|
|
101
|
+
#: What happened to the trackID; ``None`` when the call carried none.
|
|
102
|
+
track_id: Optional[str]
|
|
103
|
+
#: Has this user been acquired yet (a sign-up reported, or an app install)?
|
|
104
|
+
acquired: bool
|
|
105
|
+
attribution: Attribution
|
|
106
|
+
#: True when the call was dropped because this user asked to be forgotten.
|
|
107
|
+
erased: bool = False
|
|
108
|
+
#: The source Traqio reports this user under, when it holds one —
|
|
109
|
+
#: ``{"source", "medium", "campaign"}``: the Traqio link's network when a click won,
|
|
110
|
+
#: else the ``source`` sent (utm_*, click id, referrer). ``None`` otherwise.
|
|
111
|
+
source: Optional[Dict[str, Optional[str]]] = None
|
|
112
|
+
|
|
113
|
+
@classmethod
|
|
114
|
+
def from_dict(cls, data: Mapping[str, Any]) -> "Result":
|
|
115
|
+
raw_source = data.get("source")
|
|
116
|
+
source = None
|
|
117
|
+
if isinstance(raw_source, Mapping) and raw_source.get("source"):
|
|
118
|
+
source = {
|
|
119
|
+
"source": str(raw_source["source"]),
|
|
120
|
+
"medium": raw_source.get("medium"),
|
|
121
|
+
"campaign": raw_source.get("campaign"),
|
|
122
|
+
}
|
|
123
|
+
return cls(
|
|
124
|
+
accepted=int(data.get("accepted") or 0),
|
|
125
|
+
duplicates=int(data.get("duplicates") or 0),
|
|
126
|
+
track_id=data.get("trackId"),
|
|
127
|
+
acquired=bool(data.get("acquired")),
|
|
128
|
+
attribution=Attribution.from_dict(data.get("attribution") or {}),
|
|
129
|
+
erased=bool(data.get("erased")),
|
|
130
|
+
source=source,
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
@dataclass(frozen=True)
|
|
135
|
+
class AnalyticsResult:
|
|
136
|
+
"""What ``/ingest/analytics/server`` answered to ``capture`` / ``identify``."""
|
|
137
|
+
|
|
138
|
+
#: Events (and identify entries) recorded.
|
|
139
|
+
accepted: int
|
|
140
|
+
#: Entries refused, by reason (``invalid_name``, ``kind_not_allowed``…).
|
|
141
|
+
refused: Dict[str, int] = field(default_factory=dict)
|
|
142
|
+
#: ``recorded``, or ``debug`` when sent in debug mode (Realtime › Debug only).
|
|
143
|
+
outcome: str = "recorded"
|
|
144
|
+
|
|
145
|
+
@classmethod
|
|
146
|
+
def from_dict(cls, data: Mapping[str, Any]) -> "AnalyticsResult":
|
|
147
|
+
refused = data.get("refused")
|
|
148
|
+
return cls(
|
|
149
|
+
accepted=int(data.get("accepted") or 0),
|
|
150
|
+
refused={str(k): int(v) for k, v in refused.items()} if isinstance(refused, Mapping) else {},
|
|
151
|
+
outcome=str(data.get("outcome") or "recorded"),
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
# The server's caps (apps/api/src/product-analytics/screen.ts, identify.ts).
|
|
156
|
+
_MAX_EVENT_NAME = 128
|
|
157
|
+
_MAX_PROPS_BYTES = 4096
|
|
158
|
+
_MAX_DISTINCT_ID = 128
|
|
159
|
+
_MAX_USER_ID = 256
|
|
160
|
+
_MAX_TRAITS = 50
|
|
161
|
+
_MAX_TRAIT_TEXT = 200
|
|
162
|
+
_TRAIT_KEY = re.compile(r"^[A-Za-z0-9_][A-Za-z0-9_.-]{0,63}$")
|
|
163
|
+
_GROUP_TYPE = re.compile(r"^[a-z][a-z0-9_]{0,29}\Z")
|
|
164
|
+
_MAX_GROUP_KEY = 256
|
|
165
|
+
_MAX_GROUPS = 5
|
|
166
|
+
_MAX_EXPOSURE_TEXT = 200
|
|
167
|
+
_EXPOSURE_EVENT = "$exposure"
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def clean_event_name(name: Any) -> Optional[str]:
|
|
171
|
+
"""A custom event name the server takes, or ``None``: non-empty, ≤ 128, never ``$…`` but the experiment exposure ``$exposure``."""
|
|
172
|
+
if not isinstance(name, str):
|
|
173
|
+
return None
|
|
174
|
+
n = name.strip()
|
|
175
|
+
return n if n and len(n) <= _MAX_EVENT_NAME and (not n.startswith("$") or n == "$exposure") else None
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def clean_props(props: Any) -> Optional[Dict[str, Any]]:
|
|
179
|
+
"""Properties as they can travel: a mapping that survives JSON, under 4 KB — else ``None``."""
|
|
180
|
+
if not isinstance(props, Mapping):
|
|
181
|
+
return None
|
|
182
|
+
try:
|
|
183
|
+
# allow_nan=False: NaN is not JSON, and the server would refuse the whole body.
|
|
184
|
+
encoded = json.dumps(dict(props), separators=(",", ":"), allow_nan=False)
|
|
185
|
+
except (TypeError, ValueError):
|
|
186
|
+
return None
|
|
187
|
+
if encoded == "{}" or len(encoded) > _MAX_PROPS_BYTES:
|
|
188
|
+
return None
|
|
189
|
+
return json.loads(encoded)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def clean_group_type(group_type: Any) -> Optional[str]:
|
|
193
|
+
"""A group type the server takes (``company``, ``workspace``…), or ``None``."""
|
|
194
|
+
return group_type if isinstance(group_type, str) and _GROUP_TYPE.match(group_type) else None
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def clean_group_key(group_key: Any) -> Optional[str]:
|
|
198
|
+
"""A group key the server takes: trimmed, 1–256 characters — or ``None``."""
|
|
199
|
+
if not isinstance(group_key, str):
|
|
200
|
+
return None
|
|
201
|
+
key = group_key.strip()
|
|
202
|
+
return key if key and len(key) <= _MAX_GROUP_KEY else None
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def clean_groups(groups: Any) -> Optional[Dict[str, str]]:
|
|
206
|
+
"""An event's ``groups`` as they can travel: valid pairs only, at most 5 types — else ``None``."""
|
|
207
|
+
if not isinstance(groups, Mapping):
|
|
208
|
+
return None
|
|
209
|
+
out: Dict[str, str] = {}
|
|
210
|
+
for raw_type, raw_key in groups.items():
|
|
211
|
+
if len(out) >= _MAX_GROUPS:
|
|
212
|
+
break
|
|
213
|
+
group_type, group_key = clean_group_type(raw_type), clean_group_key(raw_key)
|
|
214
|
+
if group_type and group_key:
|
|
215
|
+
out[group_type] = group_key
|
|
216
|
+
return out or None
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def exposure_props(experiment: Any, variant: Any, props: Any = None) -> Optional[Dict[str, Any]]:
|
|
220
|
+
"""``$exposure``'s properties: ``{**props, experiment, variant}`` — the two named ones
|
|
221
|
+
win over a prop of the same name — or ``None`` when the experiment or the variant is
|
|
222
|
+
not text of 1–200 characters once trimmed."""
|
|
223
|
+
e = experiment.strip() if isinstance(experiment, str) else ""
|
|
224
|
+
v = variant.strip() if isinstance(variant, str) else ""
|
|
225
|
+
if not e or not v or len(e) > _MAX_EXPOSURE_TEXT or len(v) > _MAX_EXPOSURE_TEXT:
|
|
226
|
+
return None
|
|
227
|
+
base = dict(props) if isinstance(props, Mapping) else {}
|
|
228
|
+
merged = {**base, "experiment": e, "variant": v}
|
|
229
|
+
# Props that cannot travel (over 4 KB, not JSON) would take experiment/variant down
|
|
230
|
+
# with them in capture(): keep the exposure, drop the extras.
|
|
231
|
+
return merged if clean_props(merged) else {"experiment": e, "variant": v}
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def clean_traits(traits: Any) -> Dict[str, Any]:
|
|
235
|
+
"""Traits as the server keeps them: valid keys; text (cut at 200), finite numbers, booleans; at most 50."""
|
|
236
|
+
out: Dict[str, Any] = {}
|
|
237
|
+
if not isinstance(traits, Mapping):
|
|
238
|
+
return out
|
|
239
|
+
for key, raw in traits.items():
|
|
240
|
+
if len(out) >= _MAX_TRAITS:
|
|
241
|
+
break
|
|
242
|
+
if not isinstance(key, str) or not _TRAIT_KEY.match(key):
|
|
243
|
+
continue
|
|
244
|
+
if isinstance(raw, bool):
|
|
245
|
+
out[key] = raw
|
|
246
|
+
elif isinstance(raw, str):
|
|
247
|
+
text = raw.strip()
|
|
248
|
+
if text:
|
|
249
|
+
out[key] = text[:_MAX_TRAIT_TEXT]
|
|
250
|
+
elif isinstance(raw, (int, float)) and math.isfinite(raw):
|
|
251
|
+
out[key] = raw
|
|
252
|
+
return out
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def hash_email(email: str) -> str:
|
|
256
|
+
"""SHA-256 hex of the trimmed, lowercased email — the key Traqio matches a Stripe
|
|
257
|
+
payment on when the payment does not name the user. The address is never sent."""
|
|
258
|
+
return hashlib.sha256(email.strip().lower().encode("utf-8")).hexdigest()
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def track_id_from_cookie_header(header: Optional[str]) -> Optional[str]:
|
|
262
|
+
"""The trackID from a raw ``Cookie`` header value, or ``None``."""
|
|
263
|
+
if not header:
|
|
264
|
+
return None
|
|
265
|
+
for part in header.split(";"):
|
|
266
|
+
name, sep, value = part.partition("=")
|
|
267
|
+
if not sep or name.strip() != TRACK_ID_COOKIE:
|
|
268
|
+
continue
|
|
269
|
+
value = unquote(value.strip())
|
|
270
|
+
return value or None
|
|
271
|
+
return None
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def track_id_from_request(request: Any) -> Optional[str]:
|
|
275
|
+
"""The trackID from a request — Django, Flask, FastAPI / Starlette — or ``None``.
|
|
276
|
+
|
|
277
|
+
``@traqio/web`` writes it in a ``traq_click`` cookie on your own domain, so it
|
|
278
|
+
arrives with the sign-up request itself.
|
|
279
|
+
"""
|
|
280
|
+
meta = getattr(request, "META", None) # Django
|
|
281
|
+
if isinstance(meta, Mapping):
|
|
282
|
+
return track_id_from_cookie_header(meta.get("HTTP_COOKIE"))
|
|
283
|
+
cookies = getattr(request, "cookies", None) # Flask, Starlette / FastAPI
|
|
284
|
+
if isinstance(cookies, Mapping):
|
|
285
|
+
value = cookies.get(TRACK_ID_COOKIE)
|
|
286
|
+
return str(value) if value else None
|
|
287
|
+
headers = getattr(request, "headers", None)
|
|
288
|
+
if headers is not None and hasattr(headers, "get"):
|
|
289
|
+
return track_id_from_cookie_header(headers.get("cookie") or headers.get("Cookie"))
|
|
290
|
+
return None
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _header(request: Any, name: str) -> Optional[str]:
|
|
294
|
+
"""One header off a Django, Flask or Starlette request, or None."""
|
|
295
|
+
meta = getattr(request, "META", None)
|
|
296
|
+
if isinstance(meta, Mapping):
|
|
297
|
+
value = meta.get("HTTP_" + name.upper().replace("-", "_"))
|
|
298
|
+
else:
|
|
299
|
+
headers = getattr(request, "headers", None)
|
|
300
|
+
value = headers.get(name) if headers is not None else None
|
|
301
|
+
value = str(value).strip() if value is not None else ""
|
|
302
|
+
return value or None
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def _cookie(header: Optional[str], name: str) -> Optional[str]:
|
|
306
|
+
if not header:
|
|
307
|
+
return None
|
|
308
|
+
for part in header.split(";"):
|
|
309
|
+
key, sep, raw = part.partition("=")
|
|
310
|
+
if sep and key.strip() == name:
|
|
311
|
+
value = unquote(raw.strip())
|
|
312
|
+
return value or None
|
|
313
|
+
return None
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def parse_source_cookie(value: Optional[str]) -> Optional[Dict[str, Any]]:
|
|
317
|
+
"""The source in a ``traq_src`` cookie value (a query string), or ``None`` when it
|
|
318
|
+
holds none. Keys are the API's: ``utmSource``, ``utmMedium``, ``utmCampaign``,
|
|
319
|
+
``utmContent``, ``utmTerm``, ``referrer``, ``gclid``, ``fbclid``, ``ttclid``,
|
|
320
|
+
``landedAt`` (epoch ms)."""
|
|
321
|
+
if not value:
|
|
322
|
+
return None
|
|
323
|
+
params: Dict[str, str] = {}
|
|
324
|
+
for key, item in parse_qsl(value, keep_blank_values=True):
|
|
325
|
+
params.setdefault(key, item) # the first occurrence wins, like URLSearchParams.get
|
|
326
|
+
source: Dict[str, Any] = {}
|
|
327
|
+
for param, field in _SOURCE_FIELDS:
|
|
328
|
+
item = params.get(param, "").strip()
|
|
329
|
+
if item:
|
|
330
|
+
source[field] = item[:_MAX_SOURCE_VALUE]
|
|
331
|
+
if not source:
|
|
332
|
+
return None
|
|
333
|
+
try:
|
|
334
|
+
landed = float(params.get("ts", ""))
|
|
335
|
+
except ValueError:
|
|
336
|
+
landed = 0.0
|
|
337
|
+
if landed > 0 and landed != float("inf"):
|
|
338
|
+
source["landedAt"] = int(landed)
|
|
339
|
+
return source
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def source_from_cookie_header(header: Optional[str]) -> Optional[Dict[str, Any]]:
|
|
343
|
+
"""Where the visitor came from, read off a raw ``Cookie`` header (``traq_src``), or ``None``."""
|
|
344
|
+
return parse_source_cookie(_cookie(header, SOURCE_COOKIE))
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def source_from_request(request: Any) -> Optional[Dict[str, Any]]:
|
|
348
|
+
"""Where the visitor came from without a Traqio link — the ``traq_src`` cookie
|
|
349
|
+
``@traqio/web`` sets — off a Django, Flask or FastAPI / Starlette request, or
|
|
350
|
+
``None``. Pass it to ``signup(source=...)`` next to ``track_id_from_request``.
|
|
351
|
+
|
|
352
|
+
It reads the raw ``Cookie`` header on purpose: the cookie value is URI-encoded,
|
|
353
|
+
and the frameworks' own cookie parsers do not all decode it."""
|
|
354
|
+
return source_from_cookie_header(_header(request, "Cookie") or _header(request, "cookie"))
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def _clean_source(source: Optional[Mapping[str, Any]]) -> Optional[Dict[str, Any]]:
|
|
358
|
+
"""Only the fields Traqio reads, trimmed; ``None`` when none is left."""
|
|
359
|
+
if not isinstance(source, Mapping):
|
|
360
|
+
return None
|
|
361
|
+
out: Dict[str, Any] = {}
|
|
362
|
+
for _, field in _SOURCE_FIELDS:
|
|
363
|
+
item = source.get(field)
|
|
364
|
+
if isinstance(item, str) and item.strip():
|
|
365
|
+
out[field] = item.strip()[:_MAX_SOURCE_VALUE]
|
|
366
|
+
if not out:
|
|
367
|
+
return None
|
|
368
|
+
landed = source.get("landedAt")
|
|
369
|
+
if isinstance(landed, (int, float)) and not isinstance(landed, bool) and 0 < landed < float("inf"):
|
|
370
|
+
out["landedAt"] = int(landed)
|
|
371
|
+
return out
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def web_context_from_request(request: Any) -> Dict[str, str]:
|
|
375
|
+
"""The browser behind a request, for ``context``: the user's IP (first
|
|
376
|
+
``X-Forwarded-For`` hop, else ``X-Real-IP``), user agent, the page that sent it
|
|
377
|
+
(``Referer``), and the Meta / TikTok pixel cookies (``_fbp``, ``_fbc``, ``_ttp``,
|
|
378
|
+
``ttclid``). Behind a proxy that rewrites ``X-Forwarded-For``, pass ``ip`` yourself."""
|
|
379
|
+
cookie = _header(request, "Cookie")
|
|
380
|
+
forwarded = (_header(request, "X-Forwarded-For") or "").split(",")[0].strip()
|
|
381
|
+
ctx = {
|
|
382
|
+
"ip": forwarded or _header(request, "X-Real-IP"),
|
|
383
|
+
"userAgent": _header(request, "User-Agent"),
|
|
384
|
+
"url": _header(request, "Referer"),
|
|
385
|
+
"fbp": _cookie(cookie, "_fbp"),
|
|
386
|
+
"fbc": _cookie(cookie, "_fbc"),
|
|
387
|
+
"ttp": _cookie(cookie, "_ttp"),
|
|
388
|
+
"ttclid": _cookie(cookie, "ttclid"),
|
|
389
|
+
}
|
|
390
|
+
return {k: v for k, v in ctx.items() if v}
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def _detect_debug() -> bool:
|
|
394
|
+
"""A development process: ``TRAQIO_DEBUG`` set to ``1`` / ``true``, or Python's
|
|
395
|
+
development mode (``python -X dev``). Anything else is production."""
|
|
396
|
+
if os.environ.get("TRAQIO_DEBUG", "").strip().lower() in ("1", "true"):
|
|
397
|
+
return True
|
|
398
|
+
return bool(sys.flags.dev_mode)
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def _urllib_transport(url: str, headers: Dict[str, str], body: bytes, timeout: float) -> Tuple[int, bytes]:
|
|
402
|
+
request = urllib.request.Request(url, data=body, headers=headers, method="POST")
|
|
403
|
+
try:
|
|
404
|
+
with urllib.request.urlopen(request, timeout=timeout) as response: # noqa: S310 — https by default
|
|
405
|
+
return response.status, response.read()
|
|
406
|
+
except urllib.error.HTTPError as error: # a 4xx/5xx is an answer, not a failure to reach
|
|
407
|
+
return error.code, error.read()
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
class Traqio:
|
|
411
|
+
"""The client. One per process is enough; it holds no connection.
|
|
412
|
+
|
|
413
|
+
:param secret_key: the product's server key (``tq_sk_…``), from Integrations → SDK.
|
|
414
|
+
:param endpoint: origin of the Traqio API, default ``https://api.traqio.app``.
|
|
415
|
+
:param timeout: seconds per attempt, default 10.
|
|
416
|
+
:param max_retries: retries after a network error, a 429 or a 5xx, default 2.
|
|
417
|
+
:param transport: a custom transport (proxies, tests) — see ``Transport``.
|
|
418
|
+
:param debug: flags every call as development traffic, kept out of stats,
|
|
419
|
+
attribution and billing. ``None`` (default) detects it: ``TRAQIO_DEBUG=1`` or
|
|
420
|
+
``python -X dev``.
|
|
421
|
+
"""
|
|
422
|
+
|
|
423
|
+
def __init__(
|
|
424
|
+
self,
|
|
425
|
+
secret_key: str,
|
|
426
|
+
*,
|
|
427
|
+
endpoint: str = _DEFAULT_ENDPOINT,
|
|
428
|
+
timeout: float = 10.0,
|
|
429
|
+
max_retries: int = 2,
|
|
430
|
+
transport: Optional[Transport] = None,
|
|
431
|
+
debug: Optional[bool] = None,
|
|
432
|
+
) -> None:
|
|
433
|
+
key = (secret_key or "").strip()
|
|
434
|
+
if not key:
|
|
435
|
+
raise TraqioError("secret_key is required — a server key (tq_sk_…) from Integrations → SDK")
|
|
436
|
+
if not key.startswith(_SECRET_PREFIX):
|
|
437
|
+
if key.startswith("tq_web_"):
|
|
438
|
+
raise TraqioError("this is a web key (tq_web_…), made for the browser — the Python SDK needs a server key (tq_sk_…)")
|
|
439
|
+
raise TraqioError("secret_key must be a server key (tq_sk_…) from Integrations → SDK")
|
|
440
|
+
self._secret_key = key
|
|
441
|
+
self._url = endpoint.rstrip("/") + "/ingest/server"
|
|
442
|
+
self._analytics_url = endpoint.rstrip("/") + "/ingest/analytics/server"
|
|
443
|
+
self._timeout = float(timeout)
|
|
444
|
+
self._max_retries = max(0, int(max_retries))
|
|
445
|
+
self._transport: Transport = transport or _urllib_transport
|
|
446
|
+
self._debug = _detect_debug() if debug is None else bool(debug)
|
|
447
|
+
|
|
448
|
+
@property
|
|
449
|
+
def is_debug(self) -> bool:
|
|
450
|
+
"""Whether this client flags its calls as development traffic."""
|
|
451
|
+
return self._debug
|
|
452
|
+
|
|
453
|
+
def signup(
|
|
454
|
+
self,
|
|
455
|
+
user_id: str,
|
|
456
|
+
track_id: Optional[str] = None,
|
|
457
|
+
events: Iterable[Mapping[str, Any]] = (),
|
|
458
|
+
*,
|
|
459
|
+
email: Optional[str] = None,
|
|
460
|
+
source: Optional[Mapping[str, Any]] = None,
|
|
461
|
+
consent: Optional[str] = None,
|
|
462
|
+
context: Optional[Mapping[str, Any]] = None,
|
|
463
|
+
) -> Result:
|
|
464
|
+
"""Report a sign-up — the moment this user is acquired — with the trackID they
|
|
465
|
+
arrived with. Call it once, where you create the account.
|
|
466
|
+
|
|
467
|
+
``email`` is never sent: it is hashed here (``hash_email``) so a Stripe payment
|
|
468
|
+
without ``metadata.traqio_user_id`` can still find this user.
|
|
469
|
+
|
|
470
|
+
``source`` is where the visitor came from without a Traqio link —
|
|
471
|
+
``source_from_request(request)``. Kept once per user (the first one sent); the
|
|
472
|
+
trackID wins when both are there."""
|
|
473
|
+
email_hash = hash_email(email) if email and email.strip() else None
|
|
474
|
+
return self.send(
|
|
475
|
+
user_id,
|
|
476
|
+
track_id=track_id,
|
|
477
|
+
signup=True,
|
|
478
|
+
events=events,
|
|
479
|
+
email_hash=email_hash,
|
|
480
|
+
source=source,
|
|
481
|
+
consent=consent,
|
|
482
|
+
context=context,
|
|
483
|
+
)
|
|
484
|
+
|
|
485
|
+
def track(
|
|
486
|
+
self,
|
|
487
|
+
user_id: str,
|
|
488
|
+
name: str,
|
|
489
|
+
*,
|
|
490
|
+
value: Optional[float] = None,
|
|
491
|
+
currency: Optional[str] = None,
|
|
492
|
+
transaction_id: Optional[str] = None,
|
|
493
|
+
store: Optional[str] = None,
|
|
494
|
+
event_id: Optional[str] = None,
|
|
495
|
+
track_id: Optional[str] = None,
|
|
496
|
+
consent: Optional[str] = None,
|
|
497
|
+
context: Optional[Mapping[str, Any]] = None,
|
|
498
|
+
) -> Result:
|
|
499
|
+
"""Record one conversion of a known user: a purchase, a subscription, a trial…
|
|
500
|
+
|
|
501
|
+
``transaction_id`` is the payment's own id (a Stripe invoice ``in_…``): one payment, one row.
|
|
502
|
+
``event_id`` is your stable id for the event (default: a UUID minted once per call).
|
|
503
|
+
"""
|
|
504
|
+
event: Dict[str, Any] = {"name": name}
|
|
505
|
+
for key, item in (("value", value), ("currency", currency), ("transactionId", transaction_id), ("store", store), ("eventId", event_id)):
|
|
506
|
+
if item is not None:
|
|
507
|
+
event[key] = item
|
|
508
|
+
return self.send(user_id, track_id=track_id, events=[event], consent=consent, context=context)
|
|
509
|
+
|
|
510
|
+
def send(
|
|
511
|
+
self,
|
|
512
|
+
user_id: str,
|
|
513
|
+
*,
|
|
514
|
+
track_id: Optional[str] = None,
|
|
515
|
+
signup: bool = False,
|
|
516
|
+
events: Iterable[Mapping[str, Any]] = (),
|
|
517
|
+
email_hash: Optional[str] = None,
|
|
518
|
+
source: Optional[Mapping[str, Any]] = None,
|
|
519
|
+
consent: Optional[str] = None,
|
|
520
|
+
context: Optional[Mapping[str, Any]] = None,
|
|
521
|
+
) -> Result:
|
|
522
|
+
"""The raw call behind ``signup`` and ``track``, to send several events at once.
|
|
523
|
+
Events use the API's names: ``name``, ``eventId``, ``value``, ``currency``,
|
|
524
|
+
``transactionId``, ``store``.
|
|
525
|
+
|
|
526
|
+
For the forwarding to Meta / TikTok: ``consent`` is your banner's answer
|
|
527
|
+
(``"granted"`` / ``"denied"``; absent = your app's setting decides) and
|
|
528
|
+
``context`` the browser behind the conversion — ``ip``, ``userAgent``, ``url``,
|
|
529
|
+
``referrer``, ``fbp``, ``fbc``, ``ttp``, ``ttclid`` (see ``web_context_from_request``)."""
|
|
530
|
+
uid = str(user_id or "").strip()
|
|
531
|
+
if not uid:
|
|
532
|
+
raise TraqioError("user_id is required")
|
|
533
|
+
batch: List[Dict[str, Any]] = []
|
|
534
|
+
for event in events:
|
|
535
|
+
if not str(event.get("name") or "").strip():
|
|
536
|
+
raise TraqioError("every event needs a name")
|
|
537
|
+
item = dict(event)
|
|
538
|
+
item.setdefault("eventId", str(uuid.uuid4()))
|
|
539
|
+
batch.append(item)
|
|
540
|
+
payload: Dict[str, Any] = {"appUserId": uid}
|
|
541
|
+
tid = (track_id or "").strip()
|
|
542
|
+
if tid:
|
|
543
|
+
payload["trackId"] = tid
|
|
544
|
+
if signup:
|
|
545
|
+
payload["signup"] = True
|
|
546
|
+
if email_hash:
|
|
547
|
+
payload["emailHash"] = email_hash
|
|
548
|
+
cleaned = _clean_source(source)
|
|
549
|
+
if cleaned:
|
|
550
|
+
payload["source"] = cleaned
|
|
551
|
+
if batch:
|
|
552
|
+
payload["events"] = batch
|
|
553
|
+
if consent is not None:
|
|
554
|
+
if consent not in ("granted", "denied"):
|
|
555
|
+
raise TraqioError('consent must be "granted" or "denied"')
|
|
556
|
+
payload["consent"] = consent
|
|
557
|
+
ctx = {k: v for k, v in (context or {}).items() if v is not None and str(v).strip()}
|
|
558
|
+
if ctx:
|
|
559
|
+
payload["context"] = ctx
|
|
560
|
+
# Omitted in production, so a production body stays the same as before.
|
|
561
|
+
if self._debug:
|
|
562
|
+
payload["debug"] = True
|
|
563
|
+
# Encoded once: every retry sends the same eventIds, so Traqio keeps one row.
|
|
564
|
+
return self._post(json.dumps(payload, separators=(",", ":")).encode("utf-8"))
|
|
565
|
+
|
|
566
|
+
def capture(
|
|
567
|
+
self,
|
|
568
|
+
name: str,
|
|
569
|
+
*,
|
|
570
|
+
distinct_id: Optional[str] = None,
|
|
571
|
+
user_id: Optional[str] = None,
|
|
572
|
+
props: Optional[Mapping[str, Any]] = None,
|
|
573
|
+
timestamp: Union[datetime, float, int, None] = None,
|
|
574
|
+
groups: Optional[Mapping[str, str]] = None,
|
|
575
|
+
) -> AnalyticsResult:
|
|
576
|
+
"""A product-analytics event from your backend — ``export_finished``,
|
|
577
|
+
``subscription_churned`` — read in the console's Analytics section. NOT a
|
|
578
|
+
conversion: never billed, never sent to an ad network (that is ``track``).
|
|
579
|
+
|
|
580
|
+
``distinct_id`` is who did it as your backend knows them (an account slug, the
|
|
581
|
+
visitor id ``@traqio/web`` gave you); it defaults to ``user_id``. ``props`` must
|
|
582
|
+
survive JSON and stay under 4 KB, else they are dropped and the event kept.
|
|
583
|
+
``timestamp``: a ``datetime`` (naive = UTC) or epoch seconds; default now.
|
|
584
|
+
``groups``: the accounts it happened in, ``{"company": "acme"}`` — invalid pairs
|
|
585
|
+
are dropped, at most 5 types.
|
|
586
|
+
|
|
587
|
+
No ``screen()`` on a server, on purpose: the route takes custom events only —
|
|
588
|
+
a backend has no screen to view."""
|
|
589
|
+
uid = (user_id or "").strip() if isinstance(user_id, str) else ""
|
|
590
|
+
subject = ((distinct_id or "").strip() if isinstance(distinct_id, str) else "") or uid
|
|
591
|
+
if not subject:
|
|
592
|
+
raise TraqioError("distinct_id (or user_id) is required")
|
|
593
|
+
if len(subject) > _MAX_DISTINCT_ID:
|
|
594
|
+
raise TraqioError(f"distinct_id is longer than {_MAX_DISTINCT_ID} characters")
|
|
595
|
+
if len(uid) > _MAX_USER_ID:
|
|
596
|
+
raise TraqioError(f"user_id is longer than {_MAX_USER_ID} characters")
|
|
597
|
+
event_name = clean_event_name(name)
|
|
598
|
+
if not event_name:
|
|
599
|
+
raise TraqioError("the event name must be 1-128 characters and must not start with $")
|
|
600
|
+
event: Dict[str, Any] = {"kind": "custom", "name": event_name, "ts": _epoch_ms(timestamp)}
|
|
601
|
+
cleaned = clean_props(props)
|
|
602
|
+
if cleaned:
|
|
603
|
+
event["props"] = cleaned
|
|
604
|
+
cleaned_groups = clean_groups(groups)
|
|
605
|
+
if cleaned_groups:
|
|
606
|
+
event["groups"] = cleaned_groups
|
|
607
|
+
return self._post_analytics(subject, uid or None, [event])
|
|
608
|
+
|
|
609
|
+
def identify(
|
|
610
|
+
self,
|
|
611
|
+
user_id: str,
|
|
612
|
+
traits: Optional[Mapping[str, Any]] = None,
|
|
613
|
+
traits_once: Optional[Mapping[str, Any]] = None,
|
|
614
|
+
) -> AnalyticsResult:
|
|
615
|
+
"""A user's PROPERTIES — ``plan``, ``role``, ``seats`` — read in the console as a
|
|
616
|
+
breakdown and a cohort condition. ``traits`` overwrite, ``traits_once`` are
|
|
617
|
+
written only where the user has no value yet. Values are text, numbers or
|
|
618
|
+
booleans — never an email or a name. At most 50 keys."""
|
|
619
|
+
uid = (user_id or "").strip() if isinstance(user_id, str) else ""
|
|
620
|
+
if not uid:
|
|
621
|
+
raise TraqioError("user_id is required")
|
|
622
|
+
if len(uid) > _MAX_USER_ID:
|
|
623
|
+
raise TraqioError(f"user_id is longer than {_MAX_USER_ID} characters")
|
|
624
|
+
set_, set_once = clean_traits(traits), clean_traits(traits_once)
|
|
625
|
+
if not set_ and not set_once:
|
|
626
|
+
raise TraqioError("identify needs at least one valid trait")
|
|
627
|
+
entry: Dict[str, Any] = {"kind": "identify", "ts": _epoch_ms(None), "userId": uid}
|
|
628
|
+
if set_:
|
|
629
|
+
entry["set"] = set_
|
|
630
|
+
if set_once:
|
|
631
|
+
entry["setOnce"] = set_once
|
|
632
|
+
return self._post_analytics(uid[:_MAX_DISTINCT_ID], uid, [entry])
|
|
633
|
+
|
|
634
|
+
def alias(self, user_id: str, previous_id: str) -> AnalyticsResult:
|
|
635
|
+
"""The user known so far as ``previous_id`` (a guest id, a pre-sign-up id, an id
|
|
636
|
+
from an older system) is the same person as ``user_id``. With the secret key the
|
|
637
|
+
server merges ALL of ``previous_id``'s analytics history and properties into
|
|
638
|
+
``user_id`` (``user_id``'s own properties win). Both ids: 1–256 characters, and
|
|
639
|
+
different."""
|
|
640
|
+
uid = (user_id or "").strip() if isinstance(user_id, str) else ""
|
|
641
|
+
prev = (previous_id or "").strip() if isinstance(previous_id, str) else ""
|
|
642
|
+
if not uid:
|
|
643
|
+
raise TraqioError("user_id is required")
|
|
644
|
+
if not prev:
|
|
645
|
+
raise TraqioError("previous_id is required")
|
|
646
|
+
if len(uid) > _MAX_USER_ID or len(prev) > _MAX_USER_ID:
|
|
647
|
+
raise TraqioError(f"user_id and previous_id must be at most {_MAX_USER_ID} characters")
|
|
648
|
+
if uid == prev:
|
|
649
|
+
# The server refuses it (alias_same_id): nothing to merge.
|
|
650
|
+
raise TraqioError("previous_id must differ from user_id")
|
|
651
|
+
entry: Dict[str, Any] = {"kind": "alias", "ts": _epoch_ms(None), "userId": uid, "previousId": prev}
|
|
652
|
+
return self._post_analytics(uid[:_MAX_DISTINCT_ID], uid, [entry])
|
|
653
|
+
|
|
654
|
+
def exposure(
|
|
655
|
+
self,
|
|
656
|
+
experiment: str,
|
|
657
|
+
variant: str,
|
|
658
|
+
props: Optional[Mapping[str, Any]] = None,
|
|
659
|
+
*,
|
|
660
|
+
distinct_id: Optional[str] = None,
|
|
661
|
+
user_id: Optional[str] = None,
|
|
662
|
+
timestamp: Union[datetime, float, int, None] = None,
|
|
663
|
+
groups: Optional[Mapping[str, str]] = None,
|
|
664
|
+
) -> AnalyticsResult:
|
|
665
|
+
"""An experiment exposure: this subject saw ``variant`` of ``experiment`` — the
|
|
666
|
+
``$exposure`` event the console's experiment analysis reads. ``experiment`` and
|
|
667
|
+
``variant``: 1–200 characters; they win over a prop of the same name. The
|
|
668
|
+
subject arguments are capture()'s."""
|
|
669
|
+
merged = exposure_props(experiment, variant, props)
|
|
670
|
+
if merged is None:
|
|
671
|
+
raise TraqioError("experiment and variant must be 1-200 characters")
|
|
672
|
+
return self.capture(
|
|
673
|
+
_EXPOSURE_EVENT, distinct_id=distinct_id, user_id=user_id, props=merged, timestamp=timestamp, groups=groups
|
|
674
|
+
)
|
|
675
|
+
|
|
676
|
+
def group(
|
|
677
|
+
self,
|
|
678
|
+
group_type: str,
|
|
679
|
+
group_key: str,
|
|
680
|
+
traits: Optional[Mapping[str, Any]] = None,
|
|
681
|
+
traits_once: Optional[Mapping[str, Any]] = None,
|
|
682
|
+
distinct_id: Optional[str] = None,
|
|
683
|
+
) -> AnalyticsResult:
|
|
684
|
+
"""An ACCOUNT's properties — B2B analytics: creates or updates the ``company`` /
|
|
685
|
+
``workspace`` your users belong to, so the console can count accounts.
|
|
686
|
+
``group_type`` is lowercase (``^[a-z][a-z0-9_]{0,29}$``), ``group_key`` your own
|
|
687
|
+
account id (1–256 characters, never an email). ``traits`` follow the identify
|
|
688
|
+
rules and may be empty. Events then name their accounts through
|
|
689
|
+
``capture(..., groups={...})``."""
|
|
690
|
+
gtype = clean_group_type(group_type)
|
|
691
|
+
if not gtype:
|
|
692
|
+
raise TraqioError("group_type must match ^[a-z][a-z0-9_]{0,29}$ (e.g. company)")
|
|
693
|
+
gkey = clean_group_key(group_key)
|
|
694
|
+
if not gkey:
|
|
695
|
+
raise TraqioError(f"group_key must be 1-{_MAX_GROUP_KEY} characters")
|
|
696
|
+
subject = (distinct_id or "").strip() if isinstance(distinct_id, str) else ""
|
|
697
|
+
if len(subject) > _MAX_DISTINCT_ID:
|
|
698
|
+
raise TraqioError(f"distinct_id is longer than {_MAX_DISTINCT_ID} characters")
|
|
699
|
+
entry: Dict[str, Any] = {"kind": "group", "ts": _epoch_ms(None), "groupType": gtype, "groupKey": gkey}
|
|
700
|
+
set_, set_once = clean_traits(traits), clean_traits(traits_once)
|
|
701
|
+
if set_:
|
|
702
|
+
entry["set"] = set_
|
|
703
|
+
if set_once:
|
|
704
|
+
entry["setOnce"] = set_once
|
|
705
|
+
return self._post_analytics(subject or f"group:{gtype}:{gkey}"[:_MAX_DISTINCT_ID], None, [entry])
|
|
706
|
+
|
|
707
|
+
def _post_analytics(self, anonymous_id: str, user_id: Optional[str], events: List[Dict[str, Any]]) -> AnalyticsResult:
|
|
708
|
+
# The server stamps a backend's rows with its own session (``server``): none sent.
|
|
709
|
+
payload: Dict[str, Any] = {"anonymousId": anonymous_id}
|
|
710
|
+
if user_id:
|
|
711
|
+
payload["userId"] = user_id
|
|
712
|
+
payload["events"] = events
|
|
713
|
+
if self._debug:
|
|
714
|
+
payload["debug"] = True
|
|
715
|
+
data = self._request(self._analytics_url, json.dumps(payload, separators=(",", ":")).encode("utf-8"))
|
|
716
|
+
return AnalyticsResult.from_dict(data)
|
|
717
|
+
|
|
718
|
+
def _post(self, body: bytes) -> Result:
|
|
719
|
+
return Result.from_dict(self._request(self._url, body))
|
|
720
|
+
|
|
721
|
+
def _request(self, url: str, body: bytes) -> Dict[str, Any]:
|
|
722
|
+
headers = {
|
|
723
|
+
"Authorization": f"Bearer {self._secret_key}",
|
|
724
|
+
"Content-Type": "application/json",
|
|
725
|
+
"Accept": "application/json",
|
|
726
|
+
"User-Agent": f"traqio-python/{__version__}",
|
|
727
|
+
}
|
|
728
|
+
last: Optional[TraqioError] = None
|
|
729
|
+
for attempt in range(self._max_retries + 1):
|
|
730
|
+
if attempt:
|
|
731
|
+
time.sleep(min(0.25 * 2 ** (attempt - 1), 4.0))
|
|
732
|
+
try:
|
|
733
|
+
status, raw = self._transport(url, headers, body, self._timeout)
|
|
734
|
+
except OSError as error: # URLError, timeouts and socket errors are all OSError
|
|
735
|
+
last = TraqioError(f"Traqio API unreachable: {getattr(error, 'reason', error)}")
|
|
736
|
+
continue
|
|
737
|
+
try:
|
|
738
|
+
data = json.loads(raw.decode("utf-8")) if raw else None
|
|
739
|
+
except ValueError:
|
|
740
|
+
data = None
|
|
741
|
+
if 200 <= status < 300 and isinstance(data, dict):
|
|
742
|
+
return data
|
|
743
|
+
message = data.get("message") if isinstance(data, dict) else None
|
|
744
|
+
if isinstance(message, list):
|
|
745
|
+
message = ", ".join(str(m) for m in message)
|
|
746
|
+
last = TraqioError(f"Traqio API answered {status}" + (f": {message}" if message else ""), status, data)
|
|
747
|
+
# A 4xx is the request's fault (bad key, bad payload): sending it again
|
|
748
|
+
# cannot succeed. Only overload (429) and server errors are retried.
|
|
749
|
+
if status < 500 and status != 429:
|
|
750
|
+
raise last
|
|
751
|
+
raise last or TraqioError("Traqio API call failed")
|
|
752
|
+
|
|
753
|
+
|
|
754
|
+
def _epoch_ms(timestamp: Union[datetime, float, int, None]) -> int:
|
|
755
|
+
"""Epoch milliseconds: a ``datetime`` (naive read as UTC), epoch seconds, or now."""
|
|
756
|
+
if isinstance(timestamp, datetime):
|
|
757
|
+
if timestamp.tzinfo is None:
|
|
758
|
+
timestamp = timestamp.replace(tzinfo=timezone.utc)
|
|
759
|
+
return int(timestamp.timestamp() * 1000)
|
|
760
|
+
if isinstance(timestamp, (int, float)) and not isinstance(timestamp, bool) and math.isfinite(timestamp):
|
|
761
|
+
return int(timestamp * 1000)
|
|
762
|
+
return int(time.time() * 1000)
|
traqio/_version.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
traqio/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: traqio
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Traqio server SDK for Python — report sign-ups and conversions from your backend and tie them to the ad click (trackID) the visitor came from. Django, Flask, FastAPI.
|
|
5
|
+
Project-URL: Homepage, https://traqio.app/docs/sdks/python
|
|
6
|
+
Project-URL: Documentation, https://traqio.app/docs/sdks/python
|
|
7
|
+
Author-email: "khufu.io" <hello@khufu.io>
|
|
8
|
+
License: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: attribution,conversion-tracking,django,fastapi,roas,server-side-tracking,web-attribution
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Framework :: Django
|
|
13
|
+
Classifier: Framework :: FastAPI
|
|
14
|
+
Classifier: Framework :: Flask
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Classifier: Programming Language :: Python :: 3
|
|
19
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Python: >=3.9
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
|
|
24
|
+
# traqio
|
|
25
|
+
|
|
26
|
+
The Python server SDK of [Traqio](https://traqio.app). It reports the conversions that
|
|
27
|
+
happen on your **backend** — a sign-up, a subscription, a purchase — and ties each one
|
|
28
|
+
to the ad click the visitor came from, **deterministically**.
|
|
29
|
+
|
|
30
|
+
It is the server half of Traqio's web SDK. The browser half, `@traqio/web`, keeps the
|
|
31
|
+
ad click id — the **trackID** — in first-party storage from the landing page to the
|
|
32
|
+
sign-up form. Your backend hands that trackID to this package with your own user id,
|
|
33
|
+
and Traqio credits the campaign that brought the user. No fingerprinting, no
|
|
34
|
+
guesswork, no dependency: the standard library only. Django, Flask, FastAPI or any
|
|
35
|
+
other framework.
|
|
36
|
+
|
|
37
|
+
## Install
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
pip install traqio
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Python 3.9 or later. Typed (`py.typed`).
|
|
44
|
+
|
|
45
|
+
## Initialize
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
import os
|
|
49
|
+
from traqio import Traqio
|
|
50
|
+
|
|
51
|
+
traqio = Traqio(os.environ["TRAQIO_SECRET_KEY"])
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
One client per process is enough. **Use a server key** (`tq_sk_…`), created in the
|
|
55
|
+
Traqio console under **Integrations → SDK**. It is a secret: keep it in your server's
|
|
56
|
+
environment, never in a page or a mobile app. It is what allows a conversion to be tied
|
|
57
|
+
to a click, which a public key can never do. A web key (`tq_web_…`) is refused.
|
|
58
|
+
|
|
59
|
+
## Report the sign-up, with its trackID
|
|
60
|
+
|
|
61
|
+
Call `signup()` once, where you create the account. `@traqio/web` writes the trackID in
|
|
62
|
+
a `traq_click` cookie on your own domain, so it arrives with the sign-up request:
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
from traqio import track_id_from_request
|
|
66
|
+
|
|
67
|
+
# Django
|
|
68
|
+
def signup(request):
|
|
69
|
+
user = User.objects.create_user(...)
|
|
70
|
+
result = traqio.signup(str(user.pk), track_id_from_request(request))
|
|
71
|
+
# result.track_id: "matched" | "unknown" | "expired" | "claimed" | "refused" | None
|
|
72
|
+
# result.attribution.campaign_id, .network, .type
|
|
73
|
+
...
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
`track_id_from_request` reads Django, Flask and Starlette / FastAPI requests, and
|
|
77
|
+
returns `None` when the visitor did not come from an ad.
|
|
78
|
+
|
|
79
|
+
The sign-up is the moment the user is **acquired**. Traqio credits the **last click**
|
|
80
|
+
before it, inside your attribution window. If your backend is on another domain than
|
|
81
|
+
your site, send `Traqio.getTrackId()` from the browser with the form instead.
|
|
82
|
+
|
|
83
|
+
### Visitors without a Traqio link: their source
|
|
84
|
+
|
|
85
|
+
A visitor from an Instagram bio, a newsletter or a Google ad with plain
|
|
86
|
+
`?utm_source=…&utm_campaign=…` has no trackID. `@traqio/web` keeps their origin — the
|
|
87
|
+
`utm_*`, `gclid` / `fbclid` / `ttclid`, the referring site — in a `traq_src` cookie.
|
|
88
|
+
Send it with the sign-up and Traqio reports the user under that source and campaign
|
|
89
|
+
(`result.source`, and the **Source / Medium / Campaign (web)** report dimensions). It
|
|
90
|
+
is not an ad attribution: the credit stays organic, so no ROAS moves. A trackID, when
|
|
91
|
+
there is one, wins.
|
|
92
|
+
|
|
93
|
+
```python
|
|
94
|
+
from traqio import source_from_request, track_id_from_request
|
|
95
|
+
|
|
96
|
+
result = traqio.signup(
|
|
97
|
+
str(user.pk),
|
|
98
|
+
track_id_from_request(request),
|
|
99
|
+
source=source_from_request(request), # None when the visit carried nothing
|
|
100
|
+
)
|
|
101
|
+
# result.source: {"source": "instagram", "medium": "social", "campaign": "launch"}
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
The first source sent for a user is kept. An `fbclid` / `ttclid` in it also matches the
|
|
105
|
+
sign-up forwarded to Meta / TikTok when no trackID click carries one. Like the trackID,
|
|
106
|
+
it is read from the raw `Cookie` header (the cookie value is URI-encoded).
|
|
107
|
+
|
|
108
|
+
## Track conversions
|
|
109
|
+
|
|
110
|
+
```python
|
|
111
|
+
traqio.track(
|
|
112
|
+
str(user.pk),
|
|
113
|
+
"purchase",
|
|
114
|
+
value=49,
|
|
115
|
+
currency="EUR",
|
|
116
|
+
transaction_id=payment_intent.id, # one payment, one row
|
|
117
|
+
store="stripe",
|
|
118
|
+
)
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
Every event has an id (a UUID is minted when you pass no `event_id`), and a payment is
|
|
122
|
+
also keyed on its `transaction_id`, so a retry or a duplicate report is stored once.
|
|
123
|
+
Conversions follow the user: they are credited to the campaign that acquired them.
|
|
124
|
+
|
|
125
|
+
The client is synchronous. In FastAPI, keep it off the event loop with a background
|
|
126
|
+
task — `background_tasks.add_task(traqio.signup, str(user.id), track_id)` runs it in a
|
|
127
|
+
thread after the response.
|
|
128
|
+
|
|
129
|
+
## Product analytics
|
|
130
|
+
|
|
131
|
+
`capture()` records a product-analytics event from your backend — what the console's
|
|
132
|
+
Analytics section reads (events, funnels, property splits), next to the events your
|
|
133
|
+
site and apps send. It is **not** a conversion: it goes to `/ingest/analytics/server`,
|
|
134
|
+
is never billed and never reaches an ad network. A purchase or a sign-up stays
|
|
135
|
+
`track()` / `signup()`.
|
|
136
|
+
|
|
137
|
+
```python
|
|
138
|
+
traqio.capture("export_finished", user_id=str(user.pk), props={"rows": 1200})
|
|
139
|
+
|
|
140
|
+
# A subject that is not a signed-in user: an account, a visitor id @traqio/web gave you.
|
|
141
|
+
traqio.capture("subscription_churned", distinct_id=account.slug)
|
|
142
|
+
|
|
143
|
+
# A user's properties — a breakdown and a cohort condition in the console.
|
|
144
|
+
traqio.identify(str(user.pk), {"plan": "pro", "seats": 12}, {"signup_source": "sales"})
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
One request per call, retried like the others (keep it off an event loop, as above).
|
|
148
|
+
Names are 1-128 characters and never start with `$` (reserved); `props` must survive
|
|
149
|
+
JSON and stay under 4 KB, else they are dropped and the event kept; trait values are
|
|
150
|
+
text, numbers or booleans — never an email or a name. There is no `screen()` on a
|
|
151
|
+
server: the route takes custom events only. In debug mode the events go to
|
|
152
|
+
Analytics › Realtime › Debug and count nowhere.
|
|
153
|
+
|
|
154
|
+
## Groups (B2B accounts)
|
|
155
|
+
|
|
156
|
+
In B2B, your customer is an account — a company, a workspace — as much as a person.
|
|
157
|
+
`group()` creates or updates that account with its properties; `capture()` then names,
|
|
158
|
+
through `groups=`, the account each event happened in. The console's Analytics can then
|
|
159
|
+
count accounts instead of people: funnels and retention by account, unique accounts,
|
|
160
|
+
and the list of your accounts with their properties.
|
|
161
|
+
|
|
162
|
+
```python
|
|
163
|
+
# After sign-in, or when the account changes (a plan change in a billing webhook):
|
|
164
|
+
# create or update the account. Traits may be empty — the account is created anyway.
|
|
165
|
+
traqio.group("company", str(org.pk), {"plan": "pro", "seats": 12})
|
|
166
|
+
|
|
167
|
+
# Every event that happens in that account names it.
|
|
168
|
+
traqio.capture("export_finished", user_id=str(user.pk), groups={"company": str(org.pk)})
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
The group type is lowercase (`company`, `workspace`, `team`: a letter, then letters,
|
|
172
|
+
digits or `_`, 30 characters at most); the key is your own account id, 1-256
|
|
173
|
+
characters — never an email. A bad type or key raises `TraqioError` before any request; in
|
|
174
|
+
`capture()`, invalid pairs are dropped and at most 5 types are kept. Traits follow the
|
|
175
|
+
identify rules — never an email or a person's name. A server keeps nothing between
|
|
176
|
+
calls, so pass the groups on each event that belongs to an account; `resetGroups()` on
|
|
177
|
+
sign-out (or `reset()`) belongs to the web and app SDKs, which remember the account.
|
|
178
|
+
|
|
179
|
+
## Alias and experiments
|
|
180
|
+
|
|
181
|
+
`alias()` says that the user known so far as `previous_id` — a guest id, a pre-sign-up
|
|
182
|
+
id, an id from an older system — is `user_id`. With your secret key the server merges
|
|
183
|
+
ALL of `previous_id`'s analytics history and properties into `user_id` (`user_id`'s own
|
|
184
|
+
properties win). `exposure()` records that a user saw a variant of an experiment: a
|
|
185
|
+
`$exposure` event the console's experiment analysis reads.
|
|
186
|
+
|
|
187
|
+
```python
|
|
188
|
+
# At sign-up, when the guest becomes a user.
|
|
189
|
+
traqio.alias(str(user.pk), guest_id)
|
|
190
|
+
|
|
191
|
+
# Where the variant is decided — same subject arguments as capture().
|
|
192
|
+
traqio.exposure("checkout_v2", "treatment", {"surface": "web"}, user_id=str(user.pk))
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
Both ids are 1-256 characters and must differ; the experiment and variant are 1-200
|
|
196
|
+
characters and win over a prop of the same name. Anything else raises `TraqioError`
|
|
197
|
+
before any request. There is no `reset()` on a server — it keeps no user between
|
|
198
|
+
calls; call `reset()` at sign-out in the web and app SDKs.
|
|
199
|
+
|
|
200
|
+
## What it does today
|
|
201
|
+
|
|
202
|
+
- Ties a sign-up to its click and answers with the credited campaign — **yes**.
|
|
203
|
+
- Records conversions with value, currency and payment id, deduplicated — **yes**.
|
|
204
|
+
- Leaves your mobile apps' installs, revenue and ROAS untouched: a conversion sent
|
|
205
|
+
here is never attached to an app install — **yes**.
|
|
206
|
+
- Shows web conversions in the console's reports — **not yet**; the API response is
|
|
207
|
+
where you read the attribution today.
|
|
208
|
+
- Sends web conversions to Meta (Conversions API) and TikTok (Events API), with the ad
|
|
209
|
+
click's `fbclid` / `ttclid` — **yes**, to the product's destinations set in the console.
|
|
210
|
+
|
|
211
|
+
### Meta and TikTok: consent, context and the pixel's event id
|
|
212
|
+
|
|
213
|
+
```python
|
|
214
|
+
from traqio import web_context_from_request
|
|
215
|
+
|
|
216
|
+
traqio.track(
|
|
217
|
+
order.user_id,
|
|
218
|
+
"purchase",
|
|
219
|
+
value=order.total,
|
|
220
|
+
currency="EUR",
|
|
221
|
+
event_id=order.id, # the same id your pixel fires with, so each network keeps one
|
|
222
|
+
consent="granted", # your banner's answer; "denied" keeps it away from the networks
|
|
223
|
+
context=web_context_from_request(request), # IP, user agent, page, _fbp/_fbc/_ttp/ttclid
|
|
224
|
+
)
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
`context` is never stored by Traqio; `web_context_from_request(request)` reads it off the request.
|
|
228
|
+
|
|
229
|
+
## Errors and retries
|
|
230
|
+
|
|
231
|
+
A network error, a timeout, a `429` or a `5xx` is retried (twice by default) with the
|
|
232
|
+
same body, so nothing is counted twice. A `4xx` — a wrong key, an invalid payload — is
|
|
233
|
+
not retried. Both end as a `TraqioError` with `.status` and `.body`:
|
|
234
|
+
|
|
235
|
+
```python
|
|
236
|
+
from traqio import TraqioError
|
|
237
|
+
|
|
238
|
+
try:
|
|
239
|
+
traqio.signup(str(user.pk), track_id)
|
|
240
|
+
except TraqioError as error:
|
|
241
|
+
logger.warning("traqio: %s (status %s)", error, error.status) # never fail the sign-up
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
## Options
|
|
245
|
+
|
|
246
|
+
| Option | Default | |
|
|
247
|
+
| --- | --- | --- |
|
|
248
|
+
| `secret_key` | — | Your server key, `tq_sk_…` (first argument, required) |
|
|
249
|
+
| `endpoint` | `https://api.traqio.app` | Origin of the Traqio API |
|
|
250
|
+
| `timeout` | `10.0` | Seconds per attempt |
|
|
251
|
+
| `max_retries` | `2` | Retries after a network error, a 429 or a 5xx |
|
|
252
|
+
| `transport` | `urllib` | A custom transport (proxies, tests) |
|
|
253
|
+
| `debug` | auto | `True` / `False` forces debug mode on or off — see below |
|
|
254
|
+
|
|
255
|
+
## Debug mode
|
|
256
|
+
|
|
257
|
+
Calls from a development machine are flagged as debug traffic. The client turns it on
|
|
258
|
+
by itself when `TRAQIO_DEBUG` is `1` or `true`, or when Python runs in development
|
|
259
|
+
mode (`python -X dev`); anything else is production. `Traqio(key, debug=True)` or
|
|
260
|
+
`debug=False` overrides the detection, and `traqio.is_debug` tells which mode is on.
|
|
261
|
+
|
|
262
|
+
Debug traffic shows in the console's **Debug** view, but it is never counted,
|
|
263
|
+
attributed, forwarded to ad networks or billed.
|
|
264
|
+
|
|
265
|
+
## Requirements
|
|
266
|
+
|
|
267
|
+
Python 3.9+, no dependency. A Traqio product with a server key, and `@traqio/web`
|
|
268
|
+
on the site so the trackID is kept until sign-up.
|
|
269
|
+
|
|
270
|
+
## Documentation
|
|
271
|
+
|
|
272
|
+
Full guide, the trackID and how web attribution works:
|
|
273
|
+
https://traqio.app/docs/sdks/python
|
|
274
|
+
|
|
275
|
+
## License
|
|
276
|
+
|
|
277
|
+
MIT
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
traqio/__init__.py,sha256=o7lDodGJ1nPH58fd3XqgrmJCmrzIEzSg7w0SkTM0IZA,1507
|
|
2
|
+
traqio/_client.py,sha256=cRkOBBHxrUYzqSSbGqsFzjqaHhksC185iYxyXBOUj1k,33296
|
|
3
|
+
traqio/_version.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
|
|
4
|
+
traqio/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
traqio-0.1.0.dist-info/METADATA,sha256=mx9zv7DxllkiDfZ_8sGL7nNd5ZAccqIVKVwzn8HWdrQ,11624
|
|
6
|
+
traqio-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
7
|
+
traqio-0.1.0.dist-info/licenses/LICENSE,sha256=GP3XhAiWlY_srmaa9TIzl4M5f20_kscyaXBzyatAzv8,1067
|
|
8
|
+
traqio-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Khufu FZCO
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|