Skip to main content

Crate scyph

Crate scyph 

Source
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 query abac::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 on tower-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 in scyph-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 in scyph-notify.
  • fcm: Enables Firebase Cloud Messaging in scyph-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 in scyph-storage.
  • image: Enables image thumbnail generation in scyph-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: Enables QueryBuilder dynamic 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.
AuthUser
Authenticated user extracted from an HTTP request.
BloomFilter
A Bloom filter for approximate set membership.
ErrorDetails
Field-level detail for request payload validation or processing errors.
FilterBuilder
Wrapper around sqlx::QueryBuilder for safe parameterized ABAC query filtering.
FilterParams
Generic filtering query parameters.
LinkBuilder
Builder for fluently constructing absolute URLs and endpoint links.
LinkGenerator
Canonical URL link generator extracted from incoming request headers (X-Forwarded-Host, Host, X-Forwarded-Proto).
NoEmailService
Dummy no-op EmailService implementation that silently discards email delivery requests.
NoPushService
Dummy no-op PushService implementation that silently discards push notifications.
OptionalAuthUser
Optional authenticated user extractor for public or hybrid endpoints.
PagedResponse
Standard envelope for paginated list responses.
PaginationParams
Standardized offset pagination query parameters.
RateLimitConfig
Configurable builder for peer-IP rate limiting layers.
RealtimeBroadcaster
High-performance Redis Pub/Sub broadcaster for cross-replica WebSocket message fanout.
RealtimeEvent
Standardized wire format envelope for WebSocket event broadcasting.
RealtimeSession
RAII guard representing an active WebSocket client session registered with ConnectionRegistry.
RequestId
Type-safe Axum extractor for the current HTTP request ID.
RequestParams
Composite request parameter wrapper for combined pagination, sorting, filtering, and searching.
ResponseMeta
Standardized metadata header attached to API response envelopes.
SanitizedJson
Axum extractor for JSON request bodies that performs string sanitization without garde validation.
SearchParams
Search query string parameter (?q=term).
SharedBloomFilter
A thread-safe wrapper around BloomFilter for sharing across tasks.
SortParams
Generic sorting query parameters.
TelemetryGuard
Guard holding the non-blocking log appender worker thread.
ThumbnailConfig
Configuration builder for image thumbnail generation.
ThumbnailStoreResult
Result of storing an original file alongside its derived thumbnail.
TypedPath
Axum extractor for strongly-typed URL path parameters.
ValidatedJson
Axum extractor for JSON request bodies with automatic input sanitization and garde validation.
ValidatedPath
Axum extractor for URL path parameters with garde validation.
ValidatedQuery
Axum extractor for query string parameters with garde validation.
ValkeyBloomFilter
A Bloom filter whose bits live in a Valkey/Redis string key.
VerifiedWebhook
Type-safe Axum extractor for HMAC-SHA256 verified webhooks.
WorkerHandle
Handle for controlling, canceling, and gracefully joining a running background worker task.

Enums§

AbacError
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.
AuthError
Error type for authentication, RBAC, and JWT operations in scyph-auth.
DbError
Unified error type for all database operations in scyph-db.
ExtractorError
Granular errors encountered during request payload extraction and validation.
IdempotencyError
Errors encountered during idempotency check and storage operations.
NotifyError
Error type for all notification services and utilities in scyph-notify.
PaginationError
Errors encountered during pagination cursor encoding or decoding.
RateLimitError
Error type for rate limit layer creation and governor configuration errors.
RealtimeError
Error type for real-time Redis pub/sub and WebSocket broadcasting operations.
SortOrder
Sorting direction enumeration.
StorageError
Error type for all storage services and extractors in scyph-storage.
ValkeyBloomError
Errors returned by ValkeyBloomFilter.
WebhookError
Errors encountered during webhook signature verification.
WorkerError
Errors encountered during background worker execution.

Traits§

AbacPolicy
Core ABAC policy trait for defining domain-level authorization rules and SQL filter injections.
ApplyFiltering
Extension trait for appending single-column filter conditions to a QueryBuilder.
ApplyPagination
Extension trait for appending LIMIT and OFFSET pagination clauses to a QueryBuilder.
ApplyRequestParams
Extension trait for appending full composite RequestParams (search, filter, sort, pagination) in a single call.
ApplySearch
Extension trait for appending full-text search ILIKE filters to a QueryBuilder.
ApplySorting
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.
EmailTemplate
Contract for strongly-typed domain email templates.
PushTemplate
Contract for strongly-typed domain push notification events.
RateLimitRouterExt
Extension trait for axum::Router providing fluent rate limiting middleware registration.
RealtimeHealthExt
Extension trait enabling automated realtime broadcaster health checks against a HealthRegistry.
RealtimePayload
Trait binding an event name string constant to a strongly-typed payload structure.
StorageThumbnailExt
Extension trait for StorageService providing atomic-style original + thumbnail upload.
WebhookConfig
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 standard ResponseMeta into 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::Router with standard telemetry, UUIDv7 request ID propagation, dynamic compression, tracing, and auto-meta response injection.

Type Aliases§

PeerRateLimitLayer
Type alias for the standard peer-IP rate limiting layer.
Result
Standardized Result type alias defaulting the error type to AppError.
SmartRateLimitLayer
Type alias for the smart IP rate limiting layer for reverse-proxy deployments.