grow-jaeger 0.2.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.
- grow_jaeger/AGENTS.md +34 -0
- grow_jaeger/__init__.py +39 -0
- grow_jaeger/_core/__init__.py +116 -0
- grow_jaeger/_core/cancel.py +62 -0
- grow_jaeger/_core/config.py +157 -0
- grow_jaeger/_core/env.py +146 -0
- grow_jaeger/_core/errors.py +204 -0
- grow_jaeger/_core/health.py +99 -0
- grow_jaeger/_core/hooks.py +147 -0
- grow_jaeger/_core/http.py +929 -0
- grow_jaeger/_core/redaction.py +216 -0
- grow_jaeger/_core/resources.py +53 -0
- grow_jaeger/_core/retry.py +91 -0
- grow_jaeger/_core/useragent.py +19 -0
- grow_jaeger/_http.py +222 -0
- grow_jaeger/_tracing/__init__.py +155 -0
- grow_jaeger/_tracing/_adapters.py +295 -0
- grow_jaeger/_tracing/_config.py +169 -0
- grow_jaeger/_tracing/_helpers.py +344 -0
- grow_jaeger/_tracing/_model.py +543 -0
- grow_jaeger/_tracing/_query.py +225 -0
- grow_jaeger/_tracing/_setup.py +212 -0
- grow_jaeger/_version.py +3 -0
- grow_jaeger/client.py +461 -0
- grow_jaeger/config.py +101 -0
- grow_jaeger/normalize.py +327 -0
- grow_jaeger/py.typed +0 -0
- grow_jaeger/query.py +586 -0
- grow_jaeger/sampler.py +385 -0
- grow_jaeger/setup.py +624 -0
- grow_jaeger/testing/__init__.py +18 -0
- grow_jaeger/testing/memory_traces.py +175 -0
- grow_jaeger/testing/runner.py +703 -0
- grow_jaeger/testing/tracing_conformance.py +118 -0
- grow_jaeger-0.2.0.dist-info/METADATA +114 -0
- grow_jaeger-0.2.0.dist-info/RECORD +37 -0
- grow_jaeger-0.2.0.dist-info/WHEEL +4 -0
grow_jaeger/AGENTS.md
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
<!-- Generated by sdk-kit 0.3.0 — do not edit; change sdk-kit and run "sdk-kit sync" -->
|
|
2
|
+
|
|
3
|
+
# `grow-jaeger` (`grow_jaeger`) — agent quickstart (Python)
|
|
4
|
+
|
|
5
|
+
Ships inside the wheel (`python -c "import grow_jaeger, pathlib; print(pathlib.Path(grow_jaeger.__file__).with_name('AGENTS.md').read_text())"`).
|
|
6
|
+
Docs: https://grow-codes-packages.github.io/jaeger/ · Service: Jaeger · Categories: tracing.
|
|
7
|
+
|
|
8
|
+
```sh
|
|
9
|
+
pip install grow-jaeger
|
|
10
|
+
# PyPI may not carry it yet: pip install "grow-jaeger @ git+https://github.com/grow-codes-packages/jaeger@python-vX.Y.Z#subdirectory=python"
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Client
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
from grow_jaeger import JaegerClient
|
|
17
|
+
|
|
18
|
+
# GROW_JAEGER_* > vendor env > defaults (AsyncJaegerClient has the same API)
|
|
19
|
+
client = JaegerClient.from_env()
|
|
20
|
+
client.close()
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Errors: `JaegerError` subclasses (`ConfigError`, `AuthenticationError`, `NotFoundError`, …) with `code`,
|
|
24
|
+
`retryable`, `http_status`. Credentials are `Secret`; never log `reveal()` results.
|
|
25
|
+
|
|
26
|
+
## Tracing
|
|
27
|
+
|
|
28
|
+
The tracing entry point (`initTracing` / `InitTracing` / `init_tracing`) and its options are documented in the
|
|
29
|
+
package README and https://grow-codes-packages.github.io/jaeger/tracing/ (span helpers `withSpan`, `traced`,
|
|
30
|
+
`currentTraceId`, HTTP middleware).
|
|
31
|
+
|
|
32
|
+
## Testing
|
|
33
|
+
|
|
34
|
+
`grow_jaeger.testing`: in-memory fakes.
|
grow_jaeger/__init__.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Grow Codes SDK for Jaeger.
|
|
2
|
+
|
|
3
|
+
>>> from grow_jaeger import JaegerClient, JaegerConfig
|
|
4
|
+
>>> client = JaegerClient.from_env() # doctest: +SKIP
|
|
5
|
+
|
|
6
|
+
Modules: :class:`JaegerClient` / :class:`AsyncJaegerClient` (health, ping, version),
|
|
7
|
+
:class:`JaegerQueryClient` (trace query API), :func:`init_tracing` (OTLP export preset) and
|
|
8
|
+
:class:`JaegerRemoteSampler` (remote sampling), plus the shared tracing helpers.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from . import _core
|
|
12
|
+
from ._core import * # noqa: F403
|
|
13
|
+
from ._version import __version__
|
|
14
|
+
from .client import AsyncJaegerClient, JaegerBuildInfo, JaegerClient
|
|
15
|
+
from .config import DEFAULT_SAMPLING_URL, DEFAULT_URL, JaegerConfig
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"__version__",
|
|
19
|
+
"JaegerClient",
|
|
20
|
+
"AsyncJaegerClient",
|
|
21
|
+
"JaegerBuildInfo",
|
|
22
|
+
"JaegerConfig",
|
|
23
|
+
"DEFAULT_URL",
|
|
24
|
+
"DEFAULT_SAMPLING_URL",
|
|
25
|
+
]
|
|
26
|
+
__all__ += _core.__all__
|
|
27
|
+
|
|
28
|
+
from . import _tracing # noqa: E402
|
|
29
|
+
from ._tracing import * # noqa: E402, F403
|
|
30
|
+
|
|
31
|
+
__all__ += _tracing.__all__
|
|
32
|
+
|
|
33
|
+
from . import normalize, query, sampler, setup # noqa: E402
|
|
34
|
+
from .normalize import * # noqa: E402, F403
|
|
35
|
+
from .query import * # noqa: E402, F403
|
|
36
|
+
from .sampler import * # noqa: E402, F403
|
|
37
|
+
from .setup import * # noqa: E402, F403
|
|
38
|
+
|
|
39
|
+
__all__ += normalize.__all__ + query.__all__ + sampler.__all__ + setup.__all__
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
# Generated by sdk-kit 0.3.0 — do not edit; change sdk-kit and run "sdk-kit sync"
|
|
2
|
+
"""Shared core: errors, configuration, transport, retries, redaction, hooks."""
|
|
3
|
+
|
|
4
|
+
from .cancel import CancelToken
|
|
5
|
+
from .config import BaseConfig, TlsConfig
|
|
6
|
+
from .env import ENV_PREFIX, EnvReader, parse_bool, parse_duration, to_seconds
|
|
7
|
+
from .errors import (
|
|
8
|
+
AuthenticationError,
|
|
9
|
+
CancelledError,
|
|
10
|
+
ConfigError,
|
|
11
|
+
ConflictError,
|
|
12
|
+
ErrorCode,
|
|
13
|
+
NotFoundError,
|
|
14
|
+
PermissionDeniedError,
|
|
15
|
+
RateLimitError,
|
|
16
|
+
ServiceError,
|
|
17
|
+
TimeoutError,
|
|
18
|
+
UnavailableError,
|
|
19
|
+
UnsupportedError,
|
|
20
|
+
ValidationError,
|
|
21
|
+
error_for_code,
|
|
22
|
+
)
|
|
23
|
+
from .health import HealthStatus, apoll_until, poll_until
|
|
24
|
+
from .hooks import LOGGER_NAME, ErrorInfo, Hooks, LoggerLike, RequestInfo, ResponseInfo, get_logger
|
|
25
|
+
from .http import (
|
|
26
|
+
REQUEST_ID_HEADERS,
|
|
27
|
+
RETRY_AFTER_HEADERS,
|
|
28
|
+
AsyncHttpTransport,
|
|
29
|
+
ErrorMapper,
|
|
30
|
+
HttpTransport,
|
|
31
|
+
Request,
|
|
32
|
+
Response,
|
|
33
|
+
error_from_status,
|
|
34
|
+
new_idempotency_key,
|
|
35
|
+
retry_after_from_headers,
|
|
36
|
+
)
|
|
37
|
+
from .redaction import (
|
|
38
|
+
REDACTED,
|
|
39
|
+
Secret,
|
|
40
|
+
redact_fields,
|
|
41
|
+
redact_headers,
|
|
42
|
+
redact_text,
|
|
43
|
+
redact_url,
|
|
44
|
+
truncate,
|
|
45
|
+
)
|
|
46
|
+
from .resources import ResourceRegistry, Stoppable
|
|
47
|
+
from .retry import RetryPolicy, parse_retry_after
|
|
48
|
+
from .useragent import PACKAGE_KEY, SDK_NAME, user_agent
|
|
49
|
+
|
|
50
|
+
JaegerError = ServiceError
|
|
51
|
+
|
|
52
|
+
__all__ = [
|
|
53
|
+
# errors
|
|
54
|
+
"ErrorCode",
|
|
55
|
+
"JaegerError",
|
|
56
|
+
"ServiceError",
|
|
57
|
+
"ConfigError",
|
|
58
|
+
"AuthenticationError",
|
|
59
|
+
"PermissionDeniedError",
|
|
60
|
+
"NotFoundError",
|
|
61
|
+
"ConflictError",
|
|
62
|
+
"RateLimitError",
|
|
63
|
+
"ValidationError",
|
|
64
|
+
"UnavailableError",
|
|
65
|
+
"TimeoutError",
|
|
66
|
+
"UnsupportedError",
|
|
67
|
+
"CancelledError",
|
|
68
|
+
"error_for_code",
|
|
69
|
+
# config + env
|
|
70
|
+
"BaseConfig",
|
|
71
|
+
"TlsConfig",
|
|
72
|
+
"ENV_PREFIX",
|
|
73
|
+
"EnvReader",
|
|
74
|
+
"parse_bool",
|
|
75
|
+
"parse_duration",
|
|
76
|
+
"to_seconds",
|
|
77
|
+
# transport
|
|
78
|
+
"CancelToken",
|
|
79
|
+
"RetryPolicy",
|
|
80
|
+
"parse_retry_after",
|
|
81
|
+
"HttpTransport",
|
|
82
|
+
"AsyncHttpTransport",
|
|
83
|
+
"Request",
|
|
84
|
+
"Response",
|
|
85
|
+
"error_from_status",
|
|
86
|
+
"new_idempotency_key",
|
|
87
|
+
"ErrorMapper",
|
|
88
|
+
"REQUEST_ID_HEADERS",
|
|
89
|
+
"RETRY_AFTER_HEADERS",
|
|
90
|
+
"retry_after_from_headers",
|
|
91
|
+
"SDK_NAME",
|
|
92
|
+
"PACKAGE_KEY",
|
|
93
|
+
"user_agent",
|
|
94
|
+
# hooks + logging
|
|
95
|
+
"Hooks",
|
|
96
|
+
"RequestInfo",
|
|
97
|
+
"ResponseInfo",
|
|
98
|
+
"ErrorInfo",
|
|
99
|
+
"LoggerLike",
|
|
100
|
+
"LOGGER_NAME",
|
|
101
|
+
"get_logger",
|
|
102
|
+
# redaction
|
|
103
|
+
"REDACTED",
|
|
104
|
+
"Secret",
|
|
105
|
+
"redact_fields",
|
|
106
|
+
"redact_headers",
|
|
107
|
+
"redact_text",
|
|
108
|
+
"redact_url",
|
|
109
|
+
"truncate",
|
|
110
|
+
# misc
|
|
111
|
+
"HealthStatus",
|
|
112
|
+
"poll_until",
|
|
113
|
+
"apoll_until",
|
|
114
|
+
"ResourceRegistry",
|
|
115
|
+
"Stoppable",
|
|
116
|
+
]
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# Generated by sdk-kit 0.3.0 — do not edit; change sdk-kit and run "sdk-kit sync"
|
|
2
|
+
"""Cooperative cancellation for the synchronous client (async code uses task cancellation)."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import threading
|
|
7
|
+
from collections.abc import Callable
|
|
8
|
+
|
|
9
|
+
from .errors import CancelledError
|
|
10
|
+
|
|
11
|
+
__all__ = ["CancelToken"]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class CancelToken:
|
|
15
|
+
"""Thread-safe cancellation flag passed to sync calls as ``cancel=``.
|
|
16
|
+
|
|
17
|
+
Cancelling interrupts an in-flight request (the call returns immediately with
|
|
18
|
+
:class:`CancelledError`; the abandoned HTTP exchange finishes in the background) and any
|
|
19
|
+
retry backoff sleep.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
def __init__(self) -> None:
|
|
23
|
+
self._event = threading.Event()
|
|
24
|
+
self._lock = threading.Lock()
|
|
25
|
+
self._callbacks: list[Callable[[], None]] = []
|
|
26
|
+
|
|
27
|
+
@property
|
|
28
|
+
def cancelled(self) -> bool:
|
|
29
|
+
return self._event.is_set()
|
|
30
|
+
|
|
31
|
+
def cancel(self) -> None:
|
|
32
|
+
"""Request cancellation (idempotent)."""
|
|
33
|
+
with self._lock:
|
|
34
|
+
if self._event.is_set():
|
|
35
|
+
return
|
|
36
|
+
self._event.set()
|
|
37
|
+
callbacks, self._callbacks = self._callbacks, []
|
|
38
|
+
for cb in callbacks:
|
|
39
|
+
cb()
|
|
40
|
+
|
|
41
|
+
def wait(self, timeout: float | None = None) -> bool:
|
|
42
|
+
"""Block until cancelled or ``timeout``; return whether the token is cancelled."""
|
|
43
|
+
return self._event.wait(timeout)
|
|
44
|
+
|
|
45
|
+
def on_cancel(self, callback: Callable[[], None]) -> Callable[[], None]:
|
|
46
|
+
"""Run ``callback`` on cancellation (now if already cancelled); returns an unregister."""
|
|
47
|
+
with self._lock:
|
|
48
|
+
if not self._event.is_set():
|
|
49
|
+
self._callbacks.append(callback)
|
|
50
|
+
|
|
51
|
+
def unregister() -> None:
|
|
52
|
+
with self._lock:
|
|
53
|
+
if callback in self._callbacks:
|
|
54
|
+
self._callbacks.remove(callback)
|
|
55
|
+
|
|
56
|
+
return unregister
|
|
57
|
+
callback()
|
|
58
|
+
return lambda: None
|
|
59
|
+
|
|
60
|
+
def raise_if_cancelled(self, operation: str = "operation") -> None:
|
|
61
|
+
if self._event.is_set():
|
|
62
|
+
raise CancelledError(f"{operation}: cancelled")
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
# Generated by sdk-kit 0.3.0 — do not edit; change sdk-kit and run "sdk-kit sync"
|
|
2
|
+
"""Common configuration fields shared by every service config (SPEC section 2.2)."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import dataclasses
|
|
7
|
+
import logging
|
|
8
|
+
from collections.abc import Mapping
|
|
9
|
+
from types import MappingProxyType
|
|
10
|
+
from typing import Any, ClassVar, TypeVar
|
|
11
|
+
from urllib.parse import urlsplit
|
|
12
|
+
|
|
13
|
+
from .env import EnvReader, to_seconds
|
|
14
|
+
from .errors import ConfigError
|
|
15
|
+
from .hooks import Hooks, LoggerLike
|
|
16
|
+
from .redaction import Secret, safe_repr
|
|
17
|
+
from .retry import RetryPolicy
|
|
18
|
+
|
|
19
|
+
__all__ = ["BaseConfig", "TlsConfig"]
|
|
20
|
+
|
|
21
|
+
_C = TypeVar("_C", bound="BaseConfig")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclasses.dataclass(frozen=True, repr=False)
|
|
25
|
+
class TlsConfig:
|
|
26
|
+
"""TLS settings. ``insecure_skip_verify`` is for tests only and logs a warning once."""
|
|
27
|
+
|
|
28
|
+
ca_cert_path: str | None = None
|
|
29
|
+
ca_cert_pem: str | None = None
|
|
30
|
+
client_cert_path: str | None = None
|
|
31
|
+
client_key_path: str | None = None
|
|
32
|
+
insecure_skip_verify: bool = False
|
|
33
|
+
|
|
34
|
+
def __repr__(self) -> str:
|
|
35
|
+
return safe_repr(self)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclasses.dataclass(frozen=True, repr=False)
|
|
39
|
+
class BaseConfig:
|
|
40
|
+
"""Common, immutable client settings. Durations are float seconds (timedelta accepted).
|
|
41
|
+
|
|
42
|
+
Service configs subclass this (``@dataclass(frozen=True, repr=False)``), override ``url``
|
|
43
|
+
with the service default, add their own fields (``Secret`` for credentials), extend
|
|
44
|
+
:meth:`_env_values` and :meth:`validate`, and list vendor variables in ``ENV_VENDOR``.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
#: Vendor environment variables per GROW_* suffix, in precedence order.
|
|
48
|
+
ENV_VENDOR: ClassVar[Mapping[str, tuple[str, ...]]] = {}
|
|
49
|
+
|
|
50
|
+
url: str = ""
|
|
51
|
+
connect_timeout: float = 10.0
|
|
52
|
+
request_timeout: float = 30.0
|
|
53
|
+
total_timeout: float = 120.0
|
|
54
|
+
retry: RetryPolicy = dataclasses.field(default_factory=RetryPolicy)
|
|
55
|
+
tls: TlsConfig = dataclasses.field(default_factory=TlsConfig)
|
|
56
|
+
proxy: str | None = None
|
|
57
|
+
headers: Mapping[str, str] = dataclasses.field(default_factory=dict)
|
|
58
|
+
user_agent_suffix: str | None = None
|
|
59
|
+
hooks: Hooks | None = None
|
|
60
|
+
logger: logging.Logger | LoggerLike | None = None
|
|
61
|
+
|
|
62
|
+
def __post_init__(self) -> None:
|
|
63
|
+
for name in ("connect_timeout", "request_timeout", "total_timeout"):
|
|
64
|
+
object.__setattr__(self, name, to_seconds(getattr(self, name)))
|
|
65
|
+
object.__setattr__(self, "headers", MappingProxyType(dict(self.headers)))
|
|
66
|
+
for f in dataclasses.fields(self):
|
|
67
|
+
value = getattr(self, f.name)
|
|
68
|
+
if isinstance(value, str) and "Secret" in str(f.type):
|
|
69
|
+
object.__setattr__(self, f.name, Secret(value))
|
|
70
|
+
|
|
71
|
+
def __repr__(self) -> str:
|
|
72
|
+
return safe_repr(self)
|
|
73
|
+
|
|
74
|
+
__str__ = __repr__
|
|
75
|
+
|
|
76
|
+
def known_secrets(self) -> list[str]:
|
|
77
|
+
"""Revealed values of every :class:`Secret` field (used to redact error text)."""
|
|
78
|
+
out = []
|
|
79
|
+
for f in dataclasses.fields(self):
|
|
80
|
+
value = getattr(self, f.name)
|
|
81
|
+
if isinstance(value, Secret) and value:
|
|
82
|
+
out.append(value.reveal())
|
|
83
|
+
return out
|
|
84
|
+
|
|
85
|
+
def validate(self: _C) -> _C:
|
|
86
|
+
"""Check the common rules; raise :class:`ConfigError`. Returns ``self``."""
|
|
87
|
+
try:
|
|
88
|
+
parts = urlsplit(self.url)
|
|
89
|
+
except ValueError:
|
|
90
|
+
raise ConfigError("config: url is not a valid URL") from None
|
|
91
|
+
if parts.scheme not in ("http", "https") or not parts.hostname:
|
|
92
|
+
raise ConfigError("config: url must be an absolute http or https URL")
|
|
93
|
+
for name in ("connect_timeout", "request_timeout", "total_timeout"):
|
|
94
|
+
if not getattr(self, name) > 0:
|
|
95
|
+
raise ConfigError(f"config: {name} must be positive")
|
|
96
|
+
if self.retry.max_retries < 0:
|
|
97
|
+
raise ConfigError("config: max_retries must be >= 0")
|
|
98
|
+
if self.retry.initial_backoff < 0 or self.retry.max_backoff < 0:
|
|
99
|
+
raise ConfigError("config: retry backoff must not be negative")
|
|
100
|
+
if self.retry.multiplier < 1:
|
|
101
|
+
raise ConfigError("config: retry multiplier must be >= 1")
|
|
102
|
+
if bool(self.tls.client_cert_path) != bool(self.tls.client_key_path):
|
|
103
|
+
raise ConfigError("config: client_cert_path and client_key_path must be set together")
|
|
104
|
+
if self.proxy is not None:
|
|
105
|
+
proxy = urlsplit(self.proxy)
|
|
106
|
+
if proxy.scheme not in ("http", "https", "socks5", "socks5h") or not proxy.hostname:
|
|
107
|
+
raise ConfigError("config: proxy must be an absolute proxy URL")
|
|
108
|
+
return self
|
|
109
|
+
|
|
110
|
+
@classmethod
|
|
111
|
+
def _env_values(cls, reader: EnvReader) -> dict[str, Any]:
|
|
112
|
+
"""Values found in the environment for the common fields (unset ones are omitted)."""
|
|
113
|
+
vendor = cls.ENV_VENDOR
|
|
114
|
+
values: dict[str, Any] = {}
|
|
115
|
+
url = reader.string("URL", vendor.get("URL", ()))
|
|
116
|
+
if url is not None:
|
|
117
|
+
values["url"] = url
|
|
118
|
+
for field, suffix in (
|
|
119
|
+
("connect_timeout", "CONNECT_TIMEOUT"),
|
|
120
|
+
("request_timeout", "REQUEST_TIMEOUT"),
|
|
121
|
+
("total_timeout", "TOTAL_TIMEOUT"),
|
|
122
|
+
):
|
|
123
|
+
seconds = reader.duration(suffix, vendor.get(suffix, ()))
|
|
124
|
+
if seconds is not None:
|
|
125
|
+
values[field] = seconds
|
|
126
|
+
retries = reader.int("MAX_RETRIES", vendor.get("MAX_RETRIES", ()))
|
|
127
|
+
if retries is not None:
|
|
128
|
+
values["retry"] = RetryPolicy(max_retries=retries)
|
|
129
|
+
tls: dict[str, Any] = {}
|
|
130
|
+
for field, suffix in (
|
|
131
|
+
("ca_cert_path", "CA_CERT"),
|
|
132
|
+
("client_cert_path", "CLIENT_CERT"),
|
|
133
|
+
("client_key_path", "CLIENT_KEY"),
|
|
134
|
+
):
|
|
135
|
+
path = reader.string(suffix, vendor.get(suffix, ()))
|
|
136
|
+
if path is not None:
|
|
137
|
+
tls[field] = path
|
|
138
|
+
insecure = reader.bool("INSECURE_SKIP_VERIFY", vendor.get("INSECURE_SKIP_VERIFY", ()))
|
|
139
|
+
if insecure is not None:
|
|
140
|
+
tls["insecure_skip_verify"] = insecure
|
|
141
|
+
if tls:
|
|
142
|
+
values["tls"] = TlsConfig(**tls)
|
|
143
|
+
proxy = reader.string("PROXY", vendor.get("PROXY", ()))
|
|
144
|
+
if proxy is not None:
|
|
145
|
+
values["proxy"] = proxy
|
|
146
|
+
return values
|
|
147
|
+
|
|
148
|
+
@classmethod
|
|
149
|
+
def from_env(cls: type[_C], env: Mapping[str, str] | None = None, **overrides: Any) -> _C:
|
|
150
|
+
"""Build from the environment, then validate.
|
|
151
|
+
|
|
152
|
+
Precedence: explicit keyword > ``GROW_JAEGER_<NAME>`` > vendor variables >
|
|
153
|
+
default. ``env`` defaults to ``os.environ``; pass a dict in tests.
|
|
154
|
+
"""
|
|
155
|
+
values = cls._env_values(EnvReader(env))
|
|
156
|
+
values.update({k: v for k, v in overrides.items() if v is not None})
|
|
157
|
+
return cls(**values).validate()
|
grow_jaeger/_core/env.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
# Generated by sdk-kit 0.3.0 — do not edit; change sdk-kit and run "sdk-kit sync"
|
|
2
|
+
"""Environment helpers: :class:`EnvReader`, duration and boolean parsing (SPEC section 2.2)."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import builtins
|
|
7
|
+
import datetime as _dt
|
|
8
|
+
import math
|
|
9
|
+
import os
|
|
10
|
+
import re
|
|
11
|
+
from collections.abc import Iterable, Mapping
|
|
12
|
+
|
|
13
|
+
from .errors import ConfigError
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"ENV_PREFIX",
|
|
17
|
+
"EnvReader",
|
|
18
|
+
"parse_duration",
|
|
19
|
+
"parse_bool",
|
|
20
|
+
"to_seconds",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
ENV_PREFIX = "GROW_JAEGER_"
|
|
24
|
+
|
|
25
|
+
_TRUE = frozenset({"true", "1", "yes", "on"})
|
|
26
|
+
_FALSE = frozenset({"false", "0", "no", "off"})
|
|
27
|
+
_UNIT_SECONDS = {
|
|
28
|
+
"ns": 1e-9,
|
|
29
|
+
"us": 1e-6,
|
|
30
|
+
"µs": 1e-6, # Go accepts the micro sign
|
|
31
|
+
"μs": 1e-6, # and the Greek mu
|
|
32
|
+
"ms": 1e-3,
|
|
33
|
+
"s": 1.0,
|
|
34
|
+
"m": 60.0,
|
|
35
|
+
"h": 3600.0,
|
|
36
|
+
}
|
|
37
|
+
_DURATION_PART = re.compile(r"(\d+(?:\.\d*)?|\.\d+)(ns|us|µs|μs|ms|s|m|h)")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def parse_duration(text: str) -> float:
|
|
41
|
+
"""Parse a duration into seconds.
|
|
42
|
+
|
|
43
|
+
Accepts integer milliseconds (``"1500"`` → 1.5) or Go-style units (``"500ms"``, ``"10s"``,
|
|
44
|
+
``"2m"``, ``"1h"``, ``"1m30s"``). Raises :class:`ValueError` for anything else.
|
|
45
|
+
"""
|
|
46
|
+
value = text.strip()
|
|
47
|
+
if not value:
|
|
48
|
+
raise ValueError("empty duration")
|
|
49
|
+
if value.isdigit():
|
|
50
|
+
return int(value) / 1000.0
|
|
51
|
+
pos = 0
|
|
52
|
+
total = 0.0
|
|
53
|
+
for match in _DURATION_PART.finditer(value):
|
|
54
|
+
if match.start() != pos:
|
|
55
|
+
break
|
|
56
|
+
total += float(match.group(1)) * _UNIT_SECONDS[match.group(2)]
|
|
57
|
+
pos = match.end()
|
|
58
|
+
if pos != len(value):
|
|
59
|
+
raise ValueError(f"invalid duration {text!r}")
|
|
60
|
+
return total
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def parse_bool(text: str) -> bool:
|
|
64
|
+
"""Parse ``true/false/1/0/yes/no/on/off`` (case-insensitive); raise :class:`ValueError`."""
|
|
65
|
+
lower = text.strip().lower()
|
|
66
|
+
if lower in _TRUE:
|
|
67
|
+
return True
|
|
68
|
+
if lower in _FALSE:
|
|
69
|
+
return False
|
|
70
|
+
raise ValueError("invalid boolean")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def to_seconds(value: float | _dt.timedelta) -> float:
|
|
74
|
+
"""Normalise a duration given as float seconds or :class:`datetime.timedelta`."""
|
|
75
|
+
if isinstance(value, _dt.timedelta):
|
|
76
|
+
return value.total_seconds()
|
|
77
|
+
return float(value)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class EnvReader:
|
|
81
|
+
"""Reads ``GROW_<KEY_UPPER>_<NAME>`` and vendor variables from an injectable mapping.
|
|
82
|
+
|
|
83
|
+
Every getter returns ``None`` when no variable is set (empty strings count as unset). A
|
|
84
|
+
present but invalid value raises :class:`ConfigError` that names the variable, never its
|
|
85
|
+
value.
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
def __init__(self, env: Mapping[str, str] | None = None, prefix: str = ENV_PREFIX) -> None:
|
|
89
|
+
self._env: Mapping[str, str] = os.environ if env is None else env
|
|
90
|
+
self.prefix = prefix
|
|
91
|
+
|
|
92
|
+
def lookup(self, name: str, vendor_names: Iterable[str] = ()) -> tuple[str, str] | None:
|
|
93
|
+
"""Return ``(variable_name, raw_value)`` for the first variable that is set."""
|
|
94
|
+
for var in (self.prefix + name, *vendor_names):
|
|
95
|
+
raw = self._env.get(var)
|
|
96
|
+
if raw is not None and raw != "":
|
|
97
|
+
return var, raw
|
|
98
|
+
return None
|
|
99
|
+
|
|
100
|
+
def string(self, name: str, vendor_names: Iterable[str] = ()) -> str | None:
|
|
101
|
+
found = self.lookup(name, vendor_names)
|
|
102
|
+
return None if found is None else found[1]
|
|
103
|
+
|
|
104
|
+
def duration(self, name: str, vendor_names: Iterable[str] = ()) -> builtins.float | None:
|
|
105
|
+
"""Duration in seconds."""
|
|
106
|
+
found = self.lookup(name, vendor_names)
|
|
107
|
+
if found is None:
|
|
108
|
+
return None
|
|
109
|
+
var, raw = found
|
|
110
|
+
try:
|
|
111
|
+
return parse_duration(raw)
|
|
112
|
+
except ValueError:
|
|
113
|
+
raise ConfigError(f"config: {var} is not a valid duration") from None
|
|
114
|
+
|
|
115
|
+
def bool(self, name: str, vendor_names: Iterable[str] = ()) -> builtins.bool | None:
|
|
116
|
+
found = self.lookup(name, vendor_names)
|
|
117
|
+
if found is None:
|
|
118
|
+
return None
|
|
119
|
+
var, raw = found
|
|
120
|
+
try:
|
|
121
|
+
return parse_bool(raw)
|
|
122
|
+
except ValueError:
|
|
123
|
+
raise ConfigError(f"config: {var} is not a valid boolean") from None
|
|
124
|
+
|
|
125
|
+
def int(self, name: str, vendor_names: Iterable[str] = ()) -> builtins.int | None:
|
|
126
|
+
found = self.lookup(name, vendor_names)
|
|
127
|
+
if found is None:
|
|
128
|
+
return None
|
|
129
|
+
var, raw = found
|
|
130
|
+
try:
|
|
131
|
+
return int(raw.strip(), 10)
|
|
132
|
+
except ValueError:
|
|
133
|
+
raise ConfigError(f"config: {var} is not a valid integer") from None
|
|
134
|
+
|
|
135
|
+
def float(self, name: str, vendor_names: Iterable[str] = ()) -> builtins.float | None:
|
|
136
|
+
found = self.lookup(name, vendor_names)
|
|
137
|
+
if found is None:
|
|
138
|
+
return None
|
|
139
|
+
var, raw = found
|
|
140
|
+
try:
|
|
141
|
+
value = builtins.float(raw.strip())
|
|
142
|
+
except ValueError:
|
|
143
|
+
value = math.nan
|
|
144
|
+
if not math.isfinite(value):
|
|
145
|
+
raise ConfigError(f"config: {var} is not a valid number")
|
|
146
|
+
return value
|