API reference: servicewright¶
Everything importable from the top-level package. This is the public vocabulary — the names here are covered by semantic versioning.
Other pages: adapters, testing doubles.
Batteries-optional microservice runtime.
One Host, many Entrypoints. Describe a service once as an AppSpec and
run it through any number of pluggable entrypoints (HTTP, gRPC, scheduler,
consumer, daemon, one-shot) under one unified lifecycle.
AppScopeProtocol
¶
Bases: Protocol
Protocol for application-level dependency scope.
The application scope is opened once for the whole process lifetime and hosts long-lived singletons (connection pools, clients, ...).
Source code in servicewright/core/contracts/container.py
get(dependency_key)
async
¶
AppSpec
dataclass
¶
Complete transport-neutral declarative description of a microservice.
Source code in servicewright/core/spec.py
cleanup_timeout_seconds = DEFAULT_CLEANUP_TIMEOUT_SECONDS
class-attribute
instance-attribute
¶
Budget for each post-drain step (stop(), hooks, observability flush).
drain_grace_seconds = DEFAULT_DRAIN_GRACE_SECONDS
class-attribute
instance-attribute
¶
How long each entrypoint gets to finish in-flight work during drain.
AsyncWarmer
¶
Bases: ABC
Base class for async infrastructure warmers.
Source code in servicewright/core/contracts/warmer.py
priority
property
¶
Priority of the warmer (lower value means higher priority).
Warmers with higher priority (lower values) are executed first. Warmers with the same priority are executed in parallel.
raise_on_failure
property
¶
Whether orchestrator should raise when this warmer fails.
__init__(*, raise_on_failure=True)
¶
warmup()
abstractmethod
async
¶
Perform infrastructure warmup.
This method should initialize connection pools, fetch metadata, or perform any other operations to prepare the infrastructure for high-load production traffic.
Raises:
| Type | Description |
|---|---|
WarmupError
|
If warmup operation fails and cannot be recovered. |
Source code in servicewright/core/contracts/warmer.py
BaseServiceSettingsProtocol
¶
Bases: Protocol
Protocol for complete microservice settings.
Observability sections are named by concern; None means the concern is
unconfigured (its sink stays a NullObject).
Source code in servicewright/core/contracts/settings.py
BootstrapContext
dataclass
¶
Context available before the application scope is opened.
Source code in servicewright/core/spec.py
ChainRedactor
¶
Applies redactors left to right: ChainRedactor(KeyRedactor(), ValueRedactor(m)).
Order matters and the conventional order is key-based first: sensitive fields are already collapsed to the mask before the (potentially more expensive) value masker sees the payload.
Source code in servicewright/core/observability/redaction.py
__call__(data)
¶
Return data passed through every redactor in order.
CleanupTimeoutError
¶
Bases: ServiceWrightError, TimeoutError
Raised when graceful cleanup does not finish within the allotted timeout.
ContextSetter
¶
Bases: Protocol
Pushes context values into an external system (logging, tracing, ...).
Implementations receive the full per-unit context dictionary and return a cleanup callable that undoes the binding when the unit of work finishes.
Source code in servicewright/core/context.py
DaemonEntrypoint
¶
Bases: ScopedEntrypoint
Runs func(scope, stop) in one long-lived unit scope.
The function is expected to loop until stop is set.
Source code in servicewright/adapters/builtin/daemon.py
bind(ctx)
async
¶
drain(grace)
async
¶
serve(*, stop)
async
¶
Open one unit scope and hand control to the user loop.
stop()
async
¶
unit_scope(context=None)
¶
Open a per-unit-of-work DI scope.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If called before :meth: |
Source code in servicewright/core/contracts/bases.py
DependencyContainerProtocol
¶
Bases: Protocol
Protocol for a DI container exposing the two scope tiers.
Source code in servicewright/core/contracts/container.py
app_scope()
¶
Return async context manager for the process-lifetime application scope.
unit_scope(context=None)
¶
Return async context manager for a per-unit-of-work scope.
context keys are container-defined: string-keyed payloads and
type-keyed contexts (e.g. dishka's {Request: request}) both fit.
Source code in servicewright/core/contracts/container.py
DrainTimeoutError
¶
Bases: ServiceWrightError, TimeoutError
Raised when an entrypoint does not drain in-flight work within the grace window.
Entrypoint
¶
Bases: Protocol
Host-facing protocol implemented by every driver.
Source code in servicewright/core/contracts/entrypoint.py
essential
instance-attribute
¶
If True, this entrypoint's failure/exit stops the whole process.
A failure also propagates out of Host.run once cleanup is done, so the
process exit code distinguishes a crash from a graceful stop.
kind
instance-attribute
¶
Telemetry label only ("http"|"grpc"|"scheduler"|"kafka"|...).
bind(ctx)
async
¶
Allocate/subscribe/register. No traffic is accepted yet.
Raise here if the resource cannot be acquired (a port already in use, a missing topic): the Host aborts startup instead of reporting ready.
Source code in servicewright/core/contracts/entrypoint.py
drain(grace)
async
¶
serve(*, stop)
async
¶
Run until stop is set, then return without shutting down.
Returning is the signal that the entrypoint is still accepting work and
is ready to be torn down in order: the Host flips readiness to false
first (so load balancers stop routing), then calls :meth:drain, then
:meth:stop. Closing listeners here instead would make drain(grace)
inert and would take the readiness endpoint down before the router knows.
Raise to report a fatal serve-time failure.
Source code in servicewright/core/contracts/entrypoint.py
ErrorInfo
dataclass
¶
Normalized view of one failure, ready for rendering.
Attributes:
| Name | Type | Description |
|---|---|---|
kind |
ErrorKind
|
The failure category. |
code |
str
|
Machine-readable error code. |
detail |
str | None
|
Human-readable message ( |
params |
Mapping[str, Any]
|
Structured, JSON-safe details. |
public |
bool
|
Whether the details may be shown to the client. |
status_override |
int | None
|
Explicit HTTP status taking precedence over the kind's default (e.g. 422 for request validation). |
headers |
Mapping[str, str] | None
|
Extra response headers (e.g. from an |
Source code in servicewright/core/errors.py
ErrorKind
¶
Bases: StrEnum
Transport-neutral failure category (maps to HTTP and gRPC statuses).
Source code in servicewright/core/errors.py
ErrorTrackingSettingsProtocol
¶
Bases: Protocol
Error-tracking concern: reporting endpoint and sampling.
Source code in servicewright/core/observability/protocols.py
HealthCheckerProtocol
¶
Bases: Protocol
Protocol for component health checks (DB, Redis, etc.).
Source code in servicewright/core/contracts/health.py
HealthRegistry
¶
Holds readiness state and named component health checks.
Liveness reflects only that the process is alive and is independent of the
registered checks. Readiness requires both the ready flag (flipped on
by the Host once serving) and every registered check passing.
Source code in servicewright/core/health/registry.py
checks
property
¶
Return a copy of the registered checks mapping.
__init__(*, readiness_cache_ttl=0.0)
¶
Initialize the registry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
readiness_cache_ttl
|
float
|
When > 0, readiness results are cached for this many seconds to avoid hammering downstream checks. |
0.0
|
Source code in servicewright/core/health/registry.py
add_check(name, check)
¶
Register a named component health check.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Unique label for the check (e.g. |
required |
check
|
HealthCheckerProtocol
|
Object implementing :class: |
required |
Source code in servicewright/core/health/registry.py
liveness()
async
¶
readiness()
async
¶
Report readiness: ready flag AND all checks passing.
Checks run concurrently; any check raising is treated as a failure.
Source code in servicewright/core/health/registry.py
HealthReport
dataclass
¶
Result of a liveness or readiness probe.
Attributes:
| Name | Type | Description |
|---|---|---|
healthy |
bool
|
Aggregate health flag. |
checks |
dict[str, bool]
|
Per-named-check results (empty for liveness). |
Source code in servicewright/core/health/report.py
status
property
¶
Coarse probe status derived from :attr:healthy.
Host
¶
Runs an :class:AppSpec plus a list of :class:Entrypoint drivers.
Owns the unified lifecycle: Bootstrap -> Warmup -> Ready -> Serve -> Drain
-> Cleanup. It treats every entrypoint identically and never branches on
kind.
The run-loop reports failure by raising, so the process exit code is
meaningful: an essential entrypoint that dies during serve propagates its
exception out of :meth:run (after cleanup), and a shutdown step that blows
past its budget raises :class:DrainTimeoutError/:class:CleanupTimeoutError
when nothing else is already propagating.
Source code in servicewright/core/aio/host.py
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 | |
add_entrypoint(entrypoint)
¶
bootstrap(settings)
¶
Build the container (the application scope is not yet entered).
Source code in servicewright/core/aio/host.py
run(settings, entrypoints=(), *, plugins=(), stop=None)
async
¶
Run the full lifecycle, blocking until stop is set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
settings
|
TSettings
|
Service settings. |
required |
entrypoints
|
Iterable[Entrypoint]
|
Drivers to run. |
()
|
plugins
|
Iterable[Plugin]
|
Plugins applied via |
()
|
stop
|
Event | None
|
Externally supplied stop event. When provided, OS signal handlers are NOT installed (the embedding/test path). |
None
|
Raises:
| Type | Description |
|---|---|
Exception
|
Whatever an essential entrypoint raised while serving, or whatever startup raised — after cleanup has run. |
ServiceWrightError
|
If a shutdown step exceeded its budget and no other exception is propagating. |
Source code in servicewright/core/aio/host.py
HttpErrorRendererProtocol
¶
Bases: Protocol
Turns a normalized :class:ErrorInfo into a wire response.
Implement this to own the error wire format end to end — a custom envelope,
localized messages resolved from info.code + info.params, extra
fields. Every default exception handler renders through the configured
renderer, so one implementation switches the whole surface.
Source code in servicewright/core/errors.py
KafkaProducerWarmupError
¶
Bases: WarmupError
Raised when Kafka producer warmup fails.
KeyRedactor
¶
Masks values whose key contains a sensitive fragment (case-insensitive).
The match is by substring, which is what makes password cover
password_hash and token cover access_token — but a short fragment
such as code also masks status_code and error_code. safe_keys
is the way to say that an exact name is not a secret: those names are never
masked, whatever the fragments match.
The whole structure is walked — nested dicts and values inside lists and
tuples. That matters because the payloads this redactor is threaded into are
list-shaped where it counts: a Sentry event keeps stack-frame locals under
exception.values[i].stacktrace.frames[j].vars and breadcrumb payloads
under breadcrumbs.values[i].data, so a redactor that only recursed into
dicts would mask the flat extra block and ship the locals in plaintext.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sensitive_keys
|
frozenset[str] | set[str]
|
Fragments that make a key sensitive, matched as case-insensitive substrings of the key name. |
DEFAULT_SENSITIVE_KEYS
|
mask
|
str
|
Value written in place of a sensitive one. |
MASK
|
safe_keys
|
frozenset[str] | set[str]
|
Exact key names, compared case-insensitively, that are never masked. Checked before the fragments. |
frozenset()
|
Source code in servicewright/core/observability/redaction.py
Lifecycle
¶
Manages service lifecycle with customizable hooks.
Provides extension points for custom logic at various stages of service lifecycle without requiring inheritance.
Source code in servicewright/core/lifecycle/manager.py
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 | |
add_post_shutdown_hook(hook)
¶
Add hook to execute after service shutdown.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hook
|
LifecycleHookProtocol
|
Async callable to execute after cleanup. |
required |
add_post_start_hook(hook)
¶
Add hook to execute after service starts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hook
|
LifecycleHookProtocol
|
Async callable to execute after service is ready. |
required |
add_pre_shutdown_hook(hook)
¶
Add hook to execute before service shutdown.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hook
|
LifecycleHookProtocol
|
Async callable to execute before service stops. |
required |
add_pre_start_hook(hook)
¶
Add hook to execute before service starts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hook
|
LifecycleHookProtocol
|
Async callable to execute before service initialization. |
required |
run_post_shutdown_hooks(app_scope=None)
async
¶
Execute all post-shutdown hooks in registration order.
Continues with other hooks even if one fails to ensure maximum cleanup.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
app_scope
|
AppScopeProtocol | None
|
Optional application scope for dependency resolution. |
None
|
Source code in servicewright/core/lifecycle/manager.py
run_post_start_hooks(app_scope)
async
¶
Execute all post-start hooks in registration order.
Aborts startup if any hook fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
app_scope
|
AppScopeProtocol
|
Application scope for dependency resolution. |
required |
Source code in servicewright/core/lifecycle/manager.py
run_pre_shutdown_hooks(app_scope=None)
async
¶
Execute all pre-shutdown hooks in registration order.
Continues with other hooks even if one fails to ensure maximum cleanup.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
app_scope
|
AppScopeProtocol | None
|
Optional application scope for dependency resolution. |
None
|
Source code in servicewright/core/lifecycle/manager.py
run_pre_start_hooks(app_scope=None)
async
¶
Execute all pre-start hooks in registration order.
Aborts startup if any hook fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
app_scope
|
AppScopeProtocol | None
|
Optional application scope for dependency resolution. |
None
|
Source code in servicewright/core/lifecycle/manager.py
LifecycleHookProtocol
¶
Bases: Protocol
Protocol for lifecycle hook callbacks.
Source code in servicewright/core/contracts/lifecycle.py
LoggingSettingsProtocol
¶
Bases: Protocol
Logging concern: root level and rendering format.
Source code in servicewright/core/observability/protocols.py
MetricsSettingsProtocol
¶
Bases: Protocol
Metrics concern: standalone exposition endpoint.
Source code in servicewright/core/observability/protocols.py
ObsConfig
dataclass
¶
App-wide add-on backend defaults (the process-global selection).
Selecting a backend here says which implementation to use when the concern
is configured; whether the concern is active is decided by the settings
(settings.error_tracking.dsn present, settings.tracing present, ...).
Missing extra for a selected+configured backend hard-raises at Bootstrap.
Source code in servicewright/core/observability/config.py
ObsSetupContext
dataclass
¶
Built by the manager from settings + spec and handed to each sink's setup().
Observability config must be reachable from settings (DSN, collector URL,
tokens): setup() runs in Bootstrap, before the DI container exists, so
container-resolved secrets are unavailable at sink setup time.
redactor arrives already resolved for the receiving sink's surface: the
manager applies its per-surface overrides (log_redactor /
error_redactor / trace_redactor) before handing the context over,
so a sink never has to know which override chain produced it.
Source code in servicewright/core/observability/config.py
ObservabilityManager
¶
Resolves, sets up and tears down the four add-on sinks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
ObsConfig | None
|
App-wide backend selection by name. |
None
|
redactor
|
Redactor | None
|
Cross-cutting sensitive-data filter threaded into the logging, error-tracking and tracing sinks (every payload surface; metrics carry no payloads and are exempt). |
None
|
log_redactor
|
Redactor | None
|
Per-surface override for the logging sink; wins over
|
None
|
error_redactor
|
Redactor | None
|
Per-surface override for the error-tracking sink. The natural home for ML-grade maskers: events are rare, shipped off the request path, and leak the most (stack-frame locals, request bodies). |
None
|
trace_redactor
|
Redactor | None
|
Per-surface override for span attributes. |
None
|
metrics
|
MetricsSinkProtocol | None
|
Ready metrics sink instance (wins over |
None
|
tracing
|
TracingSinkProtocol | None
|
Ready tracing sink instance (wins over |
None
|
error_tracking
|
ErrorTrackingSinkProtocol | None
|
Ready error-tracking sink instance (wins over
|
None
|
logging
|
LoggingSinkProtocol | None
|
Ready logging sink instance (wins over |
None
|
Source code in servicewright/core/observability/manager.py
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 | |
config
property
¶
The app-wide backend selection.
error_tracking
property
¶
The error-tracking sink (NullObject until configured).
logging
property
¶
The logging sink (NullObject until configured).
metrics
property
¶
The metrics sink (NullObject until configured).
tracing
property
¶
The tracing sink (NullObject until configured).
configure(settings, *, service_name='')
¶
Resolve and set up every selected+configured sink (fail-fast).
Setup order is logging -> error-tracking -> tracing -> metrics so the
earliest failures are already logged and reported.
Source code in servicewright/core/observability/manager.py
shutdown()
¶
Tear down active sinks in reverse setup order (best-effort, never raises).
Returns the manager to its pre-configure state: the concerns fall
back to their NullObject sinks and the manager can be configured again.
A Service reuses one long-lived AppSpec across runs, so leaving
the torn-down sinks in place would give run 2 a stack that reports the
real sink type while logging, metrics and tracing all silently go
nowhere. Per-run idempotency stays where it belongs — inside each sink's
own setup.
Source code in servicewright/core/observability/manager.py
OneShotEntrypoint
¶
Bases: ScopedEntrypoint
Runs func exactly once inside a fresh unit scope, then returns.
Being essential by default, its return stops the whole service.
Source code in servicewright/adapters/builtin/oneshot.py
bind(ctx)
async
¶
drain(grace)
async
¶
serve(*, stop)
async
¶
Open a unit scope, run the function once, then return.
stop()
async
¶
unit_scope(context=None)
¶
Open a per-unit-of-work DI scope.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If called before :meth: |
Source code in servicewright/core/contracts/bases.py
Plugin
¶
Bases: Protocol
Litestar on_app_init analogue.
A plugin mutates a neutral spec/host: append entrypoints, warmers, health checks, lifecycle hooks or DI providers. This is the only batteries-optional extension surface — never an entrypoint subclass.
Source code in servicewright/core/contracts/plugin.py
PostgresWarmupError
¶
Bases: WarmupError
Raised when Postgres warmup fails.
ProbeStatus
¶
ProblemDetailsRenderer
¶
The default renderer: RFC 9457 Problem Details (application/problem+json).
Body: type (a URI built from type_base and the code, or
about:blank), title (the HTTP reason phrase), status,
detail (when present) plus the extension members code and
params (when non-empty).
Rendering is total: params are coerced with :func:to_json_safe (a
UUID or datetime renders as its string form rather than turning the
intended 404 into a masked 500) and the title tolerates non-IANA statuses.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
type_base
|
str | None
|
Base URI for the |
None
|
Source code in servicewright/core/errors.py
render(info)
¶
Render the failure as an RFC 9457 problem document.
Source code in servicewright/core/errors.py
RedisWarmupError
¶
Bases: WarmupError
Raised when Redis warmup fails.
RenderedError
dataclass
¶
A rendered wire response for one failure.
Source code in servicewright/core/errors.py
ScopedEntrypoint
¶
Bases: ABC
Base for loop/poll-driven entrypoints (scheduler, consumer, daemon, one-shot).
Provides the only sanctioned per-unit DI API: async with
self.unit_scope(context) as scope: which delegates to the container.
Source code in servicewright/core/contracts/bases.py
bind(ctx)
async
¶
drain(grace)
async
¶
serve(*, stop)
abstractmethod
async
¶
stop()
async
¶
unit_scope(context=None)
¶
Open a per-unit-of-work DI scope.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If called before :meth: |
Source code in servicewright/core/contracts/bases.py
ServerEntrypoint
¶
Bases: ABC
Base for socket-serving entrypoints (FastAPI, gRPC, Litestar, Flask).
The framework's DI integration owns the per-request scope, so this base
deliberately exposes no unit_scope and cannot double-open one.
Source code in servicewright/core/contracts/bases.py
Service
¶
Declarative facade: an :class:AppSpec plus entrypoints and plugins.
service.run(settings) builds a :class:Host and blocks until a stop
signal is received.
Source code in servicewright/core/service.py
ServiceContext
dataclass
¶
Context available once the application scope is opened.
Source code in servicewright/core/spec.py
ServiceError
¶
Bases: Exception
Base class for typed business errors raised by application code.
Subclasses set kind (and optionally code) as class attributes; the
code defaults to the snake_cased class name without the Error suffix.
Every attribute can also be overridden per-instance via keyword arguments,
and the resolved value is what the instance reports — exc.code,
exc.kind and exc.public are always the values the transports act on,
so except ServiceError as exc: if exc.code == "user_missing" works.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
detail
|
str | None
|
Human-readable message shown to the client when the error is public (falls back to a generic phrase for the kind). |
None
|
code
|
str | None
|
Machine-readable error code (stable API for clients). |
None
|
kind
|
ErrorKind | None
|
The failure category driving the transport status. |
None
|
params
|
Mapping[str, Any] | None
|
Structured details for the client. Values that are not JSON primitives are coerced by the renderer, never dropped. |
None
|
public
|
bool | None
|
When |
None
|
Source code in servicewright/core/errors.py
ServiceWrightError
¶
TracingSettingsProtocol
¶
Bases: Protocol
Tracing concern: exporter endpoint and sampling.
Source code in servicewright/core/observability/protocols.py
UnitScopeProtocol
¶
Bases: Protocol
Protocol for unit-of-work-level dependency scope.
A unit scope is minted per unit of work (one request, message, job, task
or activity) and carries that unit's payload as its context.
Source code in servicewright/core/contracts/container.py
get(dependency_key)
async
¶
ValueRedactor
¶
Lifts a value-level :class:Masker over every string value in a payload.
Same traversal as :class:KeyRedactor - nested dicts, lists and tuples,
cycle-safe - but the decision is made by the masker looking at each string
value, not by the field name. Keys are never masked.
Fail closed: if the masker raises on a value, that value becomes the mask (never the raw string), and one warning is logged per redactor instance - a broken masker is visible without a log storm and without dropping a single log line or event.
Source code in servicewright/core/observability/redaction.py
__call__(data)
¶
Return a copy of data with every string value passed through the masker.
WarmupError
¶
Bases: ServiceWrightError
Base exception for infrastructure warmup errors.
WarmupTimeoutError
¶
Bases: ServiceWrightError, TimeoutError
Raised when infrastructure warmup does not finish within the allotted timeout.
bind_context(**values)
¶
Context manager binding values for the duration of the block.
Source code in servicewright/core/context.py
bind_context_values(values)
¶
Bind values into the store; returns a remover that resets them all.
None values are skipped (absent, not bound). The remover resets in
reverse binding order and is idempotent.
Source code in servicewright/core/context.py
collect_warmers(base_warmers, warmers_factory, app_ctx)
async
¶
Collect warmers from base list and factory.
Source code in servicewright/core/warmup/orchestrator.py
current_context()
¶
Return every non-None value in the current context as a dict.
get_context_value(key, default=None)
¶
Get key from the current context (default when unset).
is_safe_context_id(value)
¶
True when value is a well-formed correlation identifier.
Rejects empty, overlong (> 256 chars) and log-unsafe values (anything
outside A-Za-z0-9 . _ - + = / space :). Transports use this to filter
identifiers extracted from headers/metadata before binding them.
Source code in servicewright/core/context.py
mask_private_error(info)
¶
Return the client-safe view: non-public errors collapse to a generic 500.
Public errors pass through unchanged. The caller is responsible for logging the original (that is where the real code/params must go).
Source code in servicewright/core/errors.py
perform_warmup(service_name, warmers, timeout=DEFAULT_WARMUP_TIMEOUT_SECONDS)
async
¶
Execute warmup with fail-fast behavior.
Source code in servicewright/core/warmup/orchestrator.py
propagation_metadata(keys=None)
¶
Collect the current context as outbound headers / gRPC metadata.
Returns {header: value} for every mapped context key currently set —
ready to merge into HTTP request headers or gRPC invocation metadata, e.g.
as the callable feeding a client context interceptor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
keys
|
Mapping[str, str] | None
|
|
None
|
Source code in servicewright/core/context.py
register_sink(concern, backend, target)
¶
Register (or override) a backend as "module.path:ClassName".
Source code in servicewright/core/observability/registry.py
run(service, settings, *, stop=None)
async
¶
Module-level convenience: await servicewright.run(service, settings).
Source code in servicewright/core/service.py
set_context_value(key, value)
¶
warmup_async(warmers=None, raise_on_failure=True, timeout=None)
async
¶
Perform asynchronous warmup of provided infrastructure warmers.
Executes warmers in dependency order based on their priority. Warmers with the same priority are executed in parallel. Failures in one warmer do not cancel other warmers in the same priority group.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
warmers
|
Sequence[AsyncWarmer] | None
|
A sequence of warmer instances to execute. |
None
|
raise_on_failure
|
bool
|
If True, raises WarmupError if any warmer fails. If False, only logs warnings. |
True
|
timeout
|
float | None
|
Maximum time to wait for all warmers to complete. |
None
|
Raises:
| Type | Description |
|---|---|
WarmupError
|
If any warmer fails and raise_on_failure is True. |
Source code in servicewright/core/warmup/engine.py
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 | |