Skip to main content

forge/
stack.rs

1//! Stack buffer for `@push`/`@stack` directives.
2//!
3//! Forge emits placeholder tokens at `@stack("name")` sites and pushes content via
4//! `forge::stack::push("name", "...")`. After Askama renders, `postprocess` swaps
5//! placeholders for the accumulated buffer contents.
6
7use std::collections::HashMap;
8
9use once_cell::sync::Lazy;
10use parking_lot::Mutex;
11
12const PLACEHOLDER_PREFIX: &str = "<!--FORGE-STACK:";
13const PLACEHOLDER_SUFFIX: &str = "-->";
14
15tokio::task_local! {
16    static REQUEST_STACKS: Mutex<HashMap<String, Vec<String>>>;
17}
18
19// Fallback stack when not in a tokio task context (e.g. integration tests).
20static GLOBAL_STACKS: Lazy<Mutex<HashMap<String, Vec<String>>>> =
21    Lazy::new(|| Mutex::new(HashMap::new()));
22
23pub fn placeholder(name: &str) -> String {
24    format!("{PLACEHOLDER_PREFIX}{name}{PLACEHOLDER_SUFFIX}")
25}
26
27pub fn push(name: &str, content: &str) {
28    let _ = REQUEST_STACKS.try_with(|stacks| {
29        stacks
30            .lock()
31            .entry(name.to_string())
32            .or_default()
33            .push(content.to_string());
34    });
35    // Best-effort fallback for non-task contexts:
36    if REQUEST_STACKS
37        .try_with(|_| ())
38        .is_err()
39    {
40        GLOBAL_STACKS
41            .lock()
42            .entry(name.to_string())
43            .or_default()
44            .push(content.to_string());
45    }
46}
47
48pub fn prepend(name: &str, content: &str) {
49    let _ = REQUEST_STACKS.try_with(|stacks| {
50        stacks
51            .lock()
52            .entry(name.to_string())
53            .or_default()
54            .insert(0, content.to_string());
55    });
56}
57
58/// Drain the request-scoped buffer and return name → joined-content.
59pub fn drain() -> HashMap<String, String> {
60    REQUEST_STACKS
61        .try_with(|stacks| {
62            let mut map = stacks.lock();
63            std::mem::take(&mut *map)
64                .into_iter()
65                .map(|(k, v)| (k, v.join("\n")))
66                .collect()
67        })
68        .unwrap_or_else(|_| {
69            let mut map = GLOBAL_STACKS.lock();
70            std::mem::take(&mut *map)
71                .into_iter()
72                .map(|(k, v)| (k, v.join("\n")))
73                .collect()
74        })
75}
76
77/// Run a future with a fresh per-request stack scope.
78pub async fn with_request_scope<F, T>(fut: F) -> T
79where
80    F: std::future::Future<Output = T>,
81{
82    REQUEST_STACKS.scope(Mutex::new(HashMap::new()), fut).await
83}
84
85/// Replace placeholder tokens in `body` with their accumulated content, drained.
86pub fn postprocess(body: &str) -> String {
87    let mut out = body.to_string();
88    let buffers = drain();
89    for (name, content) in buffers {
90        let placeholder = placeholder(&name);
91        out = out.replace(&placeholder, &content);
92    }
93    // Also strip any leftover placeholders (with no pushes) so they don't appear raw.
94    let re_prefix = PLACEHOLDER_PREFIX;
95    while let Some(start) = out.find(re_prefix) {
96        if let Some(end) = out[start..].find(PLACEHOLDER_SUFFIX) {
97            out.replace_range(start..start + end + PLACEHOLDER_SUFFIX.len(), "");
98        } else {
99            break;
100        }
101    }
102    out
103}