API Reference
Core Classes
The core a probe is built on: the protocol, the base implementation, the callable wrapper, the failure.
- ProbeCallable
Zero-argument sync or async callable returning
True/Noneon success,Falseon failure.
- format_error(exc)[source]
Format an exception for the
errorfield of a result.Always includes the exception type so that exceptions with an empty message (
TimeoutError,NotImplementedError, …) stay informative.- Parameters:
exc (
BaseException) – The exception to format.- Return type:
- Returns:
'ExcType: message'or just'ExcType'when the message is empty.
- exception ProbeFailure[source]
Bases:
ExceptionRaised by a probe when the dependency answered, but not the way a healthy one should.
Examples: Redis replied to
PINGwith something other thanTrue, an HTTP endpoint returned an unexpected status code. The message ends up inProbeResult.error.
- class Probe(*args, **kwargs)[source]
Bases:
ProtocolProtocol defining the interface for a probe.
- class ProbeBase(name=None, timeout=None, success_ttl=None, failed_ttl=None, allow_failure=False)[source]
Bases:
ABCBase implementation of a probe.
Initialize the probe.
- Parameters:
success_ttl (
int|timedelta|None) – Cache duration for successful results. If None, successful results are not cached.failed_ttl (
int|timedelta|None) – Cache duration for failed results. If None, failed results are not cached.allow_failure (
bool) – If True, a failure of this probe does not affect the overallProbirkaResult.ok; the failure is still visible in the probe’s own result.
- property allow_failure: bool
Whether this probe may fail without affecting the overall result.
- Returns:
The
allow_failuresetting of the probe.
- property info: dict[str, Any] | None
Get the information added to the probe result.
- Returns:
The information added to the probe result.
- class CallableProbe(func, name=None, timeout=None, success_ttl=None, failed_ttl=None, allow_failure=False)[source]
Bases:
ProbeBaseA probe that wraps a callable function.
Coroutine functions are awaited directly. Plain functions are executed in the event loop’s default executor so they neither block the loop nor escape the probe timeout. If a plain callable returns an awaitable (for example an object with an
async def __call__or a function returning a coroutine), that awaitable is awaited too. Note that on timeout the worker thread keeps running until the function returns; only the wait is cancelled.Initialize the probe.
- Parameters:
func (
Callable[[],bool|Awaitable[bool|None] |None]) – Sync or async callable returningTrue/Noneon success,Falseon failure.name (
str|None) – The name of the probe. Defaults tofunc.__name__, falling back to the class name for callables without one (functools.partial, objects with__call__).success_ttl (
int|timedelta|None) – Cache duration for successful results. If None, successful results are not cached.failed_ttl (
int|timedelta|None) – Cache duration for failed results. If None, failed results are not cached.allow_failure (
bool) – If True, a failure of this probe does not affect the overall result.
- class Probirka(success_ttl=None, failed_ttl=None)[source]
Bases:
objectProbirka is a health check manager that allows adding and running probes.
Initialize the Probirka instance.
- Parameters:
- property info: dict[str, Any] | None
Get the information added to the health check result.
- Returns:
The information added to the health check result.
- add_probes(*probes, groups='', allow_failure=None)[source]
Add probes to the health check.
- Parameters:
probes (
Probe) – Probes to addgroups (
str|Sequence[str]) – Groups for optional probes. Probes without groups are required.allow_failure (
bool|None) – Group-level override of the probes’ ownallow_failure.None(default) leaves the group as is, so every probe keeps its own setting.True/Falseapplies to all probes of the given groups, including ones added earlier, and replaces a value set by a previous call. A probe that is run through several sources (required list, several groups) is allowed to fail only if every source allows it. Requiresgroups.
- Raises:
ValueError – if
allow_failureis given withoutgroups- Return type:
- add(name=None, timeout=None, groups='', success_ttl=None, failed_ttl=None, allow_failure=False)[source]
Register the decorated callable as a probe.
- Parameters:
groups (
str|Sequence[str]) – Groups for optional probes. Probes without groups are required.success_ttl (
int|timedelta|None) – Cache duration for successful results. If None, uses the global success_ttl setting. Pass0to disable caching of successful results for this probe.failed_ttl (
int|timedelta|None) – Cache duration for failed results. If None, uses the global failed_ttl setting. Pass0to disable caching of failed results for this probe.allow_failure (
bool) – If True, a failure of this probe does not affect the overallok. A group-levelallow_failurepassed toadd_probes()overrides this.
- Return type:
Callable[[TypeVar(ProbeFuncT, bound=Callable[[],bool|Awaitable[bool|None] |None])],TypeVar(ProbeFuncT, bound=Callable[[],bool|Awaitable[bool|None] |None])]- Returns:
Decorated function
- async run(timeout=None, with_groups='', skip_required=False)[source]
Run health check and return results.
The overall timeout never raises: probes that did not finish in time are reported as failed and
erroris set.okisFalseonly if a probe withoutallow_failurefailed or did not finish in time.
- class ProbeResult(name, ok, cached, started_at, elapsed, info, error, allow_failure=False)[source]
Bases:
objectOutcome of a single probe run.
- Parameters:
name (
str) – Probe name.ok (
bool) – Whether the check passed.cached (
bool|None) –Trueif served from cache,Falseif freshly computed with caching enabled,Noneif the probe has no TTL configured.started_at (
datetime) – When the check started, timezone-aware in the local zone of the host.elapsed (
timedelta) – How long the check took, measured with a monotonic clock.info (
dict[str,Any] |None) – Metadata added viaProbeBase.add_info().error (
str|None) –'ExcType: message'when the check failed with an exception or timed out. Values the probe registered as secrets (the password of its connection string, its request headers) are already replaced with'***'.allow_failure (
bool) –Trueif this probe is allowed to fail without affectingProbirkaResult.ok. Effective value for the run: the probe’s own setting, overridden by the group it was run in when that group setsallow_failure.
- to_dict(*, redact=True)[source]
JSON-compatible representation of the result.
started_atis an ISO 8601 string carrying the UTC offset,elapsedis the duration in seconds.- Parameters:
redact (
bool) – Mask secrets on the way out (the default): values ofinfounder keys likepasswordorapi_keybecome'***', and passwords inside URLs and sensitive query parameters are masked ininfostrings and inerror. PassFalseto getinfoanderrorexactly as the probe produced them.- Return type:
- class ProbirkaResult(ok, started_at, elapsed, info, checks, error=None)[source]
Bases:
objectAggregated outcome of a
Probirka.run()call.- Parameters:
ok (
bool) –Trueif every probe withoutallow_failurepassed. Probes withallow_failuremay fail or time out without affecting it.started_at (
datetime) – When the run started, timezone-aware in the local zone of the host.elapsed (
timedelta) – How long the whole run took, measured with a monotonic clock.info (
dict[str,Any] |None) – Metadata added viaProbirka.add_info().checks (
Sequence[ProbeResult]) – Per-probe results in registration order.error (
str|None) – Timeout message when the overall timeout was hit (even if only probes withallow_failuredid not finish), otherwiseNone.
- checks: Sequence[ProbeResult]
- to_dict(*, redact=True)[source]
JSON-compatible representation of the result, shared by all framework integrations.
started_atis an ISO 8601 string carrying the UTC offset,elapsedis the duration in seconds,checksis a list ofProbeResult.to_dict().- Parameters:
redact (
bool) – Mask secrets ininfoand in every check, seeProbeResult.to_dict().Trueby default; the framework integrations always leave it on.- Return type:
Lazy resolution of the public names that need a third-party package (private).
The package root binds module_getattr() and module_dir() as its PEP 562 hooks, so that
import probirka never imports a client library or a framework: a probe or an adapter is
imported on first access, and MissingDependencyError tells which package to install
when that fails.
- ROOT = 'probirka'
The package whose namespace caches the resolved names (
probirka).
- exception MissingDependencyError[source]
Bases:
ImportErrorRaised when a lazily loaded name needs a package that is not installed.
Deliberately an
ImportErrorrather than anAttributeError:from probirka import Xturns anAttributeErrorinto a bare “cannot import name”, dropping the install hint. The consequence is thathasattr(probirka, 'RedisProbe')raises on a bare install; useimportlib.util.find_specto feature-detect a client library instead.
- available()[source]
List the lazily resolved names whose package is installed.
The package root appends them to
__all__, sofrom probirka import *brings the adapters and probes you can actually use and still works with nothing but probirka installed.
- module_getattr(name)[source]
Resolve a lazily loaded name of the package root (its PEP 562
__getattr__).- Parameters:
name (
str) – The attribute looked up on the package.- Return type:
- Returns:
The probe class or adapter factory.
- Raises:
AttributeError – If the name is not a lazily loaded one.
MissingDependencyError – If the package the name needs is not installed.
Secrets
MASK, mask_url and redact_value are importable from the probirka package.
Keep secrets out of health check output.
Two complementary techniques, both stdlib-only:
known values — a probe registers the password of its connection string and the values of its request headers, and
redact_secrets()replaces them wherever they show up in a message from the client library (theno_logapproach of Ansible);shape-based —
redact_value()walks theinfometadata and masks values under suspicious keys (password,token,api_key, …) and passwords inside URL-like strings (the approach of Django’sSafeExceptionReporterFilterand Sentry’sEventScrubber).
Only the password part of a URL is masked, never the user name, host or database: those are what makes an error message useful, and it is what SQLAlchemy and Celery do as well.
- MASK = '***'
What a secret is replaced with.
- MIN_SECRET_LENGTH = 4
masking them would garble unrelated text.
- Type:
Shorter values are never treated as secrets
- mask_url(url, mask='***')[source]
Return
urlwith its password replaced bymask.Everything else is kept, so
postgresql://app:hunter2@db:5432/appbecomespostgresql://app:***@db:5432/app. A URL without a password is returned unchanged.
- secrets_from_url(url)[source]
Return the password of a URL in every form a client library may echo it.
As written in the URL (
p%40ss), decoded (p@ss), and as the HTTP basic auth credentials HTTP clients derive from the user info (Basic+ base64 ofuser:password): httpx and aiohttp moveuser:pass@out of the URL into anAuthorizationheader.
- secrets_from_headers(headers)[source]
Return the values of request headers, whole and without an auth scheme prefix.
Every header value is treated as a secret: a probe sends only what is needed to be let in, and a
Bearertoken is a secret even under a custom header name. ForAuthorization: Bearer abc...bothBearer abc...andabc...are returned.
- redact_secrets(text, secrets)[source]
Replace every occurrence of the known
secretsintextwithMASK.Longer secrets are replaced first, so a secret that contains another one does not leave a fragment behind.
- redact_string(text)[source]
Mask passwords in URLs and sensitive query parameters found in
text.A heuristic for text whose origin is unknown, like a message from a client library or a value of
info:amqp://guest:guest@mq/becomesamqp://guest:***@mq/and?token=abcbecomes?token=***.
- redact_value(value)[source]
Recursively clean a JSON-like value, as found in
info.Mappings get the value under a sensitive-looking key (
password,api_key,Authorization, …) replaced withMASKwhatever it is; other values are cleaned recursively. Lists and tuples are cleaned element-wise, strings go throughredact_string(). Anything else — numbers,None, arbitrary objects — is returned as is; the framework adapters clean thestr()of an object when they serialize it.
Ready-made Probes
All probes below are importable from the probirka package, e.g. from probirka import RedisProbe,
and so are HttpProbePolicy and HttpProbePolicyViolation.
- ClientOrFactory
Either a ready client instance or a zero-argument function (lambda,
functools.partial) returning one.alias of
T|Callable[[],T]
- resolve(client_or_factory)[source]
Return the client itself, or call the factory to obtain it.
Lets a probe be constructed before the connection pool exists (for example in a FastAPI lifespan): pass
lambda: app.state.poolinstead of the pool.Only plain functions, methods, lambdas and
functools.partialobjects are treated as factories; a client object that happens to define__call__is returned as is.
- require_exactly_one(**kwargs)[source]
Ensure exactly one of the given keyword arguments is not
None.- Parameters:
kwargs (
Any) – Mutually exclusive constructor arguments (client=..., dsn=...).- Raises:
ValueError – If none or more than one of them is set.
- Return type:
- class ClientProbeBase(name=None, timeout=None, success_ttl=None, failed_ttl=None, allow_failure=False)[source]
Bases:
ProbeBaseShared lifecycle for probes that talk to a service through a client object.
Subclasses store the user’s client (or factory) in
_clientand implement two hooks:_temporary_client(), an async context manager that opens and closes a short-lived client from the connection string, and_check_client(), the actual check. An existing client is never closed by the probe.Initialize the probe.
- Parameters:
success_ttl (
int|timedelta|None) – Cache duration for successful results. If None, successful results are not cached.failed_ttl (
int|timedelta|None) – Cache duration for failed results. If None, failed results are not cached.allow_failure (
bool) – If True, a failure of this probe does not affect the overallProbirkaResult.ok; the failure is still visible in the probe’s own result.
- class TcpProbe(host, port, name=None, timeout=None, success_ttl=None, failed_ttl=None, allow_failure=False)[source]
Bases:
ProbeBaseCheck that a TCP connection to
host:portcan be established.Uses only the standard library, so it works without any extra packages. Connection errors (
ConnectionRefusedError,socket.gaierror, …) are reported inProbeResult.error.Initialize the probe.
- Parameters:
host (
str) – Host name or IP address to connect to.port (
int) – TCP port.name (
str|None) – The name of the probe. Defaults to'TcpProbe'.success_ttl (
int|timedelta|None) – Cache duration for successful results.failed_ttl (
int|timedelta|None) – Cache duration for failed results.allow_failure (
bool) – If True, a failure of this probe does not affect the overall result.
- class PostgresAsyncpgProbe(client=None, *, dsn=None, name=None, timeout=None, success_ttl=None, failed_ttl=None, allow_failure=False)[source]
Bases:
ClientProbeBaseCheck PostgreSQL availability with asyncpg.
Runs
SELECT 1on an existingasyncpg.Pool/asyncpg.Connection(or a callable returning one), or on a short-lived connection opened fromdsn.Initialize the probe.
- Parameters:
client (
Any|Callable[[],Any] |None) –asyncpg.Pool,asyncpg.Connectionor a zero-argument callable returning one.dsn (
str|None) – PostgreSQL DSN, e.g.postgresql://user:pass@host:5432/db. Mutually exclusive withclient.name (
str|None) – The name of the probe. Defaults to the class name.success_ttl (
int|timedelta|None) – Cache duration for successful results.failed_ttl (
int|timedelta|None) – Cache duration for failed results.allow_failure (
bool) – If True, a failure of this probe does not affect the overall result.
- class RedisProbe(client=None, *, url=None, name=None, timeout=None, success_ttl=None, failed_ttl=None, allow_failure=False)[source]
Bases:
ClientProbeBaseCheck Redis availability with redis-py (
redis.asyncio).Sends
PINGto an existingredis.asyncio.Redisclient (or a callable returning one), or to a short-lived client created fromurl.Initialize the probe.
- Parameters:
client (
Any|Callable[[],Any] |None) –redis.asyncio.Redis(or cluster/sentinel client withping) or a callable returning one.url (
str|None) – Redis URL, e.g.redis://localhost:6379/0. Mutually exclusive withclient.name (
str|None) – The name of the probe. Defaults to the class name.success_ttl (
int|timedelta|None) – Cache duration for successful results.failed_ttl (
int|timedelta|None) – Cache duration for failed results.allow_failure (
bool) – If True, a failure of this probe does not affect the overall result.
Security policy for the HTTP probes: which URLs a probe may request, which redirects it may follow.
A health endpoint requests whatever URL it was configured with. When that URL, or a redirect the
target answers with, points at an internal host or a cloud metadata service, the probe becomes a
server-side request forgery (SSRF) primitive. HttpProbePolicy limits what a probe will
contact. Its defaults are deliberately soft: any http or https URL is fine and redirects are
not followed. Everything stricter is opt-in.
- exception HttpProbePolicyViolation[source]
Bases:
ProbeFailureRaised when a URL, a redirect target or a resolved address is refused by
HttpProbePolicy.A
ProbeFailure: the check ran and the result is a failure with'HttpProbePolicyViolation: ...'inProbeResult.error. In the probe constructor the same violation is reported as aValueError.
- normalize_host(host)[source]
Return
hostin the form used for comparisons: lowercase, without brackets or a trailing dot.Internationalized names are converted to their IDNA (
xn--) form when possible.
- async resolve_host(host, port=None)[source]
Return every address
hostcurrently resolves to, in resolver order and without duplicates.Uses the event loop’s
getaddrinfo; a lookup failure raisessocket.gaierror.- Parameters:
- Return type:
- Returns:
The resolved addresses.
- class HttpProbePolicy(allowed_schemes=('http', 'https'), allowed_hosts=None, block_private_networks=False, blocked_networks=(), allowed_networks=(), follow_redirects=False, max_redirects=5)[source]
Bases:
objectWhat an HTTP probe may request. Pass it to a probe as
policy=.The URL given to the probe is checked against the policy when the probe is created (a violation is a
ValueError), and every URL the probe is about to request, redirect targets included, is checked again before the request (a violation is aHttpProbePolicyViolationinProbeResult.error). With the defaults anyhttporhttpsURL passes and redirects are not followed.Network rules (
block_private_networks,blocked_networks,allowed_networks) apply to IP literals in the URL and, when at least one blocking rule is set, to the addresses a host name resolves to. The name is resolved by the probe before the request, and the request is refused if any resolved address is blocked. The client library resolves the name again on its own, so a resolver that answers differently the second time (DNS rebinding) can still reach a blocked address; the policy is not a substitute for network-level controls.- Parameters:
allowed_schemes (
Collection[str]) – URL schemes a probe may request;('http', 'https')by default.allowed_hosts (
Collection[str] |None) – Host names a probe may request, exactly (api.example.com) or as a wildcard for any subdomain (*.example.commatchesa.example.comanda.b.example.combut notexample.com).None, the default, allows any host.block_private_networks (
bool) – Refuse addresses that are not globally routable: loopback, RFC 1918 andfc00::/7private ranges, link-local (including the169.254.169.254cloud metadata address), carrier-grade NAT, multicast, unspecified and reserved ranges.Falseby default.blocked_networks (
Collection[str|IPv4Network|IPv6Network]) – Networks to refuse, as'10.0.0.0/8'strings oripaddressnetwork objects.allowed_networks (
Collection[str|IPv4Network|IPv6Network]) – Networks that are always allowed, taking precedence over bothblock_private_networksandblocked_networks.follow_redirects (
bool) – Follow301,302,303,307and308responses. Every redirect target is checked against the policy first; request headers are not sent to a different origin.Falseby default: a redirect is then an ordinary status code compared withexpected_status.max_redirects (
int) – How many redirects to follow at most;5by default.
- allowed_schemes: Collection[str] = ('http', 'https')
- allowed_hosts: Collection[str] | None = None
- blocked_networks: Collection[str | IPv4Network | IPv6Network] = ()
- allowed_networks: Collection[str | IPv4Network | IPv6Network] = ()
- property needs_resolution: bool
Whether a host name has to be resolved before the request to enforce the network rules.
- check_url(url)[source]
Check a URL without touching the network: scheme, host, allowlist and IP literals.
- Parameters:
url (
str) – The URL about to be requested.- Return type:
- Returns:
The parsed URL, so that callers do not parse it twice.
- Raises:
HttpProbePolicyViolation – If the URL is malformed or refused.
- blocked_reason(address)[source]
Explain why
addressmay not be contacted, or returnNoneif it may.- Parameters:
address (
IPv4Address|IPv6Address) – A resolved or literal IP address.- Return type:
- Returns:
A short reason such as
'is not a global address', orNone.
- check_address(address, *, host=None)[source]
Refuse
addressif the network rules block it.- Parameters:
address (
IPv4Address|IPv6Address) – A resolved or literal IP address.host (
str|None) – The host name that resolved to it, for the error message.
- Raises:
HttpProbePolicyViolation – If the address is blocked.
- Return type:
- async check_resolution(parts)[source]
Resolve the host of a URL that passed
check_url()and refuse it if any address is blocked.Does nothing when no network rule needs resolution, or when the host is an IP literal (already checked by
check_url()).- Parameters:
parts (
SplitResult) – The parsed URL returned bycheck_url().- Raises:
HttpProbePolicyViolation – If a resolved address is blocked.
socket.gaierror – If the host cannot be resolved.
- Return type:
- async check(url)[source]
Run every check on a URL:
check_url(), thencheck_resolution().- Parameters:
url (
str) – The URL about to be requested.- Return type:
- Returns:
The parsed URL.
- Raises:
HttpProbePolicyViolation – If the URL is refused.
- class HttpProbeBase(url, *, method='GET', expected_status=(200,), headers=None, client=None, policy=None, name=None, timeout=None, success_ttl=None, failed_ttl=None, allow_failure=False)[source]
Bases:
ClientProbeBaseShared logic for HTTP probes: send a request and compare the status code.
Redirects are never left to the client library. The probe sends every request with automatic following disabled and, when its
HttpProbePolicyallows redirects, follows them itself so that each target is checked against the policy first.Subclasses adapt a concrete client library by implementing
_temporary_client()(a client for when none was passed, honouring the probetimeout) and_request().Initialize the probe.
- Parameters:
url (
str) – URL to request. Must be absolute and allowed bypolicy.method (
str) – HTTP method,GETby default.expected_status (
int|Collection[int]) – Status code or codes treated as healthy,(200,)by default.headers (
Mapping[str,str] |None) – Extra request headers. Not sent to a different origin after a redirect.client (
Any|Callable[[],Any] |None) – An existing client/session (or a callable returning one). If omitted, a temporary one is created per check with the probetimeoutas its request timeout.policy (
HttpProbePolicy|None) – What the probe may request, seeHttpProbePolicy. The default allows anyhttp/httpsURL and does not follow redirects.name (
str|None) – The name of the probe. Defaults to the class name.success_ttl (
int|timedelta|None) – Cache duration for successful results.failed_ttl (
int|timedelta|None) – Cache duration for failed results.allow_failure (
bool) – If True, a failure of this probe does not affect the overall result.
- Raises:
ValueError – If
urlis refused bypolicy.
- class HttpHttpxProbe(url, *, method='GET', expected_status=(200,), headers=None, client=None, policy=None, name=None, timeout=None, success_ttl=None, failed_ttl=None, allow_failure=False)[source]
Bases:
HttpProbeBaseHTTP check with httpx.
Sends a request with an existing
httpx.AsyncClient(or a callable returning one) or a temporary one, and fails unless the status code is inexpected_status.Initialize the probe.
- Parameters:
url (
str) – URL to request. Must be absolute and allowed bypolicy.method (
str) – HTTP method,GETby default.expected_status (
int|Collection[int]) – Status code or codes treated as healthy,(200,)by default.headers (
Mapping[str,str] |None) – Extra request headers. Not sent to a different origin after a redirect.client (
Any|Callable[[],Any] |None) – An existing client/session (or a callable returning one). If omitted, a temporary one is created per check with the probetimeoutas its request timeout.policy (
HttpProbePolicy|None) – What the probe may request, seeHttpProbePolicy. The default allows anyhttp/httpsURL and does not follow redirects.name (
str|None) – The name of the probe. Defaults to the class name.success_ttl (
int|timedelta|None) – Cache duration for successful results.failed_ttl (
int|timedelta|None) – Cache duration for failed results.allow_failure (
bool) – If True, a failure of this probe does not affect the overall result.
- Raises:
ValueError – If
urlis refused bypolicy.
- class HttpHttpx2Probe(url, *, method='GET', expected_status=(200,), headers=None, client=None, policy=None, name=None, timeout=None, success_ttl=None, failed_ttl=None, allow_failure=False)[source]
Bases:
HttpProbeBaseHTTP check with httpx2.
Same behaviour as
HttpHttpxProbe, built onhttpx2.AsyncClient.Initialize the probe.
- Parameters:
url (
str) – URL to request. Must be absolute and allowed bypolicy.method (
str) – HTTP method,GETby default.expected_status (
int|Collection[int]) – Status code or codes treated as healthy,(200,)by default.headers (
Mapping[str,str] |None) – Extra request headers. Not sent to a different origin after a redirect.client (
Any|Callable[[],Any] |None) – An existing client/session (or a callable returning one). If omitted, a temporary one is created per check with the probetimeoutas its request timeout.policy (
HttpProbePolicy|None) – What the probe may request, seeHttpProbePolicy. The default allows anyhttp/httpsURL and does not follow redirects.name (
str|None) – The name of the probe. Defaults to the class name.success_ttl (
int|timedelta|None) – Cache duration for successful results.failed_ttl (
int|timedelta|None) – Cache duration for failed results.allow_failure (
bool) – If True, a failure of this probe does not affect the overall result.
- Raises:
ValueError – If
urlis refused bypolicy.
- class HttpAiohttpProbe(url, *, method='GET', expected_status=(200,), headers=None, client=None, policy=None, name=None, timeout=None, success_ttl=None, failed_ttl=None, allow_failure=False)[source]
Bases:
HttpProbeBaseHTTP check with aiohttp.
Sends a request with an existing
aiohttp.ClientSession(or a callable returning one) or a temporary one, and fails unless the status code is inexpected_status.Initialize the probe.
- Parameters:
url (
str) – URL to request. Must be absolute and allowed bypolicy.method (
str) – HTTP method,GETby default.expected_status (
int|Collection[int]) – Status code or codes treated as healthy,(200,)by default.headers (
Mapping[str,str] |None) – Extra request headers. Not sent to a different origin after a redirect.client (
Any|Callable[[],Any] |None) – An existing client/session (or a callable returning one). If omitted, a temporary one is created per check with the probetimeoutas its request timeout.policy (
HttpProbePolicy|None) – What the probe may request, seeHttpProbePolicy. The default allows anyhttp/httpsURL and does not follow redirects.name (
str|None) – The name of the probe. Defaults to the class name.success_ttl (
int|timedelta|None) – Cache duration for successful results.failed_ttl (
int|timedelta|None) – Cache duration for failed results.allow_failure (
bool) – If True, a failure of this probe does not affect the overall result.
- Raises:
ValueError – If
urlis refused bypolicy.
- class KafkaAiokafkaProbe(client=None, *, bootstrap_servers=None, name=None, timeout=None, success_ttl=None, failed_ttl=None, allow_failure=False)[source]
Bases:
ClientProbeBaseCheck Kafka availability with aiokafka.
Fetches cluster metadata through an existing, already started
AIOKafkaProducer,AIOKafkaConsumerorAIOKafkaAdminClient(or a callable returning one), or through a short-lived admin client connected tobootstrap_servers.Initialize the probe.
- Parameters:
client (
Any|Callable[[],Any] |None) – StartedAIOKafkaProducer/AIOKafkaConsumer/AIOKafkaAdminClientor a callable returning one.bootstrap_servers (
str|list[str] |None) –host:portor a list of them. Mutually exclusive withclient.name (
str|None) – The name of the probe. Defaults to the class name.success_ttl (
int|timedelta|None) – Cache duration for successful results.failed_ttl (
int|timedelta|None) – Cache duration for failed results.allow_failure (
bool) – If True, a failure of this probe does not affect the overall result.
- class RabbitmqAiopikaProbe(client=None, *, url=None, name=None, timeout=None, success_ttl=None, failed_ttl=None, allow_failure=False)[source]
Bases:
ClientProbeBaseCheck RabbitMQ availability with aio-pika.
Opens and closes a channel on an existing connection (or a callable returning one), or on a short-lived connection established from
url. A closed existing connection is a failure.Initialize the probe.
- Parameters:
client (
Any|Callable[[],Any] |None) –aio_pikaconnection (AbstractConnection) or a callable returning one.url (
str|None) – AMQP URL, e.g.amqp://guest:guest@localhost/. Mutually exclusive withclient.name (
str|None) – The name of the probe. Defaults to the class name.success_ttl (
int|timedelta|None) – Cache duration for successful results.failed_ttl (
int|timedelta|None) – Cache duration for failed results.allow_failure (
bool) – If True, a failure of this probe does not affect the overall result.
- class MongoProbeBase(client=None, *, url=None, name=None, timeout=None, success_ttl=None, failed_ttl=None, allow_failure=False)[source]
Bases:
ClientProbeBaseShared logic for MongoDB probes: run the
pingadmin command.Subclasses adapt a concrete driver by implementing
_new_client()and_close_client().Initialize the probe.
- Parameters:
client (
Any|Callable[[],Any] |None) – A MongoDB client or a zero-argument callable returning one.url (
str|None) – MongoDB URI, e.g.mongodb://localhost:27017. Mutually exclusive withclient.name (
str|None) – The name of the probe. Defaults to the class name.timeout (
int|None) – The timeout for the probe. For theurlmode it is also passed to the driver asserverSelectionTimeoutMSso that the failure is reported by the driver, not as a bare timeout.success_ttl (
int|timedelta|None) – Cache duration for successful results.failed_ttl (
int|timedelta|None) – Cache duration for failed results.allow_failure (
bool) – If True, a failure of this probe does not affect the overall result.
- class MongoPymongoProbe(client=None, *, url=None, name=None, timeout=None, success_ttl=None, failed_ttl=None, allow_failure=False)[source]
Bases:
MongoProbeBaseCheck MongoDB availability with the native async client of PyMongo.
Uses
pymongo.AsyncMongoClientof PyMongo (PyMongo >= 4.9). Runs thepingadmin command on an existing client (or a callable returning one), or on a short-lived client created fromurl.Initialize the probe.
- Parameters:
client (
Any|Callable[[],Any] |None) – A MongoDB client or a zero-argument callable returning one.url (
str|None) – MongoDB URI, e.g.mongodb://localhost:27017. Mutually exclusive withclient.name (
str|None) – The name of the probe. Defaults to the class name.timeout (
int|None) – The timeout for the probe. For theurlmode it is also passed to the driver asserverSelectionTimeoutMSso that the failure is reported by the driver, not as a bare timeout.success_ttl (
int|timedelta|None) – Cache duration for successful results.failed_ttl (
int|timedelta|None) – Cache duration for failed results.allow_failure (
bool) – If True, a failure of this probe does not affect the overall result.
- class MongoMotorProbe(client=None, *, url=None, name=None, timeout=None, success_ttl=None, failed_ttl=None, allow_failure=False)[source]
Bases:
MongoProbeBaseCheck MongoDB availability with Motor (
AsyncIOMotorClient).Runs the
pingadmin command on an existing client (or a callable returning one), or on a short-lived client created fromurl.Initialize the probe.
- Parameters:
client (
Any|Callable[[],Any] |None) – A MongoDB client or a zero-argument callable returning one.url (
str|None) – MongoDB URI, e.g.mongodb://localhost:27017. Mutually exclusive withclient.name (
str|None) – The name of the probe. Defaults to the class name.timeout (
int|None) – The timeout for the probe. For theurlmode it is also passed to the driver asserverSelectionTimeoutMSso that the failure is reported by the driver, not as a bare timeout.success_ttl (
int|timedelta|None) – Cache duration for successful results.failed_ttl (
int|timedelta|None) – Cache duration for failed results.allow_failure (
bool) – If True, a failure of this probe does not affect the overall result.
Serving the result
Importable from the probirka package, e.g. from probirka import make_fastapi_endpoint.
Generic ASGI app
- Scope
ASGI connection scope.
alias of
MutableMapping[str,Any]
- Message
A single ASGI protocol message.
alias of
MutableMapping[str,Any]
- Receive
Awaitable returning the next message from the server.
alias of
Callable[[],Awaitable[MutableMapping[str,Any]]]
- Send
Coroutine function sending a message to the server.
alias of
Callable[[MutableMapping[str,Any]],Awaitable[None]]
- ASGIApp
An ASGI 3 application.
alias of
Callable[[MutableMapping[str,Any],Callable[[],Awaitable[MutableMapping[str,Any]]],Callable[[MutableMapping[str,Any]],Awaitable[None]]],Awaitable[None]]
- make_asgi_app(probirka, timeout=None, with_groups='', skip_required=False, return_results=True, success_code=200, error_code=500)[source]
Create a framework-independent ASGI application for a given Probirka instance.
The application is a plain ASGI 3 callable with no third-party dependencies. Register it as a route (
Route('/health', app, methods=['GET', 'HEAD'])in Starlette), mount it (app.mount('/health', health_app)in FastAPI,asgi('/health', is_mount=True)in Litestar), or serve it on its own port withuvicorn module:health_app.Two behaviours differ from the framework-specific adapters, because a mounted application gets no help from the host router:
The request path is ignored. Whatever reaches the application is answered, so an app mounted at
/healthalso answers/health/anything.Only
GETandHEADare served; every other method gets405with anallowheader.HEADreturns the headers aGETwould have returned, with an empty body.
- Parameters:
probirka (
Probirka) – The Probirka instance to run.with_groups (
str|Sequence[str]) – Groups to include in the Probirka run.skip_required (
bool) – Whether to skip required checks.return_results (
bool) – Whether to return the results in the response.success_code (
int) – The HTTP status code for a successful response.error_code (
int) – The HTTP status code for an error response.
- Returns:
The ASGI application.
- Return type:
Callable[[MutableMapping[str,Any],Callable[[],Awaitable[MutableMapping[str,Any]]],Callable[[MutableMapping[str,Any]],Awaitable[None]]],Awaitable[None]]
FastAPI
- make_fastapi_endpoint(probirka, timeout=None, with_groups='', skip_required=False, return_results=True, success_code=200, error_code=500)[source]
Create a FastAPI endpoint for a given Probirka instance.
- Parameters:
probirka (
Probirka) – The Probirka instance to run.with_groups (
str|Sequence[str]) – Groups to include in the Probirka run.skip_required (
bool) – Whether to skip required checks.return_results (
bool) – Whether to return the results in the response.success_code (
int) – The HTTP status code for a successful response.error_code (
int) – The HTTP status code for an error response.
- Returns:
The FastAPI endpoint.
- Return type:
AIOHTTP
- make_aiohttp_endpoint(probirka, timeout=None, with_groups='', skip_required=False, return_results=True, success_code=200, error_code=500)[source]
Create an aiohttp endpoint for a given Probirka instance.
- Parameters:
probirka (
Probirka) – The Probirka instance to run.with_groups (
str|Sequence[str]) – Groups to include in the Probirka run.skip_required (
bool) – Whether to skip required checks.return_results (
bool) – Whether to return the results in the response.success_code (
int) – The HTTP status code for a successful response.error_code (
int) – The HTTP status code for an error response.
- Returns:
The aiohttp endpoint.
- Return type:
Django
- make_django_view(probirka, timeout=None, with_groups='', skip_required=False, return_results=True, success_code=200, error_code=500)[source]
Create a Django async view for a given Probirka instance.
The view accepts
GET(andHEAD) requests only; other methods get405. The JSON body isProbirkaResult.to_dict(), the same format as the other integrations.- Parameters:
probirka (
Probirka) – The Probirka instance to run.with_groups (
str|Sequence[str]) – Groups to include in the Probirka run.skip_required (
bool) – Whether to skip required checks.return_results (
bool) – Whether to return the results in the response.success_code (
int) – The HTTP status code for a successful response.error_code (
int) – The HTTP status code for an error response.
- Returns:
The Django async view.
- Return type: