triplicity-backend 1.0.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.
@@ -0,0 +1,5 @@
1
+ """Tenant-scoped Triplicity backend reporting."""
2
+
3
+ from .client import ActivityReceipt, TriplicityClient, TriplicityError, Visit
4
+
5
+ __all__ = ["ActivityReceipt", "TriplicityClient", "TriplicityError", "Visit"]
@@ -0,0 +1,172 @@
1
+ import json
2
+ import re
3
+ from collections.abc import Callable
4
+ from dataclasses import dataclass, field
5
+ from datetime import datetime, timedelta, timezone
6
+ from functools import partial
7
+ from time import monotonic
8
+ from urllib.parse import urlsplit
9
+ from uuid import UUID, uuid4
10
+
11
+ import urllib3
12
+ from pydantic import ValidationError
13
+ from triplicity_backend_wire import ApiClient, Configuration
14
+ from triplicity_backend_wire.api.backend_api import BackendApi
15
+ from triplicity_backend_wire.exceptions import ApiException
16
+ from triplicity_backend_wire.models.activity_event import ActivityEvent
17
+ from triplicity_backend_wire.models.activity_receipt import ActivityReceipt
18
+ from triplicity_backend_wire.models.create_visit_request import CreateVisitRequest
19
+ from triplicity_backend_wire.models.visit_result import VisitResult
20
+
21
+
22
+ class TriplicityError(Exception):
23
+ """Safe diagnostic details. Retry-After is the original HTTP header value."""
24
+
25
+ def __init__(self, kind: str, status: int | None = None, retry_after: str | None = None):
26
+ self.kind = kind
27
+ self.status = status
28
+ self.retry_after = retry_after
29
+ super().__init__(f"Triplicity {kind}" + (f" (HTTP {status})" if status else ""))
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class Visit:
34
+ tenant_ref: str
35
+ visit_ref: UUID
36
+ account_ref: str | None
37
+ visit_token: str = field(repr=False)
38
+ created_at: datetime
39
+ expires_at: datetime
40
+
41
+
42
+ class TriplicityClient:
43
+ """Synchronous backend client. Reuse one instance per reporting tenant."""
44
+
45
+ def __init__(self, endpoint: str, tenant_ref: str, server_token: str):
46
+ url = urlsplit(endpoint)
47
+ local = url.hostname in {"localhost", "127.0.0.1", "::1"}
48
+ if (not url.hostname or url.username is not None or url.password is not None
49
+ or "?" in endpoint or "#" in endpoint or not url.path.endswith("/v1/")
50
+ or not (url.scheme == "https" or (url.scheme == "http" and local))):
51
+ raise ValueError("Use an HTTPS endpoint ending in /v1/, or loopback HTTP for development.")
52
+ if not re.fullmatch(r"[a-z0-9][a-z0-9_-]{0,63}", tenant_ref):
53
+ raise ValueError("Invalid tenant reference.")
54
+ if not re.fullmatch(r"tp_srv_[A-Za-z0-9_-]{43}", server_token):
55
+ raise ValueError("Invalid server token.")
56
+ self._tenant = tenant_ref
57
+ # Disable urllib3's automatic retries and redirects. Activity is the only
58
+ # operation the SDK can replay, using the same validated event each time.
59
+ config = Configuration(host=endpoint.removesuffix("/v1/"), access_token=server_token,
60
+ retries=False, proxy="")
61
+ self._client = ApiClient(config)
62
+ self._api = BackendApi(self._client)
63
+ self._closed = False
64
+
65
+ def __enter__(self):
66
+ return self
67
+
68
+ def __exit__(self, *_):
69
+ self.close()
70
+
71
+ def close(self) -> None:
72
+ self._closed = True
73
+ self._client.configuration.access_token = None
74
+ self._client.rest_client.pool_manager.clear()
75
+
76
+ def _send(self, request: Callable[..., urllib3.HTTPResponse], activity: bool):
77
+ if self._closed:
78
+ raise RuntimeError("The Triplicity client is closed.")
79
+ for attempt in range(2 if activity else 1):
80
+ try:
81
+ deadline = monotonic() + 2
82
+ response = request(_request_timeout=2.0)
83
+ try:
84
+ status = response.status
85
+ if not 200 <= status < 300:
86
+ raise TriplicityError("http", status, response.headers.get("Retry-After"))
87
+ if status != 201 and not (activity and status == 200):
88
+ raise TriplicityError("invalid_response", status)
89
+ media = response.headers.get("Content-Type", "").split(";", 1)[0].strip().lower()
90
+ if media != "application/json":
91
+ raise TriplicityError("invalid_response", status)
92
+ # urllib3's socket timeout limits an individual read. Check the
93
+ # elapsed time between chunks as well when the server trickles data.
94
+ data = bytearray()
95
+ while len(data) <= 4096:
96
+ if monotonic() >= deadline:
97
+ raise urllib3.exceptions.TimeoutError("Response deadline elapsed.")
98
+ chunk = response.read1(4097 - len(data))
99
+ if not chunk:
100
+ break
101
+ data.extend(chunk)
102
+ if len(data) > 4096:
103
+ raise TriplicityError("invalid_response", status)
104
+ try:
105
+ result = json.loads(data.decode("utf-8"))
106
+ except (UnicodeError, ValueError):
107
+ raise TriplicityError("invalid_response", status) from None
108
+ if not isinstance(result, dict):
109
+ raise TriplicityError("invalid_response", status)
110
+ return status, result
111
+ finally:
112
+ response.close()
113
+ response.release_conn()
114
+ except TriplicityError as error:
115
+ if not (activity and attempt == 0 and error.status and 500 <= error.status < 600):
116
+ raise
117
+ except (urllib3.exceptions.HTTPError, ApiException, OSError) as error:
118
+ if not activity or attempt == 1:
119
+ kind = "timeout" if isinstance(error, urllib3.exceptions.TimeoutError) else "network"
120
+ raise TriplicityError(kind) from None
121
+ raise AssertionError("unreachable")
122
+
123
+ def create_visit(self, account_ref: str | None = None) -> Visit:
124
+ try:
125
+ body = CreateVisitRequest(tenant_ref=self._tenant, account_ref=account_ref)
126
+ except ValidationError:
127
+ raise ValueError("Invalid account reference.") from None
128
+ status, result = self._send(partial(self._api.create_visit_without_preload_content, body), False)
129
+ try:
130
+ visit = VisitResult.model_validate(result, by_alias=True, by_name=False)
131
+ now = datetime.now(timezone.utc)
132
+ if (visit.tenant_ref != self._tenant or visit.account_ref != account_ref
133
+ or visit.expires_at.tzinfo is None or visit.created_at.tzinfo is None
134
+ or visit.created_at > now + timedelta(seconds=5)
135
+ or visit.expires_at <= max(now, visit.created_at)
136
+ or visit.expires_at - visit.created_at > timedelta(minutes=30)):
137
+ raise ValueError
138
+ except (ValueError, TypeError):
139
+ raise TriplicityError("invalid_response", status) from None
140
+ return Visit(visit.tenant_ref, visit.visit_ref, visit.account_ref, visit.visit_token,
141
+ visit.created_at, visit.expires_at)
142
+
143
+ def record_activity(self, visit_ref: str | UUID, *, action: str, outcome: str,
144
+ event_id: str | UUID | None = None, occurred_at: datetime | None = None,
145
+ account_ref: str | None = None, resource_ref: str | None = None,
146
+ authentication: dict | None = None, request_context: dict | None = None) -> ActivityReceipt:
147
+ now = datetime.now(timezone.utc)
148
+ timestamp = now if occurred_at is None else occurred_at
149
+ if timestamp.tzinfo is None or abs(now - timestamp) > timedelta(minutes=5):
150
+ raise ValueError("Use a current timestamp with a UTC offset.")
151
+ details = authentication is not None or request_context is not None
152
+ try:
153
+ event = ActivityEvent.model_validate({
154
+ "schemaVersion": "1.1" if details else "1.0",
155
+ "tenantRef": self._tenant, "visitRef": str(visit_ref),
156
+ "eventId": str(uuid4() if event_id is None else event_id),
157
+ "occurredAt": timestamp, "action": action, "outcome": outcome,
158
+ "accountRef": account_ref, "resourceRef": resource_ref,
159
+ "authentication": authentication, "requestContext": request_context,
160
+ }, extra="forbid")
161
+ except ValidationError:
162
+ raise ValueError("Invalid Triplicity activity fields.") from None
163
+ if len(json.dumps(self._client.sanitize_for_serialization(event)).encode("utf-8")) > 8192:
164
+ raise ValueError("Activity exceeds the 8 KiB request limit.")
165
+ status, result = self._send(partial(self._api.record_activity_without_preload_content, event), True)
166
+ try:
167
+ receipt = ActivityReceipt.model_validate(result, by_alias=True, by_name=False)
168
+ if receipt.event_id != event.event_id or receipt.duplicate != (status == 200):
169
+ raise ValueError
170
+ except ValueError:
171
+ raise TriplicityError("invalid_response", status) from None
172
+ return receipt
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,55 @@
1
+ Metadata-Version: 2.4
2
+ Name: triplicity-backend
3
+ Version: 1.0.0
4
+ Summary: Triplicity server-side visit and activity reporting
5
+ Author: IATFusion
6
+ License-Expression: MIT
7
+ License-File: LICENSE.txt
8
+ Classifier: Programming Language :: Python :: 3 :: Only
9
+ Classifier: Typing :: Typed
10
+ Requires-Python: >=3.11
11
+ Requires-Dist: pydantic<3,>=2.12
12
+ Requires-Dist: python-dateutil<3,>=2.8.2
13
+ Requires-Dist: typing-extensions<5,>=4.7.1
14
+ Requires-Dist: urllib3<3,>=2.7
15
+ Description-Content-Type: text/markdown
16
+
17
+ # Triplicity backend SDK for Python
18
+
19
+ Install the synchronous SDK into the virtual environment for your Python 3.11+
20
+ reporting service. Anyone can install the package from PyPI.
21
+
22
+ ```sh
23
+ pip install triplicity-backend
24
+ ```
25
+
26
+ Reporting requires a private server token for your tenant. Set the variables
27
+ below on your server. Use the collector's HTTPS base URL ending in `/v1/`
28
+ for `TRIPLICITY_ENDPOINT`. Call `record_activity()` after your application
29
+ has determined the outcome.
30
+
31
+ ```python
32
+ import os
33
+ from triplicity_backend import TriplicityClient
34
+
35
+ with TriplicityClient(
36
+ endpoint=os.environ["TRIPLICITY_ENDPOINT"], # HTTPS URL ending in /v1/
37
+ tenant_ref=os.environ["TRIPLICITY_TENANT"],
38
+ server_token=os.environ["TRIPLICITY_SERVER_TOKEN"],
39
+ ) as client:
40
+ visit = client.create_visit()
41
+ receipt = client.record_activity(visit.visit_ref, action="login", outcome="success")
42
+ ```
43
+
44
+ The client makes one visit creation attempt and
45
+ can repeat an activity once after a transport failure, timeout, or server error.
46
+ For subsequent application-managed retries, supply the same event ID, timestamp
47
+ and activity details while the visit is active. `TriplicityError` exposes
48
+ `kind`, HTTP `status` and the optional raw `retry_after` header. Avoid logging
49
+ credentials and payloads.
50
+
51
+ ## Release notes
52
+
53
+ Version 1.0.0 is the first public Python release. It supports backend
54
+ OpenAPI contract 1.1.0, activity payloads 1.0 and 1.1, and collector
55
+ v1.4.0 or later. The SDK is distributed under the MIT license.
@@ -0,0 +1,25 @@
1
+ triplicity_backend/__init__.py,sha256=n1BU0pdwtOFTsOFO1b4ZYCGuwkVfvEZmlvpHEUXUGoA,208
2
+ triplicity_backend/client.py,sha256=Z5g45ElJ8Vk38ioQmkxLckU7GjdUgQ_VBZrghWJXcEI,8895
3
+ triplicity_backend/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
4
+ triplicity_backend_wire/__init__.py,sha256=iAuLX04inmHCwxyB2yOiPO8zIkggq7pmQaa-dcfZOrU,2415
5
+ triplicity_backend_wire/api_client.py,sha256=E-qRZQO-iXxzJlQ8ptS-a3vQKPjl0awjBKNm7LPLwdY,31355
6
+ triplicity_backend_wire/api_response.py,sha256=eMxw1mpmJcoGZ3gs9z6jM4oYoZ10Gjk333s9sKxGv7s,652
7
+ triplicity_backend_wire/configuration.py,sha256=7JAJmLaC68gs66PdXrURdNHqZMDKmAoN6OmYTanjLAs,22016
8
+ triplicity_backend_wire/exceptions.py,sha256=kP0f2ZgpIKdtTPPLG6Zx0mwJey-8hBH8rXFJY0hFWZY,6518
9
+ triplicity_backend_wire/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
+ triplicity_backend_wire/rest.py,sha256=MlFeHRi59TL99weFlqzUivsSOdEqqD65l5Enp0s0HrI,12375
11
+ triplicity_backend_wire/api/__init__.py,sha256=JQRB2XRfe1LU7j0-NfxkZpflg36BHS27xUWh_UvcEVc,111
12
+ triplicity_backend_wire/api/backend_api.py,sha256=yH620h3HEyTw2cIQvvwwfa647njHmIObAjV49yEDki4,24695
13
+ triplicity_backend_wire/models/__init__.py,sha256=KuDYgmatIH1AB7-JMMo3MHv1rlF0YLpD2G7bnuwhcew,978
14
+ triplicity_backend_wire/models/activity_event.py,sha256=_27ReISCioXlKxQNf2vSi0UQnSwzSZigH1lE233v11k,8956
15
+ triplicity_backend_wire/models/activity_receipt.py,sha256=RSPZphNkSL9bxVgUrhIPB6LuTRcLw81VzFqMDKsjrxc,3092
16
+ triplicity_backend_wire/models/api_error.py,sha256=m5B5ZqT028Py3FIchEqjJiV6WgfMQ7Ftd5SpE7jwZIU,2452
17
+ triplicity_backend_wire/models/authentication_details.py,sha256=XAuOGkhK9njOJpToGkR0Yr_DzT3Lo8-GuMwxyZuG0fA,3936
18
+ triplicity_backend_wire/models/backend_request_context.py,sha256=BD73a9BM0D34tZAUG94yMghVaKHZ3QLilWOvraJfKik,4732
19
+ triplicity_backend_wire/models/create_visit_request.py,sha256=7hu56bLqmAC8or653si0nyg12WqE9C277kR99-ojE0c,3573
20
+ triplicity_backend_wire/models/request_metadata.py,sha256=MT8U8NTkP7GilSkA2ScbJaqulADP23U1qx5FHC8AixI,5374
21
+ triplicity_backend_wire/models/visit_result.py,sha256=areighfy2BzY28-ghl0DD-VPV9y2kKbCp4zCPt2cYj0,5430
22
+ triplicity_backend-1.0.0.dist-info/METADATA,sha256=JNVh_xX2K4mUyfNklvIOaEmNXt8S3EsN2uV1b0zkn8Q,1985
23
+ triplicity_backend-1.0.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
24
+ triplicity_backend-1.0.0.dist-info/licenses/LICENSE.txt,sha256=FwNSpRfj6olo3r_NHGTqhpifHI_oWBYG1JXhiF-4J50,1066
25
+ triplicity_backend-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 IATFusion
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.
@@ -0,0 +1,64 @@
1
+ # coding: utf-8
2
+
3
+ # flake8: noqa
4
+
5
+ """
6
+ Triplicity Backend Reporting API
7
+
8
+ Create tenant-scoped visits and report outcomes from your application server.
9
+
10
+ The version of the OpenAPI document: 1.1.0
11
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
12
+
13
+ Do not edit the class manually.
14
+ """ # noqa: E501
15
+
16
+
17
+ __version__ = "1.0.0"
18
+
19
+ # Define package exports
20
+ __all__ = [
21
+ "BackendApi",
22
+ "ApiResponse",
23
+ "ApiClient",
24
+ "Configuration",
25
+ "OpenApiException",
26
+ "ApiTypeError",
27
+ "ApiValueError",
28
+ "ApiKeyError",
29
+ "ApiAttributeError",
30
+ "ApiException",
31
+ "ActivityEvent",
32
+ "ActivityReceipt",
33
+ "ApiError",
34
+ "AuthenticationDetails",
35
+ "BackendRequestContext",
36
+ "CreateVisitRequest",
37
+ "RequestMetadata",
38
+ "VisitResult",
39
+ ]
40
+
41
+ # import apis into sdk package
42
+ from triplicity_backend_wire.api.backend_api import BackendApi as BackendApi
43
+
44
+ # import ApiClient
45
+ from triplicity_backend_wire.api_response import ApiResponse as ApiResponse
46
+ from triplicity_backend_wire.api_client import ApiClient as ApiClient
47
+ from triplicity_backend_wire.configuration import Configuration as Configuration
48
+ from triplicity_backend_wire.exceptions import OpenApiException as OpenApiException
49
+ from triplicity_backend_wire.exceptions import ApiTypeError as ApiTypeError
50
+ from triplicity_backend_wire.exceptions import ApiValueError as ApiValueError
51
+ from triplicity_backend_wire.exceptions import ApiKeyError as ApiKeyError
52
+ from triplicity_backend_wire.exceptions import ApiAttributeError as ApiAttributeError
53
+ from triplicity_backend_wire.exceptions import ApiException as ApiException
54
+
55
+ # import models into sdk package
56
+ from triplicity_backend_wire.models.activity_event import ActivityEvent as ActivityEvent
57
+ from triplicity_backend_wire.models.activity_receipt import ActivityReceipt as ActivityReceipt
58
+ from triplicity_backend_wire.models.api_error import ApiError as ApiError
59
+ from triplicity_backend_wire.models.authentication_details import AuthenticationDetails as AuthenticationDetails
60
+ from triplicity_backend_wire.models.backend_request_context import BackendRequestContext as BackendRequestContext
61
+ from triplicity_backend_wire.models.create_visit_request import CreateVisitRequest as CreateVisitRequest
62
+ from triplicity_backend_wire.models.request_metadata import RequestMetadata as RequestMetadata
63
+ from triplicity_backend_wire.models.visit_result import VisitResult as VisitResult
64
+
@@ -0,0 +1,5 @@
1
+ # flake8: noqa
2
+
3
+ # import apis into api package
4
+ from triplicity_backend_wire.api.backend_api import BackendApi
5
+