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