Skip to main content

next_rust_server/
export.rs

1//! Static generation (`next-rust build`).
2
3use std::path::{Path, PathBuf};
4use std::sync::Arc;
5use std::time::{Duration, Instant};
6
7use next_rust_cache::{CacheEntry, CacheKey, CacheStore, FileStore};
8use next_rust_router::Params;
9use serde::Serialize;
10
11use crate::app::{AppInner, Rendering, parse_pattern};
12use crate::render::{NONCE_PLACEHOLDER, render_static_html};
13
14#[derive(Debug, Clone, Default, Serialize)]
15pub struct ExportReport {
16    pub pages: Vec<ExportedPage>,
17    /// Static routes with dynamic segments but no `generate_params` (rendered on first request).
18    pub on_demand: Vec<String>,
19}
20
21#[derive(Debug, Clone, Serialize)]
22pub struct ExportedPage {
23    pub pattern: String,
24    pub path: String,
25    pub params: Params,
26    pub bytes: usize,
27    pub millis: u128,
28    pub revalidate: Option<u64>,
29}
30
31fn html_file(static_dir: &Path, path: &str) -> PathBuf {
32    let mut p = static_dir.to_path_buf();
33    for seg in path.split('/').filter(|s| !s.is_empty()) {
34        p.push(next_rust_router::decode_segment(seg).unwrap_or_else(|| seg.to_owned()));
35    }
36    p.join("index.html")
37}
38
39pub(crate) async fn export(inner: &Arc<AppInner>) -> Result<ExportReport, String> {
40    let out = &inner.output_dir;
41    let static_dir = out.join("static");
42    let store = FileStore::new(out.join("cache/pages"));
43    store.clear().await.map_err(|e| e.to_string())?;
44    let _ = tokio::fs::remove_dir_all(&static_dir).await;
45    let mut report = ExportReport::default();
46    let mut failures = Vec::new();
47
48    for (index, def) in inner.routes.pages.iter().enumerate() {
49        if def.rendering != Rendering::Static || def.intercept_from.is_some() {
50            continue;
51        }
52        let pattern = parse_pattern(def.pattern)?;
53        let list: Vec<Params> = if pattern.is_dynamic() {
54            match def.generate_params {
55                Some(f) => f()
56                    .await
57                    .map_err(|e| format!("{}: generate_params failed: {}", def.source, e.detailed_message()))?,
58                None => {
59                    report.on_demand.push(def.pattern.to_owned());
60                    continue;
61                }
62            }
63        } else {
64            vec![Params::new()]
65        };
66        let mut seen = std::collections::HashSet::new();
67        for params in list {
68            let Some(path) = pattern.to_path(&params) else {
69                failures.push(format!(
70                    "{}: generate_params returned {:?}, which is missing parameters",
71                    def.source, params
72                ));
73                continue;
74            };
75            if !seen.insert(path.clone()) {
76                continue;
77            }
78            let start = Instant::now();
79            match render_static_html(inner, index, &path, params.clone()).await {
80                Ok((html, 200)) => {
81                    let revalidate = def.revalidate.or(inner.config.rendering.revalidate);
82                    let entry = CacheEntry::new(html.clone().into_bytes())
83                        .revalidate(revalidate.map(Duration::from_secs))
84                        .tags(def.tags.iter().copied());
85                    store.set(CacheKey::page(&path), entry).await.map_err(|e| e.to_string())?;
86                    let file = html_file(&static_dir, &path);
87                    if let Some(parent) = file.parent() {
88                        tokio::fs::create_dir_all(parent).await.map_err(|e| e.to_string())?;
89                    }
90                    let plain = html.replace(&format!(" nonce=\"{NONCE_PLACEHOLDER}\""), "");
91                    tokio::fs::write(&file, &plain).await.map_err(|e| e.to_string())?;
92                    report.pages.push(ExportedPage {
93                        pattern: def.pattern.to_owned(),
94                        path,
95                        params,
96                        bytes: plain.len(),
97                        millis: start.elapsed().as_millis(),
98                        revalidate,
99                    });
100                }
101                Ok((_, status)) => failures.push(format!("{} ({path}): rendered with status {status}", def.source)),
102                Err(res) => {
103                    let status = res.status;
104                    let text = res.into_text().await;
105                    failures.push(format!("{} ({path}): {status}\n{text}", def.source));
106                }
107            }
108        }
109    }
110
111    if let Some(f) = inner.routes.sitemap {
112        write(&static_dir.join("sitemap.xml"), f().await.to_xml().as_bytes()).await?;
113    }
114    if let Some(f) = inner.routes.robots {
115        write(&static_dir.join("robots.txt"), f().await.to_text().as_bytes()).await?;
116    }
117
118    if failures.is_empty() { Ok(report) } else { Err(failures.join("\n\n")) }
119}
120
121async fn write(path: &Path, bytes: &[u8]) -> Result<(), String> {
122    if let Some(parent) = path.parent() {
123        tokio::fs::create_dir_all(parent).await.map_err(|e| e.to_string())?;
124    }
125    tokio::fs::write(path, bytes).await.map_err(|e| e.to_string())
126}