viktorbarzin-telemetry 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- viktorbarzin_telemetry-0.1.0/.gitignore +27 -0
- viktorbarzin_telemetry-0.1.0/LICENSE +21 -0
- viktorbarzin_telemetry-0.1.0/PKG-INFO +69 -0
- viktorbarzin_telemetry-0.1.0/README.md +50 -0
- viktorbarzin_telemetry-0.1.0/pyproject.toml +58 -0
- viktorbarzin_telemetry-0.1.0/src/viktorbarzin_telemetry/__init__.py +58 -0
- viktorbarzin_telemetry-0.1.0/src/viktorbarzin_telemetry/_asgi.py +39 -0
- viktorbarzin_telemetry-0.1.0/src/viktorbarzin_telemetry/_config.py +48 -0
- viktorbarzin_telemetry-0.1.0/src/viktorbarzin_telemetry/_context.py +63 -0
- viktorbarzin_telemetry-0.1.0/src/viktorbarzin_telemetry/_events.py +188 -0
- viktorbarzin_telemetry-0.1.0/src/viktorbarzin_telemetry/_logging.py +201 -0
- viktorbarzin_telemetry-0.1.0/src/viktorbarzin_telemetry/_scrub.py +54 -0
- viktorbarzin_telemetry-0.1.0/src/viktorbarzin_telemetry/_sentry.py +22 -0
- viktorbarzin_telemetry-0.1.0/src/viktorbarzin_telemetry/_validation.py +49 -0
- viktorbarzin_telemetry-0.1.0/src/viktorbarzin_telemetry/py.typed +0 -0
- viktorbarzin_telemetry-0.1.0/stubs/segment/__init__.pyi +0 -0
- viktorbarzin_telemetry-0.1.0/stubs/segment/analytics/__init__.pyi +1 -0
- viktorbarzin_telemetry-0.1.0/stubs/segment/analytics/client.pyi +49 -0
- viktorbarzin_telemetry-0.1.0/tests/test_asgi.py +66 -0
- viktorbarzin_telemetry-0.1.0/tests/test_events.py +287 -0
- viktorbarzin_telemetry-0.1.0/tests/test_logging.py +233 -0
- viktorbarzin_telemetry-0.1.0/tests/test_validation.py +96 -0
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# Python
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
.venv/
|
|
5
|
+
dist/
|
|
6
|
+
build/
|
|
7
|
+
*.egg-info/
|
|
8
|
+
.pytest_cache/
|
|
9
|
+
.mypy_cache/
|
|
10
|
+
.ruff_cache/
|
|
11
|
+
.hypothesis/
|
|
12
|
+
|
|
13
|
+
# Go
|
|
14
|
+
go/coverage.out
|
|
15
|
+
|
|
16
|
+
# Android / Gradle
|
|
17
|
+
.gradle/
|
|
18
|
+
android/**/build/
|
|
19
|
+
local.properties
|
|
20
|
+
.idea/
|
|
21
|
+
*.iml
|
|
22
|
+
|
|
23
|
+
# Editors and OS
|
|
24
|
+
.DS_Store
|
|
25
|
+
|
|
26
|
+
# agents
|
|
27
|
+
.worktrees/
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Viktor Barzin
|
|
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,69 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: viktorbarzin-telemetry
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Product events, errors and JSON logs to the viktorbarzin.me telemetry standard
|
|
5
|
+
Project-URL: Source, https://github.com/ViktorBarzin/telemetry
|
|
6
|
+
Author: Viktor Barzin
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Typing :: Typed
|
|
12
|
+
Requires-Python: >=3.10
|
|
13
|
+
Requires-Dist: segment-analytics-python<3,>=2.3
|
|
14
|
+
Provides-Extra: otel
|
|
15
|
+
Requires-Dist: opentelemetry-api>=1.20; extra == 'otel'
|
|
16
|
+
Provides-Extra: sentry
|
|
17
|
+
Requires-Dist: sentry-sdk<3,>=2.0; extra == 'sentry'
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
|
|
20
|
+
# viktorbarzin-telemetry
|
|
21
|
+
|
|
22
|
+
The Python client for the viktorbarzin.me telemetry standard: Product events
|
|
23
|
+
through Segment's `segment-analytics-python` to our Event pipeline, errors
|
|
24
|
+
through `sentry-sdk` to GlitchTip, and logs as one OpenTelemetry-shaped JSON
|
|
25
|
+
object per line on stdout.
|
|
26
|
+
|
|
27
|
+
```sh
|
|
28
|
+
pip install viktorbarzin-telemetry # events and logs
|
|
29
|
+
pip install "viktorbarzin-telemetry[sentry]" # plus Sentry
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
import logging
|
|
34
|
+
import viktorbarzin_telemetry as telemetry
|
|
35
|
+
|
|
36
|
+
telemetry.setup_logging(service_name="tv", service_version="1.4.0")
|
|
37
|
+
telemetry.configure(
|
|
38
|
+
app="tv",
|
|
39
|
+
write_key=settings.segment_write_key,
|
|
40
|
+
release="1.4.0",
|
|
41
|
+
environment="production", # or set TELEMETRY_ENVIRONMENT=production
|
|
42
|
+
host=settings.event_pipeline_url, # or set TELEMETRY_HOST
|
|
43
|
+
dsn=settings.sentry_dsn, # https://<key>@tv.viktorbarzin.me/_t/x/<project id>
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
with telemetry.log_context(enduser_id=user.sub):
|
|
47
|
+
logging.getLogger(__name__).info("recording started", extra={"channel_id": 4})
|
|
48
|
+
telemetry.track("recording.started", {"channel_id": 4})
|
|
49
|
+
|
|
50
|
+
telemetry.flush() # before exit
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
- `host` is the Event pipeline's base URL, from the argument or
|
|
54
|
+
`TELEMETRY_HOST`. Inside our cluster it is the event-pipeline Service's URL;
|
|
55
|
+
elsewhere use `telemetry.public_host("tv.viktorbarzin.me")`. Production
|
|
56
|
+
without a host raises `ValueError`.
|
|
57
|
+
- Nothing is sent unless the environment is `production`. Invalid events
|
|
58
|
+
are validated in every environment, dropped and logged as a warning.
|
|
59
|
+
- `track` takes `userId` from `log_context(enduser_id=...)` and `anonymousId`
|
|
60
|
+
from `log_context(anonymous_id=...)`, or a fresh random id.
|
|
61
|
+
- `EnduserMiddleware(app, resolve_user=...)` sets `enduser.id` per request in
|
|
62
|
+
any ASGI app. `resolve_user` gets the ASGI scope and returns the Person's
|
|
63
|
+
Authentik `sub` or None, directly or as an awaitable.
|
|
64
|
+
- `trace_id` and `span_id` come from the active OpenTelemetry span when
|
|
65
|
+
`opentelemetry-api` is installed, else from `log_context`.
|
|
66
|
+
- The JSON formatter masks the write key, values passed as `secrets=`, and
|
|
67
|
+
bearer tokens, Basic credentials, JWTs and PEM blocks.
|
|
68
|
+
|
|
69
|
+
The standard itself is in the repository README.
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# viktorbarzin-telemetry
|
|
2
|
+
|
|
3
|
+
The Python client for the viktorbarzin.me telemetry standard: Product events
|
|
4
|
+
through Segment's `segment-analytics-python` to our Event pipeline, errors
|
|
5
|
+
through `sentry-sdk` to GlitchTip, and logs as one OpenTelemetry-shaped JSON
|
|
6
|
+
object per line on stdout.
|
|
7
|
+
|
|
8
|
+
```sh
|
|
9
|
+
pip install viktorbarzin-telemetry # events and logs
|
|
10
|
+
pip install "viktorbarzin-telemetry[sentry]" # plus Sentry
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
import logging
|
|
15
|
+
import viktorbarzin_telemetry as telemetry
|
|
16
|
+
|
|
17
|
+
telemetry.setup_logging(service_name="tv", service_version="1.4.0")
|
|
18
|
+
telemetry.configure(
|
|
19
|
+
app="tv",
|
|
20
|
+
write_key=settings.segment_write_key,
|
|
21
|
+
release="1.4.0",
|
|
22
|
+
environment="production", # or set TELEMETRY_ENVIRONMENT=production
|
|
23
|
+
host=settings.event_pipeline_url, # or set TELEMETRY_HOST
|
|
24
|
+
dsn=settings.sentry_dsn, # https://<key>@tv.viktorbarzin.me/_t/x/<project id>
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
with telemetry.log_context(enduser_id=user.sub):
|
|
28
|
+
logging.getLogger(__name__).info("recording started", extra={"channel_id": 4})
|
|
29
|
+
telemetry.track("recording.started", {"channel_id": 4})
|
|
30
|
+
|
|
31
|
+
telemetry.flush() # before exit
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
- `host` is the Event pipeline's base URL, from the argument or
|
|
35
|
+
`TELEMETRY_HOST`. Inside our cluster it is the event-pipeline Service's URL;
|
|
36
|
+
elsewhere use `telemetry.public_host("tv.viktorbarzin.me")`. Production
|
|
37
|
+
without a host raises `ValueError`.
|
|
38
|
+
- Nothing is sent unless the environment is `production`. Invalid events
|
|
39
|
+
are validated in every environment, dropped and logged as a warning.
|
|
40
|
+
- `track` takes `userId` from `log_context(enduser_id=...)` and `anonymousId`
|
|
41
|
+
from `log_context(anonymous_id=...)`, or a fresh random id.
|
|
42
|
+
- `EnduserMiddleware(app, resolve_user=...)` sets `enduser.id` per request in
|
|
43
|
+
any ASGI app. `resolve_user` gets the ASGI scope and returns the Person's
|
|
44
|
+
Authentik `sub` or None, directly or as an awaitable.
|
|
45
|
+
- `trace_id` and `span_id` come from the active OpenTelemetry span when
|
|
46
|
+
`opentelemetry-api` is installed, else from `log_context`.
|
|
47
|
+
- The JSON formatter masks the write key, values passed as `secrets=`, and
|
|
48
|
+
bearer tokens, Basic credentials, JWTs and PEM blocks.
|
|
49
|
+
|
|
50
|
+
The standard itself is in the repository README.
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.27"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "viktorbarzin-telemetry"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Product events, errors and JSON logs to the viktorbarzin.me telemetry standard"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
authors = [{ name = "Viktor Barzin" }]
|
|
13
|
+
requires-python = ">=3.10"
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Typing :: Typed",
|
|
17
|
+
"License :: OSI Approved :: MIT License",
|
|
18
|
+
]
|
|
19
|
+
dependencies = ["segment-analytics-python>=2.3,<3"]
|
|
20
|
+
|
|
21
|
+
[project.optional-dependencies]
|
|
22
|
+
sentry = ["sentry-sdk>=2.0,<3"]
|
|
23
|
+
otel = ["opentelemetry-api>=1.20"]
|
|
24
|
+
|
|
25
|
+
[project.urls]
|
|
26
|
+
Source = "https://github.com/ViktorBarzin/telemetry"
|
|
27
|
+
|
|
28
|
+
[dependency-groups]
|
|
29
|
+
dev = [
|
|
30
|
+
"pytest>=8",
|
|
31
|
+
"hypothesis>=6.100",
|
|
32
|
+
"mypy>=1.11",
|
|
33
|
+
"ruff>=0.6",
|
|
34
|
+
"sentry-sdk>=2.0,<3",
|
|
35
|
+
"opentelemetry-api>=1.20",
|
|
36
|
+
"opentelemetry-sdk>=1.20",
|
|
37
|
+
"types-requests",
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
[tool.hatch.build.targets.wheel]
|
|
41
|
+
packages = ["src/viktorbarzin_telemetry"]
|
|
42
|
+
|
|
43
|
+
[tool.pytest.ini_options]
|
|
44
|
+
testpaths = ["tests"]
|
|
45
|
+
addopts = "-q"
|
|
46
|
+
|
|
47
|
+
[tool.mypy]
|
|
48
|
+
strict = true
|
|
49
|
+
python_version = "3.10"
|
|
50
|
+
mypy_path = "stubs"
|
|
51
|
+
files = ["src", "tests"]
|
|
52
|
+
|
|
53
|
+
[tool.ruff]
|
|
54
|
+
line-length = 100
|
|
55
|
+
target-version = "py310"
|
|
56
|
+
|
|
57
|
+
[tool.ruff.lint]
|
|
58
|
+
select = ["E", "F", "W", "I", "UP", "B", "SIM", "RUF", "ANN"]
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""Client library for the viktorbarzin.me telemetry standard.
|
|
2
|
+
|
|
3
|
+
Product events go to the Event pipeline through Segment's SDK, errors to
|
|
4
|
+
GlitchTip through Sentry's, and logs to stdout as OpenTelemetry-shaped JSON.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from ._asgi import EnduserMiddleware
|
|
8
|
+
from ._config import (
|
|
9
|
+
ENVIRONMENT_VARIABLE,
|
|
10
|
+
HOST_VARIABLE,
|
|
11
|
+
PRODUCTION,
|
|
12
|
+
Config,
|
|
13
|
+
public_host,
|
|
14
|
+
resolve_environment,
|
|
15
|
+
resolve_host,
|
|
16
|
+
)
|
|
17
|
+
from ._context import LogContext, current_context, log_context
|
|
18
|
+
from ._events import EventClient, Telemetry, configure, flush, identify, track
|
|
19
|
+
from ._logging import JsonFormatter, setup_logging
|
|
20
|
+
from ._scrub import Scrubber, register_secret
|
|
21
|
+
from ._sentry import init_sentry
|
|
22
|
+
from ._validation import (
|
|
23
|
+
MAX_PROPERTIES_LENGTH,
|
|
24
|
+
JsonValue,
|
|
25
|
+
Properties,
|
|
26
|
+
event_name_problem,
|
|
27
|
+
properties_problem,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"ENVIRONMENT_VARIABLE",
|
|
32
|
+
"HOST_VARIABLE",
|
|
33
|
+
"MAX_PROPERTIES_LENGTH",
|
|
34
|
+
"PRODUCTION",
|
|
35
|
+
"Config",
|
|
36
|
+
"EnduserMiddleware",
|
|
37
|
+
"EventClient",
|
|
38
|
+
"JsonFormatter",
|
|
39
|
+
"JsonValue",
|
|
40
|
+
"LogContext",
|
|
41
|
+
"Properties",
|
|
42
|
+
"Scrubber",
|
|
43
|
+
"Telemetry",
|
|
44
|
+
"configure",
|
|
45
|
+
"current_context",
|
|
46
|
+
"event_name_problem",
|
|
47
|
+
"flush",
|
|
48
|
+
"identify",
|
|
49
|
+
"init_sentry",
|
|
50
|
+
"log_context",
|
|
51
|
+
"properties_problem",
|
|
52
|
+
"public_host",
|
|
53
|
+
"register_secret",
|
|
54
|
+
"resolve_environment",
|
|
55
|
+
"resolve_host",
|
|
56
|
+
"setup_logging",
|
|
57
|
+
"track",
|
|
58
|
+
]
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""ASGI middleware that puts the signed-in Person on the request's log context."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import contextlib
|
|
6
|
+
from collections.abc import Awaitable, Callable, MutableMapping
|
|
7
|
+
|
|
8
|
+
from ._context import log_context
|
|
9
|
+
|
|
10
|
+
Scope = MutableMapping[str, object]
|
|
11
|
+
Message = MutableMapping[str, object]
|
|
12
|
+
Receive = Callable[[], Awaitable[Message]]
|
|
13
|
+
Send = Callable[[Message], Awaitable[None]]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class EnduserMiddleware:
|
|
17
|
+
"""Sets ``enduser.id`` for each HTTP or WebSocket request.
|
|
18
|
+
|
|
19
|
+
``resolve_user`` gets the ASGI scope and returns the Person's Authentik
|
|
20
|
+
``sub`` (or None), directly or as an awaitable. With Starlette or FastAPI:
|
|
21
|
+
``app.add_middleware(EnduserMiddleware, resolve_user=...)``.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
App = Callable[[Scope, Receive, Send], Awaitable[None]]
|
|
25
|
+
Resolver = Callable[[Scope], "str | Awaitable[str | None] | None"]
|
|
26
|
+
|
|
27
|
+
def __init__(self, app: App, resolve_user: Resolver) -> None:
|
|
28
|
+
self.app = app
|
|
29
|
+
self.resolve_user = resolve_user
|
|
30
|
+
|
|
31
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
32
|
+
if scope.get("type") not in ("http", "websocket"):
|
|
33
|
+
await self.app(scope, receive, send)
|
|
34
|
+
return
|
|
35
|
+
result = self.resolve_user(scope)
|
|
36
|
+
user = result if result is None or isinstance(result, str) else await result
|
|
37
|
+
block = log_context(enduser_id=user) if user else contextlib.nullcontext()
|
|
38
|
+
with block:
|
|
39
|
+
await self.app(scope, receive, send)
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import dataclasses
|
|
4
|
+
import os
|
|
5
|
+
|
|
6
|
+
PRODUCTION = "production"
|
|
7
|
+
ENVIRONMENT_VARIABLE = "TELEMETRY_ENVIRONMENT"
|
|
8
|
+
HOST_VARIABLE = "TELEMETRY_HOST"
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def resolve_environment(explicit: str | None = None) -> str:
|
|
12
|
+
"""The explicit value, else ``$TELEMETRY_ENVIRONMENT``, else ``dev``."""
|
|
13
|
+
if explicit is not None:
|
|
14
|
+
return explicit
|
|
15
|
+
return os.environ.get(ENVIRONMENT_VARIABLE) or "dev"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def resolve_host(explicit: str | None = None) -> str | None:
|
|
19
|
+
"""The explicit Event pipeline URL, else ``$TELEMETRY_HOST``, else None."""
|
|
20
|
+
if explicit:
|
|
21
|
+
return explicit
|
|
22
|
+
return os.environ.get(HOST_VARIABLE) or None
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def public_host(app_host: str) -> str:
|
|
26
|
+
"""The Event pipeline on an app's public host, for code outside the cluster."""
|
|
27
|
+
return f"https://{app_host}/_t/e"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclasses.dataclass(frozen=True)
|
|
31
|
+
class Config:
|
|
32
|
+
"""One app's telemetry settings.
|
|
33
|
+
|
|
34
|
+
``host`` is the Event pipeline's base URL; the Segment client appends
|
|
35
|
+
``/v1/batch``. Production needs one. Inside our cluster it is the
|
|
36
|
+
pipeline's Service; elsewhere it is ``public_host("<app host>")``.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
app: str
|
|
40
|
+
write_key: str
|
|
41
|
+
release: str
|
|
42
|
+
environment: str
|
|
43
|
+
host: str | None = None
|
|
44
|
+
dsn: str | None = None
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def production(self) -> bool:
|
|
48
|
+
return self.environment == PRODUCTION
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Per-request context: who the Person is and which trace the work belongs to.
|
|
2
|
+
|
|
3
|
+
Kept in a ContextVar, so each asyncio task and thread sees its own value and
|
|
4
|
+
the value unwinds when the ``log_context`` block ends.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import contextlib
|
|
10
|
+
import contextvars
|
|
11
|
+
import dataclasses
|
|
12
|
+
from collections.abc import Iterator, Mapping
|
|
13
|
+
from types import MappingProxyType
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclasses.dataclass(frozen=True)
|
|
17
|
+
class LogContext:
|
|
18
|
+
enduser_id: str | None = None
|
|
19
|
+
anonymous_id: str | None = None
|
|
20
|
+
trace_id: str | None = None
|
|
21
|
+
span_id: str | None = None
|
|
22
|
+
attributes: Mapping[str, object] = dataclasses.field(
|
|
23
|
+
default_factory=lambda: MappingProxyType({})
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
_EMPTY = LogContext()
|
|
28
|
+
_current: contextvars.ContextVar[LogContext] = contextvars.ContextVar(
|
|
29
|
+
"viktorbarzin_telemetry_context", default=_EMPTY
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def current_context() -> LogContext:
|
|
34
|
+
return _current.get()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@contextlib.contextmanager
|
|
38
|
+
def log_context(
|
|
39
|
+
*,
|
|
40
|
+
enduser_id: str | None = None,
|
|
41
|
+
anonymous_id: str | None = None,
|
|
42
|
+
trace_id: str | None = None,
|
|
43
|
+
span_id: str | None = None,
|
|
44
|
+
**attributes: object,
|
|
45
|
+
) -> Iterator[LogContext]:
|
|
46
|
+
"""Add fields to every log line, and ids to every event, inside the block.
|
|
47
|
+
|
|
48
|
+
Values left as None keep whatever an enclosing block set. Keyword
|
|
49
|
+
``attributes`` merge over the enclosing ones.
|
|
50
|
+
"""
|
|
51
|
+
outer = _current.get()
|
|
52
|
+
merged = LogContext(
|
|
53
|
+
enduser_id=enduser_id if enduser_id is not None else outer.enduser_id,
|
|
54
|
+
anonymous_id=anonymous_id if anonymous_id is not None else outer.anonymous_id,
|
|
55
|
+
trace_id=trace_id if trace_id is not None else outer.trace_id,
|
|
56
|
+
span_id=span_id if span_id is not None else outer.span_id,
|
|
57
|
+
attributes=MappingProxyType({**outer.attributes, **attributes}),
|
|
58
|
+
)
|
|
59
|
+
token = _current.set(merged)
|
|
60
|
+
try:
|
|
61
|
+
yield merged
|
|
62
|
+
finally:
|
|
63
|
+
_current.reset(token)
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
"""Product events through Segment's Python SDK, pointed at the Event pipeline."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import uuid
|
|
7
|
+
from typing import Protocol
|
|
8
|
+
|
|
9
|
+
from segment.analytics.client import Client
|
|
10
|
+
|
|
11
|
+
from ._config import HOST_VARIABLE, Config, resolve_environment, resolve_host
|
|
12
|
+
from ._context import current_context
|
|
13
|
+
from ._scrub import register_secret
|
|
14
|
+
from ._sentry import init_sentry
|
|
15
|
+
from ._validation import JsonValue, Properties, event_name_problem, properties_problem
|
|
16
|
+
|
|
17
|
+
_log = logging.getLogger("viktorbarzin_telemetry")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class EventClient(Protocol):
|
|
21
|
+
"""The part of ``segment.analytics.Client`` this package calls."""
|
|
22
|
+
|
|
23
|
+
def track(
|
|
24
|
+
self,
|
|
25
|
+
*,
|
|
26
|
+
user_id: str | None,
|
|
27
|
+
event: str,
|
|
28
|
+
properties: dict[str, JsonValue],
|
|
29
|
+
context: dict[str, JsonValue],
|
|
30
|
+
anonymous_id: str,
|
|
31
|
+
) -> object: ...
|
|
32
|
+
|
|
33
|
+
def identify(
|
|
34
|
+
self,
|
|
35
|
+
*,
|
|
36
|
+
user_id: str,
|
|
37
|
+
traits: dict[str, JsonValue],
|
|
38
|
+
context: dict[str, JsonValue],
|
|
39
|
+
anonymous_id: str,
|
|
40
|
+
) -> object: ...
|
|
41
|
+
|
|
42
|
+
def flush(self) -> None: ...
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _on_error(err: Exception, batch: list[dict[str, object]]) -> None:
|
|
46
|
+
_log.warning("sending %d events failed: %s", len(batch), err)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def segment_client(config: Config) -> Client:
|
|
50
|
+
if not config.host:
|
|
51
|
+
raise ValueError(
|
|
52
|
+
f"production telemetry needs the Event pipeline URL: pass host or set ${HOST_VARIABLE}"
|
|
53
|
+
)
|
|
54
|
+
return Client(config.write_key, host=config.host, on_error=_on_error)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class Telemetry:
|
|
58
|
+
"""One app's event sender. Outside production it validates and sends nothing."""
|
|
59
|
+
|
|
60
|
+
def __init__(self, config: Config, client: EventClient | None = None) -> None:
|
|
61
|
+
self.config = config
|
|
62
|
+
self._client: EventClient | None = None
|
|
63
|
+
if config.production:
|
|
64
|
+
self._client = client if client is not None else segment_client(config)
|
|
65
|
+
self._context: dict[str, JsonValue] = {
|
|
66
|
+
"app": {"name": config.app, "version": config.release}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def enabled(self) -> bool:
|
|
71
|
+
"""True when events leave the process."""
|
|
72
|
+
return self._client is not None
|
|
73
|
+
|
|
74
|
+
@property
|
|
75
|
+
def segment_client(self) -> Client | None:
|
|
76
|
+
return self._client if isinstance(self._client, Client) else None
|
|
77
|
+
|
|
78
|
+
def _ids(self, user_id: str | None, anonymous_id: str | None) -> tuple[str | None, str]:
|
|
79
|
+
ctx = current_context()
|
|
80
|
+
user = user_id if user_id is not None else ctx.enduser_id
|
|
81
|
+
anon = anonymous_id or ctx.anonymous_id or str(uuid.uuid4())
|
|
82
|
+
return user, anon
|
|
83
|
+
|
|
84
|
+
def track(
|
|
85
|
+
self,
|
|
86
|
+
event: str,
|
|
87
|
+
properties: Properties | None = None,
|
|
88
|
+
*,
|
|
89
|
+
user_id: str | None = None,
|
|
90
|
+
anonymous_id: str | None = None,
|
|
91
|
+
) -> bool:
|
|
92
|
+
"""Queue a Product event. False when it was invalid and dropped."""
|
|
93
|
+
props = dict(properties or {})
|
|
94
|
+
problem = event_name_problem(event) or properties_problem(props)
|
|
95
|
+
if problem is not None:
|
|
96
|
+
_log.warning("event dropped: %s", problem, extra={"event_name": event})
|
|
97
|
+
return False
|
|
98
|
+
if self._client is not None:
|
|
99
|
+
user, anon = self._ids(user_id, anonymous_id)
|
|
100
|
+
self._client.track(
|
|
101
|
+
user_id=user,
|
|
102
|
+
event=event,
|
|
103
|
+
properties=props,
|
|
104
|
+
context=dict(self._context),
|
|
105
|
+
anonymous_id=anon,
|
|
106
|
+
)
|
|
107
|
+
return True
|
|
108
|
+
|
|
109
|
+
def identify(
|
|
110
|
+
self,
|
|
111
|
+
user_id: str,
|
|
112
|
+
traits: Properties | None = None,
|
|
113
|
+
*,
|
|
114
|
+
anonymous_id: str | None = None,
|
|
115
|
+
) -> bool:
|
|
116
|
+
"""Tie ``anonymous_id`` to the Person ``user_id`` (their Authentik ``sub``)."""
|
|
117
|
+
values = dict(traits or {})
|
|
118
|
+
problem = "identify without a user id" if not user_id else properties_problem(values)
|
|
119
|
+
if problem is not None:
|
|
120
|
+
_log.warning("identify dropped: %s", problem)
|
|
121
|
+
return False
|
|
122
|
+
if self._client is not None:
|
|
123
|
+
_, anon = self._ids(user_id, anonymous_id)
|
|
124
|
+
self._client.identify(
|
|
125
|
+
user_id=user_id, traits=values, context=dict(self._context), anonymous_id=anon
|
|
126
|
+
)
|
|
127
|
+
return True
|
|
128
|
+
|
|
129
|
+
def flush(self) -> None:
|
|
130
|
+
"""Block until queued events are sent."""
|
|
131
|
+
if self._client is not None:
|
|
132
|
+
self._client.flush()
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
_default = Telemetry(Config(app="unconfigured", write_key="", release="0", environment="unset"))
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def configure(
|
|
139
|
+
app: str,
|
|
140
|
+
write_key: str,
|
|
141
|
+
release: str,
|
|
142
|
+
environment: str | None = None,
|
|
143
|
+
dsn: str | None = None,
|
|
144
|
+
host: str | None = None,
|
|
145
|
+
*,
|
|
146
|
+
client: EventClient | None = None,
|
|
147
|
+
) -> Telemetry:
|
|
148
|
+
"""Set up events (and Sentry when ``dsn`` is given) for this process.
|
|
149
|
+
|
|
150
|
+
Sending happens only when the environment, explicit or from
|
|
151
|
+
``$TELEMETRY_ENVIRONMENT``, is ``production``. ``host`` is the Event
|
|
152
|
+
pipeline's base URL, explicit or from ``$TELEMETRY_HOST``; production
|
|
153
|
+
without one raises ValueError.
|
|
154
|
+
"""
|
|
155
|
+
global _default
|
|
156
|
+
config = Config(
|
|
157
|
+
app=app,
|
|
158
|
+
write_key=write_key,
|
|
159
|
+
release=release,
|
|
160
|
+
environment=resolve_environment(environment),
|
|
161
|
+
host=resolve_host(host),
|
|
162
|
+
dsn=dsn,
|
|
163
|
+
)
|
|
164
|
+
register_secret(write_key)
|
|
165
|
+
_default = Telemetry(config, client=client)
|
|
166
|
+
if dsn and config.production:
|
|
167
|
+
init_sentry(dsn, release=release, environment=config.environment)
|
|
168
|
+
return _default
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def track(
|
|
172
|
+
event: str,
|
|
173
|
+
properties: Properties | None = None,
|
|
174
|
+
*,
|
|
175
|
+
user_id: str | None = None,
|
|
176
|
+
anonymous_id: str | None = None,
|
|
177
|
+
) -> bool:
|
|
178
|
+
return _default.track(event, properties, user_id=user_id, anonymous_id=anonymous_id)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def identify(
|
|
182
|
+
user_id: str, traits: Properties | None = None, *, anonymous_id: str | None = None
|
|
183
|
+
) -> bool:
|
|
184
|
+
return _default.identify(user_id, traits, anonymous_id=anonymous_id)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def flush() -> None:
|
|
188
|
+
_default.flush()
|