Skip to main content

tork_core/
lib.rs

1//! Core runtime for the Tork web framework.
2//!
3//! This crate holds everything that runs at request time: the HTTP server built
4//! on Hyper and Tokio, the router, the dependency-injection traits, response and
5//! error types. It contains no procedural macros; those live in `tork-macros`.
6//!
7//! End users do not depend on this crate directly. They depend on the `tork`
8//! facade crate, which re-exports the public surface defined here.
9#![forbid(unsafe_code)]
10
11pub mod constants;
12
13mod app;
14mod body;
15mod cache;
16mod env;
17mod error;
18mod extract;
19mod hooks;
20mod lifespan;
21mod logging;
22pub mod middleware;
23mod multipart;
24mod openapi;
25mod realtime;
26#[cfg(feature = "redis")]
27mod redis_handle;
28mod resources;
29mod response;
30mod router;
31pub mod security;
32mod server;
33#[cfg(feature = "tls")]
34pub mod tls;
35mod service;
36mod settings;
37mod sse;
38mod state;
39pub mod testing;
40mod throttle;
41mod ws;
42
43pub use app::{App, AppInner, TestApp};
44pub use lifespan::{Lifespan, LifespanContext, ReadyContext};
45pub use logging::{
46    ErrorLogDetail, FileLogConfig, LogEvent, LogFormat, LogSpan, Logger, LoggerConfig, Rotation,
47    TelemetryConfig,
48};
49pub use middleware::{DuplicatePolicy, Middleware, Next, Request};
50#[doc(hidden)]
51pub use multipart::{
52    __parse_multipart, __validate_file_bytes, __validate_upload, FileRule, MultipartForm,
53};
54pub use multipart::{FileBytes, Form, FromMultipart, Multipart, UploadConfig, UploadFile};
55// Re-exported so handlers can name `Mime` without depending on the `mime` crate.
56pub use body::{box_body, BoxError, ReqBody, RespBody};
57#[cfg(feature = "redis")]
58pub use cache::RedisStore;
59pub use cache::{Cache, CacheStore, MemoryStore};
60pub use ipnet::IpNet;
61pub use mime;
62#[cfg(feature = "redis")]
63pub use redis_handle::Redis;
64pub use resources::Resources;
65pub use server::{Http1Config, Http2Config, TorkService};
66#[doc(hidden)]
67pub use throttle::check_request as __throttle_check;
68#[cfg(feature = "redis")]
69pub use throttle::RedisThrottleStore;
70pub use throttle::{
71    ByIp, MemoryThrottleStore, Throttle, ThrottleKey, ThrottlePolicy, ThrottleStore, Throttler,
72};
73// Re-export the Redis client so applications use the same version for raw access
74// (commands, Lua scripts, pipelines) without adding their own dependency.
75#[cfg(feature = "redis")]
76pub use ::redis;
77pub use error::{Error, ErrorDetail, ErrorKind, Result};
78pub use extract::{
79    __extract_path_param, BearerToken, FromPathParam, FromRequest, LastEventId, PathParams,
80    RequestContext, SseResume, Valid,
81};
82pub use hooks::{
83    ErrorContext, ErrorEvent, PanicEvent, RequestEvent, ResponseEvent, ValidationErrorEvent,
84};
85pub use openapi::{AsyncApiProvider, OpenApiProvider};
86pub use realtime::{Hub, Room};
87// Re-exported so WebSocket handlers can name a subscription without depending on
88// tokio directly.
89pub use response::{
90    __finish, __finish_into, bytes_response, json_response, IntoResponse, Json, Response,
91};
92pub use router::matcher::{Match, Matcher};
93pub use router::{BoxFuture, HandlerFn, RequestBodyKind, Route, RouteMeta, Router, SchemaThunk};
94pub use settings::{SecretString, SettingsLoader};
95pub use security::constant_time_eq;
96#[cfg(feature = "tls")]
97pub use tls::TlsConfig;
98pub use tokio::sync::broadcast::Receiver as WsReceiver;
99// Generated-code support for `#[derive(Inject)]` test overrides.
100#[doc(hidden)]
101pub use sse::__sse_into_response;
102pub use sse::{Sse, SseEvent};
103pub use state::{AppStateRef, State, StateMap};
104#[doc(hidden)]
105pub use testing::__take_override;
106pub use ws::{
107    __ws_handshake, WebSocket, WebSocketConfig, WebSocketConn, WsClose, WsCloseCode, WsConnectInfo,
108    WsDisconnectInfo, WsError, WsMessage,
109};
110
111// Commonly used `http` types are re-exported so users do not need to depend on
112// the `http` crate directly.
113pub use http::{header, HeaderMap, HeaderName, HeaderValue, Method, StatusCode};
114
115/// Runtime support for the `#[tork::main]` macro.
116///
117/// This is generated-code support, not part of the user-facing API.
118#[doc(hidden)]
119pub mod __rt {
120    /// Builds a multi-threaded Tokio runtime and blocks on `future` to completion.
121    pub fn block_on<F: std::future::Future>(future: F) -> F::Output {
122        tokio::runtime::Builder::new_multi_thread()
123            .enable_all()
124            .build()
125            .expect("failed to build the Tokio runtime")
126            .block_on(future)
127    }
128
129    /// Spawns a background task on the current Tokio runtime.
130    ///
131    /// Used by `#[websocket]` to drive a connection after the upgrade response is
132    /// returned.
133    pub fn spawn<F>(future: F)
134    where
135        F: std::future::Future<Output = ()> + Send + 'static,
136    {
137        tokio::spawn(future);
138    }
139}
140
141#[cfg(test)]
142mod tests {
143    #[test]
144    fn runtime_block_on_executes_future() {
145        let value = crate::__rt::block_on(async { 7usize });
146        assert_eq!(value, 7);
147    }
148}