Skip to main content

appstruct_compiler/
preset.rs

1mod lock;
2
3pub use lock::ProjectLayout;
4
5use crate::surface::{SurfacePreset, SurfaceRoot};
6use crate::yaml::{self, MappingEntry, Node, NodeKind};
7use appstruct_ir::Diagnostic;
8use sha2::{Digest, Sha256};
9use std::fmt::Write;
10use std::path::Path;
11
12const SAAS_NAME: &str = "appstruct/saas";
13const SAAS_VERSION: u64 = 1;
14pub(super) const MODULE_VERSION: &str = env!("CARGO_PKG_VERSION");
15pub const CURRENT_PROJECT_LAYOUT_VERSION: u64 = appstruct_contracts::PROJECT_LAYOUT.current as u64;
16const MODULES: &[&str] = &["audit", "auth", "file", "jobs", "mail", "rbac", "tenant"];
17const EXPANDED: &str = concat!(
18    "modules:\n",
19    "  auth:\n",
20    "    enabled: true\n",
21    "    user_entity: User\n",
22    "    registration: true\n",
23    "    password_reset: true\n",
24    "  rbac:\n",
25    "    roles: [member, admin]\n",
26    "    default_role: member\n",
27    "  tenant:\n",
28    "    enabled: true\n",
29    "  audit:\n",
30    "    enabled: true\n",
31    "    reader_roles: [admin]\n",
32    "  mail:\n",
33    "    enabled: true\n",
34    "    provider: capture\n",
35    "    from: \"AppStruct <notifications@example.com>\"\n",
36    "    templates:\n",
37    "      invitation:\n",
38    "        subject: \"You are invited to {{ organization_name }}\"\n",
39    "        text: \"Accept your invitation to join {{ organization_name }}.\"\n",
40    "      welcome:\n",
41    "        subject: \"Welcome {{ recipient_name }}\"\n",
42    "        text: \"Your AppStruct workspace is ready.\"\n",
43    "  jobs:\n",
44    "    enabled: true\n",
45    "    poll_interval_ms: 250\n",
46    "    lease_seconds: 30\n",
47    "    queues:\n",
48    "      default: { max_attempts: 5, backoff_seconds: 2 }\n",
49    "      mail: { max_attempts: 8, backoff_seconds: 5 }\n",
50    "  file:\n",
51    "    enabled: true\n",
52    "    provider: local\n",
53    "    local_root: .appstruct/files\n",
54    "    max_bytes: 10485760\n",
55    "    allowed_content_types: [text/plain, application/json, image/png, image/jpeg]\n",
56);
57
58#[derive(Clone, Debug)]
59pub struct PresetInfo {
60    pub name: &'static str,
61    pub version: u64,
62    pub digest: String,
63    pub modules: &'static [&'static str],
64    pub defaults: &'static str,
65}
66
67#[must_use]
68pub fn preset_info(name: &str, version: u64) -> Option<PresetInfo> {
69    supported(name, version).then(|| PresetInfo {
70        name: SAAS_NAME,
71        version: SAAS_VERSION,
72        digest: preset_digest(),
73        modules: MODULES,
74        defaults: EXPANDED,
75    })
76}
77
78pub(crate) fn preset_digest() -> String {
79    format!("sha256:{:x}", Sha256::digest(EXPANDED.as_bytes()))
80}
81
82/// Build the canonical project lock used by official templates.
83#[must_use]
84pub fn project_lock(template: &str, preset: Option<(&str, u64)>) -> Option<String> {
85    lock::source(template, preset, ProjectLayout::CompositionRoot, &[])
86}
87
88/// Read the explicit project layout contract used by build and development commands.
89///
90/// # Errors
91///
92/// Returns a diagnostic for invalid, unversioned, or unsupported project locks. Lockless custom
93/// projects are treated as legacy layout v1 for backward compatibility.
94pub fn project_layout(project: &Path) -> Result<ProjectLayout, Diagnostic> {
95    lock::layout(project)
96}
97
98pub(crate) fn expand_modules(
99    preset: Option<&SurfacePreset>,
100    overrides: Option<&MappingEntry>,
101) -> Result<Option<MappingEntry>, Diagnostic> {
102    let Some(preset) = preset else {
103        return Ok(overrides.cloned());
104    };
105    if !supported(&preset.name.value, preset.version.value) {
106        return Ok(overrides.cloned());
107    }
108    let defaults = yaml::parse("<preset appstruct/saas@1>", EXPANDED)?;
109    let mut modules = defaults
110        .mapping()
111        .and_then(|mapping| mapping.get("modules"))
112        .cloned()
113        .expect("official preset must contain modules");
114    if let Some(overrides) = overrides {
115        merge(&mut modules.value, &overrides.value);
116    }
117    Ok(Some(modules))
118}
119
120fn merge(defaults: &mut Node, overrides: &Node) {
121    match (&mut defaults.kind, &overrides.kind) {
122        (NodeKind::Mapping(defaults), NodeKind::Mapping(overrides)) => {
123            for (key, value) in overrides {
124                if let Some(default) = defaults.get_mut(key) {
125                    merge(&mut default.value, &value.value);
126                    default.key_span = value.key_span.clone();
127                } else {
128                    defaults.insert(key.clone(), value.clone());
129                }
130            }
131        }
132        _ => *defaults = overrides.clone(),
133    }
134}
135
136pub(crate) fn validate_lock(project: &Path, root: &SurfaceRoot) -> Vec<Diagnostic> {
137    lock::validate(project, root)
138}
139
140pub(crate) fn validate_local_module_lock(
141    project: &Path,
142    local_modules: &[crate::module::LoadedModule],
143) -> Vec<Diagnostic> {
144    lock::validate_local_modules(project, local_modules)
145}
146
147pub(crate) fn updated_lock(
148    project: &Path,
149    root: &SurfaceRoot,
150    local_modules: &[crate::module::LoadedModule],
151) -> Result<String, Diagnostic> {
152    lock::updated_source(project, root, local_modules)
153}
154
155pub(crate) fn render_expanded_modules(modules: &MappingEntry) -> String {
156    let mut output = "modules:\n".to_owned();
157    render_node(&modules.value, 2, &mut output);
158    output
159}
160
161fn supported(name: &str, version: u64) -> bool {
162    name == SAAS_NAME && version == SAAS_VERSION
163}
164
165fn render_node(node: &Node, indent: usize, output: &mut String) {
166    match &node.kind {
167        NodeKind::Mapping(entries) => {
168            for (key, entry) in entries {
169                let _ = write!(output, "{}{key}:", " ".repeat(indent));
170                match entry.value.kind {
171                    NodeKind::Scalar { .. } => {
172                        output.push(' ');
173                        render_scalar(&entry.value, output);
174                        output.push('\n');
175                    }
176                    NodeKind::Mapping(ref entries) if entries.is_empty() => {
177                        output.push_str(" {}\n");
178                    }
179                    NodeKind::Sequence(ref items)
180                        if items
181                            .iter()
182                            .all(|item| matches!(item.kind, NodeKind::Scalar { .. })) =>
183                    {
184                        output.push_str(" [");
185                        for (index, item) in items.iter().enumerate() {
186                            if index > 0 {
187                                output.push_str(", ");
188                            }
189                            render_scalar(item, output);
190                        }
191                        output.push_str("]\n");
192                    }
193                    _ => {
194                        output.push('\n');
195                        render_node(&entry.value, indent + 2, output);
196                    }
197                }
198            }
199        }
200        NodeKind::Sequence(items) => {
201            for item in items {
202                let _ = write!(output, "{}- ", " ".repeat(indent));
203                if matches!(item.kind, NodeKind::Scalar { .. }) {
204                    render_scalar(item, output);
205                    output.push('\n');
206                } else {
207                    output.push('\n');
208                    render_node(item, indent + 2, output);
209                }
210            }
211        }
212        NodeKind::Scalar { .. } => {
213            let _ = write!(output, "{}", " ".repeat(indent));
214            render_scalar(node, output);
215            output.push('\n');
216        }
217    }
218}
219
220fn render_scalar(node: &Node, output: &mut String) {
221    let Some((value, plain)) = node.scalar() else {
222        return;
223    };
224    if plain && !value.is_empty() {
225        output.push_str(value);
226    } else {
227        output.push('"');
228        for character in value.chars() {
229            match character {
230                '"' => output.push_str("\\\""),
231                '\\' => output.push_str("\\\\"),
232                '\n' => output.push_str("\\n"),
233                '\r' => output.push_str("\\r"),
234                '\t' => output.push_str("\\t"),
235                other => output.push(other),
236            }
237        }
238        output.push('"');
239    }
240}
241
242#[cfg(test)]
243mod tests {
244    use super::*;
245
246    #[test]
247    fn official_preset_digest_is_stable() {
248        assert_eq!(
249            preset_digest(),
250            "sha256:7267c3a362b328d5b162f4536ac7115c72ab81cf9f3e17542a8d9b6eba7965c5"
251        );
252    }
253}