Stripe/McMaster-Carr quality remediations Tier 1 - Error fidelity: ResultExt trait for error context chains, structured error logging, user_id in request spans, context on payment/auth/S3 paths Tier 2 - Observability: Prometheus metrics (/metrics endpoint, request counters, duration histograms, error counters, DB pool gauges), Grafana+Prometheus on Hetzner, admin metrics dashboard, resource IDs in handler spans, rate limit response headers (X-RateLimit-*) Tier 3 - API discipline: API versioning (/api/v1/ for SyncKit, license keys, OTA, public), MNW-Version response header, idempotency keys (table + middleware), webhook retry queue (table + exponential backoff + scheduler worker) Tier 4 - Testability: EmailTransport trait + PostmarkTransport, PaymentProvider trait, MockEmailTransport + MockPaymentProvider, TestHarness::with_mocks(), 6 new integration tests (checkout flow, email assertions, failure modes) Tier 5 - Database resilience: Pool health (test_before_acquire, max_lifetime, idle_timeout, min_connections), slow query logging (100ms WARN threshold), index coverage audit (all hot paths verified) Tier 6 - Performance: Cache-Control middleware (CDN caching for public pages, no-cache for dashboard, no-store for APIs), page weight audit (31KB gzipped total) Type safety: Visibility, ProjectRole, SubscriptionStatus enums replacing strings, PriceCents newtype, impl_str_enum! macro enhanced with PartialEq<str>
Author: Max J. <87768334+MaxJMath@users.noreply.github.com> - 2026-04-23 19:16 UTC
Commit:
b3f80f618a6724bd6e816bd408990cecd348418bParent:
85 files changed,
+2501 insertions,
-372 deletions
"cpufeatures",][[package]]name = "ahash"version = "0.8.12"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"dependencies = [ "cfg-if", "once_cell", "version_check", "zerocopy",][[package]]name = "aho-corasick"version = "1.1.4"[[package]]name = "makenotwork"version = "0.3.25"version = "0.3.26"dependencies = [ "anyhow", "argon2", "http-body-util", "infer 0.19.0", "jsonwebtoken", "log", "metrics", "metrics-exporter-prometheus", "openssl", "rand 0.8.5", "regex", "libc",][[package]]name = "metrics"version = "0.24.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5d5312e9ba3771cfa961b585728215e3d972c950a3eed9252aa093d6301277e8"dependencies = [ "ahash", "portable-atomic",][[package]]name = "metrics-exporter-prometheus"version = "0.18.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3589659543c04c7dc5526ec858591015b87cd8746583b51b48ef4353f99dbcda"dependencies = [ "base64 0.22.1", "indexmap", "metrics", "metrics-util", "quanta", "thiserror 2.0.18",][[package]]name = "metrics-util"version = "0.20.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "cdfb1365fea27e6dd9dc1dbc19f570198bc86914533ad639dae939635f096be4"dependencies = [ "crossbeam-epoch", "crossbeam-utils", "hashbrown 0.16.1", "metrics", "quanta", "rand 0.9.2", "rand_xoshiro", "sketches-ddsketch",][[package]]name = "mime"version = "0.3.17" "rand_core 0.5.1",][[package]]name = "rand_xoshiro"version = "0.7.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f703f4665700daf5512dcca5f43afa6af89f09db47fb56be587f80636bda2d41"dependencies = [ "rand_core 0.9.5",][[package]]name = "raw-cpuid"version = "11.6.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b2aa850e253778c88a04c3d7323b043aeda9d3e30d5971937c1855769763678e"[[package]]name = "sketches-ddsketch"version = "0.3.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0c6f73aeb92d671e0cc4dca167e59b2deb6387c375391bc99ee743f326994a2b"[[package]]name = "slab"version = "0.4.12"# CLIclap = { version = "4", features = ["derive"] }# Logging (used by sqlx slow query config)log = "0.4"# Error handlingthiserror = "2.0.18"anyhow = "1.0.101"# Metricsmetrics = "0.24"metrics-exporter-prometheus = { version = "0.18.1", default-features = false }# Markdown rendering + documentation enginedocengine = { path = "../shared/docengine", features = ["doc-loader", "directives", "frontmatter", "media-urls"] } } } // Record user_id in the current span so all downstream logs // (DB queries, error handlers, etc.) include it automatically. tracing::Span::current().record("user_id", tracing::field::display(&user.id)); Ok(AuthUser(user)) }}// -- Database --pub const DB_POOL_MAX_CONNECTIONS: u32 = 25;pub const DB_POOL_MIN_CONNECTIONS: u32 = 2;pub const DB_ACQUIRE_TIMEOUT_SECS: u64 = 3;/// Rotate connections after 30 minutes to prevent stale sessions.pub const DB_MAX_LIFETIME_SECS: u64 = 1800;/// Prune idle connections after 10 minutes.pub const DB_IDLE_TIMEOUT_SECS: u64 = 600;// -- Sessions --pub const SESSION_EXPIRY_DAYS: i64 = 7; let status = self.status_code(); let message = self.user_message(); // Log internal errors // Increment error counter for Prometheus metrics::counter!("http_errors_total", "kind" => self.tag()).increment(1); // Log server errors with structured fields. // The request_id and user_id are already in the parent tracing span // (set by TraceLayer and AuthUser respectively), so they appear // automatically in these log lines. match &self { AppError::Database(e) => { tracing::error!("Database error: {:?}", e); tracing::error!(error.kind = "database", error.detail = ?e, "request failed"); } AppError::Internal(e) => { tracing::error!("Internal error: {:?}", e); tracing::error!(error.kind = "internal", error.detail = ?e, "request failed"); } AppError::Storage(e) => { tracing::error!("Storage error: {:?}", e); tracing::error!(error.kind = "storage", error.detail = %e, "request failed"); } AppError::MalwareDetected(detail) => { tracing::warn!("File quarantined: {}", detail); tracing::warn!(error.kind = "malware_detected", error.detail = %detail, "file quarantined"); } _ => {} }/// Result type alias for handlerspub type Result<T> = std::result::Result<T, AppError>;/// Extension trait for adding context to any `Result<T, E>` where `E` can/// convert into `AppError`. The context string is preserved in the error chain/// via `anyhow::Context`, making it visible in structured error logs.////// ```ignore/// use crate::error::ResultExt;/// let user = db::users::get_user_by_id(&db, id)/// .await/// .context("fetch user for checkout")?;/// ```pub trait ResultExt<T> { fn context(self, msg: &'static str) -> Result<T>; fn with_context<F: FnOnce() -> String>(self, f: F) -> Result<T>;}impl<T, E> ResultExt<T> for std::result::Result<T, E>where E: std::error::Error + Send + Sync + 'static,{ fn context(self, msg: &'static str) -> Result<T> { self.map_err(|e| AppError::Internal(anyhow::Error::new(e).context(msg))) } fn with_context<F: FnOnce() -> String>(self, f: F) -> Result<T> { self.map_err(|e| AppError::Internal(anyhow::Error::new(e).context(f()))) }}#[cfg(test)]mod tests { use super::*;}/// Build a rate limiter config from a per-millisecond interval and burst size./// Includes `x-ratelimit-limit`, `x-ratelimit-remaining`, and `retry-after` headers.pub fn rate_limiter_ms( ms: u64, burst: u32,) -> std::sync::Arc< tower_governor::governor::GovernorConfig< tower_governor::key_extractor::SmartIpKeyExtractor, ::governor::middleware::NoOpMiddleware, ::governor::middleware::StateInformationMiddleware, >,> { std::sync::Arc::new( .key_extractor(tower_governor::key_extractor::SmartIpKeyExtractor) .per_millisecond(ms) .burst_size(burst) .use_headers() .finish() .expect("rate limiter config"), )}/// Build a rate limiter config from a per-second rate and burst size./// Includes `x-ratelimit-limit`, `x-ratelimit-remaining`, and `retry-after` headers.pub fn rate_limiter_per_sec( per_sec: u64, burst: u32,) -> std::sync::Arc< tower_governor::governor::GovernorConfig< tower_governor::key_extractor::SmartIpKeyExtractor, ::governor::middleware::NoOpMiddleware, ::governor::middleware::StateInformationMiddleware, >,> { std::sync::Arc::new( .key_extractor(tower_governor::key_extractor::SmartIpKeyExtractor) .per_second(per_sec) .burst_size(burst) .use_headers() .finish() .expect("rate limiter config"), )pub mod helpers;pub mod import;pub mod markdown;pub mod metrics;pub mod monitor;pub mod mt_client;pub mod payments;use config::Config;use docengine::DocLoader;use email::EmailClient;use payments::StripeClient;use payments::PaymentProvider;use routes::{ admin_routes, api_routes, auth_routes, build_routes, git_routes, git_issue_routes, oauth_routes, ota_routes, page_routes, postmark_routes, storage_routes, stripe_routes, pub config: Config, pub s3: Option<Arc<dyn StorageBackend>>, pub synckit_s3: Option<Arc<dyn StorageBackend>>, pub stripe: Option<StripeClient>, pub stripe: Option<Arc<dyn PaymentProvider>>, pub email: EmailClient, pub docs: Arc<DocLoader>, pub scanner: Option<Arc<ScanPipeline>>, /// SSE push notification channels for SyncKit subscribers. /// Key: (app_id, user_id), Value: broadcast sender that SSE connections subscribe to. pub sync_notify: Arc<DashMap<(SyncAppId, UserId), tokio::sync::broadcast::Sender<()>>>, /// Prometheus metrics handle for rendering the admin dashboard. `None` in tests. pub metrics_handle: Option<metrics_exporter_prometheus::PrometheusHandle>,}impl AppState {}/// Build the app router with all routes and middleware (minus tracing/TCP).pub fn build_app(state: AppState, session_layer: SessionManagerLayer<PostgresStore>) -> Router { Router::new()pub fn build_app( state: AppState, session_layer: SessionManagerLayer<PostgresStore>,) -> Router { let metrics_handle = state.metrics_handle.clone(); let mut app = Router::new() .merge(page_routes()) .merge(auth_routes()) .merge(api_routes()) .service(ServeDir::new("rustdoc")), ) .fallback(routes::custom_domain::custom_domain_fallback) .with_state(state) .with_state(state.clone()); // /metrics endpoint (Prometheus scrape target). Only available when the // recorder is installed (i.e. in the real server, not in integration tests). if let Some(handle) = metrics_handle { app = app.merge( Router::new() .route("/metrics", axum::routing::get(metrics::render)) .with_state(handle), ); } app.layer(middleware::from_fn(metrics::cache_control_middleware)) .layer(middleware::from_fn(metrics::metrics_middleware)) .layer(middleware::from_fn(csrf::csrf_middleware)) .layer(middleware::from_fn_with_state(state.clone(), metrics::idempotency_middleware)) .layer(session_layer) .layer(RequestBodyLimitLayer::new(1024 * 1024))}