Skip to main content

next_rust_server/
lib.rs

1//! The Next Rust runtime.
2//!
3//! Most applications use this crate through the `next-rust` facade. It
4//! contains the request pipeline (middleware → routing → pages/API routes/
5//! server actions), server-side rendering with streaming, incremental static
6//! regeneration, static files, the development endpoints and the hyper-based
7//! production server.
8
9#![forbid(unsafe_code)]
10
11mod action_token;
12pub mod actions;
13pub mod app;
14mod banner;
15mod client_runtime;
16pub mod context;
17pub mod cookies;
18pub mod embed;
19pub mod error;
20pub mod export;
21pub mod http_date;
22mod internal;
23pub mod jobs;
24pub mod log;
25pub mod middleware;
26mod params_de;
27pub mod plugin;
28mod redirects;
29mod render;
30pub mod request;
31pub mod response;
32pub mod runtime;
33pub mod seo;
34pub mod server;
35pub mod session;
36pub mod sse;
37pub mod static_files;
38pub mod testing;
39#[cfg(feature = "websocket")]
40pub mod ws;
41
42use std::sync::atomic::{AtomicBool, Ordering};
43
44pub use action_token::SECRET_ENV;
45pub use actions::{ActionContext, ActionRef};
46pub use app::{
47    ActionDef, ApiDef, App, AppBuilder, ErrorInfo, PageBody, PageDef, Rendering, Routes, SegmentDef, SlotDef,
48    parse_pattern,
49};
50pub use context::{
51    Auth, AuthUser, ClientIp, CsrfToken, Ctx, Data, Extension, FormState, FromContext, Headers, Nonce, Path, Query,
52    QueryMap, RenderMode, RequestContext, RequestInfo, ResponseHeaders,
53};
54pub use cookies::{Cookie, Cookies, SameSite};
55pub use embed::{Embedded, EmbeddedFile};
56pub use error::{Error, ErrorKind, OrNotFound, Result, not_found, permanent_redirect, redirect};
57pub use middleware::{
58    BoxFuture, Cors, Middleware, Next, RateLimit, RequestId, cors, csrf, protected, rate_limit, request_id,
59    security_headers,
60};
61pub use request::Request;
62pub use response::{Body, Html, IntoResponse, Json, Response};
63pub use runtime::{run, run_with};
64pub use seo::{Feed, FeedEntry, Robots, RobotsRule, Sitemap, SitemapEntry};
65pub use session::{MemorySessionStore, Session, SessionStore, sessions};
66pub use sse::SseEvent;
67pub use testing::{TestClient, TestResponse};
68
69pub use bytes;
70pub use futures_util as futures;
71pub use http;
72pub use tokio;
73
74static PAGE_STORE: std::sync::OnceLock<std::sync::Arc<dyn next_rust_cache::CacheStore>> = std::sync::OnceLock::new();
75
76/// Re-render `path` on its next request (pages rendered statically) and
77/// drop the matching data-cache entry. Usable from API routes and actions.
78pub async fn revalidate_path(path: &str) {
79    let path = if path.len() > 1 { path.trim_end_matches('/') } else { path };
80    if let Some(store) = PAGE_STORE.get() {
81        let _ = store.delete(&next_rust_cache::CacheKey::page(path)).await;
82    }
83    next_rust_cache::revalidate_path(path).await;
84}
85
86/// Invalidate every cached page and data entry tagged with `tag`.
87pub async fn revalidate_tag(tag: &str) {
88    if let Some(store) = PAGE_STORE.get() {
89        let _ = store.delete_tag(tag).await;
90    }
91    next_rust_cache::revalidate_tag(tag).await;
92}
93
94/// Name of the CSRF double-submit cookie.
95pub const CSRF_COOKIE: &str = "next_rust_csrf";
96
97/// The framework's version, as in `Cargo.toml`.
98pub const VERSION: &str = env!("CARGO_PKG_VERSION");
99
100/// The build signature (`Next Rust 0.1.10`): what a page's
101/// `<meta name="generator">` and the framework's scripts say built them
102/// while `[build] signature = true`.
103pub fn signature() -> String {
104    format!("Next Rust {VERSION}")
105}
106
107pub use middleware::STRICT_CSP;
108
109/// Per-request CSP nonce stored in request extensions.
110#[derive(Debug, Clone)]
111pub struct CspNonce(pub String);
112
113static DEV: AtomicBool = AtomicBool::new(cfg!(debug_assertions));
114static TRUST_PROXY: AtomicBool = AtomicBool::new(false);
115
116/// Whether the process runs in development mode (detailed errors).
117pub fn is_dev() -> bool {
118    DEV.load(Ordering::Relaxed)
119}
120
121pub(crate) fn set_dev(v: bool) {
122    DEV.store(v, Ordering::Relaxed);
123}
124
125pub(crate) fn trust_proxy() -> bool {
126    TRUST_PROXY.load(Ordering::Relaxed)
127}
128
129pub(crate) fn set_trust_proxy(v: bool) {
130    TRUST_PROXY.store(v, Ordering::Relaxed);
131}
132
133/// `n` random bytes from the operating system CSPRNG, hex encoded.
134pub fn random_hex(n: usize) -> String {
135    let mut buf = vec![0u8; n];
136    fill_random(&mut buf);
137    buf.iter().map(|b| format!("{b:02x}")).collect()
138}
139
140/// Fill `buf` from the operating system CSPRNG.
141pub(crate) fn fill_random(buf: &mut [u8]) {
142    if getrandom::fill(buf).is_err() {
143        // The OS RNG failing is unrecoverable for security-sensitive tokens.
144        panic!("operating system random number generator unavailable");
145    }
146}
147
148/// Constant-time byte comparison (for tokens).
149pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
150    if a.len() != b.len() {
151        return false;
152    }
153    a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
154}
155
156/// Items used by generated code and macros. Not a stable API.
157#[doc(hidden)]
158pub mod __private {
159    pub use http::Method;
160    pub use next_rust_router::Params;
161    pub use next_rust_view::{Children, IntoViewResult, Metadata, Node, Slots, Stylesheet, View};
162
163    pub use crate::actions::{ActionContext, ActionRef, run_action, run_action_ctx, run_action_ctx0, run_action0};
164    pub use crate::app::{
165        ActionDef, ApiDef, ErrorInfo, HandlerFn, MiddlewareFn, PageBody, PageDef, Rendering, Routes, SegmentDef,
166        SlotDef,
167    };
168    pub use crate::context::{Ctx, Data, FromContext};
169    pub use crate::embed::{Embedded, EmbeddedFile};
170
171    /// The TOML parser handed to development builds (see `Routes::toml`).
172    pub const TOML: Option<next_rust_core::config::TomlParser> = Some(next_rust_core::Config::from_toml_str);
173    pub use crate::error::{Error, IntoResult, Result};
174    pub use crate::middleware::{BoxFuture, Next};
175    pub use crate::render::is_bot;
176    pub use crate::request::Request;
177    pub use crate::response::{IntoResponse, Response};
178    pub use crate::seo::{Feed, FeedEntry, Robots, RobotsRule, Sitemap, SitemapEntry};
179    pub use crate::server::into_hyper;
180
181    pub fn log_error(msg: &str) {
182        crate::log::error(msg);
183    }
184}