Skip to main content

fastapi_core/
lib.rs

1//! Core types and traits for fastapi_rust.
2//!
3//! This crate provides the fundamental building blocks:
4//! - [`Request`] and [`Response`] types
5//! - [`RequestContext`] wrapping asupersync's `Cx`
6//! - [`FromRequest`] trait for extractors
7//! - Error types and [`IntoResponse`] trait
8//!
9//! # Design Principles
10//!
11//! - Zero-copy where possible
12//! - No runtime reflection
13//! - All types support `Send + Sync`
14//! - Cancel-correct via asupersync integration
15//!
16//! # Asupersync Integration
17//!
18//! This crate uses [asupersync](https://github.com/user/asupersync) as its async
19//! runtime foundation, providing:
20//!
21//! - **Structured concurrency**: Request handlers run in regions
22//! - **Cancel-correctness**: Graceful cancellation via checkpoints
23//! - **Budgeted timeouts**: Request timeouts via budget exhaustion
24//! - **Deterministic testing**: Lab runtime for reproducible tests
25
26#![forbid(unsafe_code)]
27// Pedantic clippy lints allowed (style suggestions, not correctness issues)
28#![allow(clippy::uninlined_format_args)]
29#![allow(clippy::single_char_pattern)]
30#![allow(clippy::unused_async)]
31#![allow(clippy::cast_possible_truncation)]
32#![allow(clippy::unreadable_literal)]
33#![allow(clippy::type_complexity)]
34#![allow(clippy::must_use_candidate)]
35#![allow(clippy::derivable_impls)]
36#![allow(clippy::missing_fields_in_debug)]
37#![allow(clippy::single_match)]
38#![allow(clippy::unused_self)]
39#![allow(clippy::redundant_closure)]
40#![allow(clippy::semicolon_if_nothing_returned)]
41#![allow(clippy::never_loop)]
42#![allow(clippy::needless_lifetimes)]
43#![allow(clippy::needless_pass_by_value)]
44#![allow(clippy::needless_borrow)]
45#![allow(clippy::match_same_arms)]
46#![allow(clippy::items_after_statements)]
47#![allow(clippy::manual_strip)]
48#![allow(clippy::format_push_string)]
49#![allow(clippy::struct_field_names)]
50#![allow(clippy::single_match_else)]
51#![allow(clippy::elidable_lifetime_names)]
52#![allow(clippy::map_unwrap_or)]
53
54pub mod app;
55mod context;
56pub mod coverage;
57mod dependency;
58pub mod digest;
59pub mod docs;
60pub mod error;
61mod extract;
62pub mod logging;
63pub mod middleware;
64pub mod multipart;
65mod password;
66mod request;
67mod response;
68pub mod routing;
69pub mod shutdown;
70#[cfg(feature = "testing")]
71pub mod testing;
72pub mod validation;
73pub mod websocket;
74
75pub use context::{CancelledError, IntoOutcome, RequestContext};
76pub use dependency::{
77    DefaultConfig, DefaultDependencyConfig, DependencyCache, DependencyOverrides, DependencyScope,
78    Depends, DependsCleanup, DependsConfig, FromDependency, FromDependencyWithCleanup, NoCache,
79};
80pub use digest::{DigestAlgorithm, DigestAuth, DigestAuthError, DigestAuthErrorKind, DigestQop};
81pub use error::{HttpError, LocItem, ValidationError, ValidationErrors};
82pub use extract::{
83    Accept, ApiKey, ApiKeyConfig, ApiKeyError, ApiKeyErrorKind, ApiKeyLocation, AppState,
84    Authorization, BasicAuth, BasicAuthError, BasicAuthErrorKind, BearerToken, BearerTokenError,
85    BearerTokenErrorKind, ContentType, Cookie, CookieExtractError, CookieExtractErrorKind,
86    CookieName, CsrfToken, CsrfTokenCookie, DEFAULT_JSON_LIMIT, DEFAULT_PAGE, DEFAULT_PER_PAGE,
87    Form, FormExtractError, FormExtractErrorKind, FromHeaderValue, FromRequest, Header,
88    HeaderExtractError, HeaderName, HeaderValues, Host, Json, JsonConfig, JsonExtractError,
89    MAX_PER_PAGE, MultipartExtractError, NamedHeader, OAuth2BearerError, OAuth2BearerErrorKind,
90    OAuth2PasswordBearer, OAuth2PasswordBearerConfig, Page, Pagination, PaginationConfig, Path,
91    PathExtractError, PathParams, Query, QueryExtractError, QueryParams, SessionId, State,
92    StateExtractError, UserAgent, Valid, ValidExtractError, Validate, XRequestId,
93    snake_to_header_case,
94};
95pub use middleware::{
96    AddResponseHeader, BoxFuture, ControlFlow, Cors, CorsConfig, Handler, Layer, Layered,
97    Middleware, MiddlewareStack, NoopMiddleware, OriginPattern, PathPrefixFilter, ReferrerPolicy,
98    RequestId, RequestIdConfig, RequestIdMiddleware, RequestResponseLogger, RequireHeader,
99    SecurityHeaders, SecurityHeadersConfig, XFrameOptions,
100};
101pub use multipart::{
102    DEFAULT_MAX_FIELDS, DEFAULT_MAX_FILE_SIZE, DEFAULT_MAX_TOTAL_SIZE, MultipartConfig,
103    MultipartError, MultipartForm, MultipartParser, Part, UploadFile, parse_boundary,
104};
105pub use request::{
106    BackgroundTasks, BackgroundTasksInner, Body, Headers, HttpVersion, Method, Request,
107    RequestBodyStream, RequestBodyStreamError,
108};
109pub use response::{
110    Binary, BodyStream, FileResponse, Html, IntoResponse, Link, LinkHeader, LinkRel, NoContent,
111    Redirect, Response, ResponseBody, ResponseModelAliases, ResponseModelConfig, ResponseProduces,
112    SameSite, SetCookie, StatusCode, Text, ValidatedResponse, apply_conditional, check_if_match,
113    check_if_none_match, exclude_fields, include_fields, mime_type_for_extension,
114};
115pub use websocket::{
116    Frame as WebSocketFrame, OpCode as WebSocketOpCode, WS_GUID, WebSocket, WebSocketError,
117    WebSocketHandshakeError, websocket_accept_from_key,
118};
119
120// Re-export interactive docs helpers.
121pub use docs::{
122    DocsConfig, oauth2_redirect_html, oauth2_redirect_response, redoc_html, redoc_response,
123    swagger_ui_html, swagger_ui_response,
124};
125
126// Re-export key asupersync types for convenience
127pub use asupersync::{Budget, Cx, Outcome, RegionId, TaskId};
128
129// Re-export security helpers
130pub use password::{Algorithm, HashConfig, PasswordHasher, SecureCompare, constant_time_eq};
131
132// Re-export testing utilities
133#[cfg(feature = "testing")]
134pub use testing::{
135    CookieJar, FixtureGuard, IntegrationTest, RequestBuilder, TestClient, TestFixture,
136    TestResponse, json_contains,
137};
138
139// Re-export assertion macros (defined via #[macro_export] in testing module)
140// Note: The macros assert_status!, assert_header!, assert_body_contains!,
141// assert_json!, and assert_body_matches! are automatically exported at the crate root
142// due to #[macro_export]. Users can import them with `use fastapi_core::assert_status;`
143// They are available when the `testing` feature is enabled.
144
145// Re-export logging utilities
146pub use logging::{AutoSpan, LogConfig, LogEntry, LogLevel, Span};
147
148// Re-export app utilities
149pub use app::{
150    App, AppBuilder, AppConfig, ExceptionHandlers, OpenApiConfig, RouteEntry, StartupHook,
151    StartupHookError, StartupOutcome, StateContainer,
152};
153
154// Re-export shutdown utilities
155pub use shutdown::{
156    GracefulConfig, GracefulShutdown, InFlightGuard, ShutdownAware, ShutdownController,
157    ShutdownHook, ShutdownOutcome, ShutdownPhase, ShutdownReceiver, grace_expired_cancel_reason,
158    shutdown_cancel_reason, subdivide_grace_budget,
159};