Bridges¶
TaipanStack's bridges module provides adapters connecting TaipanStack's security, resilience, and error handling with popular Python libraries.
DB Bridge¶
DB Bridge — resilient database wrappers.
Wraps SQLAlchemy async engine and Redis async client with TaipanStack's circuit breaker and retry patterns.
ResilientDatabase
¶
ResilientDatabase(
engine: AsyncEngine,
*,
circuit_breaker: CircuitBreaker | None = None,
retry_config: RetryConfig | None = None,
)
Wraps a SQLAlchemy async engine with resilience patterns.
| PARAMETER | DESCRIPTION |
|---|---|
engine
|
SQLAlchemy
TYPE:
|
circuit_breaker
|
Optional circuit breaker.
TYPE:
|
retry_config
|
Optional retry configuration.
TYPE:
|
Example
db = ResilientDatabase(engine, circuit_breaker=breaker) result = await db.execute(text("SELECT 1"))
Initialize the resilient database wrapper.
| PARAMETER | DESCRIPTION |
|---|---|
engine
|
SQLAlchemy AsyncEngine.
TYPE:
|
circuit_breaker
|
Optional circuit breaker.
TYPE:
|
retry_config
|
Optional retry config.
TYPE:
|
execute
async
¶
execute(
statement: Executable, **kwargs: object
) -> Result[Result[object], Exception]
Execute a SQL statement with resilience.
| PARAMETER | DESCRIPTION |
|---|---|
statement
|
SQLAlchemy statement to execute.
TYPE:
|
**kwargs
|
Passed to
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Result[Result[object], Exception]
|
|
health_check
async
¶
health_check() -> Result[bool, Exception]
Check database connectivity.
Executes SELECT 1 to verify the connection is alive.
| RETURNS | DESCRIPTION |
|---|---|
Result[bool, Exception]
|
|
ResilientRedis
¶
ResilientRedis(
client: Redis[bytes | str],
*,
circuit_breaker: CircuitBreaker | None = None,
)
Wraps a Redis async client with resilience patterns.
| PARAMETER | DESCRIPTION |
|---|---|
client
|
TYPE:
|
circuit_breaker
|
Optional circuit breaker.
TYPE:
|
Example
r = ResilientRedis(redis_client, circuit_breaker=breaker) result = await r.execute("GET", "my_key")
Initialize the resilient Redis wrapper.
| PARAMETER | DESCRIPTION |
|---|---|
client
|
Redis async client.
TYPE:
|
circuit_breaker
|
Optional circuit breaker.
TYPE:
|
execute
async
¶
execute(
command: str, *args: object
) -> Result[object, Exception]
Execute a Redis command with resilience.
| PARAMETER | DESCRIPTION |
|---|---|
command
|
Redis command name (e.g.
TYPE:
|
*args
|
Command arguments.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Result[object, Exception]
|
|
health_check
async
¶
health_check() -> Result[bool, Exception]
Check Redis connectivity via PING.
| RETURNS | DESCRIPTION |
|---|---|
Result[bool, Exception]
|
|
HTTP Bridge¶
HTTP Bridge — safe httpx client with SSRF protection and resilience.
Wraps httpx.AsyncClient with TaipanStack's guard_ssrf,
retry, and circuit breaker integrations. All outbound URLs are
validated against SSRF before the request is sent.
HttpRequestKwargs
¶
Bases: TypedDict
Type definitions for HTTP request kwargs.
HttpClientKwargs
¶
Bases: TypedDict
Type definitions for HTTP client kwargs.
SafeHttpClient
¶
SafeHttpClient(
*,
ssrf_protection: bool = True,
retry_config: RetryConfig | None = None,
circuit_breaker: CircuitBreaker | None = None,
retryable_status_codes: frozenset[
int
] = _RETRYABLE_STATUS_CODES,
timeout: float = 10.0,
**client_kwargs: Unpack[HttpClientKwargs],
)
Async context manager wrapping httpx with TaipanStack safety.
| PARAMETER | DESCRIPTION |
|---|---|
ssrf_protection
|
Enable SSRF validation on all requests.
TYPE:
|
retry_config
|
Retry configuration for transient failures.
TYPE:
|
circuit_breaker
|
Optional circuit breaker for all requests.
TYPE:
|
retryable_status_codes
|
HTTP status codes to retry on.
TYPE:
|
**client_kwargs
|
Passed to
TYPE:
|
Example
async with SafeHttpClient() as client: ... result = await client.get("https://api.example.com/data") ... if isinstance(result, Ok): print(result.unwrap().json()) ... else: print(f"Error: {result.unwrap_err()}")
Initialize the safe HTTP client.
| PARAMETER | DESCRIPTION |
|---|---|
ssrf_protection
|
Enable SSRF validation.
TYPE:
|
retry_config
|
Retry configuration.
TYPE:
|
circuit_breaker
|
Circuit breaker instance.
TYPE:
|
retryable_status_codes
|
Status codes to retry.
TYPE:
|
**client_kwargs
|
Keyword args for httpx.AsyncClient. Default timeout is 10.0 seconds if not provided.
TYPE:
|
__aexit__
async
¶
__aexit__(
_exc_type: type[BaseException] | None,
_exc_val: BaseException | None,
_exc_tb: object,
) -> None
Exit the async context manager.
request
async
¶
request(
method: str,
url: str,
**kwargs: Unpack[HttpRequestKwargs],
) -> Result[Response, Exception]
Send an HTTP request with safety features.
| PARAMETER | DESCRIPTION |
|---|---|
method
|
HTTP method.
TYPE:
|
url
|
Target URL.
TYPE:
|
**kwargs
|
Passed to the underlying client.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Result[Response, Exception]
|
|
get
async
¶
get(
url: str, **kw: Unpack[HttpRequestKwargs]
) -> Result[Response, Exception]
Send a GET request.
post
async
¶
post(
url: str, **kw: Unpack[HttpRequestKwargs]
) -> Result[Response, Exception]
Send a POST request.
put
async
¶
put(
url: str, **kw: Unpack[HttpRequestKwargs]
) -> Result[Response, Exception]
Send a PUT request.
delete
async
¶
delete(
url: str, **kw: Unpack[HttpRequestKwargs]
) -> Result[Response, Exception]
Send a DELETE request.
patch
async
¶
patch(
url: str, **kw: Unpack[HttpRequestKwargs]
) -> Result[Response, Exception]
Send a PATCH request.
safe_request
async
¶
safe_request(
method: str,
url: str,
*,
ssrf_protection: bool = True,
retry_config: RetryConfig | None = None,
circuit_breaker: CircuitBreaker | None = None,
retryable_status_codes: frozenset[
int
] = _RETRYABLE_STATUS_CODES,
timeout: float | None = 10.0,
**kwargs: Unpack[HttpRequestKwargs],
) -> Result[Response, Exception]
Perform a one-shot HTTP request with safety features.
| PARAMETER | DESCRIPTION |
|---|---|
method
|
HTTP method (GET, POST, etc.).
TYPE:
|
url
|
Target URL.
TYPE:
|
ssrf_protection
|
Validate URL against SSRF.
TYPE:
|
retry_config
|
Optional retry configuration.
TYPE:
|
circuit_breaker
|
Optional circuit breaker.
TYPE:
|
retryable_status_codes
|
Status codes that trigger retries.
TYPE:
|
timeout
|
Explicit timeout in seconds (default: 10.0).
TYPE:
|
**kwargs
|
Passed to
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Result[Response, Exception]
|
|
Web Bridge¶
Web Bridge — ASGI middleware for rate limiting and security headers.
Provides a framework-agnostic ASGI middleware that integrates TaipanStack's rate limiter and security headers into any ASGI application (FastAPI, Litestar, Starlette, etc.).
SecurityHeadersConfig
dataclass
¶
SecurityHeadersConfig(
x_content_type_options: Literal["nosniff"] = "nosniff",
x_frame_options: Literal["DENY", "SAMEORIGIN"] = "DENY",
x_xss_protection: Literal[
"1; mode=block", "0"
] = "1; mode=block",
strict_transport_security: str = "max-age=31536000; includeSubDomains",
referrer_policy: Literal[
"no-referrer",
"no-referrer-when-downgrade",
"origin",
"origin-when-cross-origin",
"same-origin",
"strict-origin",
"strict-origin-when-cross-origin",
"unsafe-url",
] = "strict-origin-when-cross-origin",
content_security_policy: str = "default-src 'self'",
)
Configuration for security response headers.
| ATTRIBUTE | DESCRIPTION |
|---|---|
x_content_type_options |
Value for X-Content-Type-Options.
TYPE:
|
x_frame_options |
Value for X-Frame-Options.
TYPE:
|
x_xss_protection |
Value for X-XSS-Protection.
TYPE:
|
strict_transport_security |
Value for Strict-Transport-Security.
TYPE:
|
referrer_policy |
Value for Referrer-Policy.
TYPE:
|
content_security_policy |
Value for Content-Security-Policy.
TYPE:
|
to_headers
¶
to_headers() -> list[tuple[bytes, bytes]]
Convert config to ASGI header pairs.
| RETURNS | DESCRIPTION |
|---|---|
list[tuple[bytes, bytes]]
|
List of (name, value) byte tuples. |
TaipanMiddleware
¶
TaipanMiddleware(
app: ASGIApp,
*,
rate_limiter: RateLimiter | None = None,
security_headers: bool = True,
headers_config: SecurityHeadersConfig | None = None,
)
ASGI middleware providing rate limiting and security headers.
| PARAMETER | DESCRIPTION |
|---|---|
app
|
The wrapped ASGI application.
TYPE:
|
rate_limiter
|
Optional rate limiter instance.
TYPE:
|
security_headers
|
Whether to inject security headers.
TYPE:
|
headers_config
|
Custom security headers configuration.
TYPE:
|
Example
from taipanstack.utils.rate_limit import RateLimiter app = TaipanMiddleware( ... my_asgi_app, ... rate_limiter=RateLimiter(max_calls=100, time_window=60), ... security_headers=True, ... )
Initialize the middleware.
| PARAMETER | DESCRIPTION |
|---|---|
app
|
ASGI application to wrap.
TYPE:
|
rate_limiter
|
Optional rate limiter.
TYPE:
|
security_headers
|
Inject security headers.
TYPE:
|
headers_config
|
Custom headers config.
TYPE:
|
__call__
async
¶
__call__(
scope: Scope, receive: Receive, send: Send
) -> None
Process an ASGI request.
| PARAMETER | DESCRIPTION |
|---|---|
scope
|
ASGI scope dict.
TYPE:
|
receive
|
ASGI receive callable.
TYPE:
|
send
|
ASGI send callable.
TYPE:
|
result_to_response
¶
result_to_response(
result: Result[T, Exception],
*,
status_ok: int = 200,
status_err: int = 500,
) -> dict[str, object]
Convert a Result to a JSON-friendly response dict.
| PARAMETER | DESCRIPTION |
|---|---|
result
|
The Result to convert.
TYPE:
|
status_ok
|
HTTP status for
TYPE:
|
status_err
|
HTTP status for
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, object]
|
Dict with |
Example
result_to_response(Ok({"id": 1})) {"status": 200, "data": {"id": 1}}