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