Skip to main content

qualia_core_db/audio/qac/
persistence.rs

1//! Native immutable publication of admitted final acoustic bytes.
2//!
3//! The caller must exclusively control a trusted storage root and its directory
4//! access. Redirect checks are not a sandbox against directory-replacement races.
5//! Publication is atomic and no-clobber, not an aggregate quota or authorization
6//! mechanism. File syncing does not establish directory-fsync crash durability.
7use super::{QacStorageError, QacStorageOptions, QacStorageView};
8use std::{
9    fs::{self, File},
10    io::{self, Read, Write},
11    path::{Path, PathBuf},
12};
13
14#[derive(Debug, Clone, Copy)]
15pub struct QacPublishOptions {
16    /// Maximum bytes in this object and its temporary file; not total disk usage.
17    pub max_bytes: usize,
18    /// Current envelope limits; publication checks structure and every payload digest.
19    pub storage: QacStorageOptions,
20}
21impl Default for QacPublishOptions {
22    fn default() -> Self {
23        Self {
24            max_bytes: 256 * 1024 * 1024,
25            storage: QacStorageOptions::default(),
26        }
27    }
28}
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum QacPublicationAdmission {
32    /// Structural/index and every chunk digest checked; no scientific admission.
33    CurrentStructure,
34}
35
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct QacArtifact {
38    /// BLAKE3 of every final byte, including headers, metadata and padding.
39    pub blake3: [u8; 32],
40    pub byte_length: u64,
41    /// Canonical `spectral/audio/{64 lowercase hex digits}.qac` destination.
42    pub path: PathBuf,
43    pub admission: QacPublicationAdmission,
44}
45
46#[derive(Debug)]
47pub enum QacPublishError {
48    Io(io::Error),
49    Budget,
50    Admission(QacStorageError),
51    Conflict,
52    InvalidPath,
53}
54impl From<io::Error> for QacPublishError {
55    fn from(error: io::Error) -> Self {
56        Self::Io(error)
57    }
58}
59impl std::fmt::Display for QacPublishError {
60    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61        match self {
62            Self::Io(e) => write!(f, "QAC publication IO: {e}"),
63            Self::Budget => f.write_str("QAC publication byte budget exceeded"),
64            Self::Admission(e) => write!(f, "QAC publication admission: {e:?}"),
65            Self::Conflict => f.write_str("QAC destination contains different bytes"),
66            Self::InvalidPath => f.write_str("QAC destination redirects or is not a regular file"),
67        }
68    }
69}
70impl std::error::Error for QacPublishError {}
71
72fn child(parent: &Path, name: &str) -> Result<PathBuf, QacPublishError> {
73    let path = parent.join(name);
74    match fs::create_dir(&path) {
75        Ok(()) => {}
76        Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {}
77        Err(e) => return Err(e.into()),
78    }
79    let meta = fs::symlink_metadata(&path)?;
80    if meta.file_type().is_symlink() || !meta.is_dir() {
81        return Err(QacPublishError::InvalidPath);
82    }
83    let canonical = path.canonicalize()?;
84    if canonical.parent() != Some(parent) {
85        return Err(QacPublishError::InvalidPath);
86    }
87    Ok(canonical)
88}
89
90fn directory(root: &Path) -> Result<PathBuf, QacPublishError> {
91    fs::create_dir_all(root)?;
92    let root = root.canonicalize()?;
93    child(&child(&root, "spectral")?, "audio")
94}
95
96fn verify_exact(path: &Path, bytes: &[u8]) -> Result<(), QacPublishError> {
97    let meta = fs::symlink_metadata(path)?;
98    if meta.file_type().is_symlink() || !meta.is_file() {
99        return Err(QacPublishError::InvalidPath);
100    }
101    let mut file = File::open(path)?;
102    if file.metadata()?.len() != bytes.len() as u64 {
103        return Err(QacPublishError::Conflict);
104    }
105    let mut scratch = [0u8; 8192];
106    for expected in bytes.chunks(scratch.len()) {
107        file.read_exact(&mut scratch[..expected.len()])?;
108        if &scratch[..expected.len()] != expected {
109            return Err(QacPublishError::Conflict);
110        }
111    }
112    if file.read(&mut scratch[..1])? != 0 {
113        return Err(QacPublishError::Conflict);
114    }
115    Ok(())
116}
117
118fn stage_file(path: &Path, bytes: &[u8]) -> Result<tempfile::NamedTempFile, QacPublishError> {
119    let parent = path.parent().ok_or(QacPublishError::InvalidPath)?;
120    let mut staging = tempfile::NamedTempFile::new_in(parent)?;
121    staging.write_all(bytes)?;
122    staging.as_file().sync_all()?;
123    Ok(staging)
124}
125
126fn publish_exact(path: &Path, bytes: &[u8]) -> Result<(), QacPublishError> {
127    let staging = stage_file(path, bytes)?;
128    match staging.persist_noclobber(path) {
129        Ok(_) => Ok(()),
130        // The error owns the temporary file; dropping it cleans scratch on all exits.
131        Err(e) if e.error.kind() == io::ErrorKind::AlreadyExists => verify_exact(path, bytes),
132        Err(e) => Err(e.error.into()),
133    }
134}
135
136/// Admit without transcoding, hash all final bytes, then sync and publish a
137/// same-directory temporary file without replacing an existing destination.
138/// Identical existing content is verified byte-for-byte and reused. No source
139/// is changed, and scratch is removed on errors/unwind. Current payload chunk
140/// digests are verified in addition to structural admission; semantics stay opaque.
141pub fn publish_qac(
142    root: &Path,
143    bytes: &[u8],
144    options: QacPublishOptions,
145) -> Result<QacArtifact, QacPublishError> {
146    if bytes.len() > options.max_bytes {
147        return Err(QacPublishError::Budget);
148    }
149    let admitted =
150        QacStorageView::open(bytes, options.storage).map_err(QacPublishError::Admission)?;
151    for index in 1..=admitted.structure().entry_count() {
152        admitted
153            .structure()
154            .verify_chunk(index)
155            .map_err(|e| QacPublishError::Admission(QacStorageError::Envelope(e)))?;
156    }
157    let admission = QacPublicationAdmission::CurrentStructure;
158    let digest = blake3::hash(bytes);
159    let path = directory(root)?.join(format!("{}.qac", digest.to_hex()));
160    publish_exact(&path, bytes)?;
161    Ok(QacArtifact {
162        blake3: *digest.as_bytes(),
163        byte_length: bytes.len() as u64,
164        path,
165        admission,
166    })
167}
168
169#[cfg(test)]
170#[path = "persistence_tests.rs"]
171mod tests;