trodo-python 1.0.0__py3-none-any.whl → 1.0.1__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.
trodo/__init__.py CHANGED
@@ -1,134 +1,134 @@
1
- """
2
- trodo-python — Trodo Analytics SDK for Python
3
-
4
- Usage (module-level singleton):
5
- import trodo
6
- trodo.init(site_id='your-site-id')
7
- user = trodo.for_user('user-123')
8
- user.track('purchase_completed', {'amount': 99.99})
9
-
10
- Usage (class):
11
- from trodo import TrodoClient
12
- client = TrodoClient(site_id='your-site-id')
13
- user = client.for_user('user-123')
14
- user.track('purchase_completed', {'amount': 99.99})
15
- """
16
-
17
- from __future__ import annotations
18
-
19
- from typing import Any, Dict, List, Optional, Union
20
-
21
- from .client import TrodoClient
22
- from .user_context import UserContext
23
- from .managers.group_manager import GroupProfile
24
- from .types import ApiResult, IdentifyResult, ResetResult, WalletAddressResult
25
-
26
- __all__ = [
27
- "TrodoClient",
28
- "UserContext",
29
- "GroupProfile",
30
- "init",
31
- "for_user",
32
- "track",
33
- "identify",
34
- "wallet_address",
35
- "reset",
36
- "enable_auto_events",
37
- "disable_auto_events",
38
- "flush",
39
- "shutdown",
40
- ]
41
-
42
- # ============================================================================
43
- # Singleton convenience API
44
- # ============================================================================
45
-
46
- _client: Optional[TrodoClient] = None
47
-
48
-
49
- def _get_client() -> TrodoClient:
50
- if _client is None:
51
- raise RuntimeError(
52
- "trodo-python: Call trodo.init(site_id=...) before using the SDK."
53
- )
54
- return _client
55
-
56
-
57
- def init(
58
- site_id: str,
59
- api_base: str = "https://sdkapi.trodo.ai",
60
- timeout: int = 10,
61
- retries: int = 2,
62
- batch_enabled: bool = False,
63
- batch_size: int = 50,
64
- batch_flush_interval: float = 5.0,
65
- auto_events: bool = False,
66
- on_error: Optional[Any] = None,
67
- debug: bool = False,
68
- ) -> TrodoClient:
69
- """Initialise the singleton SDK instance."""
70
- global _client
71
- _client = TrodoClient(
72
- site_id=site_id,
73
- api_base=api_base,
74
- timeout=timeout,
75
- retries=retries,
76
- batch_enabled=batch_enabled,
77
- batch_size=batch_size,
78
- batch_flush_interval=batch_flush_interval,
79
- auto_events=auto_events,
80
- on_error=on_error,
81
- debug=debug,
82
- )
83
- return _client
84
-
85
-
86
- def for_user(
87
- distinct_id: str,
88
- session_id: Optional[str] = None,
89
- ) -> UserContext:
90
- """Return a UserContext bound to the given distinctId."""
91
- return _get_client().for_user(distinct_id, session_id)
92
-
93
-
94
- def track(
95
- distinct_id: str,
96
- event_name: str,
97
- properties: Optional[Dict[str, Any]] = None,
98
- category: str = "custom",
99
- ) -> None:
100
- """Track an event for a user (direct-call pattern)."""
101
- _get_client().track(distinct_id, event_name, properties, category)
102
-
103
-
104
- def identify(distinct_id: str, identify_id: str) -> IdentifyResult:
105
- """Alias a user's distinctId to an external identifier."""
106
- return _get_client().identify(distinct_id, identify_id)
107
-
108
-
109
- def wallet_address(distinct_id: str, wallet_addr: str) -> WalletAddressResult:
110
- """Associate a wallet address with a user."""
111
- return _get_client().wallet_address(distinct_id, wallet_addr)
112
-
113
-
114
- def reset(distinct_id: str) -> ResetResult:
115
- """Reset a user's session."""
116
- return _get_client().reset(distinct_id)
117
-
118
-
119
- def enable_auto_events() -> None:
120
- _get_client().enable_auto_events()
121
-
122
-
123
- def disable_auto_events() -> None:
124
- _get_client().disable_auto_events()
125
-
126
-
127
- def flush() -> None:
128
- """Flush any queued batch events."""
129
- _get_client().flush()
130
-
131
-
132
- def shutdown() -> None:
133
- """Flush, stop timers, and disable auto events."""
134
- _get_client().shutdown()
1
+ """
2
+ trodo-python — Trodo Analytics SDK for Python
3
+
4
+ Usage (module-level singleton):
5
+ import trodo
6
+ trodo.init(site_id='your-site-id')
7
+ user = trodo.for_user('user-123')
8
+ user.track('purchase_completed', {'amount': 99.99})
9
+
10
+ Usage (class):
11
+ from trodo import TrodoClient
12
+ client = TrodoClient(site_id='your-site-id')
13
+ user = client.for_user('user-123')
14
+ user.track('purchase_completed', {'amount': 99.99})
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from typing import Any, Dict, List, Optional, Union
20
+
21
+ from .client import TrodoClient
22
+ from .user_context import UserContext
23
+ from .managers.group_manager import GroupProfile
24
+ from .types import ApiResult, IdentifyResult, ResetResult, WalletAddressResult
25
+
26
+ __all__ = [
27
+ "TrodoClient",
28
+ "UserContext",
29
+ "GroupProfile",
30
+ "init",
31
+ "for_user",
32
+ "track",
33
+ "identify",
34
+ "wallet_address",
35
+ "reset",
36
+ "enable_auto_events",
37
+ "disable_auto_events",
38
+ "flush",
39
+ "shutdown",
40
+ ]
41
+
42
+ # ============================================================================
43
+ # Singleton convenience API
44
+ # ============================================================================
45
+
46
+ _client: Optional[TrodoClient] = None
47
+
48
+
49
+ def _get_client() -> TrodoClient:
50
+ if _client is None:
51
+ raise RuntimeError(
52
+ "trodo-python: Call trodo.init(site_id=...) before using the SDK."
53
+ )
54
+ return _client
55
+
56
+
57
+ def init(
58
+ site_id: str,
59
+ api_base: str = "https://sdkapi.trodo.ai",
60
+ timeout: int = 10,
61
+ retries: int = 2,
62
+ batch_enabled: bool = False,
63
+ batch_size: int = 50,
64
+ batch_flush_interval: float = 5.0,
65
+ auto_events: bool = False,
66
+ on_error: Optional[Any] = None,
67
+ debug: bool = False,
68
+ ) -> TrodoClient:
69
+ """Initialise the singleton SDK instance."""
70
+ global _client
71
+ _client = TrodoClient(
72
+ site_id=site_id,
73
+ api_base=api_base,
74
+ timeout=timeout,
75
+ retries=retries,
76
+ batch_enabled=batch_enabled,
77
+ batch_size=batch_size,
78
+ batch_flush_interval=batch_flush_interval,
79
+ auto_events=auto_events,
80
+ on_error=on_error,
81
+ debug=debug,
82
+ )
83
+ return _client
84
+
85
+
86
+ def for_user(
87
+ distinct_id: str,
88
+ session_id: Optional[str] = None,
89
+ ) -> UserContext:
90
+ """Return a UserContext bound to the given distinctId."""
91
+ return _get_client().for_user(distinct_id, session_id)
92
+
93
+
94
+ def track(
95
+ distinct_id: str,
96
+ event_name: str,
97
+ properties: Optional[Dict[str, Any]] = None,
98
+ category: str = "custom",
99
+ ) -> None:
100
+ """Track an event for a user (direct-call pattern)."""
101
+ _get_client().track(distinct_id, event_name, properties, category)
102
+
103
+
104
+ def identify(distinct_id: str, identify_id: str) -> IdentifyResult:
105
+ """Alias a user's distinctId to an external identifier."""
106
+ return _get_client().identify(distinct_id, identify_id)
107
+
108
+
109
+ def wallet_address(distinct_id: str, wallet_addr: str) -> WalletAddressResult:
110
+ """Associate a wallet address with a user."""
111
+ return _get_client().wallet_address(distinct_id, wallet_addr)
112
+
113
+
114
+ def reset(distinct_id: str) -> ResetResult:
115
+ """Reset a user's session."""
116
+ return _get_client().reset(distinct_id)
117
+
118
+
119
+ def enable_auto_events() -> None:
120
+ _get_client().enable_auto_events()
121
+
122
+
123
+ def disable_auto_events() -> None:
124
+ _get_client().disable_auto_events()
125
+
126
+
127
+ def flush() -> None:
128
+ """Flush any queued batch events."""
129
+ _get_client().flush()
130
+
131
+
132
+ def shutdown() -> None:
133
+ """Flush, stop timers, and disable auto events."""
134
+ _get_client().shutdown()
trodo/api/async_client.py CHANGED
@@ -1,96 +1,96 @@
1
- """Async HTTP client using httpx (optional dependency)."""
2
-
3
- from __future__ import annotations
4
-
5
- import sys
6
- import asyncio
7
- from typing import Any, Callable, Dict, Optional
8
-
9
- from ..types import ApiResult, EventPayload
10
-
11
-
12
- class AsyncHttpClient:
13
- def __init__(
14
- self,
15
- api_base: str,
16
- site_id: str,
17
- timeout: int = 10,
18
- retries: int = 2,
19
- on_error: Optional[Callable[[Exception], None]] = None,
20
- debug: bool = False,
21
- ) -> None:
22
- try:
23
- import httpx # noqa: F401
24
- except ImportError:
25
- raise ImportError(
26
- "trodo-python async support requires httpx: pip install trodo-python[async]"
27
- )
28
-
29
- self.api_base = api_base.rstrip("/")
30
- self.site_id = site_id
31
- self.timeout = timeout
32
- self.retries = retries
33
- self.on_error = on_error
34
- self.debug = debug
35
-
36
- def _log(self, *args: Any) -> None:
37
- if self.debug:
38
- sys.stderr.write(f"[trodo-python-async] {' '.join(str(a) for a in args)}\n")
39
-
40
- async def _request(
41
- self, path: str, body: Dict[str, Any], attempt: int = 0
42
- ) -> ApiResult:
43
- import httpx
44
-
45
- url = f"{self.api_base}{path}"
46
- self._log(f"POST {url}")
47
- headers = {
48
- "Content-Type": "application/json",
49
- "X-Trodo-Site-Id": self.site_id,
50
- }
51
- try:
52
- async with httpx.AsyncClient(timeout=self.timeout) as client:
53
- resp = await client.post(url, json=body, headers=headers)
54
- if resp.status_code >= 500 and attempt < self.retries:
55
- delay = 2 ** attempt
56
- self._log(f"Retry {attempt + 1} after {delay}s")
57
- await asyncio.sleep(delay)
58
- return await self._request(path, body, attempt + 1)
59
- try:
60
- return resp.json()
61
- except Exception:
62
- return {}
63
- except Exception as exc:
64
- if attempt < self.retries:
65
- await asyncio.sleep(2 ** attempt)
66
- return await self._request(path, body, attempt + 1)
67
- self._log(f"Error: {exc}")
68
- if self.on_error:
69
- self.on_error(exc)
70
- return {}
71
-
72
- async def post_track(self, session_data: Dict[str, Any]) -> ApiResult:
73
- return await self._request("/api/sdk/track", {"sessionData": session_data})
74
-
75
- async def post_event(self, event: EventPayload) -> ApiResult:
76
- return await self._request("/api/events", event.to_dict())
77
-
78
- async def post_bulk_events(self, events: list) -> ApiResult:
79
- return await self._request(
80
- "/api/events/bulk", {"events": [e.to_dict() for e in events]}
81
- )
82
-
83
- async def post_identify(self, payload: Dict[str, Any]) -> ApiResult:
84
- return await self._request("/api/sdk/identify", payload)
85
-
86
- async def post_wallet_address(self, payload: Dict[str, Any]) -> ApiResult:
87
- return await self._request("/api/sdk/wallet-address", payload)
88
-
89
- async def post_reset(self, payload: Dict[str, Any]) -> ApiResult:
90
- return await self._request("/api/sdk/reset", payload)
91
-
92
- async def post_people(self, path: str, payload: Dict[str, Any]) -> ApiResult:
93
- return await self._request(path, payload)
94
-
95
- async def post_group(self, path: str, payload: Dict[str, Any]) -> ApiResult:
96
- return await self._request(path, payload)
1
+ """Async HTTP client using httpx (optional dependency)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+ import asyncio
7
+ from typing import Any, Callable, Dict, Optional
8
+
9
+ from ..types import ApiResult, EventPayload
10
+
11
+
12
+ class AsyncHttpClient:
13
+ def __init__(
14
+ self,
15
+ api_base: str,
16
+ site_id: str,
17
+ timeout: int = 10,
18
+ retries: int = 2,
19
+ on_error: Optional[Callable[[Exception], None]] = None,
20
+ debug: bool = False,
21
+ ) -> None:
22
+ try:
23
+ import httpx # noqa: F401
24
+ except ImportError:
25
+ raise ImportError(
26
+ "trodo-python async support requires httpx: pip install trodo-python[async]"
27
+ )
28
+
29
+ self.api_base = api_base.rstrip("/")
30
+ self.site_id = site_id
31
+ self.timeout = timeout
32
+ self.retries = retries
33
+ self.on_error = on_error
34
+ self.debug = debug
35
+
36
+ def _log(self, *args: Any) -> None:
37
+ if self.debug:
38
+ sys.stderr.write(f"[trodo-python-async] {' '.join(str(a) for a in args)}\n")
39
+
40
+ async def _request(
41
+ self, path: str, body: Dict[str, Any], attempt: int = 0
42
+ ) -> ApiResult:
43
+ import httpx
44
+
45
+ url = f"{self.api_base}{path}"
46
+ self._log(f"POST {url}")
47
+ headers = {
48
+ "Content-Type": "application/json",
49
+ "X-Trodo-Site-Id": self.site_id,
50
+ }
51
+ try:
52
+ async with httpx.AsyncClient(timeout=self.timeout) as client:
53
+ resp = await client.post(url, json=body, headers=headers)
54
+ if resp.status_code >= 500 and attempt < self.retries:
55
+ delay = 2 ** attempt
56
+ self._log(f"Retry {attempt + 1} after {delay}s")
57
+ await asyncio.sleep(delay)
58
+ return await self._request(path, body, attempt + 1)
59
+ try:
60
+ return resp.json()
61
+ except Exception:
62
+ return {}
63
+ except Exception as exc:
64
+ if attempt < self.retries:
65
+ await asyncio.sleep(2 ** attempt)
66
+ return await self._request(path, body, attempt + 1)
67
+ self._log(f"Error: {exc}")
68
+ if self.on_error:
69
+ self.on_error(exc)
70
+ return {}
71
+
72
+ async def post_track(self, session_data: Dict[str, Any]) -> ApiResult:
73
+ return await self._request("/api/sdk/track", {"sessionData": session_data})
74
+
75
+ async def post_event(self, event: EventPayload) -> ApiResult:
76
+ return await self._request("/api/events", event.to_dict())
77
+
78
+ async def post_bulk_events(self, events: list) -> ApiResult:
79
+ return await self._request(
80
+ "/api/events/bulk", {"events": [e.to_dict() for e in events]}
81
+ )
82
+
83
+ async def post_identify(self, payload: Dict[str, Any]) -> ApiResult:
84
+ return await self._request("/api/sdk/identify", payload)
85
+
86
+ async def post_wallet_address(self, payload: Dict[str, Any]) -> ApiResult:
87
+ return await self._request("/api/sdk/wallet-address", payload)
88
+
89
+ async def post_reset(self, payload: Dict[str, Any]) -> ApiResult:
90
+ return await self._request("/api/sdk/reset", payload)
91
+
92
+ async def post_people(self, path: str, payload: Dict[str, Any]) -> ApiResult:
93
+ return await self._request(path, payload)
94
+
95
+ async def post_group(self, path: str, payload: Dict[str, Any]) -> ApiResult:
96
+ return await self._request(path, payload)
trodo/api/endpoints.py CHANGED
@@ -1,20 +1,20 @@
1
- TRACK = "/api/sdk/track"
2
- EVENTS = "/api/events"
3
- EVENTS_BULK = "/api/events/bulk"
4
- IDENTIFY = "/api/sdk/identify"
5
- WALLET_ADDRESS = "/api/sdk/wallet-address"
6
- RESET = "/api/sdk/reset"
7
- PEOPLE_SET = "/api/sdk/people/set"
8
- PEOPLE_SET_ONCE = "/api/sdk/people/set_once"
9
- PEOPLE_UNSET = "/api/sdk/people/unset"
10
- PEOPLE_INCREMENT = "/api/sdk/people/increment"
11
- PEOPLE_APPEND = "/api/sdk/people/append"
12
- PEOPLE_UNION = "/api/sdk/people/union"
13
- PEOPLE_REMOVE = "/api/sdk/people/remove"
14
- PEOPLE_TRACK_CHARGE = "/api/sdk/people/track_charge"
15
- PEOPLE_CLEAR_CHARGES = "/api/sdk/people/clear_charges"
16
- PEOPLE_DELETE_USER = "/api/sdk/people/delete_user"
17
- GROUPS_SET = "/api/sdk/groups/set_group"
18
- GROUPS_ADD = "/api/sdk/groups/add_group"
19
- GROUPS_REMOVE = "/api/sdk/groups/remove_group"
20
- GROUPS_PROFILE = "/api/sdk/groups/profile"
1
+ TRACK = "/api/sdk/track"
2
+ EVENTS = "/api/events"
3
+ EVENTS_BULK = "/api/events/bulk"
4
+ IDENTIFY = "/api/sdk/identify"
5
+ WALLET_ADDRESS = "/api/sdk/wallet-address"
6
+ RESET = "/api/sdk/reset"
7
+ PEOPLE_SET = "/api/sdk/people/set"
8
+ PEOPLE_SET_ONCE = "/api/sdk/people/set_once"
9
+ PEOPLE_UNSET = "/api/sdk/people/unset"
10
+ PEOPLE_INCREMENT = "/api/sdk/people/increment"
11
+ PEOPLE_APPEND = "/api/sdk/people/append"
12
+ PEOPLE_UNION = "/api/sdk/people/union"
13
+ PEOPLE_REMOVE = "/api/sdk/people/remove"
14
+ PEOPLE_TRACK_CHARGE = "/api/sdk/people/track_charge"
15
+ PEOPLE_CLEAR_CHARGES = "/api/sdk/people/clear_charges"
16
+ PEOPLE_DELETE_USER = "/api/sdk/people/delete_user"
17
+ GROUPS_SET = "/api/sdk/groups/set_group"
18
+ GROUPS_ADD = "/api/sdk/groups/add_group"
19
+ GROUPS_REMOVE = "/api/sdk/groups/remove_group"
20
+ GROUPS_PROFILE = "/api/sdk/groups/profile"