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, CsrfToken, Ctx, Data, Extension, FormState, FromContext, Headers, Nonce, Path, Query, QueryMap,
52    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 = "nr_csrf";
96
97/// Per-request CSP nonce stored in request extensions.
98#[derive(Debug, Clone)]
99pub struct CspNonce(pub String);
100
101static DEV: AtomicBool = AtomicBool::new(cfg!(debug_assertions));
102static TRUST_PROXY: AtomicBool = AtomicBool::new(false);
103
104/// Whether the process runs in development mode (detailed errors).
105pub fn is_dev() -> bool {
106    DEV.load(Ordering::Relaxed)
107}
108
109pub(crate) fn set_dev(v: bool) {
110    DEV.store(v, Ordering::Relaxed);
111}
112
113pub(crate) fn trust_proxy() -> bool {
114    TRUST_PROXY.load(Ordering::Relaxed)
115}
116
117pub(crate) fn set_trust_proxy(v: bool) {
118    TRUST_PROXY.store(v, Ordering::Relaxed);
119}
120
121/// `n` random bytes from the operating system CSPRNG, hex encoded.
122pub fn random_hex(n: usize) -> String {
123    let mut buf = vec![0u8; n];
124    fill_random(&mut buf);
125    buf.iter().map(|b| format!("{b:02x}")).collect()
126}
127
128/// Fill `buf` from the operating system CSPRNG.
129pub(crate) fn fill_random(buf: &mut [u8]) {
130    if getrandom::fill(buf).is_err() {
131        // The OS RNG failing is unrecoverable for security-sensitive tokens.
132        panic!("operating system random number generator unavailable");
133    }
134}
135
136/// Constant-time byte comparison (for tokens).
137pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
138    if a.len() != b.len() {
139        return false;
140    }
141    a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
142}
143
144/// Items used by generated code and macros. Not a stable API.
145#[doc(hidden)]
146pub mod __private {
147    pub use http::Method;
148    pub use next_rust_router::Params;
149    pub use next_rust_view::{Children, IntoViewResult, Metadata, Node, Slots, Stylesheet, View};
150
151    pub use crate::actions::{ActionContext, ActionRef, run_action, run_action_ctx, run_action0};
152    pub use crate::app::{
153        ActionDef, ApiDef, ErrorInfo, HandlerFn, MiddlewareFn, PageBody, PageDef, Rendering, Routes, SegmentDef,
154        SlotDef,
155    };
156    pub use crate::context::{Ctx, Data, FromContext};
157    pub use crate::embed::{Embedded, EmbeddedFile};
158
159    /// The TOML parser handed to development builds (see `Routes::toml`).
160    pub const TOML: Option<next_rust_core::config::TomlParser> = Some(next_rust_core::Config::from_toml_str);
161    pub use crate::error::{Error, IntoResult, Result};
162    pub use crate::middleware::{BoxFuture, Next};
163    pub use crate::render::is_bot;
164    pub use crate::request::Request;
165    pub use crate::response::{IntoResponse, Response};
166    pub use crate::seo::{Feed, FeedEntry, Robots, RobotsRule, Sitemap, SitemapEntry};
167    pub use crate::server::into_hyper;
168
169    pub fn log_error(msg: &str) {
170        crate::log::error(msg);
171    }
172}