Skip to main content

effindom_native_packaging/
bundle.rs

1use crate::{Error, Result};
2use serde::{Deserialize, Serialize};
3use sha2::{Digest, Sha256};
4use std::collections::BTreeMap;
5use std::fs::{self, File};
6use std::io::{self, Read};
7use std::path::{Component, Path, PathBuf};
8use std::sync::atomic::{AtomicU64, Ordering};
9
10const PACKAGE_RECORD_SCHEMA_VERSION: u32 = 2;
11static NEXT_STAGING_ID: AtomicU64 = AtomicU64::new(1);
12
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub enum OverwritePolicy {
15    Reject,
16    Replace,
17}
18
19#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
20#[serde(rename_all = "camelCase")]
21pub enum BundleFileRole {
22    ApplicationExecutable,
23    EffinDomRuntimeLibrary,
24    ThirdPartyLibrary,
25    RuntimeResource,
26    ApplicationResource,
27    MetadataArtifact,
28}
29
30#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
31#[serde(rename_all = "camelCase")]
32pub enum PackageOperatingSystem {
33    MacOs,
34    Windows,
35    Linux,
36}
37
38#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
39#[serde(rename_all = "camelCase")]
40pub enum PackageArchitecture {
41    Arm64,
42    X64,
43    Universal,
44}
45
46#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
47#[serde(rename_all = "camelCase")]
48pub enum PackageBuildMode {
49    Debug,
50    Release,
51}
52
53#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
54#[serde(rename_all = "camelCase")]
55pub struct PackageMetadata {
56    pub application_identifier: String,
57    pub application_version: String,
58    pub operating_system: PackageOperatingSystem,
59    pub architecture: PackageArchitecture,
60    pub target_triple: String,
61    pub build_mode: PackageBuildMode,
62    pub core_abi: u32,
63    pub ui_abi: u32,
64}
65
66#[derive(Clone, Debug, PartialEq, Eq)]
67pub struct BundleFile {
68    pub source: PathBuf,
69    pub destination: PathBuf,
70}
71
72impl BundleFile {
73    pub fn new(source: impl Into<PathBuf>, destination: impl Into<PathBuf>) -> Self {
74        Self {
75            source: source.into(),
76            destination: destination.into(),
77        }
78    }
79}
80
81#[derive(Clone, Debug, PartialEq, Eq)]
82pub struct PackagingInputs {
83    pub destination: PathBuf,
84    pub package_record: PathBuf,
85    pub metadata: PackageMetadata,
86    pub application_executable: BundleFile,
87    pub effindom_runtime_libraries: Vec<BundleFile>,
88    pub third_party_libraries: Vec<BundleFile>,
89    pub runtime_resources: Vec<BundleFile>,
90    pub application_resources: Vec<BundleFile>,
91    pub metadata_artifacts: Vec<BundleFile>,
92}
93
94#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
95#[serde(rename_all = "camelCase")]
96pub struct PackageRecord {
97    pub schema_version: u32,
98    pub metadata: PackageMetadata,
99    pub files: Vec<PackageRecordFile>,
100}
101
102#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
103#[serde(rename_all = "camelCase")]
104pub struct PackageRecordFile {
105    pub path: String,
106    pub role: BundleFileRole,
107    pub byte_length: u64,
108    pub sha256: String,
109}
110
111#[derive(Clone)]
112struct ValidatedEntry {
113    source: PathBuf,
114    destination: PathBuf,
115    record_path: String,
116    role: BundleFileRole,
117}
118
119struct ValidatedInputs {
120    destination: PathBuf,
121    package_record: PathBuf,
122    metadata: PackageMetadata,
123    entries: Vec<ValidatedEntry>,
124}
125
126pub fn stage_bundle(inputs: &PackagingInputs, overwrite: OverwritePolicy) -> Result<PackageRecord> {
127    let validated = validate_inputs(inputs, overwrite)?;
128    let staging = unique_sibling(&validated.destination, "staging")?;
129    create_dir_all(&staging, "create bundle staging directory")?;
130
131    let result = stage_validated_bundle(&validated, &staging).and_then(|record| {
132        publish_staging(&staging, &validated.destination, overwrite, || Ok(()))?;
133        Ok(record)
134    });
135    if result.is_err() {
136        let _ = fs::remove_dir_all(&staging);
137    }
138    result
139}
140
141pub fn verify_bundle(
142    bundle_root: impl AsRef<Path>,
143    package_record: impl AsRef<Path>,
144) -> Result<PackageRecord> {
145    let package_record = validate_relative_path(package_record.as_ref())?;
146    let root = fs::canonicalize(bundle_root.as_ref()).map_err(|source| Error::BundleIo {
147        operation: "resolve bundle root",
148        path: bundle_root.as_ref().to_path_buf(),
149        source,
150    })?;
151    let record_path = root.join(&package_record);
152    let bytes = fs::read(&record_path).map_err(|source| Error::BundleIo {
153        operation: "read package record",
154        path: record_path.clone(),
155        source,
156    })?;
157    let record: PackageRecord =
158        serde_json::from_slice(&bytes).map_err(|source| Error::ParsePackageRecord {
159            path: record_path,
160            source,
161        })?;
162    if record.schema_version != PACKAGE_RECORD_SCHEMA_VERSION {
163        return Err(Error::UnsupportedPackageRecordSchema(record.schema_version));
164    }
165    for file in &record.files {
166        let relative = validate_relative_path(Path::new(&file.path))?;
167        let candidate = root.join(&relative);
168        let canonical = fs::canonicalize(&candidate)
169            .map_err(|_| Error::PackageRecordArtifactMissing(relative.clone()))?;
170        if !canonical.starts_with(&root) {
171            return Err(Error::InvalidBundlePath {
172                path: relative,
173                message: "must remain inside the bundle root",
174            });
175        }
176        let actual_length = fs::metadata(&canonical)
177            .map_err(|source| Error::BundleIo {
178                operation: "inspect packaged artifact",
179                path: canonical.clone(),
180                source,
181            })?
182            .len();
183        if actual_length != file.byte_length {
184            return Err(Error::PackageRecordLengthMismatch {
185                path: relative,
186                expected: file.byte_length,
187                actual: actual_length,
188            });
189        }
190        let actual_sha256 = sha256_file(&canonical)?;
191        if actual_sha256 != file.sha256 {
192            return Err(Error::PackageRecordChecksumMismatch {
193                path: relative,
194                expected: file.sha256.clone(),
195                actual: actual_sha256,
196            });
197        }
198    }
199    Ok(record)
200}
201
202fn validate_inputs(
203    inputs: &PackagingInputs,
204    overwrite: OverwritePolicy,
205) -> Result<ValidatedInputs> {
206    let destination = absolute_destination(&inputs.destination)?;
207    let package_record = validate_relative_path(&inputs.package_record)?;
208    let mut entries = Vec::new();
209    push_entry(
210        &mut entries,
211        &inputs.application_executable,
212        BundleFileRole::ApplicationExecutable,
213        &destination,
214    )?;
215    for entry in &inputs.effindom_runtime_libraries {
216        push_entry(
217            &mut entries,
218            entry,
219            BundleFileRole::EffinDomRuntimeLibrary,
220            &destination,
221        )?;
222    }
223    for entry in &inputs.third_party_libraries {
224        push_entry(
225            &mut entries,
226            entry,
227            BundleFileRole::ThirdPartyLibrary,
228            &destination,
229        )?;
230    }
231    for entry in &inputs.runtime_resources {
232        push_entry(
233            &mut entries,
234            entry,
235            BundleFileRole::RuntimeResource,
236            &destination,
237        )?;
238    }
239    for entry in &inputs.application_resources {
240        push_entry(
241            &mut entries,
242            entry,
243            BundleFileRole::ApplicationResource,
244            &destination,
245        )?;
246    }
247    for entry in &inputs.metadata_artifacts {
248        push_entry(
249            &mut entries,
250            entry,
251            BundleFileRole::MetadataArtifact,
252            &destination,
253        )?;
254    }
255
256    entries.sort_by(|left, right| left.record_path.cmp(&right.record_path));
257    let mut destinations = BTreeMap::new();
258    destinations.insert(path_key(&package_record)?, ());
259    for entry in &entries {
260        if destinations.insert(entry.record_path.clone(), ()).is_some() {
261            return Err(Error::DuplicateBundlePath(entry.destination.clone()));
262        }
263    }
264    if destination.exists() && overwrite == OverwritePolicy::Reject {
265        return Err(Error::BundleOutputExists(destination));
266    }
267    Ok(ValidatedInputs {
268        destination,
269        package_record,
270        metadata: inputs.metadata.clone(),
271        entries,
272    })
273}
274
275fn push_entry(
276    entries: &mut Vec<ValidatedEntry>,
277    entry: &BundleFile,
278    role: BundleFileRole,
279    output: &Path,
280) -> Result<()> {
281    let destination = validate_relative_path(&entry.destination)?;
282    let metadata = fs::symlink_metadata(&entry.source).map_err(|source| {
283        if source.kind() == io::ErrorKind::NotFound {
284            Error::MissingBundleInput(entry.source.clone())
285        } else {
286            Error::BundleIo {
287                operation: "inspect bundle input",
288                path: entry.source.clone(),
289                source,
290            }
291        }
292    })?;
293    if !metadata.file_type().is_file() || metadata.file_type().is_symlink() {
294        return Err(Error::UnsupportedBundleInput(entry.source.clone()));
295    }
296    let source = fs::canonicalize(&entry.source).map_err(|source| Error::BundleIo {
297        operation: "resolve bundle input",
298        path: entry.source.clone(),
299        source,
300    })?;
301    if source.starts_with(output) {
302        return Err(Error::SourceOutputOverlap {
303            source,
304            destination: output.to_path_buf(),
305        });
306    }
307    entries.push(ValidatedEntry {
308        source,
309        record_path: path_key(&destination)?,
310        destination,
311        role,
312    });
313    Ok(())
314}
315
316fn stage_validated_bundle(inputs: &ValidatedInputs, staging: &Path) -> Result<PackageRecord> {
317    let mut files = Vec::with_capacity(inputs.entries.len());
318    for entry in &inputs.entries {
319        let target = staging.join(&entry.destination);
320        let parent = target.parent().ok_or_else(|| Error::InvalidBundlePath {
321            path: entry.destination.clone(),
322            message: "must have a parent directory",
323        })?;
324        create_dir_all(parent, "create bundle payload directory")?;
325        fs::copy(&entry.source, &target).map_err(|source| Error::BundleIo {
326            operation: "copy bundle input",
327            path: entry.source.clone(),
328            source,
329        })?;
330        let byte_length = fs::metadata(&target)
331            .map_err(|source| Error::BundleIo {
332                operation: "inspect staged bundle file",
333                path: target.clone(),
334                source,
335            })?
336            .len();
337        files.push(PackageRecordFile {
338            path: entry.record_path.clone(),
339            role: entry.role,
340            byte_length,
341            sha256: sha256_file(&target)?,
342        });
343    }
344    let record = PackageRecord {
345        schema_version: PACKAGE_RECORD_SCHEMA_VERSION,
346        metadata: inputs.metadata.clone(),
347        files,
348    };
349    let record_path = staging.join(&inputs.package_record);
350    let parent = record_path
351        .parent()
352        .ok_or_else(|| Error::InvalidBundlePath {
353            path: inputs.package_record.clone(),
354            message: "must have a parent directory",
355        })?;
356    create_dir_all(parent, "create package record directory")?;
357    let mut json = serde_json::to_vec_pretty(&record).map_err(Error::SerializePackageRecord)?;
358    json.push(b'\n');
359    fs::write(&record_path, json).map_err(|source| Error::BundleIo {
360        operation: "write package record",
361        path: record_path,
362        source,
363    })?;
364    Ok(record)
365}
366
367fn publish_staging<F>(
368    staging: &Path,
369    destination: &Path,
370    overwrite: OverwritePolicy,
371    before_publish: F,
372) -> Result<()>
373where
374    F: FnOnce() -> io::Result<()>,
375{
376    if overwrite == OverwritePolicy::Replace && destination.exists() {
377        let backup = unique_sibling(destination, "backup")?;
378        fs::rename(destination, &backup).map_err(|source| Error::PublishBundle {
379            from: destination.to_path_buf(),
380            to: backup.clone(),
381            source,
382        })?;
383        if let Err(source) = before_publish().and_then(|()| fs::rename(staging, destination)) {
384            fs::rename(&backup, destination).map_err(|rollback| Error::RollbackBundle {
385                backup,
386                destination: destination.to_path_buf(),
387                source: rollback,
388            })?;
389            return Err(Error::PublishBundle {
390                from: staging.to_path_buf(),
391                to: destination.to_path_buf(),
392                source,
393            });
394        }
395        fs::remove_dir_all(&backup).map_err(|source| Error::BundleIo {
396            operation: "remove replaced bundle backup",
397            path: backup,
398            source,
399        })?;
400        return Ok(());
401    }
402    before_publish().map_err(|source| Error::PublishBundle {
403        from: staging.to_path_buf(),
404        to: destination.to_path_buf(),
405        source,
406    })?;
407    fs::rename(staging, destination).map_err(|source| Error::PublishBundle {
408        from: staging.to_path_buf(),
409        to: destination.to_path_buf(),
410        source,
411    })
412}
413
414fn absolute_destination(destination: &Path) -> Result<PathBuf> {
415    let name = destination
416        .file_name()
417        .ok_or_else(|| Error::InvalidBundlePath {
418            path: destination.to_path_buf(),
419            message: "must name a bundle directory",
420        })?;
421    let parent = destination.parent().unwrap_or_else(|| Path::new("."));
422    let parent = fs::canonicalize(parent).map_err(|source| Error::BundleIo {
423        operation: "resolve bundle output parent",
424        path: parent.to_path_buf(),
425        source,
426    })?;
427    Ok(parent.join(name))
428}
429
430fn validate_relative_path(path: &Path) -> Result<PathBuf> {
431    if path.as_os_str().is_empty() || path.is_absolute() {
432        return Err(Error::InvalidBundlePath {
433            path: path.to_path_buf(),
434            message: "must be a non-empty relative path",
435        });
436    }
437    let mut normalized = PathBuf::new();
438    for component in path.components() {
439        match component {
440            Component::Normal(value) if value.to_str().is_some() => normalized.push(value),
441            _ => {
442                return Err(Error::InvalidBundlePath {
443                    path: path.to_path_buf(),
444                    message: "must contain only UTF-8 normal path components",
445                });
446            }
447        }
448    }
449    Ok(normalized)
450}
451
452fn path_key(path: &Path) -> Result<String> {
453    let mut parts = Vec::new();
454    for component in path.components() {
455        match component {
456            Component::Normal(value) => {
457                parts.push(value.to_str().ok_or_else(|| Error::InvalidBundlePath {
458                    path: path.to_path_buf(),
459                    message: "must be valid UTF-8",
460                })?)
461            }
462            _ => {
463                return Err(Error::InvalidBundlePath {
464                    path: path.to_path_buf(),
465                    message: "must be relative and normalized",
466                });
467            }
468        }
469    }
470    Ok(parts.join("/"))
471}
472
473fn create_dir_all(path: &Path, operation: &'static str) -> Result<()> {
474    fs::create_dir_all(path).map_err(|source| Error::BundleIo {
475        operation,
476        path: path.to_path_buf(),
477        source,
478    })
479}
480
481fn unique_sibling(destination: &Path, kind: &str) -> Result<PathBuf> {
482    let parent = destination
483        .parent()
484        .ok_or_else(|| Error::InvalidBundlePath {
485            path: destination.to_path_buf(),
486            message: "must have a parent directory",
487        })?;
488    let name = destination
489        .file_name()
490        .and_then(|name| name.to_str())
491        .ok_or_else(|| Error::InvalidBundlePath {
492            path: destination.to_path_buf(),
493            message: "must have a UTF-8 file name",
494        })?;
495    loop {
496        let id = NEXT_STAGING_ID.fetch_add(1, Ordering::Relaxed);
497        let candidate = parent.join(format!(
498            ".{name}.effindom-{kind}-{}-{id}",
499            std::process::id()
500        ));
501        if !candidate.exists() {
502            return Ok(candidate);
503        }
504    }
505}
506
507fn sha256_file(path: &Path) -> Result<String> {
508    let mut file = File::open(path).map_err(|source| Error::BundleIo {
509        operation: "open staged bundle file for hashing",
510        path: path.to_path_buf(),
511        source,
512    })?;
513    let mut digest = Sha256::new();
514    let mut buffer = [0u8; 64 * 1024];
515    loop {
516        let count = file.read(&mut buffer).map_err(|source| Error::BundleIo {
517            operation: "hash staged bundle file",
518            path: path.to_path_buf(),
519            source,
520        })?;
521        if count == 0 {
522            break;
523        }
524        digest.update(&buffer[..count]);
525    }
526    Ok(digest
527        .finalize()
528        .iter()
529        .map(|byte| format!("{byte:02x}"))
530        .collect())
531}
532
533#[cfg(test)]
534mod tests {
535    use super::*;
536
537    #[test]
538    fn failed_replacement_restores_the_previous_bundle() {
539        let root = std::env::temp_dir().join(format!(
540            "effindom-bundle-rollback-{}-{}",
541            std::process::id(),
542            NEXT_STAGING_ID.fetch_add(1, Ordering::Relaxed)
543        ));
544        let destination = root.join("app");
545        let staging = root.join("staging");
546        fs::create_dir_all(&destination).expect("create destination");
547        fs::create_dir_all(&staging).expect("create staging");
548        fs::write(destination.join("old.txt"), "old").expect("write old bundle");
549        fs::write(staging.join("new.txt"), "new").expect("write staged bundle");
550
551        let error = publish_staging(&staging, &destination, OverwritePolicy::Replace, || {
552            Err(io::Error::other("injected publication failure"))
553        })
554        .expect_err("publication must fail");
555        assert!(matches!(error, Error::PublishBundle { .. }));
556        assert_eq!(
557            fs::read_to_string(destination.join("old.txt")).expect("read restored bundle"),
558            "old"
559        );
560        assert!(!destination.join("new.txt").exists());
561        fs::remove_dir_all(root).expect("remove rollback fixture");
562    }
563}