Expand description
§Scyph
scyph is a modular, high-performance framework for building production-grade web services with Axum.
§Framework Architecture
scyph aggregates cross-cutting application concerns into decoupled, independently usable crates:
core: Foundational RFC 7807 problem details (AppError), standard JSON response envelopes (ApiResponse,PagedResponse,ResponseMeta), and identity traits (Claims).auth: JWT token creation/verification, Argon2id password hashing, Moka claims caching, and role-based route guards.abac: Attribute-Based Access Control policies, SQL queryabac::FilterBuilder, and Cedar policy evaluation.db: PostgreSQL connection pooling via SQLx, transaction context management, database migration/seeding tools, and dynamic QueryBuilder search/filter/sort/pagination extensions.health: Service health registries and Kubernetes liveness/readiness endpoint handlers.notify: Email delivery via Lettre & Tera templates, Firebase Cloud Messaging push notifications, and in-app repository traits.realtime: Redis Pub/Sub WebSocket broadcasting, multi-recipient fanout, multiplexed connection pooling, and bounded per-session message queues.storage: AWS S3 / MinIO (path-style aware) and in-memory object storage abstractions with streaming multipart extractors and image thumbnail processing.telemetry: Non-blocking tracing subscribers, time-ordered UUIDv7 request ID propagation, HTTP response telemetry headers (x-response-time-ms,x-api-version,x-library-version,x-trace-id), safe JSON response metadata injection, and dynamic compression.ratelimit: IP-based and reverse-proxy-aware smart rate limiting layers built ontower-governor.utils: Constant-time HMAC webhooks (direct digests and timestamped), background worker task loops with graceful shutdown, Base64 pagination cursors, and Redis API idempotency.
§Feature Flags
auth: Enables authentication and RBAC utilities (scyph-auth).abac: Enables Attribute-Based Access Control (scyph-abac).cedar: Enables Cedar policy evaluation inscyph-abac.db: Enables PostgreSQL pool management and migration tools (scyph-db).health: Enables health check endpoint registries (scyph-health).notify: Enables notification services (scyph-notify).email: Enables SMTP email delivery via Lettre inscyph-notify.fcm: Enables Firebase Cloud Messaging inscyph-notify.realtime: Enables Redis Pub/Sub WebSocket broadcaster (scyph-realtime).storage: Enables object storage and file extractors (scyph-storage).s3: Enables AWS S3 / MinIO backend inscyph-storage.image: Enables image thumbnail generation inscyph-storage.telemetry: Enables tracing, UUIDv7 request IDs, and auto-meta response injection (scyph-telemetry).ratelimit: Enables IP-based rate limiting middleware (scyph-ratelimit).utils: Enables utility primitives, HMAC webhooks, background workers, and API idempotency (scyph-utils).extractors: Enables type-safe validated JSON body, query parameter, and URL path extractors (scyph-extractors).query: EnablesQueryBuilderdynamic filtering, sorting, pagination, and search extensions (scyph-db).full: Umbrella feature enabling all framework sub-crates and sub-features.
§Quickstart Example
ⓘ
use axum::{routing::get, Router};
use scyph::prelude::*;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// 1. Initialize non-blocking telemetry logging
let _guard = init_tracing().expect("Tracing subscriber initialized");
// 2. Define application router
let app = Router::new()
.route("/api/hello", get(hello_handler));
// 3. Wrap router with telemetry (tracing spans, UUIDv7 request IDs, auto-meta injection, compression)
let app = with_telemetry(app);
Ok(())
}
async fn hello_handler(RequestId(req_id): RequestId) -> ApiResponse<String> {
ApiResponse::ok(format!("Hello! Request ID is {req_id}"))
}Re-exports§
pub use scyph_core as core;pub use scyph_auth as auth;pub use scyph_abac as abac;pub use scyph_db as db;pub use scyph_health as health;pub use scyph_notify as notify;pub use scyph_storage as storage;pub use scyph_realtime as realtime;pub use scyph_telemetry as telemetry;pub use scyph_ratelimit as ratelimit;pub use scyph_utils as utils;pub use scyph_extractors as extractors;
Modules§
- prelude
- Convenient prelude re-exporting common framework types for single-line imports (
use scyph::prelude::*;).
Structs§
- ApiResponse
- Standard JSON envelope for successful API responses.
- Auth
User - Authenticated user extracted from an HTTP request.
- Bloom
Filter - A Bloom filter for approximate set membership.
- Error
Details - Field-level detail for request payload validation or processing errors.
- Filter
Builder - Wrapper around
sqlx::QueryBuilderfor safe parameterized ABAC query filtering. - Filter
Params - Generic filtering query parameters.
- Link
Builder - Builder for fluently constructing absolute URLs and endpoint links.
- Link
Generator - Canonical URL link generator extracted from incoming request headers (
X-Forwarded-Host,Host,X-Forwarded-Proto). - NoEmail
Service - Dummy no-op
EmailServiceimplementation that silently discards email delivery requests. - NoPush
Service - Dummy no-op
PushServiceimplementation that silently discards push notifications. - Optional
Auth User - Optional authenticated user extractor for public or hybrid endpoints.
- Paged
Response - Standard envelope for paginated list responses.
- Pagination
Params - Standardized offset pagination query parameters.
- Rate
Limit Config - Configurable builder for peer-IP rate limiting layers.
- Realtime
Broadcaster - High-performance Redis Pub/Sub broadcaster for cross-replica WebSocket message fanout.
- Realtime
Event - Standardized wire format envelope for WebSocket event broadcasting.
- Realtime
Session - RAII guard representing an active WebSocket client session registered with
ConnectionRegistry. - Request
Id - Type-safe Axum extractor for the current HTTP request ID.
- Request
Params - Composite request parameter wrapper for combined pagination, sorting, filtering, and searching.
- Response
Meta - Standardized metadata header attached to API response envelopes.
- Sanitized
Json - Axum extractor for JSON request bodies that performs string sanitization without
gardevalidation. - Search
Params - Search query string parameter (
?q=term). - Shared
Bloom Filter - A thread-safe wrapper around
BloomFilterfor sharing across tasks. - Sort
Params - Generic sorting query parameters.
- Telemetry
Guard - Guard holding the non-blocking log appender worker thread.
- Thumbnail
Config - Configuration builder for image thumbnail generation.
- Thumbnail
Store Result - Result of storing an original file alongside its derived thumbnail.
- Typed
Path - Axum extractor for strongly-typed URL path parameters.
- Validated
Json - Axum extractor for JSON request bodies with automatic input sanitization and
gardevalidation. - Validated
Path - Axum extractor for URL path parameters with
gardevalidation. - Validated
Query - Axum extractor for query string parameters with
gardevalidation. - Valkey
Bloom Filter - A Bloom filter whose bits live in a Valkey/Redis string key.
- Verified
Webhook - Type-safe Axum extractor for HMAC-SHA256 verified webhooks.
- Worker
Handle - Handle for controlling, canceling, and gracefully joining a running background worker task.
Enums§
- Abac
Error - Error type for attribute-based access control policy evaluation in
scyph-abac. - Action
- Authorization actions used in Attribute-Based Access Control (ABAC) or Policy evaluation.
- AppError
- The canonical error type for all Scyph-based HTTP backends.
- Auth
Error - Error type for authentication, RBAC, and JWT operations in
scyph-auth. - DbError
- Unified error type for all database operations in
scyph-db. - Extractor
Error - Granular errors encountered during request payload extraction and validation.
- Idempotency
Error - Errors encountered during idempotency check and storage operations.
- Notify
Error - Error type for all notification services and utilities in
scyph-notify. - Pagination
Error - Errors encountered during pagination cursor encoding or decoding.
- Rate
Limit Error - Error type for rate limit layer creation and governor configuration errors.
- Realtime
Error - Error type for real-time Redis pub/sub and WebSocket broadcasting operations.
- Sort
Order - Sorting direction enumeration.
- Storage
Error - Error type for all storage services and extractors in
scyph-storage. - Valkey
Bloom Error - Errors returned by
ValkeyBloomFilter. - Webhook
Error - Errors encountered during webhook signature verification.
- Worker
Error - Errors encountered during background worker execution.
Traits§
- Abac
Policy - Core ABAC policy trait for defining domain-level authorization rules and SQL filter injections.
- Apply
Filtering - Extension trait for appending single-column filter conditions to a
QueryBuilder. - Apply
Pagination - Extension trait for appending LIMIT and OFFSET pagination clauses to a
QueryBuilder. - Apply
Request Params - Extension trait for appending full composite
RequestParams(search, filter, sort, pagination) in a single call. - Apply
Search - Extension trait for appending full-text search ILIKE filters to a
QueryBuilder. - Apply
Sorting - Extension trait for appending ORDER BY sorting clauses to a
QueryBuilder. - Authorizable
- Marker trait representing a role or permission identifier usable for authorization.
- Claims
- Core trait to implement on your application’s custom JWT claims struct.
- Email
Template - Contract for strongly-typed domain email templates.
- Push
Template - Contract for strongly-typed domain push notification events.
- Rate
Limit Router Ext - Extension trait for
axum::Routerproviding fluent rate limiting middleware registration. - Realtime
Health Ext - Extension trait enabling automated realtime broadcaster health checks against a
HealthRegistry. - Realtime
Payload - Trait binding an event name string constant to a strongly-typed payload structure.
- Storage
Thumbnail Ext - Extension trait for
StorageServiceproviding atomic-style original + thumbnail upload. - Webhook
Config - Declarative configuration template for webhook verification.
Functions§
- auto_
meta_ middleware - Axum middleware for injecting telemetry headers (
x-response-time-ms,x-api-version,x-library-version,x-trace-id) on all responses, and automatically injecting standardResponseMetainto JSON response bodies. - derive_
thumbnail_ key - Derives a thumbnail storage key by inserting a subdirectory before the file name.
- derive_
thumbnail_ key_ with_ format - Derives a thumbnail storage key by inserting a subdirectory before the file name and replacing the file extension with the target format extension.
- deserialize_
number_ from_ string - Helper deserializer to parse numbers from either raw JSON integers or query string numbers (
"10"->10). - escape_
like_ pattern - Helper function to escape special SQL LIKE pattern wildcards (
%,_,\). - format_
content_ type - Returns the canonical MIME content-type string corresponding to an
ImageFormat. - format_
extension - Returns the primary file extension (without leading dot) corresponding to an
ImageFormat. - generate_
thumbnail - Generates a JPEG thumbnail buffer from raw image bytes.
- generate_
thumbnail_ with_ format - Generates a thumbnail buffer encoded with a specified destination format.
- init_
tracing - Initializes global tracing subscriber with environment filtering (
RUST_LOG) and non-blocking stdout log output. - per_
ip_ layer - Creates a peer-IP rate limiting layer with specified burst capacity and replenishment interval.
- relaxed_
layer - Creates a relaxed peer-IP rate limiting layer (500 requests per 100 milliseconds).
- smart_
ip_ layer - Creates a reverse-proxy-aware smart IP rate limiting layer with specified burst and interval.
- smart_
relaxed_ layer - Creates a relaxed smart rate limiting layer for proxy environments (500 requests per 100 milliseconds).
- smart_
strict_ layer - Creates a strict smart rate limiting layer for proxy environments (5 requests per 2 seconds).
- strict_
layer - Creates a strict peer-IP rate limiting layer (5 requests per 2 seconds).
- thumbnail_
key - Replaces a folder segment in a storage key string with a thumbnail subfolder.
- verify_
raw_ webhook - Verifies an incoming HMAC-SHA256 webhook payload directly without timestamps (e.g. GitHub
X-Hub-Signature-256, Shopify, etc.). - verify_
webhook - Verifies an incoming HMAC-SHA256 webhook payload against a expected hex signature.
- verify_
webhook_ header - Helper function to parse standard webhook signature headers and dispatch to the correct verifier.
- with_
telemetry - Wraps an
axum::Routerwith standard telemetry, UUIDv7 request ID propagation, dynamic compression, tracing, and auto-meta response injection.
Type Aliases§
- Peer
Rate Limit Layer - Type alias for the standard peer-IP rate limiting layer.
- Result
- Standardized
Resulttype alias defaulting the error type toAppError. - Smart
Rate Limit Layer - Type alias for the smart IP rate limiting layer for reverse-proxy deployments.