Skip to main content

next_rust_server/
export.rs

1//! Static generation: renders static routes into a page cache.
2
3use std::sync::Arc;
4use std::time::{Duration, Instant};
5
6use next_rust_cache::{CacheEntry, CacheKey, CacheStore};
7use next_rust_router::Params;
8use serde::Serialize;
9
10use crate::app::{AppInner, Rendering, parse_pattern};
11use crate::render::{NONCE_PLACEHOLDER, render_static_html};
12
13#[derive(Debug, Clone, Default, Serialize)]
14pub struct ExportReport {
15    pub pages: Vec<ExportedPage>,
16    /// Static routes with dynamic segments but no `generate_params` (rendered on first request).
17    pub on_demand: Vec<String>,
18}
19
20#[derive(Debug, Clone, Serialize)]
21pub struct ExportedPage {
22    pub pattern: String,
23    pub path: String,
24    pub params: Params,
25    pub bytes: usize,
26    pub millis: u128,
27    pub revalidate: Option<u64>,
28}
29
30pub(crate) async fn prerender(inner: &Arc<AppInner>, store: &dyn CacheStore) -> Result<ExportReport, String> {
31    let mut report = ExportReport::default();
32    let mut failures = Vec::new();
33
34    for (index, def) in inner.routes.pages.iter().enumerate() {
35        if def.rendering != Rendering::Static || def.intercept_from.is_some() {
36            continue;
37        }
38        let pattern = parse_pattern(def.pattern)?;
39        let list: Vec<Params> = if pattern.is_dynamic() {
40            match def.generate_params {
41                Some(f) => f()
42                    .await
43                    .map_err(|e| format!("{}: generate_params failed: {}", def.source, e.detailed_message()))?,
44                None => {
45                    report.on_demand.push(def.pattern.to_owned());
46                    continue;
47                }
48            }
49        } else {
50            vec![Params::new()]
51        };
52        let mut seen = std::collections::HashSet::new();
53        for params in list {
54            let Some(path) = pattern.to_path(&params) else {
55                failures.push(format!(
56                    "{}: generate_params returned {:?}, which is missing parameters",
57                    def.source, params
58                ));
59                continue;
60            };
61            if !seen.insert(path.clone()) {
62                continue;
63            }
64            let start = Instant::now();
65            match render_static_html(inner, index, &path, params.clone()).await {
66                Ok((html, 200)) => {
67                    let revalidate = def.revalidate.or(inner.config.rendering.revalidate);
68                    let entry = CacheEntry::new(html.clone().into_bytes())
69                        .revalidate(revalidate.map(Duration::from_secs))
70                        .tags(def.tags.iter().copied());
71                    let bytes = html.replace(&format!(" nonce=\"{NONCE_PLACEHOLDER}\""), "").len();
72                    store.set(CacheKey::page(&path), entry).await.map_err(|e| e.to_string())?;
73                    report.pages.push(ExportedPage {
74                        pattern: def.pattern.to_owned(),
75                        path,
76                        params,
77                        bytes,
78                        millis: start.elapsed().as_millis(),
79                        revalidate,
80                    });
81                }
82                Ok((_, status)) => failures.push(format!("{} ({path}): rendered with status {status}", def.source)),
83                Err(res) => {
84                    let status = res.status;
85                    let text = res.into_text().await;
86                    failures.push(format!("{} ({path}): {status}\n{text}", def.source));
87                }
88            }
89        }
90    }
91
92    if failures.is_empty() { Ok(report) } else { Err(failures.join("\n\n")) }
93}