1use super::{MODULE_VERSION, preset_info};
2use crate::loading::synthetic_span;
3use crate::module::LoadedModule;
4use crate::surface::SurfaceRoot;
5use appstruct_ir::Diagnostic;
6use serde::Deserialize;
7use std::collections::BTreeMap;
8use std::fmt::Write;
9use std::fs;
10use std::path::Path;
11
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13pub enum ProjectLayout {
14 LegacyGeneratedBackend = 1,
15 CompositionRoot = 2,
16}
17
18pub(super) fn source(
19 template: &str,
20 preset: Option<(&str, u64)>,
21 layout: ProjectLayout,
22 local_modules: &[LoadedModule],
23) -> Option<String> {
24 let mut output = format!(
25 "lock_version = 1\nproject_layout_version = {}\nappstruct = {:?}\n\n[template]\nname = {template:?}\nversion = {:?}\n",
26 layout as u64,
27 env!("CARGO_PKG_VERSION"),
28 env!("CARGO_PKG_VERSION"),
29 );
30 if let Some((name, version)) = preset {
31 let info = preset_info(name, version)?;
32 let _ = write!(
33 output,
34 "\n[preset]\nname = {:?}\nversion = {}\ndigest = {:?}\n\n[modules]\n",
35 info.name, info.version, info.digest,
36 );
37 for module in info.modules {
38 let _ = writeln!(output, "{module} = {MODULE_VERSION:?}");
39 }
40 }
41 append_local_modules(&mut output, local_modules);
42 Some(output)
43}
44
45fn append_local_modules(output: &mut String, modules: &[LoadedModule]) {
46 let mut modules = modules.iter().collect::<Vec<_>>();
47 modules.sort_by(|left, right| {
48 left.manifest
49 .name
50 .cmp(&right.manifest.name)
51 .then(left.manifest_path.cmp(&right.manifest_path))
52 });
53 for module in modules {
54 let _ = write!(
55 output,
56 "\n[[local_modules]]\nname = {:?}\nversion = {:?}\nmanifest_path = {:?}\nmanifest_sha256 = {:?}\n",
57 module.manifest.name,
58 module.manifest.version,
59 module.manifest_path,
60 module.content_sha256,
61 );
62 for artifact in &module.artifacts {
63 let _ = write!(
64 output,
65 "\n[[local_modules.artifacts]]\npath = {:?}\nsource = {:?}\nsha256 = {:?}\nbyte_len = {}\n",
66 artifact.path,
67 artifact.source.as_deref().unwrap_or_default(),
68 artifact.sha256,
69 artifact.byte_len,
70 );
71 }
72 }
73}
74
75pub(super) fn layout(project: &Path) -> Result<ProjectLayout, Diagnostic> {
76 let path = project.join("appstruct.lock");
77 let source = match fs::read_to_string(path) {
78 Ok(source) => source,
79 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
80 return Ok(ProjectLayout::LegacyGeneratedBackend);
81 }
82 Err(error) => {
83 return Err(lock_error(
84 "AS3064",
85 format!("cannot read project layout from `appstruct.lock`: {error}"),
86 ));
87 }
88 };
89 let lock = toml::from_str::<ProjectLock>(&source).map_err(|error| {
90 lock_error(
91 "AS3064",
92 format!("invalid project lock `appstruct.lock`: {error}"),
93 )
94 })?;
95 if lock.lock_version != 1 || lock.appstruct != env!("CARGO_PKG_VERSION") {
96 return Err(lock_error(
97 "AS3064",
98 "project lock version or AppStruct version does not match this compiler; run `appstruct update`",
99 ));
100 }
101 parse_layout(lock.project_layout_version).ok_or_else(|| {
102 lock_error(
103 "AS3064",
104 "project lock has no supported `project_layout_version`; run `appstruct update`",
105 )
106 })
107}
108
109pub(super) fn validate(project: &Path, root: &SurfaceRoot) -> Vec<Diagnostic> {
110 if let Err(diagnostic) = layout(project) {
111 return vec![diagnostic];
112 }
113 let Some(selected) = &root.preset else {
114 return Vec::new();
115 };
116 let Some(info) = preset_info(&selected.name.value, selected.version.value) else {
117 return vec![
118 Diagnostic::error(
119 "AS3058",
120 format!(
121 "unsupported preset `{}@{}`",
122 selected.name.value, selected.version.value
123 ),
124 selected.name.span.clone(),
125 )
126 .with_help("this compiler supports `appstruct/saas` version 1"),
127 ];
128 };
129 let path = project.join("appstruct.lock");
130 let source = match fs::read_to_string(&path) {
131 Ok(source) => source,
132 Err(error) => {
133 return vec![lock_error(
134 "AS3059",
135 format!("cannot read preset lock `appstruct.lock`: {error}"),
136 )];
137 }
138 };
139 let lock = match toml::from_str::<ProjectLock>(&source) {
140 Ok(lock) => lock,
141 Err(error) => {
142 return vec![lock_error(
143 "AS3059",
144 format!("invalid preset lock `appstruct.lock`: {error}"),
145 )];
146 }
147 };
148 validate_contract(&lock, &info)
149}
150
151pub(super) fn validate_local_modules(
152 project: &Path,
153 local_modules: &[LoadedModule],
154) -> Vec<Diagnostic> {
155 let path = project.join("appstruct.lock");
156 let source = match fs::read_to_string(path) {
157 Ok(source) => source,
158 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
159 if local_modules.is_empty() {
160 return Vec::new();
161 }
162 return vec![local_module_lock_error(
163 "local module provenance is not locked",
164 )];
165 }
166 Err(error) => {
167 return vec![local_module_lock_error(format!(
168 "cannot read local module provenance: {error}"
169 ))];
170 }
171 };
172 let Ok(lock) = toml::from_str::<ProjectLock>(&source) else {
173 return Vec::new();
174 };
175 let actual = local_modules
176 .iter()
177 .map(LockedLocalModule::from)
178 .collect::<Vec<_>>();
179 let mut actual = actual;
180 actual.sort_by(|left, right| {
181 left.name
182 .cmp(&right.name)
183 .then(left.manifest_path.cmp(&right.manifest_path))
184 });
185 if lock.local_modules == actual {
186 Vec::new()
187 } else {
188 vec![local_module_lock_error(
189 "local module manifest or artifact provenance has drifted",
190 )]
191 }
192}
193
194pub(super) fn updated_source(
195 project: &Path,
196 root: &SurfaceRoot,
197 local_modules: &[LoadedModule],
198) -> Result<String, Diagnostic> {
199 let (template, layout) = read_update_metadata(project)?;
200 let selected = root
201 .preset
202 .as_ref()
203 .map(|preset| (preset.name.value.as_str(), preset.version.value));
204 source(&template, selected, layout, local_modules).ok_or_else(|| {
205 let preset = root
206 .preset
207 .as_ref()
208 .expect("only presets can be unsupported");
209 Diagnostic::error(
210 "AS3058",
211 format!(
212 "unsupported preset `{}@{}`",
213 preset.name.value, preset.version.value
214 ),
215 preset.name.span.clone(),
216 )
217 .with_help("this compiler supports `appstruct/saas` version 1")
218 })
219}
220
221fn read_update_metadata(project: &Path) -> Result<(String, ProjectLayout), Diagnostic> {
222 let path = project.join("appstruct.lock");
223 let source = match fs::read_to_string(path) {
224 Ok(source) => source,
225 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
226 return Ok(("custom".to_owned(), infer_legacy_layout(project)?));
227 }
228 Err(error) => {
229 return Err(lock_error(
230 "AS3059",
231 format!("cannot read preset lock `appstruct.lock`: {error}"),
232 ));
233 }
234 };
235 let lock = toml::from_str::<ProjectLock>(&source).map_err(|error| {
236 lock_error(
237 "AS3059",
238 format!("invalid preset lock `appstruct.lock`: {error}"),
239 )
240 })?;
241 let template = lock
242 .template
243 .map_or_else(|| "custom".to_owned(), |template| template.name);
244 let layout = match lock.project_layout_version {
245 Some(version) => parse_layout(Some(version)).ok_or_else(|| {
246 lock_error(
247 "AS3064",
248 format!("unsupported project layout version `{version}`"),
249 )
250 })?,
251 None => infer_legacy_layout(project)?,
252 };
253 Ok((template, layout))
254}
255
256fn infer_legacy_layout(project: &Path) -> Result<ProjectLayout, Diagnostic> {
257 let manifest = project.join("app/backend/Cargo.toml").is_file();
258 let library = project.join("app/backend/src/lib.rs").is_file();
259 match (manifest, library) {
260 (false, false) => Ok(ProjectLayout::LegacyGeneratedBackend),
261 (true, true) => Ok(ProjectLayout::CompositionRoot),
262 _ => Err(lock_error(
263 "AS3064",
264 "cannot migrate a partial `app/backend` layout; expected both `Cargo.toml` and `src/lib.rs`",
265 )),
266 }
267}
268
269fn parse_layout(version: Option<u64>) -> Option<ProjectLayout> {
270 match version {
271 Some(1) => Some(ProjectLayout::LegacyGeneratedBackend),
272 Some(2) => Some(ProjectLayout::CompositionRoot),
273 Some(_) | None => None,
274 }
275}
276
277fn validate_contract(lock: &ProjectLock, info: &super::PresetInfo) -> Vec<Diagnostic> {
278 let mut diagnostics = Vec::new();
279 if lock.lock_version != 1 || lock.appstruct != env!("CARGO_PKG_VERSION") {
280 diagnostics.push(lock_error(
281 "AS3060",
282 "preset lock version or AppStruct version does not match this compiler",
283 ));
284 }
285 if lock.preset.as_ref().is_none_or(|preset| {
286 preset.name != info.name || preset.version != info.version || preset.digest != info.digest
287 }) {
288 diagnostics.push(lock_error(
289 "AS3060",
290 format!(
291 "locked preset name, version, or digest does not match `{}@{}`",
292 info.name, info.version
293 ),
294 ));
295 }
296 let expected_modules = info
297 .modules
298 .iter()
299 .map(|name| ((*name).to_owned(), MODULE_VERSION.to_owned()))
300 .collect::<BTreeMap<_, _>>();
301 if lock.modules != expected_modules {
302 diagnostics.push(lock_error(
303 "AS3061",
304 "locked preset module set or version is incomplete",
305 ));
306 }
307 diagnostics
308}
309
310fn lock_error(code: &str, message: impl Into<String>) -> Diagnostic {
311 Diagnostic::error(code, message, synthetic_span("appstruct.lock"))
312}
313
314fn local_module_lock_error(message: impl Into<String>) -> Diagnostic {
315 Diagnostic::error("AS3065", message, synthetic_span("appstruct.lock"))
316 .with_help("run `appstruct update` to refresh locked local module provenance")
317}
318
319#[derive(Debug, Deserialize)]
320struct ProjectLock {
321 lock_version: u64,
322 project_layout_version: Option<u64>,
323 appstruct: String,
324 template: Option<LockedTemplate>,
325 preset: Option<LockedPreset>,
326 #[serde(default)]
327 modules: BTreeMap<String, String>,
328 #[serde(default)]
329 local_modules: Vec<LockedLocalModule>,
330}
331
332#[derive(Debug, Deserialize, PartialEq, Eq)]
333struct LockedLocalModule {
334 name: String,
335 version: String,
336 manifest_path: String,
337 manifest_sha256: String,
338 #[serde(default)]
339 artifacts: Vec<LockedModuleArtifact>,
340}
341
342impl From<&LoadedModule> for LockedLocalModule {
343 fn from(module: &LoadedModule) -> Self {
344 Self {
345 name: module.manifest.name.clone(),
346 version: module.manifest.version.clone(),
347 manifest_path: module.manifest_path.clone(),
348 manifest_sha256: module.content_sha256.clone(),
349 artifacts: module
350 .artifacts
351 .iter()
352 .map(|artifact| LockedModuleArtifact {
353 path: artifact.path.clone(),
354 source: artifact.source.clone().unwrap_or_default(),
355 sha256: artifact.sha256.clone(),
356 byte_len: artifact.byte_len,
357 })
358 .collect(),
359 }
360 }
361}
362
363#[derive(Debug, Deserialize, PartialEq, Eq)]
364struct LockedModuleArtifact {
365 path: String,
366 source: String,
367 sha256: String,
368 byte_len: u64,
369}
370
371#[derive(Debug, Deserialize)]
372struct LockedTemplate {
373 name: String,
374}
375
376#[derive(Debug, Deserialize)]
377struct LockedPreset {
378 name: String,
379 version: u64,
380 digest: String,
381}