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