API Reference¶
The root package __all__ is the single source for stable root-level exports. Prefer from fast_healthchecks import Probe, run_probe, healthcheck_shutdown, HealthCheckReport, HealthCheckResult, Check, FunctionConfig and the exception hierarchy (HealthCheckError, HealthCheckTimeoutError, HealthCheckSSRFError). Check classes (e.g. RedisHealthCheck) and other configs are available from fast_healthchecks.checks or their submodules (e.g. fast_healthchecks.checks.redis). See fast_healthchecks.__all__ and fast_healthchecks.checks.__all__.
Config types (e.g. RedisConfig, UrlConfig) in fast_healthchecks.checks.configs are part of the supported API for passing config=... to check constructors. The to_dict() methods on check classes are for internal test use only and are not part of the supported public API; do not rely on them in production code.
Secrets and redaction: Check and config to_dict(redact_secrets=True) redacts credential-style keys (same set as in fast_healthchecks.utils). The structured logging layer used by run_probe does not log config or secrets; see fast_healthchecks.logging and the run_probe docs.
Exception hierarchy (public)¶
The following exceptions are part of the public API and are documented for callers who want to handle them explicitly. Existing code that catches asyncio.TimeoutError or ValueError continues to work, because the new types subclass those.
- HealthCheckError — Base for health-check-related exceptions.
- HealthCheckTimeoutError — Raised when a probe or check run times out. Subclass of
HealthCheckErrorandasyncio.TimeoutError. - HealthCheckSSRFError — Raised when URL/host SSRF validation fails (e.g.
validate_url_ssrf,validate_host_ssrf_async). Subclass ofHealthCheckErrorandValueError. See SSRF documentation for behaviour and edge cases.
Structured Error Reporting with HealthError¶
For programmatic error handling and detailed diagnostics, use the HealthError dataclass which provides structured error information:
Machine-readable error details for failed health checks.
Attributes:
| Name | Type | Description |
|---|---|---|
code |
str
|
Machine-readable error code (e.g., "PROBE_TIMEOUT", "CHECK_EXCEPTION"). |
message |
str
|
Human-readable error message describing what went wrong. |
duration_ms |
int
|
Time in milliseconds that the probe took to execute. |
timeout_ms |
int | None
|
Timeout limit in milliseconds that was applied to the probe. |
meta |
dict[str, object]
|
Additional metadata about the error (e.g., exception type, URL). Secrets are automatically redacted from this field. |
Source code in fast_healthchecks/models.py
Error Codes:
| Code | Description |
|---|---|
CHECK_TIMEOUT |
Overall check execution exceeded timeout |
PROBE_TIMEOUT |
Individual probe exceeded its timeout |
CHECK_EXCEPTION |
Check raised an unexpected exception |
DEPENDENCY_UNHEALTHY |
A dependency was marked unhealthy |
Troubleshooting: Legacy Exception Mapping¶
The following table maps legacy exception classes to their corresponding ErrorCode values:
| Legacy Exception | ErrorCode | Notes |
|---|---|---|
HealthCheckTimeoutError |
CHECK_TIMEOUT |
Overall check execution timeout |
asyncio.TimeoutError |
CHECK_TIMEOUT |
Caught at runner level |
HealthCheckSSRFError |
CHECK_EXCEPTION |
SSRF validation failure |
HealthCheckError |
CHECK_EXCEPTION |
General check failure |
Other Exception |
CHECK_EXCEPTION |
Unexpected errors |
Automatic mapping: The map_exception_to_health_error() function automatically converts legacy exceptions to HealthError with the appropriate error code:
from fast_healthchecks.errors import map_exception_to_health_error
# These are equivalent:
result.error = map_exception_to_health_error(exc)
result.error = HealthError(code="CHECK_EXCEPTION", message=str(exc), ...)
Migration guide:
- Replace
except HealthCheckTimeoutErrorwithif result.error.code == "CHECK_TIMEOUT" - Replace
except HealthCheckErrorwithif result.error.code == "CHECK_EXCEPTION" - Access structured error info via
result.error.code,result.error.message,result.error.meta
Migration from legacy exceptions:
The old exception-based approach (HealthCheckError, HealthCheckTimeoutError) is still supported for backward compatibility. However, the new HealthError model provides more structured information:
# Old way (still works)
try:
await runner.run(probe)
except asyncio.TimeoutError as e:
logger.error(f"Timeout: {e}")
# New way (recommended) - use map_exception_to_health_error
from fast_healthchecks.errors import map_exception_to_health_error
result = await runner.run(probe)
if not result.healthy and result.error:
# Structured error information
print(f"Error code: {result.error.code}") # e.g., "PROBE_TIMEOUT"
print(f"Message: {result.error.message}") # Human-readable message
print(f"Duration: {result.error.duration_ms}ms")
print(f"Meta: {result.error.meta}") # Additional context
The map_exception_to_health_error function in fast_healthchecks.errors converts exceptions to structured HealthError instances with official error codes.
Models for healthchecks.
HealthCheckError
¶
Bases: Exception
Base exception for health-check-related failures.
Raised or used as a base for timeouts, SSRF validation, and other health-check errors. Subclasses preserve the original exception type (e.g. HealthCheckTimeoutError is also an asyncio.TimeoutError) so existing code that catches TimeoutError or ValueError continues to work.
Source code in fast_healthchecks/models.py
HealthCheckReport
dataclass
¶
Report of healthchecks.
Attributes:
| Name | Type | Description |
|---|---|---|
results |
list[HealthCheckResult]
|
List of healthcheck results. |
allow_partial_failure |
bool
|
If True, report is healthy when at least one check passes. |
Source code in fast_healthchecks/models.py
healthy
property
¶
Return whether all healthchecks passed (or allowed partial failure).
HealthCheckResult
dataclass
¶
Result of a healthcheck.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Name of the healthcheck. |
healthy |
bool
|
Whether the healthcheck passed. |
error |
HealthError | None
|
Structured error details if the healthcheck failed. |
Source code in fast_healthchecks/models.py
error_details
property
¶
Backward-compatible error message accessor.
__init__(name, healthy, error=None, *, error_details=None)
¶
Create a health check result.
The error_details keyword is accepted for backward compatibility
and is converted into error.message.
Raises:
| Type | Description |
|---|---|
ValueError
|
If both |
Source code in fast_healthchecks/models.py
HealthCheckSSRFError
¶
Bases: HealthCheckError, ValueError
Raised when URL or host validation fails (SSRF / block_private_hosts).
Subclass of both HealthCheckError and ValueError so that
except ValueError still catches it.
HealthCheckTimeoutError
¶
Bases: HealthCheckError, TimeoutError
Raised when a probe or check run exceeds its timeout.
Subclass of both HealthCheckError and asyncio.TimeoutError so that
except asyncio.TimeoutError or except TimeoutError still catch it.
Source code in fast_healthchecks/models.py
__init__(message='Probe timed out', *, code='PROBE_TIMEOUT')
¶
Create timeout error with machine-readable timeout code.
HealthError
dataclass
¶
Machine-readable error details for failed health checks.
Attributes:
| Name | Type | Description |
|---|---|---|
code |
str
|
Machine-readable error code (e.g., "PROBE_TIMEOUT", "CHECK_EXCEPTION"). |
message |
str
|
Human-readable error message describing what went wrong. |
duration_ms |
int
|
Time in milliseconds that the probe took to execute. |
timeout_ms |
int | None
|
Timeout limit in milliseconds that was applied to the probe. |
meta |
dict[str, object]
|
Additional metadata about the error (e.g., exception type, URL). Secrets are automatically redacted from this field. |
Source code in fast_healthchecks/models.py
Execution primitives and policy models for healthchecks.
ProbeRunner
dataclass
¶
Immutable runner that executes probes according to RunPolicy.
Use as an async context manager to ensure proper resource cleanup:
async with ProbeRunner(policy) as runner:
report = await runner.run(probe)
Attributes:
| Name | Type | Description |
|---|---|---|
policy |
RunPolicy
|
RunPolicy instance controlling execution behavior. |
_probes |
list[Probe]
|
Internal list of probes that have been registered with this runner. |
_probe_ids |
set[int]
|
Internal set of probe object IDs for deduplication. |
Source code in fast_healthchecks/execution.py
__aenter__()
async
¶
__aexit__(_exc_type, _exc, _tb)
async
¶
Always close managed probes on context exit.
close()
async
¶
run(probe)
async
¶
Run probe checks and return a report.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
probe
|
Probe
|
Probe with checks to execute. |
required |
Returns:
| Type | Description |
|---|---|
HealthCheckReport
|
HealthCheckReport for the probe run. |
Source code in fast_healthchecks/execution.py
RunPolicy
dataclass
¶
Immutable policy controlling probe execution behavior.
Attributes:
| Name | Type | Description |
|---|---|---|
mode |
RunMode
|
Controls how probe failures affect overall health status. - "strict": Any failure marks the health check as failed - "reporting": Failures are reported but don't fail the check |
execution |
ExecutionMode
|
Controls how probes are executed. - "parallel": All probes run concurrently - "sequential": Probes run one at a time |
probe_timeout_ms |
int | None
|
Optional timeout in milliseconds for each probe. If None, probes use their default timeout. |
health_evaluation |
HealthEvaluationMode
|
Controls evaluation strategy. - "all_required": All probes must pass for overall health - "partial_allowed": Some probes can fail without failing overall |
Source code in fast_healthchecks/execution.py
__post_init__()
¶
Validate policy values.
Raises:
| Type | Description |
|---|---|
ValueError
|
If mode/execution/health_evaluation is invalid or timeout is non-positive. |
Source code in fast_healthchecks/execution.py
DSN NewTypes for type hints only.
These types annotate DSN strings (e.g. AmqpDsn, RedisDsn) but are not used at runtime by check classes. Each HealthCheckDSN subclass implements its own parse_dsn() and validate_dsn(); dsn.py provides no parsing or validation logic. Use these types to annotate configuration or function parameters.
Checks¶
Immutable configuration dataclasses for health checks.
Encapsulates connection parameters to avoid long parameter lists (PLR0913) and centralize serialization for to_dict().
FunctionConfig
dataclass
¶
Configuration for function health check.
Source code in fast_healthchecks/checks/configs.py
to_dict()
¶
Return config as a dict for serialization.
KafkaConfig
dataclass
¶
Configuration for Kafka health check.
Source code in fast_healthchecks/checks/configs.py
__post_init__()
¶
Validate security_protocol and sasl_mechanism.
Raises:
| Type | Description |
|---|---|
ValueError
|
If security_protocol or sasl_mechanism is invalid. |
Source code in fast_healthchecks/checks/configs.py
to_dict()
¶
Return config as a dict for serialization.
Source code in fast_healthchecks/checks/configs.py
MongoConfig
dataclass
¶
Configuration for MongoDB health check.
Source code in fast_healthchecks/checks/configs.py
OpenSearchConfig
dataclass
¶
Configuration for OpenSearch health check.
Source code in fast_healthchecks/checks/configs.py
PostgresAsyncPGConfig
dataclass
¶
Configuration for PostgreSQL health check (asyncpg driver).
Source code in fast_healthchecks/checks/configs.py
to_dict()
¶
Return config as a dict for serialization.
Source code in fast_healthchecks/checks/configs.py
PostgresPsycopgConfig
dataclass
¶
Configuration for PostgreSQL health check (psycopg driver).
Source code in fast_healthchecks/checks/configs.py
RabbitMQConfig
dataclass
¶
Configuration for RabbitMQ health check.
Security: The default user and password ("guest") match
RabbitMQ's default credentials and are intended for local development only.
Do not use these defaults in production or on non-local brokers; set
explicit credentials or use a secrets manager. See SECURITY.md.
Source code in fast_healthchecks/checks/configs.py
RedisConfig
dataclass
¶
Configuration for Redis health check.
Source code in fast_healthchecks/checks/configs.py
UrlConfig
dataclass
¶
Configuration for URL health check.
Use only trusted URLs from application configuration; do not pass
user-controlled input to avoid SSRF. Validation and behaviour are
provided by :func:~fast_healthchecks.utils.validate_url_ssrf and
:func:~fast_healthchecks.utils.validate_host_ssrf_async. See the
SSRF documentation in the docs.
Source code in fast_healthchecks/checks/configs.py
Type aliases for health checks.
HealthCheck
¶
HealthCheckDSN
¶
Bases: ConfigDictMixin, HealthCheck[T_co], Generic[T_co, T_parsed]
Base class for health checks that can be created from a DSN.
Contract: subclasses must define _allowed_schemes(), _default_name(), parse_dsn(), and _from_parsed_dsn(). The check stores its display name in _name (used in HealthCheckResult and error reporting). DSN validation uses validate_dsn(); fast_healthchecks.dsn NewTypes are typing-only, not runtime.
Type parameters: T_co is the result type (e.g. HealthCheckResult); T_parsed is the type returned by parse_dsn() and accepted by _from_parsed_dsn().
Source code in fast_healthchecks/checks/_base.py
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 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 | |
from_dsn(dsn, *, name=None, timeout=DEFAULT_HC_TIMEOUT, **kwargs)
classmethod
¶
Create a check instance from a DSN string.
Returns:
| Name | Type | Description |
|---|---|---|
HealthCheckDSN |
HealthCheckDSN[T_co, T_parsed]
|
Configured check instance. |
Source code in fast_healthchecks/checks/_base.py
parse_dsn(dsn)
abstractmethod
classmethod
¶
validate_dsn(dsn, *, allowed_schemes)
classmethod
¶
Validate the DSN has an allowed scheme.
Allows compound schemes (e.g. postgresql+asyncpg) when the base part before '+' is in allowed_schemes. Scheme comparison is case-insensitive.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The DSN string (stripped of leading/trailing whitespace). |
Raises:
| Type | Description |
|---|---|
TypeError
|
If dsn is not a string. |
ValueError
|
If DSN is empty or scheme is not in allowed_schemes. |
Source code in fast_healthchecks/checks/_base.py
Health check that runs a user-provided callable (sync or async).
FunctionHealthCheck runs the callable each time the check is executed; sync functions are run in a thread pool via run_in_executor.
FunctionHealthCheck
¶
Bases: ConfigDictMixin, HealthCheck[HealthCheckResult]
Health check that runs a callable (sync or async) each time it is executed.
Synchronous functions are run via loop.run_in_executor(executor, ...).
The default executor is None (shared thread pool). Long-running blocking
sync checks can exhaust the pool; pass a dedicated :class:Executor if needed.
Source code in fast_healthchecks/checks/function.py
__call__()
async
¶
Perform the health check on the function.
Sync functions run in the given executor (default: shared thread pool).
Returns:
| Name | Type | Description |
|---|---|---|
HealthCheckResult |
HealthCheckResult
|
The result of the health check. |
Source code in fast_healthchecks/checks/function.py
__init__(*, config=None, func=None, name='Function', executor=None, **kwargs)
¶
Initialize the FunctionHealthCheck.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
FunctionConfig | None
|
Config (args, kwargs, timeout). If None, built from kwargs. |
None
|
func
|
Callable[..., Any] | None
|
The function to perform the health check on (required if config is None). |
None
|
name
|
str
|
The name of the health check. |
'Function'
|
executor
|
Executor | None
|
Executor for sync functions. Defaults to None (thread pool). |
None
|
**kwargs
|
Any
|
Passed to FunctionConfig when config is None (args, kwargs, timeout). |
{}
|
Raises:
| Type | Description |
|---|---|
TypeError
|
When func is not provided. |
Source code in fast_healthchecks/checks/function.py
This module provides a health check class for Redis.
Classes:
| Name | Description |
|---|---|
RedisHealthCheck |
A class to perform health checks on Redis. |
Usage
The RedisHealthCheck class can be used to perform health checks on Redis by calling it.
Example
health_check = RedisHealthCheck( host="localhost", port=6379, ) result = await health_check() print(result.healthy)
RedisHealthCheck
¶
Bases: ClientCachingMixin['Redis'], HealthCheckDSN[HealthCheckResult, RedisParseDsnResult]
A class to perform health checks on Redis.
Attributes:
| Name | Type | Description |
|---|---|---|
_database |
The database to connect to. |
|
_host |
The host to connect to. |
|
_name |
str
|
The name of the health check. |
_password |
str
|
The password to authenticate with. |
_port |
str
|
The port to connect to. |
_timeout |
str
|
The timeout for the connection. |
_user |
str
|
The user to authenticate with. |
_ssl |
str
|
Whether to use SSL or not. |
_ssl_ca_certs |
str
|
The path to the CA certificate. |
Source code in fast_healthchecks/checks/redis.py
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 | |
__call__()
async
¶
Perform a health check on Redis.
Returns:
| Name | Type | Description |
|---|---|---|
HealthCheckResult |
HealthCheckResult
|
The result of the health check. |
Source code in fast_healthchecks/checks/redis.py
__init__(*, config=None, name='Redis', close_client_fn=_close_redis_client, **kwargs)
¶
Initialize the RedisHealthCheck class.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
RedisConfig | None
|
Connection config. If None, built from kwargs (host, port, database, etc.). |
None
|
name
|
str
|
The name of the health check. |
'Redis'
|
close_client_fn
|
Callable[[Redis], Awaitable[None]]
|
Callable to close the cached client. Defaults to the standard Redis aclose. |
_close_redis_client
|
**kwargs
|
Any
|
Passed to RedisConfig when config is None (host, port, database, user, password, ssl, ssl_ca_certs, timeout). |
{}
|
Source code in fast_healthchecks/checks/redis.py
parse_dsn(dsn)
classmethod
¶
Parse the DSN and return the results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dsn
|
str
|
The DSN to parse. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
RedisParseDsnResult |
RedisParseDsnResult
|
The results of parsing the DSN. |
Source code in fast_healthchecks/checks/redis.py
This module provides a health check class for Kafka.
Classes:
| Name | Description |
|---|---|
KafkaHealthCheck |
A class to perform health checks on Kafka. |
Usage
The KafkaHealthCheck class can be used to perform health checks on Kafka by calling it.
Example
health_check = KafkaHealthCheck( bootstrap_servers="localhost:9092", security_protocol="PLAINTEXT", ) result = await health_check() print(result.healthy)
KafkaHealthCheck
¶
Bases: ClientCachingMixin['AIOKafkaAdminClient'], HealthCheckDSN[HealthCheckResult, KafkaParseDsnResult]
A class to perform health checks on Kafka.
Attributes:
| Name | Type | Description |
|---|---|---|
_bootstrap_servers |
The Kafka bootstrap servers. |
|
_name |
str
|
The name of the health check. |
_sasl_mechanism |
str
|
The SASL mechanism to use. |
_sasl_plain_password |
str
|
The SASL plain password. |
_sasl_plain_username |
str
|
The SASL plain username. |
_security_protocol |
str
|
The security protocol to use. |
_ssl_context |
str
|
The SSL context to use. |
_timeout |
str
|
The timeout for the health check. |
Source code in fast_healthchecks/checks/kafka.py
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 | |
__call__()
async
¶
Perform the health check on Kafka.
Returns:
| Name | Type | Description |
|---|---|---|
HealthCheckResult |
HealthCheckResult
|
The result of the health check. |
Source code in fast_healthchecks/checks/kafka.py
__init__(*, config=None, name='Kafka', close_client_fn=_close_kafka_client, **kwargs)
¶
Initialize the KafkaHealthCheck.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
KafkaConfig | None
|
Connection config. If None, built from kwargs (bootstrap_servers, etc.). |
None
|
name
|
str
|
The name of the health check. |
'Kafka'
|
close_client_fn
|
Callable[[AIOKafkaAdminClient], Awaitable[None]]
|
Callable to close the cached client. |
_close_kafka_client
|
**kwargs
|
Any
|
Passed to KafkaConfig when config is None. |
{}
|
Source code in fast_healthchecks/checks/kafka.py
parse_dsn(dsn)
classmethod
¶
Parse the Kafka DSN and return the results.
Scheme kafkas implies SSL (SASL_SSL when credentials present).
Scheme kafka implies PLAINTEXT (SASL_PLAINTEXT when credentials present).
Kwargs to from_dsn override DSN-derived values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dsn
|
str
|
The DSN to parse. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
KafkaParseDsnResult |
KafkaParseDsnResult
|
The results of parsing the DSN. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If bootstrap servers are missing. |
Source code in fast_healthchecks/checks/kafka.py
This module provides a health check class for MongoDB.
Classes:
| Name | Description |
|---|---|
MongoHealthCheck |
A class to perform health checks on MongoDB. |
Usage
The MongoHealthCheck class can be used to perform health checks on MongoDB by calling it.
Example
health_check = MongoHealthCheck( hosts=["host1:27017", "host2:27017"], # or hosts="localhost", port=27017, user="myuser", password="mypassword", database="mydatabase" ) result = await health_check() print(result.healthy)
MongoHealthCheck
¶
Bases: ClientCachingMixin['AsyncIOMotorClient[dict[str, Any]]'], HealthCheckDSN[HealthCheckResult, MongoParseDsnResult]
A class to perform health checks on MongoDB.
Attributes:
| Name | Type | Description |
|---|---|---|
_auth_source |
The MongoDB authentication source. |
|
_database |
The MongoDB database to use. |
|
_hosts |
The MongoDB host or a list of hosts. |
|
_name |
str
|
The name of the health check. |
_password |
str
|
The MongoDB password. |
_port |
str
|
The MongoDB port. |
_timeout |
str
|
The timeout for the health check. |
_user |
str
|
The MongoDB user. |
Source code in fast_healthchecks/checks/mongo.py
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 | |
__call__()
async
¶
Perform the health check on MongoDB.
Returns:
| Name | Type | Description |
|---|---|---|
HealthCheckResult |
HealthCheckResult
|
The result of the health check. |
Source code in fast_healthchecks/checks/mongo.py
__init__(*, config=None, name='MongoDB', close_client_fn=_close_mongo_client, **kwargs)
¶
Initialize the MongoHealthCheck.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
MongoConfig | None
|
Connection config. If None, built from kwargs (hosts, port, etc.). |
None
|
name
|
str
|
The name of the health check. |
'MongoDB'
|
close_client_fn
|
Callable[[AsyncIOMotorClient[dict[str, Any]]], Awaitable[None]]
|
Callable to close the cached client. |
_close_mongo_client
|
**kwargs
|
Any
|
Passed to MongoConfig when config is None. |
{}
|
Source code in fast_healthchecks/checks/mongo.py
parse_dsn(dsn)
classmethod
¶
Parse the DSN and return the results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dsn
|
str
|
The DSN to parse. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
MongoParseDsnResult |
MongoParseDsnResult
|
The results of parsing the DSN. |
Source code in fast_healthchecks/checks/mongo.py
This module provides a health check class for OpenSearch.
Classes:
| Name | Description |
|---|---|
OpenSearchHealthCheck |
A class to perform health checks on OpenSearch. |
Usage
The OpenSearchHealthCheck class can be used to perform health checks on OpenSearch by calling it.
Example
health_check = OpenSearchHealthCheck( hosts=["localhost:9200"], http_auth=("username", "password"), use_ssl=True, verify_certs=True, ssl_show_warn=False, ca_certs="/path/to/ca.pem", ) result = await health_check() print(result.healthy)
OpenSearchHealthCheck
¶
Bases: ClientCachingMixin['AsyncOpenSearch'], HealthCheckDSN[HealthCheckResult, OpenSearchParseDsnResult]
A class to perform health checks on OpenSearch.
Attributes:
| Name | Type | Description |
|---|---|---|
_hosts |
The OpenSearch hosts. |
|
_name |
str
|
The name of the health check. |
_http_auth |
str
|
The HTTP authentication. |
_use_ssl |
str
|
Whether to use SSL or not. |
_verify_certs |
str
|
Whether to verify certificates or not. |
_ssl_show_warn |
str
|
Whether to show SSL warnings or not. |
_ca_certs |
str
|
The CA certificates. |
_timeout |
str
|
The timeout for the health check. |
Source code in fast_healthchecks/checks/opensearch.py
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 | |
__call__()
async
¶
Perform the health check on OpenSearch.
Returns:
| Name | Type | Description |
|---|---|---|
HealthCheckResult |
HealthCheckResult
|
The result of the health check. |
Source code in fast_healthchecks/checks/opensearch.py
__init__(*, config=None, name='OpenSearch', close_client_fn=_close_opensearch_client, **kwargs)
¶
Initialize the OpenSearchHealthCheck.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
OpenSearchConfig | None
|
Connection config. If None, built from kwargs (hosts, http_auth, etc.). |
None
|
name
|
str
|
The name of the health check. |
'OpenSearch'
|
close_client_fn
|
Callable[[AsyncOpenSearch], Awaitable[None]]
|
Callable to close the cached client. |
_close_opensearch_client
|
**kwargs
|
Any
|
Passed to OpenSearchConfig when config is None. |
{}
|
Source code in fast_healthchecks/checks/opensearch.py
parse_dsn(dsn)
classmethod
¶
Parse the OpenSearch DSN and return the results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dsn
|
str
|
The DSN to parse. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
OpenSearchParseDsnResult |
OpenSearchParseDsnResult
|
The results of parsing the DSN. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If DSN has missing host. |
Source code in fast_healthchecks/checks/opensearch.py
This module provides a health check class for RabbitMQ.
Classes:
| Name | Description |
|---|---|
RabbitMQHealthCheck |
A class to perform health checks on RabbitMQ. |
Security: When using DSN or config without a password (or with default
credentials), the library falls back to user="guest" and password="guest".
These defaults are for local development only; do not use them in production or
on non-local brokers. See SECURITY.md and :class:RabbitMQConfig docstring.
Usage
The RabbitMQHealthCheck class can be used to perform health checks on RabbitMQ by calling it.
Example
health_check = RabbitMQHealthCheck( host="localhost", port=5672, username="guest", password="guest", ) result = await health_check() print(result.healthy)
RabbitMQHealthCheck
¶
Bases: ClientCachingMixin['AbstractRobustConnection'], HealthCheckDSN[HealthCheckResult, RabbitMQParseDsnResult]
A class to perform health checks on RabbitMQ.
Uses ClientCachingMixin to reuse a single connection instead of opening a new one on every check.
Attributes:
| Name | Type | Description |
|---|---|---|
_host |
The RabbitMQ host. |
|
_name |
str
|
The name of the health check. |
_password |
str
|
The RabbitMQ password. |
_port |
str
|
The RabbitMQ port. |
_secure |
str
|
Whether to use a secure connection. |
_timeout |
str
|
The timeout for the health check. |
_user |
str
|
The RabbitMQ user. |
_vhost |
str
|
The RabbitMQ virtual host. |
Source code in fast_healthchecks/checks/rabbitmq.py
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 | |
__call__()
async
¶
Perform the health check on RabbitMQ.
ClientCachingMixin handles connection persistence; _ensure_client validates the connection via aio-pika's robust logic.
Returns:
| Name | Type | Description |
|---|---|---|
HealthCheckResult |
HealthCheckResult
|
The result of the health check. |
Source code in fast_healthchecks/checks/rabbitmq.py
__init__(*, config=None, name='RabbitMQ', close_client_fn=_close_rabbitmq_client, **kwargs)
¶
Initialize the RabbitMQHealthCheck.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
RabbitMQConfig | None
|
Connection config. If None, built from kwargs (host, user, password, etc.). |
None
|
name
|
str
|
The name of the health check. |
'RabbitMQ'
|
close_client_fn
|
Callable[[AbstractRobustConnection], Awaitable[None]]
|
Callable to close the cached connection. |
_close_rabbitmq_client
|
**kwargs
|
Any
|
Passed to RabbitMQConfig when config is None. |
{}
|
Source code in fast_healthchecks/checks/rabbitmq.py
parse_dsn(dsn)
classmethod
¶
Parse the DSN and return the results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dsn
|
str
|
The DSN to parse. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
RabbitMQParseDsnResult |
RabbitMQParseDsnResult
|
The results of parsing the DSN. |
Source code in fast_healthchecks/checks/rabbitmq.py
Health check that performs an HTTP GET to a URL.
UrlHealthCheck caches an httpx AsyncClient and supports optional basic auth, SSL verification, and SSRF protection (block_private_hosts).
UrlHealthCheck
¶
Bases: ClientCachingMixin['AsyncClient'], ConfigDictMixin, HealthCheck[HealthCheckResult]
Health check that performs an HTTP GET to a configurable URL.
Supports basic auth, custom timeout, SSL verification, and optional
SSRF protection via block_private_hosts (see config).
Source code in fast_healthchecks/checks/url.py
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 | |
__call__()
async
¶
Perform the health check.
When block_private_hosts is True, resolves the URL host before the request and rejects if it resolves to loopback/private (SSRF/DNS rebinding protection).
Returns:
| Name | Type | Description |
|---|---|---|
HealthCheckResult |
HealthCheckResult
|
Result with healthy=True if response is success. |
Source code in fast_healthchecks/checks/url.py
__init__(*, config=None, name='HTTP', close_client_fn=_close_url_client, **kwargs)
¶
Initialize the health check.
Warning
Pass only trusted URLs from application configuration. Do not use
user-controlled input for url to avoid SSRF.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
UrlConfig | None
|
Connection config. If None, built from kwargs (url, username, etc.). |
None
|
name
|
str
|
The name of the health check. |
'HTTP'
|
close_client_fn
|
Callable[[AsyncClient], Awaitable[None]]
|
Callable to close the cached client. |
_close_url_client
|
**kwargs
|
Any
|
Passed to UrlConfig when config is None (url required). |
{}
|
Source code in fast_healthchecks/checks/url.py
This module provides a health check class for PostgreSQL using asyncpg.
Classes:
| Name | Description |
|---|---|
PostgreSQLAsyncPGHealthCheck |
A class to perform health checks on a PostgreSQL database using asyncpg. |
Usage
The PostgreSQLAsyncPGHealthCheck class can be used to perform health checks on a PostgreSQL database by connecting to the database and executing a simple query.
Example
health_check = PostgreSQLAsyncPGHealthCheck( host="localhost", port=5432, user="username", password="password", database="dbname" )
or¶
health_check = PostgreSQLAsyncPGHealthCheck.from_dsn( "postgresql://username:password@localhost:5432/dbname", ) result = await health_check() print(result.healthy)
PostgreSQLAsyncPGHealthCheck
¶
Bases: BasePostgreSQLHealthCheck[HealthCheckResult]
Health check class for PostgreSQL using asyncpg.
Attributes:
| Name | Type | Description |
|---|---|---|
_name |
str
|
The name of the health check. |
_host |
str
|
The hostname of the PostgreSQL server. |
_port |
str
|
The port number of the PostgreSQL server. |
_user |
str
|
The username for authentication. |
_password |
str
|
The password for authentication. |
_database |
str
|
The database name. |
_ssl |
str
|
The SSL context for secure connections. |
_direct_tls |
str
|
Whether to use direct TLS. |
_timeout |
str
|
The timeout for the connection. |
Source code in fast_healthchecks/checks/postgresql/asyncpg.py
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 | |
__call__()
async
¶
Perform the health check.
Returns:
| Name | Type | Description |
|---|---|---|
HealthCheckResult |
HealthCheckResult
|
The result of the health check. |
Source code in fast_healthchecks/checks/postgresql/asyncpg.py
__init__(*, config=None, name='PostgreSQL', **kwargs)
¶
Initialize the PostgreSQLAsyncPGHealthCheck.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
PostgresAsyncPGConfig | None
|
Connection config. If None, built from kwargs (host, port, user, etc.). |
None
|
name
|
str
|
The name of the health check. |
'PostgreSQL'
|
**kwargs
|
Any
|
Passed to PostgresAsyncPGConfig when config is None. |
{}
|
Source code in fast_healthchecks/checks/postgresql/asyncpg.py
This module provides a health check for PostgreSQL using psycopg.
Classes:
| Name | Description |
|---|---|
PostgreSQLPsycopgHealthCheck |
A class for health checking PostgreSQL using psycopg. |
Usage
The PostgreSQLPsycopgHealthCheck class can be used to perform health checks on a PostgreSQL database by connecting to the database and executing a simple query.
Example
health_check = PostgreSQLPsycopgHealthCheck( host="localhost", port=5432, user="username", password="password", database="dbname" )
or¶
health_check = PostgreSQLPsycopgHealthCheck.from_dsn( "postgresql://username:password@localhost:5432/dbname", ) result = await health_check() print(result.healthy)
PostgreSQLPsycopgHealthCheck
¶
Bases: BasePostgreSQLHealthCheck[HealthCheckResult]
Health check class for PostgreSQL using psycopg.
Attributes:
| Name | Type | Description |
|---|---|---|
_name |
str
|
The name of the health check. |
_host |
str
|
The hostname of the PostgreSQL server. |
_port |
str
|
The port number of the PostgreSQL server. |
_user |
str
|
The username for authentication. |
_password |
str
|
The password for authentication. |
_database |
str
|
The database name. |
_sslmode |
str
|
The SSL mode to use for the connection. |
_sslcert |
str
|
The path to the SSL certificate file. |
_sslkey |
str
|
The path to the SSL key file. |
_sslrootcert |
str
|
The path to the SSL root certificate file. |
_timeout |
str
|
The timeout for the health check. |
Source code in fast_healthchecks/checks/postgresql/psycopg.py
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 | |
__call__()
async
¶
Perform the health check.
Returns:
| Name | Type | Description |
|---|---|---|
HealthCheckResult |
HealthCheckResult
|
The result of the health check. |
Source code in fast_healthchecks/checks/postgresql/psycopg.py
__init__(*, config=None, name='PostgreSQL', **kwargs)
¶
Initialize the PostgreSQLPsycopgHealthCheck.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
PostgresPsycopgConfig | None
|
Connection config. If None, built from kwargs (host, port, user, etc.). |
None
|
name
|
str
|
The name of the health check. |
'PostgreSQL'
|
**kwargs
|
Any
|
Passed to PostgresPsycopgConfig when config is None. |
{}
|
Source code in fast_healthchecks/checks/postgresql/psycopg.py
Integrations¶
Base for FastAPI, FastStream, and Litestar integrations.
Provides Probe, run_probe(), healthcheck_shutdown(), and helpers to build health routes. Framework-specific routers use these to expose liveness/readiness.
Probe
¶
Bases: NamedTuple
A probe is a collection of health checks that can be run together.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
The name of the probe. |
checks |
Sequence[Check]
|
A sequence of health checks to run. |
summary |
str | None
|
A summary of the probe. If not provided, a default summary will be generated. |
default_check_timeout_ms |
int | None
|
Default per-check timeout (ms) when check timeout is not set. |
Source code in fast_healthchecks/integrations/base.py
endpoint_summary
property
¶
Return a summary for the endpoint.
If a summary is provided, it will be used. Otherwise, a default summary will be generated.
ProbeAsgi
¶
An ASGI probe.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
probe
|
Probe
|
The probe to run. |
required |
options
|
ProbeRouteOptions | None
|
Route options (handlers, status codes, debug, timeout). When None, defaults from build_probe_route_options() are used. |
None
|
Source code in fast_healthchecks/integrations/base.py
__call__()
async
¶
Run the probe via run_probe (unified execution and timeout handling).
Returns:
| Type | Description |
|---|---|
tuple[bytes, dict[str, str] | None, int]
|
A tuple containing the response body, headers, and status code. |
Source code in fast_healthchecks/integrations/base.py
__init__(probe, *, options=None, runner=None)
¶
Initialize the ASGI probe.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
probe
|
Probe
|
The probe to run. |
required |
options
|
ProbeRouteOptions | None
|
Route options (handlers, status codes, debug, timeout). When None, defaults from build_probe_route_options() are used. |
None
|
runner
|
ProbeRunner | None
|
Optional ProbeRunner. When None, uses an internal reporting-mode runner with the configured timeout. |
None
|
Source code in fast_healthchecks/integrations/base.py
ProbeRouteOptions
¶
Bases: NamedTuple
Options for probe routes. Combines handler params and path prefix.
Source code in fast_healthchecks/integrations/base.py
to_route_params()
¶
Return ProbeRouteParams for create_probe_route_handler.
Source code in fast_healthchecks/integrations/base.py
ProbeRouteParams
¶
Bases: NamedTuple
Parameters for probe route handlers. Used by framework integrations.
Source code in fast_healthchecks/integrations/base.py
to_options(prefix='/health')
¶
Return ProbeRouteOptions with the given prefix.
Source code in fast_healthchecks/integrations/base.py
build_health_routes(probes, add_route, *, options=None)
¶
Build health route entries for framework integrations.
Used by Litestar and FastStream health() functions. When options is None, uses build_probe_route_options() defaults.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
probes
|
Iterable[Probe]
|
Probes to build routes for. |
required |
add_route
|
Callable[[Probe, ProbeRouteOptions], _T]
|
Callback (probe, options) -> route entry for the framework. |
required |
options
|
ProbeRouteOptions | None
|
Route options. When None, defaults from build_probe_route_options(). |
None
|
Returns:
| Type | Description |
|---|---|
list[_T]
|
List of route entries produced by add_route for each probe. |
Source code in fast_healthchecks/integrations/base.py
build_probe_route_options(*, success_handler=default_handler, failure_handler=default_handler, success_status=HTTPStatus.NO_CONTENT, failure_status=HTTPStatus.SERVICE_UNAVAILABLE, debug=False, prefix='/health', timeout=None)
¶
Build ProbeRouteOptions with defaults. Used by health() and _add_probe_route.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
success_handler
|
HandlerType
|
Handler for healthy responses. Receives ProbeAsgiResponse. |
default_handler
|
failure_handler
|
HandlerType
|
Handler for unhealthy responses. Same signature. |
default_handler
|
success_status
|
int
|
HTTP status for healthy (default 204 No Content). |
NO_CONTENT
|
failure_status
|
int
|
HTTP status for unhealthy (default 503). |
SERVICE_UNAVAILABLE
|
debug
|
bool
|
Include check details in responses. |
False
|
prefix
|
str
|
URL prefix for probe routes (e.g. "/health"). |
'/health'
|
timeout
|
float | None
|
Max seconds for all checks; on exceed returns failure. None = no limit. |
None
|
Returns:
| Type | Description |
|---|---|
ProbeRouteOptions
|
ProbeRouteOptions for use with HealthcheckRouter or health(). |
Source code in fast_healthchecks/integrations/base.py
close_probes(probes)
async
¶
Close resources owned by checks in the given probes.
Calls aclose() on each check that has it (e.g. checks with cached
clients). Ignores exceptions so one failure does not block others.
After closing, yields to the event loop a few times so that any
transport/socket cleanup callbacks (e.g. from aiohttp connector) can run
before the caller's context is torn down (avoids unclosed-resource
warnings in tests).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
probes
|
Iterable[Probe]
|
Probes whose checks should be closed. |
required |
Source code in fast_healthchecks/integrations/base.py
create_probe_route_handler(probe, params, *, response_factory, runner=None)
¶
Create an async handler for a probe route.
Framework integrations use this with their response_factory to build the handler, then register it (FastAPI add_api_route, FastStream/Litestar return).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
probe
|
Probe
|
The probe to run when the route is called. |
required |
params
|
ProbeRouteParams
|
Route params (handlers, status codes, etc.). |
required |
response_factory
|
Callable[[bytes, dict[str, str], int], _T]
|
Called with (body, headers, status_code); returns framework response. |
required |
runner
|
ProbeRunner | None
|
Optional ProbeRunner used for probe execution. |
None
|
Returns:
| Type | Description |
|---|---|
Callable[[], Awaitable[_T]]
|
Async callable that runs the probe and returns the framework response. |
Source code in fast_healthchecks/integrations/base.py
default_handler(response)
async
¶
Default handler for health check route.
Returns a minimal body {"status": "healthy"|"unhealthy"} for responses
that require content (e.g. 503). Returns None for 204 No Content.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
response
|
ProbeAsgiResponse
|
The response from the probe. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any] | None
|
Minimal status dict, or None for no response body. |
Source code in fast_healthchecks/integrations/base.py
healthcheck_shutdown(probes)
¶
Return an async shutdown callback that closes the given probes' checks.
Use this with framework lifespan/shutdown hooks (e.g. Litestar on_shutdown,
FastStream shutdown) so that health check resources are closed on app shutdown.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
probes
|
Iterable[Probe]
|
The same probes passed to your health routes. |
required |
Returns:
| Type | Description |
|---|---|
Callable[[], Awaitable[None]]
|
An async callable with no arguments that closes all checks with |
Source code in fast_healthchecks/integrations/base.py
make_probe_asgi(probe, *, options=None, runner=None)
¶
Create an ASGI probe from a probe.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
probe
|
Probe
|
The probe to create the ASGI probe from. |
required |
options
|
ProbeRouteOptions | None
|
Route options. When None, defaults from build_probe_route_options(). |
None
|
runner
|
ProbeRunner | None
|
Optional ProbeRunner. When None, uses an internal reporting-mode runner. |
None
|
Returns:
| Type | Description |
|---|---|
Callable[[], Awaitable[tuple[bytes, dict[str, str] | None, int]]]
|
An ASGI probe. |
Source code in fast_healthchecks/integrations/base.py
probe_path_suffix(probe)
¶
probe_route_path(probe, prefix='/health')
¶
Return the route path for a probe given a prefix.
run_probe(probe, *, timeout=None, on_check_start=None, on_check_end=None, on_timeout_return_failure=False)
async
¶
Run a probe and return the health check report.
Can be used without ASGI (CLI, cron, tests). ProbeAsgi uses this with on_timeout_return_failure=True so timeout behavior is unified.
When on_check_start or on_check_end are provided, checks run
sequentially (for ordering guarantees). Otherwise they run in parallel.
Cleanup and cancellation: On cancellation or timeout, run_probe does not
close cached clients (checks with aclose). The caller must call
healthcheck_shutdown(probes) or close_probes(probes) to close them.
There are no dangling background tasks after run_probe returns or raises.
See lifecycle and run-probe docs for cleanup paths X and Y.
Timeout semantics (probe-level only): When timeout is exceeded,
all pending checks are cancelled. Mode A (on_timeout_return_failure=False):
raise TimeoutError, no report. Mode B (on_timeout_return_failure=True):
return HealthCheckReport with failed results for timed-out checks.
ProbeAsgi uses Mode B. See docs run-probe.md for full semantics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
probe
|
Probe
|
The probe to run. |
required |
timeout
|
float | None
|
Maximum seconds for all checks. Raises asyncio.TimeoutError if exceeded unless on_timeout_return_failure is True. |
None
|
on_check_start
|
OnCheckStart | None
|
Optional callback before each check runs. Receives (check, index). |
None
|
on_check_end
|
OnCheckEnd | None
|
Optional callback after each check completes. Receives (check, index, result). |
None
|
on_timeout_return_failure
|
bool
|
If True, on timeout return a report with failed results instead of raising TimeoutError. |
False
|
Returns:
| Type | Description |
|---|---|
HealthCheckReport
|
HealthCheckReport with results from all checks. |
Raises:
| Type | Description |
|---|---|
HealthCheckTimeoutError
|
When timeout is exceeded and on_timeout_return_failure is False.
(Subclass of asyncio.TimeoutError; existing |
Source code in fast_healthchecks/integrations/base.py
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 | |
FastAPI integration for health checks.
HealthcheckRouter
¶
Bases: APIRouter
A router for health checks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*probes
|
Probe
|
Probes to run (e.g. liveness, readiness, startup). |
()
|
options
|
ProbeRouteOptions | None
|
Route options. When None, uses build_probe_route_options() defaults. |
None
|
To close health check resources (e.g. cached clients) on app shutdown,
call await router.close() from your FastAPI lifespan, or use
healthcheck_shutdown(probes) and call the returned callback.
Source code in fast_healthchecks/integrations/fastapi.py
__init__(*probes, options=None, runner=None)
¶
Initialize the router.
Source code in fast_healthchecks/integrations/fastapi.py
close()
async
¶
Close resources owned by this router's health check probes.
Call this from your FastAPI lifespan shutdown (e.g. after yield
in an @asynccontextmanager lifespan) so cached clients are closed.
Source code in fast_healthchecks/integrations/fastapi.py
healthcheck_shutdown(probes)
¶
Return an async shutdown callback that closes the given probes' checks.
Use this with framework lifespan/shutdown hooks (e.g. Litestar on_shutdown,
FastStream shutdown) so that health check resources are closed on app shutdown.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
probes
|
Iterable[Probe]
|
The same probes passed to your health routes. |
required |
Returns:
| Type | Description |
|---|---|
Callable[[], Awaitable[None]]
|
An async callable with no arguments that closes all checks with |
Source code in fast_healthchecks/integrations/base.py
FastStream integration for health checks.
health(*probes, options=None, runner=None)
¶
Make list of routes for healthchecks.
Returns:
| Type | Description |
|---|---|
Iterable[tuple[str, ASGIApp]]
|
Iterable[tuple[str, ASGIApp]]: Generated healthcheck routes. |
To close health check resources on app shutdown, pass the same probes
to healthcheck_shutdown(probes) and register the returned callback
with your FastStream app's shutdown hooks (e.g. @app.on_shutdown).
Source code in fast_healthchecks/integrations/faststream.py
healthcheck_shutdown(probes)
¶
Return an async shutdown callback that closes the given probes' checks.
Use this with framework lifespan/shutdown hooks (e.g. Litestar on_shutdown,
FastStream shutdown) so that health check resources are closed on app shutdown.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
probes
|
Iterable[Probe]
|
The same probes passed to your health routes. |
required |
Returns:
| Type | Description |
|---|---|
Callable[[], Awaitable[None]]
|
An async callable with no arguments that closes all checks with |
Source code in fast_healthchecks/integrations/base.py
Litestar integration for health checks.
health(*probes, options=None, runner=None)
¶
Make list of routes for healthchecks.
Returns:
| Type | Description |
|---|---|
Iterable[HTTPRouteHandler]
|
Iterable[HTTPRouteHandler]: Generated healthcheck route handlers. |
To close health check resources on app shutdown, pass the same probes
to healthcheck_shutdown(probes) and add the returned callback to
Litestar's on_shutdown list.
Source code in fast_healthchecks/integrations/litestar.py
healthcheck_shutdown(probes)
¶
Return an async shutdown callback that closes the given probes' checks.
Use this with framework lifespan/shutdown hooks (e.g. Litestar on_shutdown,
FastStream shutdown) so that health check resources are closed on app shutdown.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
probes
|
Iterable[Probe]
|
The same probes passed to your health routes. |
required |
Returns:
| Type | Description |
|---|---|
Callable[[], Awaitable[None]]
|
An async callable with no arguments that closes all checks with |
Source code in fast_healthchecks/integrations/base.py
Utility functions for fast-healthchecks.
maybe_redact(data, *, redact_secrets)
¶
Return data with secrets redacted if requested, otherwise return as-is.
parse_query_string(query)
¶
Parse a URL query string into a dictionary.
Keys and values are URL-decoded (unquoted). Pairs without '=' are stored with an empty value. Values containing '=' are preserved.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
The query string (e.g. 'key1=value1&key2=value2'). |
required |
Returns:
| Type | Description |
|---|---|
dict[str, str]
|
A dictionary of key-value pairs. |
Source code in fast_healthchecks/utils.py
redact_secrets_in_dict(data)
¶
Return a copy of data with secret-like keys redacted recursively.
Source code in fast_healthchecks/utils.py
validate_host_ssrf_async(host)
async
¶
Resolve host to IP(s) and reject if any are loopback/private/reserved (SSRF/DNS rebinding).
Call this before making the request when block_private_hosts=True, so that hostnames that resolve to private IPs (e.g. internal DNS or DNS rebinding) are rejected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
host
|
str
|
The hostname to resolve and validate. |
required |
Raises:
| Type | Description |
|---|---|
HealthCheckSSRFError
|
If any resolved IP is loopback, private, or reserved. |
Source code in fast_healthchecks/utils.py
validate_url_ssrf(url, *, allowed_schemes=frozenset({'http', 'https'}), block_private_hosts=False)
¶
Validate URL for SSRF-sensitive use (e.g. healthchecks from config).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The URL string to validate. |
required |
allowed_schemes
|
frozenset[str]
|
Schemes permitted (default http, https). |
frozenset({'http', 'https'})
|
block_private_hosts
|
bool
|
If True, reject localhost and private IP ranges. |
False
|
Raises:
| Type | Description |
|---|---|
HealthCheckSSRFError
|
If scheme is not allowed or host is in blocked range. |