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.try_with(|_| ()).is_err() {
37        GLOBAL_STACKS
38            .lock()
39            .entry(name.to_string())
40            .or_default()
41            .push(content.to_string());
42    }
43}
44
45pub fn prepend(name: &str, content: &str) {
46    let _ = REQUEST_STACKS.try_with(|stacks| {
47        stacks
48            .lock()
49            .entry(name.to_string())
50            .or_default()
51            .insert(0, content.to_string());
52    });
53}
54
55/// Drain the request-scoped buffer and return name → joined-content.
56pub fn drain() -> HashMap<String, String> {
57    REQUEST_STACKS
58        .try_with(|stacks| {
59            let mut map = stacks.lock();
60            std::mem::take(&mut *map)
61                .into_iter()
62                .map(|(k, v)| (k, v.join("\n")))
63                .collect()
64        })
65        .unwrap_or_else(|_| {
66            let mut map = GLOBAL_STACKS.lock();
67            std::mem::take(&mut *map)
68                .into_iter()
69                .map(|(k, v)| (k, v.join("\n")))
70                .collect()
71        })
72}
73
74/// Run a future with a fresh per-request stack scope.
75pub async fn with_request_scope<F, T>(fut: F) -> T
76where
77    F: std::future::Future<Output = T>,
78{
79    REQUEST_STACKS.scope(Mutex::new(HashMap::new()), fut).await
80}
81
82/// Replace placeholder tokens in `body` with their accumulated content, drained.
83pub fn postprocess(body: &str) -> String {
84    let mut out = body.to_string();
85    let buffers = drain();
86    for (name, content) in buffers {
87        let placeholder = placeholder(&name);
88        out = out.replace(&placeholder, &content);
89    }
90    // Also strip any leftover placeholders (with no pushes) so they don't appear raw.
91    let re_prefix = PLACEHOLDER_PREFIX;
92    while let Some(start) = out.find(re_prefix) {
93        if let Some(end) = out[start..].find(PLACEHOLDER_SUFFIX) {
94            out.replace_range(start..start + end + PLACEHOLDER_SUFFIX.len(), "");
95        } else {
96            break;
97        }
98    }
99    out
100}