API reference¶
Generated reference documentation for each package. The pages are rebuilt and published with this
site from main.
| Language | Reference | Generated by |
|---|---|---|
| TypeScript | TypeScript API | TypeDoc |
| Rust | Rust API · docs.rs | rustdoc |
| Go | pkg.go.dev | Go doc comments |
| Python | below | mkdocstrings |
| Java | Java API | Javadoc |
Build them locally with make docs (per language: make -C <lang> docs).
Python¶
Grow Codes SDK for Zipkin.
The Zipkin v2 query API (:class:ZipkinQueryClient), a span reporter for applications without
OpenTelemetry (:class:ZipkinReporter) and OpenTelemetry tracing that exports Zipkin v2 JSON
(:func:init_tracing, :class:ZipkinSpanExporter), with sync and async clients.
from grow_zipkin import ZipkinClient, init_tracing client = ZipkinClient.from_env() # doctest: +SKIP client.query.list_services() # doctest: +SKIP
Zipkin is a trademark of The OpenZipkin authors. This package is not affiliated with or endorsed by The OpenZipkin authors.
AsyncBaseTraceQueryClient ¶
Async :class:BaseTraceQueryClient.
query_trace_id ¶
The id wait_for_trace passes to get_trace; override to keep native ids.
AsyncHttpTransport ¶
Asynchronous transport (one per async client); options as for :class:HttpTransport.
Cancelling the calling task raises :class:CancelledError (an asyncio.CancelledError
subclass) so asyncio's cancellation machinery keeps working. Every call after
:meth:aclose raises :class:CancelledError ("client is closed").
AsyncTraceQueryClient ¶
Bases: Protocol
Asynchronous trace query API (same methods, awaited).
AsyncZipkinClient ¶
Asynchronous Zipkin client; use async with or call :meth:aclose.
Same surface as :class:ZipkinClient (:attr:query and :attr:reporter are the async
variants). Cancel a call by cancelling its task: the SDK raises
:class:~grow_zipkin.CancelledError, which is also an :class:asyncio.CancelledError.
query
property
¶
The async trace query client (shares this client's connections).
reporter
property
¶
The async span reporter (shares this client's connections).
aclose
async
¶
Shut down tracing handles, close reporters and connections. Idempotent.
create_reporter ¶
An async reporter with other options; closed by :meth:aclose.
from_env
classmethod
¶
Build an async client from the environment.
init_tracing ¶
See :meth:ZipkinClient.init_tracing (OpenTelemetry export runs on its own worker
thread; the handle is shut down by :meth:aclose).
request
async
¶
Send a raw request through the client's transport.
AsyncZipkinQueryClient ¶
Bases: AsyncBaseTraceQueryClient
Asynchronous :class:ZipkinQueryClient (same methods, awaited; cancel by cancelling the
task). source may be an :class:~grow_zipkin.AsyncZipkinClient.
autocomplete_keys
async
¶
See :meth:ZipkinQueryClient.autocomplete_keys.
autocomplete_values
async
¶
See :meth:ZipkinQueryClient.autocomplete_values.
from_env
classmethod
¶
A standalone async query client from the environment.
get_dependencies
async
¶
get_dependencies(*, start: datetime | None = None, end: datetime | None = None, end_ts: datetime | int | None = None, lookback_s: float | timedelta | None = None) -> list[ZipkinDependencyLink]
See :meth:ZipkinQueryClient.get_dependencies.
get_trace_many
async
¶
See :meth:ZipkinQueryClient.get_trace_many.
get_trace_spans
async
¶
See :meth:ZipkinQueryClient.get_trace_spans.
get_traces
async
¶
See :meth:ZipkinQueryClient.get_traces.
list_operations
async
¶
SPEC §5 alias of :meth:list_spans.
list_remote_services
async
¶
See :meth:ZipkinQueryClient.list_remote_services.
list_spans
async
¶
See :meth:ZipkinQueryClient.list_spans.
search_traces
async
¶
See :meth:ZipkinQueryClient.search_traces.
AsyncZipkinReporter ¶
Bases: _ReporterBase
Asynchronous :class:ZipkinReporter (same arguments; source may be an
:class:~grow_zipkin.AsyncZipkinClient). Call :meth:aclose when it owns its
connections.
AuthenticationError ¶
Bases: ZipkinError
Credentials missing or rejected (HTTP 401).
BaseConfig
dataclass
¶
Common, immutable client settings. Durations are float seconds (timedelta accepted).
Service configs subclass this (@dataclass(frozen=True, repr=False)), override url
with the service default, add their own fields (Secret for credentials), extend
:meth:_env_values and :meth:validate, and list vendor variables in ENV_VENDOR.
BaseTraceQueryClient ¶
Base for service query clients; every method raises UnsupportedError until overridden
(wait_for_trace uses :func:wait_for_trace on top of get_trace, passing the id
through :meth:query_trace_id).
query_trace_id ¶
The id wait_for_trace passes to get_trace; override to keep native ids.
CancelToken ¶
Thread-safe cancellation flag passed to sync calls as cancel=.
Cancelling interrupts an in-flight request (the call returns immediately with
:class:CancelledError; the abandoned HTTP exchange finishes in the background) and any
retry backoff sleep.
CancelledError ¶
Bases: ZipkinError, CancelledError
The caller cancelled the operation (task cancel, :class:CancelToken, client close).
Also an :class:asyncio.CancelledError so asyncio keeps treating the task as cancelled.
ConfigError ¶
Bases: ZipkinError
Invalid or missing configuration.
ConflictError ¶
Bases: ZipkinError
Conflict or failed precondition (HTTP 409, 412, CAS mismatch).
EnvReader ¶
Reads GROW_<KEY_UPPER>_<NAME> and vendor variables from an injectable mapping.
Every getter returns None when no variable is set (empty strings count as unset). A
present but invalid value raises :class:ConfigError that names the variable, never its
value.
ErrorCode ¶
Bases: str, Enum
Canonical error codes; the value is the wire form used by the conformance suite.
ErrorInfo
dataclass
¶
Passed to Hooks.on_error; error is the (redacted) SDK error.
HealthStatus
dataclass
¶
Result of health(); status is ok/degraded/unhealthy/unreachable or a vendor word.
Hooks
dataclass
¶
Optional callbacks invoked on every attempt. Exceptions raised by hooks are ignored.
HttpTransport ¶
Synchronous transport (one per client).
Service options (all optional):
request_id_headers: vendor request id headers, checked before :data:REQUEST_ID_HEADERS.retry_after_headers: headers read (in order) for the delay a 429/503 response asks for; default("retry-after",), e.g.("retry-after", "x-ratelimit-reset"). See :func:retry_after_from_headers.error_mapper:mapper(error, response)returns a service-specific error for an HTTP error response (orNoneto keep the default). The mapped error is whatHooks.on_error, the retry planner (retry_after) and the caller see; whether a status is retried stays the SPEC rule. Exceptions raised by the mapper are logged and ignored.
Every call after :meth:close raises :class:CancelledError ("client is closed").
LoggerLike ¶
Bases: Protocol
Structured logger interface accepted in configuration (SPEC Logger).
NotFoundError ¶
Bases: ZipkinError
Missing record (HTTP 404).
PermissionDeniedError ¶
Bases: ZipkinError
Authenticated but not allowed (HTTP 403).
RateLimitError ¶
Bases: ZipkinError
Too many requests (HTTP 429); retry_after holds the requested delay when known.
Request
dataclass
¶
One logical API call (possibly several attempts).
path is joined to the base URL ({name} style values must already be encoded; use
:func:urllib.parse.quote); an absolute http:///https:// URL is used as is (for
pagination links the service returns; the default headers, config.headers included,
are sent there too, so only pass URLs of the same service). json is encoded when not
None; content sends raw bytes. idempotent overrides the method rule; an
idempotency_key sends the Idempotency-Key header and marks the request idempotent.
raise_for_status=False returns error responses instead of raising (retries still
apply). Statuses in allow_status are expected answers (a 404 that carries data, a
health endpoint's 503): the response is returned at once, like a success, without retries
or on_error.
RequestInfo
dataclass
¶
Passed to Hooks.on_request; url and headers are redacted.
ResourceRegistry ¶
Holds :class:Stoppable objects; :meth:stop_all stops each once, ignoring errors.
register ¶
Track item; when the registry is already closed the item is stopped now.
Response
dataclass
¶
A completed HTTP response (body fully read).
ResponseInfo
dataclass
¶
Passed to Hooks.on_response; headers are the redacted response headers (rate
limit headers and the like stay readable).
RetryPolicy
dataclass
¶
Retry settings. Durations are seconds (datetime.timedelta is accepted).
Backoff for retry n (0-based) is full jitter:
random(0, min(max_backoff, initial_backoff * multiplier ** n)).
random returns a float in [0, 1); inject it in tests for deterministic sleeps.
Secret ¶
Wraps a credential so it never shows up in str/repr/logs.
s = Secret("hunter2") str(s), s.reveal() ('[REDACTED]', 'hunter2')
Span
dataclass
¶
A finished span as returned by a query API.
Ids are normalized on construction (an all-zero or empty parent_span_id becomes
None); a negative duration_micros (the default) is computed from start and end.
A subclass with normalize_ids = False keeps native ids verbatim (an empty
parent_span_id still becomes None); link_class is used by :meth:from_json.
SpanBatchOptions
dataclass
¶
BatchSpanProcessor settings; durations are float seconds (timedelta accepted).
SpanLink
dataclass
¶
A link to another span. Set normalize_ids = False on a subclass for native ids.
SpanNode
dataclass
¶
A span with its children (sorted like :func:sort_spans).
SpanStatus
dataclass
¶
from_json
classmethod
¶
Parse {"code", "message"?} (a bare code string is accepted too).
TimeoutError ¶
Bases: ZipkinError
A connect, request or total deadline was exceeded (also HTTP 408, 504).
TlsConfig
dataclass
¶
TLS settings. insecure_skip_verify is for tests only and logs a warning once.
Trace
dataclass
¶
All spans of one trace, sorted by start time then span id.
A subclass with normalize_ids = False keeps a native trace id verbatim; span_class
is used by :meth:from_json.
TraceQueryClient ¶
Bases: Protocol
Synchronous trace query API.
TraceSearchQuery
dataclass
¶
matches ¶
Client-side filter: a span must match service/operation/tags; duration and time bounds apply to the whole trace.
TraceSummary
dataclass
¶
TracingASGIMiddleware ¶
ASGI middleware: one SERVER span per HTTP request, parent taken from request headers.
Non-HTTP scopes (lifespan, websocket) and excluded_paths pass through untraced.
TracingConfig
dataclass
¶
Settings for :func:init_tracing_with. repr redacts credential headers.
protocol and endpoint are interpreted by the service's exporter factory; the
template default protocol is http/protobuf. propagators beyond tracecontext,
baggage, b3 and b3multi need a factory from the service package.
protocol and propagators remember whether the caller set them: left out (or passed
as None) they read as :data:DEFAULT_TRACE_PROTOCOL / :data:DEFAULT_TRACE_PROPAGATORS
exactly as before, and :attr:protocol_set / :attr:propagators_set are False so a
service default can apply instead. The marker travels with the value, so
:meth:with_changes, dataclasses.replace and TracingConfig(**fields) keep an unset
field unset; passing the default value explicitly counts as set.
TracingHandle ¶
TracingWSGIMiddleware ¶
WSGI middleware: one SERVER span per request; ends when the response is closed.
UnavailableError ¶
Bases: ZipkinError
Network error or server unavailable (HTTP 500, 502, 503).
UnsupportedError ¶
Bases: ZipkinError
The service or deployment does not offer this capability (HTTP 501, missing API).
ValidationError ¶
Bases: ZipkinError
Bad input (HTTP 400, 413, 422, other 4xx, client-side validation).
ZipkinAnnotation
dataclass
¶
A timestamped event on a span (timestamp in epoch microseconds).
ZipkinClient ¶
Synchronous client for Zipkin (port 9411). Thread-safe; use as a context manager or call
:meth:close.
Health, ping and server version, plus the query API (:attr:query), the direct span
reporter (:attr:reporter) and tracing setup (:meth:init_tracing). :meth:close also
shuts down every tracing handle created through this client. Every I/O method accepts
cancel= (a :class:~grow_zipkin.CancelToken) to abort from another thread.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
ZipkinConfig | None
|
Settings; default :meth: |
None
|
http_transport
|
BaseTransport | None
|
Test seam (an |
None
|
query
property
¶
The trace query client (shares this client's connections).
reporter
property
¶
The span reporter (shares this client's connections; no compression, 512 spans per POST).
close ¶
Shut down tracing handles created through this client (flushing their batch processors), close reporters and connections. Idempotent.
create_reporter ¶
A reporter with other options (compression, max_batch_size, endpoint) that
shares this client's connections; closed by :meth:close.
from_env
classmethod
¶
Build a client from the GROW_ZIPKIN_* and vendor environment variables.
health ¶
Liveness: GET /health → {"status":"UP"}.
A 503 (DOWN, storage unavailable) gives healthy=False without retries. Never
raises for an unhealthy or unreachable service (only CANCELLED and CONFIG).
init_tracing ¶
Starts OpenTelemetry tracing to this Zipkin (see :func:~grow_zipkin.init_tracing).
The native exporter uses this client's endpoint, headers, TLS, proxy, retries, hooks and
logger; an explicit tracing endpoint wins. The handle is shut down by :meth:close.
options are the keywords of :func:~grow_zipkin.init_tracing.
ping ¶
Round trip through the query API and storage (GET /api/v2/services; through a
gateway this also proves the auth headers). Returns the latency in milliseconds.
request ¶
Send a raw request through the client's transport (retries, hooks, redaction).
server_info ¶
Build information: GET /info → {"zipkin":{"version","commit"}}.
server_version ¶
Server version (e.g. 3.6.1) from GET /info; :class:UnsupportedError when
the server (or a gateway) does not report one.
ZipkinConfig
dataclass
¶
Bases: BaseConfig
Immutable settings for :class:~grow_zipkin.ZipkinClient.
Common fields (url, timeouts, retry, tls, proxy, headers,
user_agent_suffix, hooks, logger) come from :class:BaseConfig. Durations are
float seconds; datetime.timedelta is accepted.
Attributes:
| Name | Type | Description |
|---|---|---|
url |
str
|
Base URL of the Zipkin server. A gateway path prefix is kept
( |
endpoint |
str
|
Full span ingest URL used by :class: |
Environment (:meth:from_env, explicit > GROW_ZIPKIN_* > vendor > default):
url:GROW_ZIPKIN_URL>ZIPKIN_URL>OTEL_EXPORTER_ZIPKIN_ENDPOINTwithout its trailing/api/v2/spans>http://127.0.0.1:9411.endpoint:GROW_ZIPKIN_ENDPOINT>OTEL_EXPORTER_ZIPKIN_ENDPOINT(verbatim) ><url>/api/v2/spans.CONNECT_TIMEOUT,REQUEST_TIMEOUT,TOTAL_TIMEOUT,MAX_RETRIES,CA_CERT,CLIENT_CERT,CLIENT_KEY,INSECURE_SKIP_VERIFY,PROXYwith theGROW_ZIPKIN_prefix (SPEC §2.2).
from_env
classmethod
¶
Build from the environment, then validate.
Precedence: explicit keyword > GROW_ZIPKIN_<NAME> > vendor variables > default;
without any URL variable the base of OTEL_EXPORTER_ZIPKIN_ENDPOINT is the url.
env defaults to os.environ; pass a dict in tests.
known_secrets ¶
Values of sensitive headers (Authorization, X-Api-Key …) to redact from error
messages and logs; for <scheme> <credential> values also the bare credential.
validate ¶
Common checks plus endpoint (http/https URL); raises :class:ConfigError.
ZipkinDependencyLink
dataclass
¶
Bases: DependencyLink
A dependency edge with Zipkin's errorCount (0 when the server omits it).
ZipkinEndpoint
dataclass
¶
Network endpoint of a span (localEndpoint / remoteEndpoint).
service_name is lower-cased by the server on ingest.
ZipkinQueryClient ¶
Bases: BaseTraceQueryClient
Reads traces back from Zipkin (port 9411), synchronously.
The native v2 query API (:meth:get_trace_spans, :meth:get_traces,
:meth:get_trace_many, :meth:list_services, :meth:list_spans,
:meth:list_remote_services, :meth:get_dependencies, :meth:autocomplete_keys,
:meth:autocomplete_values) and the SPEC §5 TraceQueryClient (:meth:get_trace,
:meth:search_traces, :meth:list_operations, :meth:wait_for_trace) on top of it. Every
call is a GET (retried on 5xx, 429 and network errors) and accepts cancel=.
Get one from :attr:ZipkinClient.query <grow_zipkin.ZipkinClient.query> (shares the
client's connections) or construct it from a config (owns its connections; call
:meth:close).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
ZipkinClient | ZipkinConfig | None
|
A :class: |
None
|
http_transport
|
BaseTransport | None
|
Test seam (an |
None
|
clock
|
Callable[[], float]
|
Wall clock in epoch seconds (test seam; default |
time
|
autocomplete_keys ¶
Tag keys the server indexes for autocomplete: GET /api/v2/autocompleteKeys (the
server's AUTOCOMPLETE_KEYS in configured order, [] when unset).
autocomplete_values ¶
Distinct values seen for an autocomplete key: GET /api/v2/autocompleteValues?key=
(sorted; [] for a key that is not in AUTOCOMPLETE_KEYS).
close ¶
Releases connections when this client owns them (no-op for client.query).
Idempotent.
from_env
classmethod
¶
A standalone query client from GROW_ZIPKIN_* / ZIPKIN_URL.
get_dependencies ¶
get_dependencies(*, start: datetime | None = None, end: datetime | None = None, end_ts: datetime | int | None = None, lookback_s: float | timedelta | None = None, cancel: CancelToken | None = None) -> list[ZipkinDependencyLink]
Service dependency edges: GET /api/v2/dependencies?endTs=&lookback=.
The window is either the category window (start/end) or Zipkin's native
end_ts (datetime or epoch ms) + lookback_s (these win). end defaults to now;
without start/lookback_s the server default (24 h) applies. Sorted by parent and
child, error_count defaulting to 0. In-memory storage computes edges on read;
persistent backends need the zipkin-dependencies job, so [] is normal there.
get_trace ¶
One trace in the SPEC §5 model (see :func:~grow_zipkin.zipkin_span_to_span);
None when it does not exist.
get_trace_many ¶
get_trace_many(trace_ids: Iterable[str], *, cancel: CancelToken | None = None) -> list[list[ZipkinSpan]]
Several traces by id: GET /api/v2/traceMany.
Ids are lower-cased and de-duplicated (a 16-character id equals its zero-padded
32-character form); an empty list returns [] without a request, a single id uses
GET /api/v2/trace/{id}, more are fetched in chunks of :data:TRACE_MANY_CHUNK.
Missing traces are omitted; the result follows the request order.
get_trace_spans ¶
One trace in the native model: GET /api/v2/trace/{traceId}.
Returns None when the trace does not exist (404). The id is lower-cased; anything but
16 or 32 hex characters raises :class:ValidationError without a request. Spans come
back in storage order.
get_traces ¶
get_traces(query: ZipkinTraceQuery | None = None, /, *, cancel: CancelToken | None = None, **filters: Any) -> list[list[ZipkinSpan]]
Searches traces: GET /api/v2/traces, newest first, one span list per trace.
Pass a :class:ZipkinTraceQuery and/or its fields as keywords (keywords win). No match
returns []. Invalid filters (limit <= 0, max_duration_micros without or below
min_duration_micros, non-positive end_ts/lookback_s) raise
:class:ValidationError without a request.
list_operations ¶
SPEC §5 alias of :meth:list_spans.
list_remote_services ¶
Remote services called by a service (remoteEndpoint.serviceName on its spans):
GET /api/v2/remoteServices?serviceName= (sorted).
list_services ¶
Service names that reported spans: GET /api/v2/services (sorted, lower-case).
list_spans ¶
Span names of a service: GET /api/v2/spans?serviceName= (sorted; an unknown
service gives []).
search_traces ¶
search_traces(query: TraceSearchQuery | None = None, *, cancel: CancelToken | None = None) -> list[TraceSummary]
SPEC §5 search.
service → serviceName, operation → spanName, tags → exact tag terms
(see :attr:ZipkinTraceQuery.tags), durations in µs, endTs = end (default now),
lookback = end - start (the last hour without start), limit default 20.
Returns one summary per trace (root = the span without a parent, else the earliest).
ZipkinReporter ¶
Bases: _ReporterBase
Reports spans to Zipkin without OpenTelemetry (synchronous).
POST /api/v2/spans with a JSON array of v2 spans (202 Accepted). Spans are
normalized locally first (:func:~grow_zipkin.normalize_zipkin_span), so an invalid span
raises :class:~grow_zipkin.ValidationError before anything is sent. Ingest is idempotent
(Zipkin merges spans by id), so 5xx, 429 and network errors are retried; a 400 or 413 is
permanent.
Get one from :attr:ZipkinClient.reporter <grow_zipkin.ZipkinClient.reporter> (shares the
client's connections) or construct it from a config (owns its connections; call
:meth:close).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
ZipkinClient | ZipkinConfig | None
|
A :class: |
None
|
compression
|
ReporterCompression
|
|
'none'
|
max_batch_size
|
int
|
Spans per POST; larger reports are split. Default 512. |
DEFAULT_MAX_BATCH_SIZE
|
endpoint
|
str | None
|
Ingest URL; default the config's |
None
|
http_transport
|
BaseTransport | None
|
Test seam (an |
None
|
close ¶
Releases connections when this reporter owns them (no-op for client.reporter
with the client's endpoint). Idempotent.
from_env
classmethod
¶
A standalone reporter from GROW_ZIPKIN_* / ZIPKIN_URL /
OTEL_EXPORTER_ZIPKIN_ENDPOINT; options are the constructor keywords.
report ¶
Sends spans.
An empty list sends nothing; more than max_batch_size spans are sent in several
POSTs, in order. Spans are queryable once the call returns (immediately with in-memory
storage; persistent backends may lag — use query.wait_for_trace).
ZipkinServerInfo
dataclass
¶
Build information of the server (GET /info).
ZipkinSpan
dataclass
¶
A Zipkin v2 span.
As returned by the server every tag value is a string, ids are lower-case hex and names are
lower-case. As input of :meth:ZipkinReporter.report <grow_zipkin.ZipkinReporter.report>
ids may be upper-case, kind lower-case and tag values numbers or booleans
(:func:normalize_zipkin_span converts them).
Attributes:
| Name | Type | Description |
|---|---|---|
trace_id |
str
|
16 or 32 hex characters. |
id |
str
|
Span id, 16 hex characters. |
parent_id |
str | None
|
Parent span id; |
kind |
str | None
|
|
name |
str | None
|
Span name. |
timestamp |
int | float | None
|
Start, epoch microseconds. |
duration |
int | float | None
|
Duration in microseconds. |
local_endpoint |
ZipkinEndpoint | None
|
The service that recorded the span. |
remote_endpoint |
ZipkinEndpoint | None
|
The other side of a CLIENT/SERVER/PRODUCER/CONSUMER span. |
annotations |
Sequence[ZipkinAnnotation]
|
Timestamped events. |
tags |
Mapping[str, Any]
|
String tags. |
debug |
bool
|
Force-store this span (B3 debug). |
shared |
bool
|
A server span that shares its id with the client span. |
ZipkinSpanExporter ¶
Bases: SpanExporter
OpenTelemetry SpanExporter for Zipkin.
Maps each span with :func:to_zipkin_span and sends the batch with a
:class:~grow_zipkin.ZipkinReporter (POST /api/v2/spans, JSON v2, gzip by default,
retries on 5xx/429/network errors). A failed batch returns FAILURE to the span
processor and is dropped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reporter
|
ZipkinReporter | None
|
Send through this reporter (not closed by :meth: |
None
|
config
|
ZipkinConfig | None
|
Otherwise: connection settings of an owned reporter (default
|
None
|
compression
|
ReporterCompression
|
Request body compression of an owned reporter. Default |
'gzip'
|
max_batch_size
|
int
|
Spans per POST of an owned reporter. Default 512. |
DEFAULT_MAX_BATCH_SIZE
|
on_error
|
Callable[[BaseException], None] | None
|
Called with every failed export (the batch is dropped). Never raises. |
None
|
http_transport
|
BaseTransport | None
|
Test seam for an owned reporter. |
None
|
ZipkinTraceQuery
dataclass
¶
Filter of :meth:ZipkinQueryClient.get_traces (GET /api/v2/traces).
Every field is optional; unset fields use the server defaults (end_ts = now,
lookback = 24 h, limit = 10). annotation_query, tags and annotations are
combined with and (Zipkin supports AND only).
Attributes:
| Name | Type | Description |
|---|---|---|
service_name |
str | None
|
Local service name (matched case-insensitively). |
remote_service_name |
str | None
|
|
span_name |
str | None
|
Span name. |
annotation_query |
str | None
|
Raw Zipkin annotation query, e.g. |
tags |
Mapping[str, str]
|
Exact tag matches ( |
annotations |
Sequence[str]
|
Bare terms: a tag key or an annotation value ( |
min_duration_micros |
int | None
|
Minimum span duration in microseconds. |
max_duration_micros |
int | None
|
Maximum span duration (needs |
end_ts |
datetime | int | None
|
End of the window: a |
lookback_s |
float | timedelta | None
|
Window length before |
limit |
int | None
|
Maximum number of traces. Default: the server default (10). |
ZipkinTraceSpan
dataclass
¶
ZipkinTracingConfig
dataclass
¶
Bases: TracingConfig
:class:~grow_zipkin.TracingConfig with the Zipkin defaults: protocol="native",
propagators=("tracecontext", "baggage", "b3") and service_name optional (it may come
from OTEL_SERVICE_NAME).
ZipkinTracingHandle ¶
Bases: TracingHandle
A running Zipkin tracing setup: :class:~grow_zipkin.TracingHandle plus the exporter
endpoint in use.
add_event ¶
Add an event to the active span (no-op without one).
annotation_to_event ¶
Decodes an annotation into an event.
A value of the form {"<name>": {…attributes}} (how
:class:~grow_zipkin.ZipkinSpanExporter encodes an event with attributes) becomes that name
and attributes; any other value is the event name with no attributes.
apoll_until
async
¶
apoll_until(fn: Callable[[], Awaitable[T | None]], *, timeout_s: float = 30.0, interval_s: float = 1.0, predicate: Callable[[T], bool] | None = None, operation: str = 'poll', clock: Callable[[], float] = time.monotonic) -> T
Async :func:poll_until; fn is an async callable.
async_httpx_event_hooks ¶
async_httpx_event_hooks(*, tracer: Tracer | None = None, propagator: TextMapPropagator | None = None) -> dict[str, list[Callable[..., Any]]]
event_hooks for httpx.AsyncClient (same behaviour as :func:httpx_event_hooks).
async_wait_for_trace
async
¶
async_wait_for_trace(client: AsyncTraceQueryClient, trace_id: str, *, timeout_s: float | timedelta = 30.0, interval_s: float | timedelta = 1.0, min_spans: int = 1, normalize: Callable[[str], str] | None = normalize_trace_id) -> Trace
Async form of :func:wait_for_trace.
attribute_to_tag ¶
Converts an OpenTelemetry attribute value to a Zipkin tag (sequences become JSON).
base_from_endpoint ¶
The server base URL of a spans endpoint: strips one trailing /api/v2/spans.
build_annotation_query ¶
build_annotation_query(tags: Mapping[str, str] | None = None, annotations: Iterable[str] = ()) -> str | None
Builds a Zipkin annotationQuery from exact tag matches and bare terms (joined with
and); None when there are none.
Raises :class:ValidationError for a term Zipkin cannot express (contains and, or a
key with =).
build_propagator ¶
build_propagator(names: Sequence[str], factories: Mapping[str, PropagatorFactory] | None = None) -> TextMapPropagator
Composite propagator for names; factories adds or overrides propagators by name.
build_resource ¶
Resource with service.name/service.version/deployment.environment and extras.
The environment is written both as deployment.environment.name (current semantic
conventions) and as the older deployment.environment. Merged on top of the SDK default
resource (telemetry.sdk.*, OTEL_RESOURCE_ATTRIBUTES); explicit config values win.
build_sampler ¶
OpenTelemetry sampler for a TracingConfig.sampler name.
build_tree ¶
Parent/child forest; spans whose parent is missing become roots.
create_zipkin_exporter_factory ¶
create_zipkin_exporter_factory(client_config: ZipkinConfig | None = None, *, on_export_error: Callable[[BaseException], None] | None = None, http_transport: BaseTransport | None = None) -> ExporterFactory
Builds the exporter_factory of :func:~grow_zipkin.init_tracing_with.
native(default) → :class:~grow_zipkin.ZipkinSpanExportertoconfig.endpoint(else the client config's endpoint). Headers = client headers + tracing headers; TLS = client TLS + tracing TLS; request and total timeout =batch.export_timeout_s;compression(default gzip); proxy, retries, hooks and logger from the client config.http/protobuf/grpc→ the official OTLP exporter to an OpenTelemetry Collector (config.endpointis required; the Collector'szipkinexporter forwards to Zipkin).
current_span ¶
The active span (a non-recording invalid span when none is active).
current_span_id ¶
16-char lower-hex span id of the active span, or None.
current_trace_id ¶
32-char lower-hex trace id of the active span, or None.
datetime_to_micros ¶
Microseconds since the epoch (naive datetimes are UTC).
default_tracer ¶
Tracer of this package from the global provider.
dependencies_from_body ¶
Decodes /api/v2/dependencies: errorCount defaults to 0, sorted by parent, child.
dependencies_from_spans ¶
Service dependency links (parent service → child service, different services only).
encode_spans ¶
encode_spans(spans: Iterable[ZipkinSpanInput], operation: str = 'zipkin.report') -> list[ZipkinSpan]
Normalizes spans for ingest (see :func:~grow_zipkin.normalize_zipkin_span).
error_for_code ¶
Return the error class for a code (ErrorCode member or wire value).
error_from_status ¶
error_from_status(status: int, operation: str, *, content: bytes = b'', headers: Headers | None = None, known_secrets: list[str] | None = None, retry_after: float | None = None, request_id_headers: Sequence[str] = ()) -> ServiceError
Map an HTTP error status to the SPEC 2.1 error with a redacted, truncated message.
request_id_headers are checked before the default :data:REQUEST_ID_HEADERS.
extract ¶
extract(carrier: Mapping[str, str], *, context: Context | None = None, propagator: TextMapPropagator | None = None) -> otel_context.Context
Read a context from carrier (exact key match; use :func:extract_headers for HTTP).
extract_headers ¶
extract_headers(headers: HeaderSource, *, context: Context | None = None, propagator: TextMapPropagator | None = None) -> otel_context.Context
Read a context from HTTP headers (case-insensitive; mapping or ASGI-style byte pairs).
get_logger ¶
The package logger (LOGGER_NAME), silent by default (NullHandler).
httpx_event_hooks ¶
httpx_event_hooks(*, tracer: Tracer | None = None, propagator: TextMapPropagator | None = None) -> dict[str, list[Callable[..., Any]]]
event_hooks for httpx.Client: a CLIENT span per request with injected headers.
A request that fails before a response arrives (connection error) never reaches the
response hook, so its span is not exported; use :func:instrument_requests_session style
wrapping or with_span around the call when such failures must be traced.
init_tracing ¶
init_tracing(config: TracingConfig | None = None, *, env: Mapping[str, str] | Literal[False] | None = None, client_config: ZipkinConfig | None = None, on_export_error: Callable[[BaseException], None] | None = None, propagator_factories: Mapping[str, PropagatorFactory] | None = None, span_processors: Sequence[SpanProcessor] = (), id_generator: IdGenerator | None = None, http_transport: BaseTransport | None = None, **overrides: Any) -> ZipkinTracingHandle
Sets up OpenTelemetry tracing for Zipkin (SPEC §5).
Defaults: protocol native (Zipkin v2 JSON via :class:~grow_zipkin.ZipkinSpanExporter
to http://127.0.0.1:9411/api/v2/spans), propagators tracecontext, baggage, b3
composed B3-first so W3C wins on conflict (:func:order_propagators). The environment fills
every field the config leaves unset (see :func:tracing_config_from_env and
:meth:ZipkinConfig.from_env <grow_zipkin.ZipkinConfig.from_env>); pass env=False to
ignore it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
TracingConfig | None
|
A :class: |
None
|
env
|
Mapping[str, str] | Literal[False] | None
|
Environment beneath the config; default |
None
|
client_config
|
ZipkinConfig | None
|
Connection settings of the native exporter (proxy, TLS, retries, hooks,
logger, headers, endpoint). Default |
None
|
on_export_error
|
Callable[[BaseException], None] | None
|
Called with every failed native export (the batch is dropped). |
None
|
propagator_factories
|
Mapping[str, PropagatorFactory] | None
|
Extra propagators by name (see |
None
|
span_processors
|
Sequence[SpanProcessor]
|
Extra span processors added after the batch processor. |
()
|
id_generator
|
IdGenerator | None
|
Custom id generator. |
None
|
http_transport
|
BaseTransport | None
|
Test seam of the native exporter. |
None
|
**overrides
|
Any
|
Any :class: |
{}
|
init_tracing_with ¶
init_tracing_with(config: TracingConfig, exporter_factory: ExporterFactory, *, propagator_factories: Mapping[str, PropagatorFactory] | None = None, span_processors: Sequence[SpanProcessor] = (), id_generator: IdGenerator | None = None, sampler: Sampler | None = None) -> TracingHandle
Build a TracerProvider for config with a BatchSpanProcessor around the exporter.
Services wrap this in their init_tracing(config). propagator_factories lets a
service add datadog/sw8 style propagators; span_processors (extra processors,
e.g. a second exporter) are added after the batch processor; sampler replaces the one
built from config.sampler/sampler_ratio (remote or vendor samplers). With
config.set_global the provider and propagator become the
OpenTelemetry globals (the API allows one global provider per process: is_global on
the handle tells whether it took effect).
inject ¶
inject(carrier: MutableMapping[str, str] | None = None, *, context: Context | None = None, propagator: TextMapPropagator | None = None) -> MutableMapping[str, str]
Write the current (or given) context into carrier and return it.
Uses propagator or the global propagator (set by init_tracing_with).
inject_headers ¶
inject_headers(headers: MutableMapping[str, str] | None = None, *, context: Context | None = None, propagator: TextMapPropagator | None = None) -> MutableMapping[str, str]
Add propagation headers (traceparent, baggage …) to headers and return them.
instrument_requests_session ¶
instrument_requests_session(session: Session, *, tracer: Tracer | None = None, propagator: TextMapPropagator | None = None) -> requests.Session
Trace every request sent through session (CLIENT span, headers injected).
Wraps session.send once; calling it again on the same session is a no-op.
mark_span_error ¶
Set ERROR status on span and record the exception (when error is one).
micros_to_datetime ¶
Exact UTC datetime for microseconds since the epoch.
normalize_headers ¶
Lower-cased header names → values; accepts mappings and (name, value) pairs incl. bytes.
normalize_span_id ¶
16-char lower-hex span id (left-padded); raises ValidationError when invalid.
normalize_trace_id ¶
32-char lower-hex trace id; 64-bit ids (16 hex chars, ints, 8 bytes) are left-padded.
Raises ValidationError for non-hex, too long or all-zero ids.
normalize_zipkin_span ¶
Normalizes one span for ingest.
Applies the rules Zipkin enforces locally, so one bad span never makes the server reject
the whole batch: ids lower-cased and validated, kind upper-cased, timestamps rounded to
integer microseconds (0 dropped), tag values converted to strings (None dropped), empty
fields dropped. Raises :class:ValidationError naming the problem.
order_propagators ¶
The order in which propagators are composed.
B3 (b3, b3multi) first, every other propagator after it in the given order. On
extract, later propagators overwrite earlier ones, so W3C traceparent wins when it and
B3 disagree. Names are trimmed and lower-cased; duplicates are removed.
parse_bool ¶
Parse true/false/1/0/yes/no/on/off (case-insensitive); raise :class:ValueError.
parse_duration ¶
Parse a duration into seconds.
Accepts integer milliseconds ("1500" → 1.5) or Go-style units ("500ms", "10s",
"2m", "1h", "1m30s"). Raises :class:ValueError for anything else.
parse_retry_after ¶
Parse Retry-After as delta seconds or an HTTP-date; return seconds (>= 0) or None.
poll_until ¶
poll_until(fn: Callable[[], T | None], *, timeout_s: float = 30.0, interval_s: float = 1.0, predicate: Callable[[T], bool] | None = None, operation: str = 'poll', sleep: Callable[[float], None] = time.sleep, clock: Callable[[], float] = time.monotonic) -> T
Call fn every interval_s until it returns a ready value; return that value.
A value is ready when it is not None and predicate(value) is true (without a
predicate: not an empty container). Retryable SDK errors raised by fn are remembered
and polling continues; other errors propagate. Raises :class:TimeoutError after timeout_s.
record_exception ¶
Record error as an exception event on the active span (status unchanged).
redact_fields ¶
Recursively redact values whose key looks sensitive in nested mappings and lists.
redact_headers ¶
Copy of headers with sensitive values replaced by [REDACTED].
redact_text ¶
Replace every known secret value (length >= 4) in text with [REDACTED].
redact_url ¶
Redact user info and every query value (all values, not only sensitive ones).
Query names are kept so the URL stays useful in logs.
resolve_otlp_endpoint ¶
The OTLP endpoint for a protocol: for http/protobuf an endpoint without a path gets
/v1/traces; any other endpoint is used as-is.
retry_after_from_headers ¶
retry_after_from_headers(headers: Headers | Mapping[str, str], names: Sequence[str] = RETRY_AFTER_HEADERS, *, now: Callable[[], float] = time.time) -> float | None
Server requested delay in seconds from the first of names that parses.
Retry-After is delta seconds or an HTTP-date. Other headers (X-RateLimit-Reset,
RateLimit-Reset …) may be delta seconds or a Unix timestamp in seconds or milliseconds;
timestamps are turned into the remaining delay.
set_error ¶
Mark the active span as failed: ERROR status, plus an exception event for exceptions.
sort_spans ¶
Spans sorted by start time, then span id.
span_from_readable ¶
Convert a finished OpenTelemetry SDK span (e.g. from an in-memory exporter).
span_kind ¶
SpanKind from an enum member or a name ("server"); None → INTERNAL.
spans_endpoint ¶
<base>/api/v2/spans, appended once.
A base that already ends with the spans path is kept, a gateway prefix is preserved and
trailing slashes are dropped (https://gw.example/zipkin/ →
https://gw.example/zipkin/api/v2/spans).
strings_from_body ¶
Decodes a string list response (string[]).
summarize_zipkin_trace ¶
Summarises one Zipkin trace (root = the span without a parent in the trace, else the
earliest); None when empty.
tag_value ¶
Converts a tag value to Zipkin's string form.
Strings as-is, booleans "true"/"false", numbers in decimal ("7", "1.5",
1.0 → "1"), None → "", anything else (lists, dicts) compact JSON.
to_seconds ¶
Normalise a duration given as float seconds or :class:datetime.timedelta.
to_zipkin_span ¶
Maps a finished OpenTelemetry span to a Zipkin v2 span.
Identical in every language of this SDK (based on the OpenTelemetry Zipkin exporter specification):
============================== ===========================================================
Zipkin OpenTelemetry
============================== ===========================================================
traceId, id span context ids (lower-case hex, 32 / 16)
parentId parent span id when valid, else omitted
kind SERVER/CLIENT/PRODUCER/CONSUMER 1:1; INTERNAL → omitted
name span name (the server lower-cases it)
timestamp start time, epoch µs (truncated)
duration end - start in µs, rounded, at least 1
localEndpoint.serviceName resource service.name, else unknown_service
remoteEndpoint CLIENT/PRODUCER only: serviceName = first non-empty
string of peer.service, server.address,
net.peer.name, network.peer.address
tags span attributes (strings as-is, numbers/booleans as text,
sequences JSON); then otel.scope.name /
otel.scope.version; otel.dropped_attributes_count /
otel.dropped_events_count when > 0; status ERROR →
otel.status_code=ERROR + error=<description or "">,
OK → otel.status_code=OK (status tags win). Resource
attributes are not copied
annotations events: timestamp = event time µs, value = event
name, or the JSON text {"<name>":{…attributes}} when the
event has attributes
debug, shared never set
============================== ===========================================================
Links, trace state and resource attributes other than service.name are not mapped.
trace_fields ¶
{"trace_id": …, "span_id": …} of the active span for log fields; {} without one.
traced ¶
traced(name_or_fn: str | Callable[P, R] | None = None, /, *, attributes: Attributes = None, kind: SpanKindLike = None, tracer: Tracer | None = None) -> Callable[P, R] | Callable[[Callable[P, R]], Callable[P, R]]
Decorator that runs a function (sync or async def) inside a span.
@traced, @traced() and @traced("name") all work; the default span name is the
function's qualified name. Async generators are not supported (the span would end before
iteration).
tracing_config_from_env ¶
tracing_config_from_env(config: TracingConfig | None = None, *, env: Mapping[str, str] | None = None, **overrides: Any) -> ZipkinTracingConfig
A :class:ZipkinTracingConfig from the environment beneath config/overrides.
A field of config counts as explicit when it differs from its class default; keyword
overrides (any field) are always explicit; a blank service_name counts as unset.
Per field: explicit > environment > preset default.
============================== ======================================================
Field Variables
============================== ======================================================
protocol GROW_ZIPKIN_PROTOCOL (native, grpc,
http/protobuf)
endpoint (native) GROW_ZIPKIN_ENDPOINT,
OTEL_EXPORTER_ZIPKIN_ENDPOINT (as-is),
GROW_ZIPKIN_URL / ZIPKIN_URL + /api/v2/spans
endpoint (OTLP, Collector) OTEL_EXPORTER_OTLP_TRACES_ENDPOINT (as-is),
OTEL_EXPORTER_OTLP_ENDPOINT (HTTP appends
/v1/traces)
batch.export_timeout_s OTEL_EXPORTER_ZIPKIN_TIMEOUT (ms or 10s)
compression GROW_ZIPKIN_COMPRESSION (gzip, none)
service_name OTEL_SERVICE_NAME, else service.name in
OTEL_RESOURCE_ATTRIBUTES
resource_attributes OTEL_RESOURCE_ATTRIBUTES
sampler, sampler_ratio OTEL_TRACES_SAMPLER, OTEL_TRACES_SAMPLER_ARG
propagators OTEL_PROPAGATORS
============================== ======================================================
Headers come from code only (no credential variables exist). env defaults to
os.environ. A present but invalid value raises :class:ConfigError naming the variable,
never its value. The result is not validated (init_tracing does that);
service_name is "" when nothing sets it.
truncate ¶
Truncate text to limit characters (adds an ellipsis when cut).
user_agent ¶
grow-codes-<key>/<version> (python) plus <suffix> when given.
wait_for_trace ¶
wait_for_trace(client: TraceQueryClient, trace_id: str, *, timeout_s: float | timedelta = 30.0, interval_s: float | timedelta = 1.0, min_spans: int = 1, normalize: Callable[[str], str] | None = normalize_trace_id) -> Trace
Poll get_trace until the trace has min_spans spans; TimeoutError otherwise.
NotFoundError and retryable errors count as "not there yet". normalize turns
trace_id into the id passed to get_trace (default: 32-char lower hex); None
passes native ids verbatim.
with_span ¶
with_span(name: str, fn: Callable[[Span], R] | None = None, *, attributes: Attributes = None, kind: SpanKindLike = None, links: Sequence[Link | SpanContext] | None = None, tracer: Tracer | None = None) -> R | AbstractContextManager[otel_trace.Span]
Run fn(span) inside a new current span, or return a context manager without fn.
The span always ends. An exception is recorded, sets ERROR status and is re-raised
(cancellation, asyncio.CancelledError or the SDK CancelledError, is not). The
context-manager form also works inside async code (context is kept in contextvars).
zipkin_span_to_span ¶
Converts a Zipkin span into the SPEC §5 model.
Trace id padded to 32 characters, kind lower-cased (absent → internal),
service_name = local_endpoint.service_name (or ""), attributes = tags,
annotations → events, status from the error tag (error, message = its value) or
otel.status_code (OK/ERROR), no links. Endpoints, shared and debug are
kept.
zipkin_spans_from_body ¶
Keeps the well-formed spans of a response body (ZipkinSpan[]).
zipkin_trace_id ¶
Lower-cases and validates a Zipkin trace id (16 or 32 hex characters, not all zero).
Raises :class:ValidationError without a request otherwise.
zipkin_trace_to_trace ¶
Converts the spans of one Zipkin trace into a :class:Trace (sorted); None if empty.
zipkin_traces_from_body ¶
Keeps the well-formed traces of a response body (ZipkinSpan[][]), dropping empty ones.