Skip to main content

arcly_http/
lib.rs

1//! **arcly-http** — NestJS ergonomics meets Rust safety & speed.
2//!
3//! An enterprise-grade web framework on [axum]: declarative controllers,
4//! zero-lock dependency injection, one shared request pipeline for every
5//! entry point, and the operational machinery (multi-tenancy, transactional
6//! outbox, ABAC, PII masking, field-level encryption, graceful shutdown
7//! governance) that production systems otherwise hand-roll.
8//!
9//! ```ignore
10//! use arcly_http::prelude::*;
11//!
12//! #[Injectable]
13//! pub struct GreetService;
14//! impl GreetService {
15//!     fn greet(&self, name: &str) -> String { format!("hello, {name}") }
16//! }
17//!
18//! #[Controller("/hello")]
19//! impl HelloController {
20//!     #[Get("/:name")]
21//!     async fn hello(&self, #[Param] name: String, svc: Inject<GreetService>) -> String {
22//!         svc.greet(&name)
23//!     }
24//! }
25//!
26//! #[Module(controllers(HelloController), providers(GreetService))]
27//! pub struct AppModule;
28//!
29//! #[tokio::main]
30//! async fn main() -> std::io::Result<()> {
31//!     App::launch::<AppModule>("0.0.0.0:3000").await // Swagger UI at /docs
32//! }
33//! ```
34//!
35//! ## Design invariants
36//!
37//! - **One request pipeline** — HTTP routes, plugin routes, and WebSocket
38//!   handshakes authenticate through the same boundary; a security fix lands
39//!   everywhere at once.
40//! - **No locks on the request path** — frozen `&'static` DI container,
41//!   atomics, and `ArcSwap` snapshots only.
42//! - **Handlers never see axum** — [`RequestContext`] is the only request
43//!   surface, so the HTTP layer can evolve without breaking user code.
44//!
45//! ## Module layout
46//!
47//! | Module          | Responsibility                                              |
48//! |-----------------|--------------------------------------------------------------|
49//! | [`app`]         | Launch contract, [`LaunchConfig`] governance knobs           |
50//! | [`auth`]        | Identity & access: JWT, cookies, sessions, OAuth2, ABAC, guards |
51//! | [`core`]        | DI engine + plugin lifecycle (HTTP-agnostic)                 |
52//! | [`web`]         | HTTP layer: boundary, context, errors, interceptors, CORS    |
53//! | [`data`]        | DB facade (SQLx/SeaORM/Diesel), tenancy, migrations, outbox  |
54//! | [`messaging`]   | Event consumer mesh, retries, dead-letter                    |
55//! | [`compliance`]  | PII masking + field-level envelope encryption                |
56//! | [`realtime`]    | WebSocket gateways + SSE                                      |
57//! | [`observability`] | Structured logs, Prometheus, OTLP, health, trace propagation |
58//! | [`resilience`]  | Circuit breaker, rate limiting, bulkhead, distributed locks  |
59//! | [`security`]    | Security headers                                              |
60//!
61//! ## Cargo features
62//!
63//! | Feature | Effect |
64//! |---|---|
65//! | *(none)* | Full framework, no database driver |
66//! | `db-sqlx` / `db-sqlx-postgres` / `db-sqlx-mysql` / `db-sqlx-sqlite` | SQLx-backed [`data`] layer |
67//! | `db-seaorm` | SeaORM driver |
68//! | `db-diesel` | Diesel (r2d2) driver |
69//!
70//! Most applications only need `use arcly_http::prelude::*;`.
71//!
72//! [axum]: https://docs.rs/axum
73
74#![deny(unsafe_code)]
75#![deny(rustdoc::broken_intra_doc_links)]
76
77pub mod app;
78pub mod auth;
79pub mod compliance;
80pub mod core;
81pub mod data;
82pub mod docs;
83pub mod http;
84pub mod messaging;
85pub mod observability;
86pub mod pipeline;
87pub mod realtime;
88pub mod resilience;
89pub mod testing;
90pub mod web;
91
92// ─── Path-compat shims ─────────────────────────────────────────────────────────
93// The auth subsystem was consolidated from five root files into `auth/`.
94// These re-exports keep every pre-existing import path compiling unchanged:
95// `arcly_http::cookie::CookieService`, `arcly_http::guards::Guard`, etc.
96pub use auth::cookie;
97
98// Path-compat shims for the module re-org (root files moved into their
99// owning domains). Every pre-existing import path keeps compiling:
100// `arcly_http::security::…`, `arcly_http::validation::…`,
101// `arcly_http::openapi::…`, `arcly_http::event::…`.
102pub use auth::guards;
103pub use auth::oauth;
104pub use auth::session;
105pub use docs::openapi;
106pub use messaging::event;
107pub use web::security;
108pub use web::validation;
109
110// Convenience re-exports.
111pub use core::plugins;
112pub use web::cache;
113pub use web::interceptors;
114
115// Re-exports needed by macro expansions.
116#[doc(hidden)]
117pub use axum as __axum;
118pub use futures;
119pub use inventory;
120pub use schemars;
121pub use serde_json;
122pub use validator;
123
124pub use app::{App, LaunchConfig};
125pub use web::{Error, RequestContext};
126
127#[doc(hidden)]
128#[inline]
129pub fn __schema_for<T: schemars::JsonSchema>() -> serde_json::Value {
130    serde_json::to_value(schemars::schema_for!(T)).unwrap_or(serde_json::Value::Null)
131}
132
133/// Single stable surface for `arcly-http-macros` codegen.
134///
135/// Every symbol the proc-macros emit is re-exported here, so internal files
136/// can move freely without touching the macro crate — only this module's
137/// `pub use` lines need to follow.
138#[doc(hidden)]
139pub mod __macro_support {
140    pub use crate::auth::guards::Guard;
141    pub use crate::auth::policy::check_policies;
142    pub use crate::compliance::crypto::EncryptRecord;
143    pub use crate::compliance::masking::mask_response;
144    // Explicit list — ONLY what macro expansions actually reference.
145    // A glob here silently turned every engine internal into a contract
146    // with the macro crate; new drivers/transports must not widen this
147    // surface by accident.
148    pub use crate::core::engine::{
149        FrozenDiContainer, HttpMethod, Module, ModuleDescriptor, ParamLoc, ParamSpec,
150        ProviderDescriptor, Resolver, RouteDescriptor, RouteSpec,
151    };
152    pub use crate::data::tx::run_transactional;
153    pub use crate::http::Json;
154    pub use crate::messaging::{EventContext, EventError, EventHandlerDescriptor};
155    pub use crate::observability::audit::emit_route_audit;
156    pub use crate::realtime::gateway::{GatewayDescriptor, GatewayRuntime, MessageHandler};
157    pub use crate::realtime::{ArclyGateway, WsClient};
158    pub use crate::resilience::timeout::run_with_timeout;
159    pub use crate::resilience::{BreakerOpen, CircuitBreaker};
160    pub use crate::web::context::RequestContext;
161    pub use crate::web::extract::{
162        extract_body_validated, extract_header, extract_param, extract_query_validated, Inject,
163    };
164    pub use crate::web::idempotency::run_idempotent;
165    pub use crate::web::interceptors::{Interceptor, NextHandler};
166    pub use crate::web::Error;
167}
168
169/// `use arcly_http::prelude::*;` brings in everything a user needs.
170pub mod prelude {
171    pub use crate::app::{App, LaunchConfig};
172    pub use crate::auth::cookie::{CookieConfig, CookieService, SameSite};
173    pub use crate::auth::guards::{
174        JwtAuthGuard, RoleGuard, SessionAuthGuard, JWT_AUTH, SESSION_AUTH,
175    };
176    pub use crate::auth::oauth::{OAuth2Provider, OAuth2Service, OAuth2UserInfo};
177    pub use crate::auth::policy::{
178        check_policies, Decision, EnvAttributes, PolicyEngine, PolicyInput, PolicySet, PolicySource,
179    };
180    pub use crate::auth::secrets::{spawn_secret_watcher, Rotating, SecretSource, SecretVersion};
181    pub use crate::auth::session::{Session, SessionConfig, SessionManager, SessionStore};
182    pub use crate::auth::{JwtConfig, JwtService};
183    pub use crate::cache::{stats as cache_stats, CacheInterceptor, CacheStats};
184    pub use crate::compliance::{
185        CryptoError, CryptoVault, DataKey, EncryptRecord, EncryptedField, KekSource, KeyId,
186        MaskRule, MaskStrategy, Masker, MaskingPolicy,
187    };
188    pub use crate::core::engine::FrozenDiContainer;
189    pub use crate::core::plugins::{ArclyPlugin, ArclyPluginContext, PluginError, PluginStage};
190    pub use crate::data::db::{ArclyDbPool, DbDriver, DbHealthCheck, OwnedDbConn};
191    #[cfg(feature = "db-sqlx")]
192    pub use crate::data::migrate::{Migration, MigrationReport, MigrationRunner};
193    pub use crate::data::outbox::{
194        with_transaction, OutboxEntry, OutboxPublisher, OutboxRelay, OutboxStore, OutboxTx,
195        TransactionalDataSource,
196    };
197    pub use crate::data::tx::{in_transaction, with_current_tx, ArclyTransaction};
198    pub use crate::data::{
199        AccessIntent, DataError, DataErrorKind, DataSource, DataSourceRegistry, ReadAfterWritePin,
200    };
201    pub use crate::http::{IntoResponse, Json, Response};
202    pub use crate::interceptors::{
203        EnvelopeResponse, Interceptor, LatencyLog, NextHandler, TelemetryLog, TraceInterceptor,
204    };
205    pub use crate::messaging::{
206        ConsumerRuntime, EventContext, EventHandlerDescriptor, InboundMessage, MessageTransport,
207    };
208    pub use crate::observability::audit::{AuditOutcome, AuditPipeline, AuditRecord, AuditSink};
209    pub use crate::observability::health::{HealthCheck, HealthRegistry, HealthStatus};
210    pub use crate::observability::plugin::ArclyObservabilityPlugin;
211    pub use crate::openapi::{ApiKeyIn, OpenApiInfo, SecurityScheme};
212    pub use crate::pipeline::Provenance;
213    pub use crate::resilience::{
214        Bulkhead, DLockBackend, DistributedLock, DistributedRateLimit, FailurePolicy, LockGuard,
215        RateDecision, RateLimit, RateLimitBackend,
216    };
217    pub use crate::security::{configure as configure_security, FrameOptions, SecurityConfig};
218    pub use crate::validation::Validated;
219    pub use crate::web::boundary::BoundaryFilter;
220    pub use crate::web::cors::CorsConfig;
221    pub use crate::web::dynamic::{DynamicRouteTable, DYNAMIC_PREFIX};
222    pub use crate::web::error::{
223        BadRequest, Conflict, FieldError, Forbidden, GatewayTimeout, HttpError, HttpException,
224        Internal, NotFound, ProblemDetails, ServiceUnavailable, TooManyRequests, Unauthorized,
225        Validation,
226    };
227    pub use crate::web::idempotency::{IdempotencyDecision, IdempotencyStore};
228    pub use crate::web::responses::{Accepted, Created, NoContent};
229    pub use crate::web::tenant::{
230        TenantConfig, TenantGuard, TenantId, TenantRegistry, TenantStrategy, TENANT,
231    };
232    pub use crate::web::{Error, Inject, RequestContext};
233    pub use arcly_http_macros::{
234        circuit_breaker, AuditLog, CacheKey, CacheTTL, Controller, Delete, Deprecated,
235        EncryptFields, EventConsumer, EventPattern, Get, Idempotent, Injectable, MaskFields,
236        Module, Patch, Post, Put, RequirePolicies, Timeout, Transactional, UseInterceptors,
237        Version,
238    };
239    pub use schemars::JsonSchema;
240    pub use validator::Validate;
241}