1use 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
19static 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 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
58pub 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
77pub 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
85pub 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 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}