Skip to main content

dive_api/
publication.rs

1//! Explicit publication of admitted PlusCal artifacts.
2use crate::{ApiError, RewriteReport, RewriteRequest, rewrite_source};
3use serde_json::json;
4use std::fs::{self, File, OpenOptions};
5use std::io::{Read as _, Write as _};
6use std::path::{Path, PathBuf};
7use std::sync::atomic::{AtomicU64, Ordering};
8
9const MAX_BYTES: u64 = 4_194_304;
10const CFG_DELIMITER: &str = "\\* Add statements after this line.";
11static NEXT_FILE: AtomicU64 = AtomicU64::new(0);
12
13fn io(path: &Path, error: std::io::Error) -> ApiError {
14    ApiError::Io {
15        path: path.display().to_string(),
16        error,
17    }
18}
19fn rejected(message: &str) -> ApiError {
20    ApiError::Rejected {
21        message: format!("DIVE-P0100: {message}"),
22    }
23}
24
25#[derive(Debug)]
26struct Snapshot {
27    bytes: Option<Vec<u8>>,
28    permissions: Option<fs::Permissions>,
29}
30impl Snapshot {
31    fn read(path: &Path) -> Result<Self, ApiError> {
32        let metadata = match fs::symlink_metadata(path) {
33            Ok(metadata) => metadata,
34            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
35                return Ok(Self {
36                    bytes: None,
37                    permissions: None,
38                });
39            }
40            Err(error) => return Err(io(path, error)),
41        };
42        if !metadata.is_file() || metadata.file_type().is_symlink() {
43            return Err(rejected(&format!(
44                "publication target must be a regular file: {}",
45                path.display()
46            )));
47        }
48        let mut bytes = Vec::new();
49        File::open(path)
50            .map_err(|e| io(path, e))?
51            .take(MAX_BYTES + 1)
52            .read_to_end(&mut bytes)
53            .map_err(|e| io(path, e))?;
54        if bytes.len() as u64 > MAX_BYTES {
55            return Err(rejected("publication input exceeds 4 MiB"));
56        }
57        Ok(Self {
58            bytes: Some(bytes),
59            permissions: Some(metadata.permissions()),
60        })
61    }
62    fn unchanged(&self, path: &Path) -> Result<bool, ApiError> {
63        Ok(self.bytes == Self::read(path)?.bytes)
64    }
65}
66#[derive(Debug)]
67struct Output {
68    path: PathBuf,
69    previous: Snapshot,
70    bytes: Vec<u8>,
71    permissions: Option<fs::Permissions>,
72}
73
74/// An admitted translation and exact filesystem inputs awaiting explicit publication.
75///
76/// Preparation writes nothing. Publication checks all input bytes again, stages
77/// every output beside its destination, and atomically replaces each file. An
78/// ordinary commit failure restores earlier destinations. This is not a
79/// cross-file crash-atomic transaction or a lock against concurrent editors.
80/// The input and existing cfg/backup are bounded to 4 MiB and must be regular files.
81#[derive(Debug)]
82pub struct TranslationPublication {
83    source: PathBuf,
84    original: Snapshot,
85    outputs: Vec<Output>,
86    report: RewriteReport,
87}
88impl TranslationPublication {
89    /// The in-memory admission result; no writes have been performed.
90    #[must_use]
91    pub const fn report(&self) -> &RewriteReport {
92        &self.report
93    }
94
95    /// Publishes all prepared outputs after checking that the source and existing
96    /// destinations have not changed. Rejected translations perform no writes.
97    ///
98    /// # Errors
99    /// An I/O error or `DIVE-P0100` rejection, including a concurrent edit. A
100    /// rollback failure retains the original staging file and reports its path;
101    /// it never succeeds.
102    pub fn publish(mut self) -> Result<RewriteReport, ApiError> {
103        if !self.report.accepted() {
104            return Ok(self.report);
105        }
106        self.verify_inputs()?;
107        let mut staged = Vec::new();
108        let mut restores = Vec::new();
109        for output in &self.outputs {
110            staged.push(Staged::new(
111                &output.path,
112                &output.bytes,
113                output.permissions.as_ref(),
114            )?);
115            restores.push(
116                output
117                    .previous
118                    .bytes
119                    .as_deref()
120                    .map(|bytes| {
121                        Staged::new(&output.path, bytes, output.previous.permissions.as_ref())
122                    })
123                    .transpose()?,
124            );
125        }
126        self.verify_inputs()?;
127        commit(&self.outputs, &staged, &restores)?;
128        self.report.document["filesystem_plan"]["writes_performed"] = json!(true);
129        self.report.document["filesystem_plan"]["written_files"] = json!(
130            self.outputs
131                .iter()
132                .map(|o| o.path.display().to_string())
133                .collect::<Vec<_>>()
134        );
135        Ok(self.report)
136    }
137    fn verify_inputs(&self) -> Result<(), ApiError> {
138        if !self.original.unchanged(&self.source)?
139            || self
140                .outputs
141                .iter()
142                .map(|o| o.previous.unchanged(&o.path))
143                .collect::<Result<Vec<_>, _>>()?
144                .contains(&false)
145        {
146            return Err(rejected(
147                "source, configuration or backup changed after translation preparation; no publication performed",
148            ));
149        }
150        Ok(())
151    }
152}
153
154fn commit(
155    outputs: &[Output],
156    staged: &[Staged],
157    restores: &[Option<Staged>],
158) -> Result<(), ApiError> {
159    for (index, output) in outputs.iter().enumerate() {
160        if let Err(error) = fs::rename(&staged[index].path, &output.path) {
161            let rollback_errors = rollback(outputs, restores, index);
162            if !rollback_errors.is_empty() {
163                return Err(rejected(&format!(
164                    "commit failed: {error}; rollback failed: {}",
165                    rollback_errors.join("; ")
166                )));
167            }
168            return Err(io(&output.path, error));
169        }
170    }
171    Ok(())
172}
173
174fn rollback(outputs: &[Output], restores: &[Option<Staged>], committed: usize) -> Vec<String> {
175    let mut failures = Vec::new();
176    for previous in (0..committed).rev() {
177        let destination = &outputs[previous].path;
178        let outcome = if let Some(restore) = &restores[previous] {
179            fs::rename(&restore.path, destination)
180        } else {
181            fs::remove_file(destination)
182        };
183        if let Err(error) = outcome {
184            let recovery = if let Some(restore) = &restores[previous] {
185                restore.preserve.set(true);
186                format!("; original retained at {}", restore.path.display())
187            } else {
188                String::new()
189            };
190            failures.push(format!("{}: {error}{recovery}", destination.display()));
191        }
192    }
193    failures
194}
195
196#[derive(Debug)]
197struct Staged {
198    path: PathBuf,
199    preserve: std::cell::Cell<bool>,
200}
201impl Staged {
202    fn new(
203        target: &Path,
204        bytes: &[u8],
205        permissions: Option<&fs::Permissions>,
206    ) -> Result<Self, ApiError> {
207        let parent = target
208            .parent()
209            .filter(|p| !p.as_os_str().is_empty())
210            .unwrap_or_else(|| Path::new("."));
211        for _ in 0..64 {
212            let path = parent.join(format!(
213                ".dive-pcal-{}-{}.tmp",
214                std::process::id(),
215                NEXT_FILE.fetch_add(1, Ordering::Relaxed)
216            ));
217            let mut file = match OpenOptions::new().write(true).create_new(true).open(&path) {
218                Ok(file) => file,
219                Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
220                Err(error) => return Err(io(&path, error)),
221            };
222            let staged = Self {
223                path,
224                preserve: std::cell::Cell::new(false),
225            };
226            if let Some(permissions) = permissions {
227                file.set_permissions(permissions.clone())
228                    .map_err(|e| io(&staged.path, e))?;
229            }
230            file.write_all(bytes).map_err(|e| io(&staged.path, e))?;
231            file.sync_all().map_err(|e| io(&staged.path, e))?;
232            return Ok(staged);
233        }
234        Err(rejected("cannot reserve a publication staging file"))
235    }
236}
237impl Drop for Staged {
238    fn drop(&mut self) {
239        if !self.preserve.get() {
240            let _ = fs::remove_file(&self.path);
241        }
242    }
243}
244
245// Pinned trans.run: discard the previous generated prefix; retain the delimiter
246// and user suffix, including an existing uncommented SPECIFICATION directive.
247fn configuration(
248    previous: Option<&[u8]>,
249    requirements: &str,
250    newline: &str,
251) -> Result<Vec<u8>, ApiError> {
252    let previous = std::str::from_utf8(previous.unwrap_or_default())
253        .map_err(|e| rejected(&format!("configuration is not UTF-8: {e}")))?;
254    let normalized = previous.replace("\r\n", "\n").replace('\r', "\n");
255    let mut lines: Vec<&str> = normalized.lines().collect();
256    if let Some(delimiter) = lines.iter().position(|line| line.contains(CFG_DELIMITER)) {
257        lines.drain(..delimiter);
258    } else {
259        lines.insert(0, CFG_DELIMITER);
260    }
261    let has_spec = lines.iter().any(|line| {
262        line.find("SPECIFICATION")
263            .is_some_and(|at| line.find("\\*").is_none_or(|comment| comment > at))
264    });
265    let mut result = String::new();
266    if !has_spec {
267        result.push_str("SPECIFICATION Spec");
268        result.push_str(newline);
269    }
270    for line in requirements.lines().rev() {
271        result.push_str(line);
272        result.push_str(newline);
273    }
274    for line in lines {
275        result.push_str(line);
276        result.push_str(newline);
277    }
278    Ok(result.into_bytes())
279}
280
281/// Prepares a bounded PlusCal rewrite and cfg/backup updates without writing files.
282/// Source-option `-noold`/`-nocfg` settings are effective, and the existing default
283/// modified-body protection and TLC overwrite policy are retained.
284///
285/// ```no_run
286/// use dive_api::{prepare_translation_file, RewriteRequest};
287/// let pending = prepare_translation_file(std::path::Path::new("Algorithm.tla"), &RewriteRequest::default())?;
288/// if pending.report().accepted() { let written = pending.publish()?; assert!(written.accepted()); }
289/// # Ok::<(), dive_api::ApiError>(())
290/// ```
291///
292/// # Errors
293/// I/O or bounded/regular-file input errors. Translation failures remain reports.
294pub fn prepare_translation_file(
295    path: &Path,
296    request: &RewriteRequest,
297) -> Result<TranslationPublication, ApiError> {
298    let absolute = std::path::absolute(path).map_err(|error| io(path, error))?;
299    let path = absolute.as_path();
300    if path.extension().is_none_or(|extension| extension != "tla") {
301        return Err(rejected("publication requires a .tla module"));
302    }
303    let original = Snapshot::read(path)?;
304    let bytes = original
305        .bytes
306        .as_deref()
307        .ok_or_else(|| rejected("translation source does not exist"))?;
308    let source = std::str::from_utf8(bytes)
309        .map_err(|e| rejected(&format!("translation source is not UTF-8: {e}")))?;
310    let mut request = request.clone();
311    if let Some(parent) = path.parent() {
312        request
313            .translation
314            .analyze
315            .after_standard
316            .push(parent.to_path_buf());
317    }
318    let report = rewrite_source(&path.display().to_string(), source, &request);
319    let mut outputs = Vec::new();
320    if report.accepted() {
321        let doc = report.to_json();
322        let module = doc["replacement"]["module_source"]
323            .as_str()
324            .ok_or_else(|| rejected("admitted rewrite omitted module bytes"))?;
325        if doc["filesystem_plan"]["backup_requested"] == true {
326            let backup = path.with_extension("old");
327            outputs.push(Output {
328                previous: Snapshot::read(&backup)?,
329                path: backup,
330                bytes: bytes.to_vec(),
331                permissions: original.permissions.clone(),
332            });
333        }
334        if doc["filesystem_plan"]["configuration_requested"] == true {
335            let cfg = path.with_extension("cfg");
336            let previous = Snapshot::read(&cfg)?;
337            let requirements = doc["artifact"]["configuration"]
338                .as_str()
339                .ok_or_else(|| rejected("admitted rewrite omitted configuration requirements"))?;
340            let newline = match doc["filesystem_plan"]["body_newlines"].as_str() {
341                Some("crlf") => "\r\n",
342                Some("cr") => "\r",
343                _ => "\n",
344            };
345            let bytes = configuration(previous.bytes.as_deref(), requirements, newline)?;
346            outputs.push(Output {
347                path: cfg,
348                permissions: previous.permissions.clone(),
349                previous,
350                bytes,
351            });
352        }
353        outputs.push(Output {
354            path: path.to_path_buf(),
355            previous: Snapshot::read(path)?,
356            bytes: module.as_bytes().to_vec(),
357            permissions: original.permissions.clone(),
358        });
359    }
360    Ok(TranslationPublication {
361        source: path.to_path_buf(),
362        original,
363        outputs,
364        report,
365    })
366}
367
368/// Translates and publishes an admitted PlusCal module, backup and configuration.
369/// This is the explicit write counterpart of [`crate::rewrite_file`].
370///
371/// # Errors
372/// The same preparation, concurrent-edit and publication errors as
373/// [`prepare_translation_file`] and [`TranslationPublication::publish`].
374pub fn write_translation_file(
375    path: &Path,
376    request: &RewriteRequest,
377) -> Result<RewriteReport, ApiError> {
378    prepare_translation_file(path, request)?.publish()
379}
380
381/// Original-AST publication result. Available AST bytes are not a translated
382/// module or model proof. Successful writes retain pinned `-writeAST` exit 255.
383#[derive(Clone, Debug)]
384pub struct OriginalAstWriteReport {
385    document: serde_json::Value,
386    status: u8,
387}
388impl OriginalAstWriteReport {
389    /// Whether `AST.tla` bytes were written successfully.
390    #[must_use]
391    pub fn written(&self) -> bool {
392        self.document["writes_performed"] == true
393    }
394    /// Pinned successful-write/source-rejection exit 255; unsupported and bug exits stay native.
395    #[must_use]
396    pub const fn exit_code(&self) -> u8 {
397        self.status
398    }
399    /// Source-stage information and actual write disposition, never admission.
400    #[must_use]
401    pub fn to_json(&self) -> serde_json::Value {
402        self.document.clone()
403    }
404}
405
406/// Writes the bounded pre-generation original AST to an explicit destination.
407/// CLI `-writeAST` passes `AST.tla` in the current directory. The input module,
408/// its backup and configuration are unchanged; no translation is generated.
409///
410/// # Errors
411/// I/O, nonregular target, concurrent-edit or bounded-input errors.
412pub fn write_original_ast_file(
413    input: &Path,
414    target: &Path,
415    request: &crate::TranslationRequest,
416) -> Result<OriginalAstWriteReport, ApiError> {
417    let absolute_input = std::path::absolute(input).map_err(|error| io(input, error))?;
418    let absolute_target = std::path::absolute(target).map_err(|error| io(target, error))?;
419    let input = absolute_input.as_path();
420    let target = absolute_target.as_path();
421    let original = Snapshot::read(input)?;
422    let bytes = original
423        .bytes
424        .as_deref()
425        .ok_or_else(|| rejected("AST source does not exist"))?;
426    let source = std::str::from_utf8(bytes)
427        .map_err(|e| rejected(&format!("AST source is not UTF-8: {e}")))?;
428    let requested_limits = &request.limits;
429    let mut parsing = request.clone();
430    parsing.limits.write_ast = false;
431    let report = crate::original_ast_source(&input.display().to_string(), source, &parsing);
432    let mut document = report.to_json();
433    document["requested_translation_options"] = json!(requested_limits);
434    if !report.artifact_available() {
435        let status = if report.exit_code() == 1 {
436            255
437        } else {
438            report.exit_code()
439        };
440        document["exit_code"] = json!(status);
441        return Ok(OriginalAstWriteReport { document, status });
442    }
443    let module = document["ast_artifact"]["module_source"]
444        .as_str()
445        .ok_or_else(|| rejected("available AST omitted module bytes"))?;
446    if input == target
447        || fs::canonicalize(target)
448            .is_ok_and(|destination| fs::canonicalize(input).ok().as_ref() == Some(&destination))
449    {
450        return Err(rejected("AST destination must differ from input"));
451    }
452    let previous = Snapshot::read(target)?;
453    let staged = Staged::new(target, module.as_bytes(), previous.permissions.as_ref())?;
454    if !original.unchanged(input)? || !previous.unchanged(target)? {
455        return Err(rejected(
456            "source or AST destination changed during preparation",
457        ));
458    }
459    fs::rename(&staged.path, target).map_err(|e| io(target, e))?;
460    document["writes_performed"] = json!(true);
461    document["written_file"] = json!(target.display().to_string());
462    document["exit_code"] = json!(255);
463    Ok(OriginalAstWriteReport {
464        document,
465        status: 255,
466    })
467}
468
469#[cfg(test)]
470mod tests {
471    #![allow(
472        clippy::unwrap_used,
473        reason = "real filesystem rollback failure controls"
474    )]
475    use super::*;
476    #[test]
477    fn commit_failure_restores_replaced_and_removes_new_destinations() {
478        for existing in [false, true] {
479            let parent = std::env::temp_dir().join(format!(
480                "dive-pcal-rollback-{}-{existing}",
481                std::process::id()
482            ));
483            let _ = fs::remove_dir_all(&parent);
484            fs::create_dir_all(&parent).unwrap();
485            let first = parent.join("first");
486            let failing = parent.join("failing");
487            if existing {
488                fs::write(&first, b"original").unwrap();
489            }
490            let outputs = [
491                Output {
492                    previous: Snapshot::read(&first).unwrap(),
493                    path: first.clone(),
494                    bytes: b"new".to_vec(),
495                    permissions: None,
496                },
497                Output {
498                    previous: Snapshot::read(&failing).unwrap(),
499                    path: failing.clone(),
500                    bytes: b"fail".to_vec(),
501                    permissions: None,
502                },
503            ];
504            let staged = outputs
505                .iter()
506                .map(|o| Staged::new(&o.path, &o.bytes, None).unwrap())
507                .collect::<Vec<_>>();
508            let restores = outputs
509                .iter()
510                .map(|o| {
511                    o.previous
512                        .bytes
513                        .as_ref()
514                        .map(|bytes| Staged::new(&o.path, bytes, None).unwrap())
515                })
516                .collect::<Vec<_>>();
517            // A directory appearing after staging forces a real rename failure
518            // after the first destination has already committed.
519            fs::create_dir(&failing).unwrap();
520            assert!(commit(&outputs, &staged, &restores).is_err());
521            if existing {
522                assert_eq!(fs::read(&first).unwrap(), b"original");
523            } else {
524                assert!(!first.exists());
525            }
526            assert!(failing.is_dir());
527            drop(staged);
528            drop(restores);
529            assert_eq!(
530                fs::read_dir(&parent).unwrap().count(),
531                1 + usize::from(existing)
532            );
533            fs::remove_dir_all(parent).unwrap();
534        }
535    }
536    #[test]
537    fn rollback_failure_retains_original_bytes_and_reports_recovery_path() {
538        let parent = std::env::temp_dir().join(format!(
539            "dive-pcal-rollback-recovery-{}",
540            std::process::id()
541        ));
542        let _ = fs::remove_dir_all(&parent);
543        fs::create_dir_all(&parent).unwrap();
544        let target = parent.join("changed-to-directory");
545        let saved = Staged::new(&target, b"original private data", None).unwrap();
546        let saved_path = saved.path.clone();
547        fs::create_dir(&target).unwrap();
548        let outputs = [Output {
549            path: target.clone(),
550            previous: Snapshot {
551                bytes: Some(b"original private data".to_vec()),
552                permissions: None,
553            },
554            bytes: b"replacement".to_vec(),
555            permissions: None,
556        }];
557        let restores = [Some(saved)];
558        let failures = rollback(&outputs, &restores, 1);
559        assert_eq!(failures.len(), 1);
560        assert!(failures[0].contains(&saved_path.display().to_string()));
561        drop(restores);
562        assert_eq!(fs::read(saved_path).unwrap(), b"original private data");
563        assert!(target.is_dir());
564        fs::remove_dir_all(parent).unwrap();
565    }
566}