Skip to main content

agentmux_srv_core/backend/agent_archive/
writer.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Writes an agent archive as a stream: each part is read from its source and written to the file as it goes,
5//! hashed per chunk on the way, so a history of any size never sits in memory (and never goes through base64).
6//! The manifest is written last, because it holds what the parts turned out to be.
7
8use std::collections::HashSet;
9use std::io::{Read, Seek, Write};
10
11use sha2::{Digest, Sha256};
12use zip::write::SimpleFileOptions;
13use zip::{CompressionMethod, ZipWriter};
14
15use super::manifest::{valid_part_path, AgentInfo, Manifest, Part, Signature, Source, CHUNK_BYTES, FORMAT, KIND, MANIFEST_NAME};
16use super::{ArchiveError, Limits};
17
18/// Signs the manifest's bytes: returns the signer's public key and the signature, or `None` when this computer
19/// cannot sign (the archive is then written unsigned).
20pub type Signer<'a> = &'a dyn Fn(&[u8]) -> Option<([u8; 32], [u8; 64])>;
21
22pub struct ArchiveWriter<W: Write + Seek> {
23    zip: ZipWriter<W>,
24    parts: Vec<Part>,
25    names: HashSet<String>,
26    total: u64,
27    limits: Limits,
28}
29
30impl<W: Write + Seek> ArchiveWriter<W> {
31    pub fn new(out: W, limits: Limits) -> Self {
32        Self { zip: ZipWriter::new(out), parts: Vec::new(), names: HashSet::new(), total: 0, limits }
33    }
34
35    /// Adds the part `path`, reading `source` to its end. Refused when the name is not a plain relative one, is
36    /// there already, or the part or the whole archive would pass its cap; the file is then unusable and is to be
37    /// discarded.
38    pub fn add_part(&mut self, path: &str, source: &mut dyn Read) -> Result<&Part, ArchiveError> {
39        if !valid_part_path(path) {
40            return Err(ArchiveError::BadPath(path.to_string()));
41        }
42        if self.parts.len() >= self.limits.max_parts {
43            return Err(ArchiveError::TooManyParts(self.limits.max_parts));
44        }
45        if !self.names.insert(path.to_string()) {
46            return Err(ArchiveError::DuplicatePart(path.to_string()));
47        }
48        let options = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated).large_file(true);
49        self.zip.start_file(path, options).map_err(|e| ArchiveError::Io(e.to_string()))?;
50
51        let room = self.limits.max_total_bytes.saturating_sub(self.total).min(self.limits.max_part_bytes);
52        let mut whole = Sha256::new();
53        let mut chunks = Vec::new();
54        let mut size = 0u64;
55        let mut buf = vec![0u8; CHUNK_BYTES as usize];
56        loop {
57            let n = fill(source, &mut buf).map_err(|e| ArchiveError::Io(e.to_string()))?;
58            if n == 0 {
59                break;
60            }
61            size += n as u64;
62            if size > room {
63                return Err(if size > self.limits.max_part_bytes { ArchiveError::PartTooBig(path.to_string(), self.limits.max_part_bytes) } else { ArchiveError::TooBig(self.limits.max_total_bytes) });
64            }
65            whole.update(&buf[..n]);
66            chunks.push(hex::encode(Sha256::digest(&buf[..n])));
67            self.zip.write_all(&buf[..n]).map_err(|e| ArchiveError::Io(e.to_string()))?;
68            if (n as u64) < CHUNK_BYTES {
69                break;
70            }
71        }
72        self.total += size;
73        self.parts.push(Part { path: path.to_string(), size, sha256: hex::encode(whole.finalize()), chunks });
74        Ok(self.parts.last().expect("just pushed"))
75    }
76
77    pub fn add_bytes(&mut self, path: &str, bytes: &[u8]) -> Result<&Part, ArchiveError> {
78        self.add_part(path, &mut &*bytes)
79    }
80
81    /// The bytes added so far.
82    pub fn total_bytes(&self) -> u64 {
83        self.total
84    }
85
86    /// Writes the manifest and closes the file. Returns the manifest and the file's writer.
87    pub fn finish(mut self, agent: AgentInfo, source: Source, created_at: i64, signer: Option<Signer<'_>>) -> Result<(Manifest, W), ArchiveError> {
88        let mut manifest = Manifest { kind: KIND.to_string(), format: FORMAT, created_at, agent, source, parts: self.parts, signature: None };
89        if let Some(sign) = signer {
90            if let Some((public_key, signature)) = sign(&manifest.signed_bytes()) {
91                use base64::Engine;
92                let b64 = base64::engine::general_purpose::STANDARD;
93                manifest.signature = Some(Signature { alg: "ed25519".to_string(), public_key: b64.encode(public_key), value: b64.encode(signature) });
94            }
95        }
96        let json = serde_json::to_vec_pretty(&manifest).map_err(|e| ArchiveError::Io(e.to_string()))?;
97        let options = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated);
98        self.zip.start_file(MANIFEST_NAME, options).map_err(|e| ArchiveError::Io(e.to_string()))?;
99        self.zip.write_all(&json).map_err(|e| ArchiveError::Io(e.to_string()))?;
100        let out = self.zip.finish().map_err(|e| ArchiveError::Io(e.to_string()))?;
101        Ok((manifest, out))
102    }
103}
104
105/// Reads until `buf` is full or the source ends.
106fn fill(source: &mut dyn Read, buf: &mut [u8]) -> std::io::Result<usize> {
107    let mut at = 0;
108    while at < buf.len() {
109        match source.read(&mut buf[at..]) {
110            Ok(0) => break,
111            Ok(n) => at += n,
112            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
113            Err(e) => return Err(e),
114        }
115    }
116    Ok(at)
117}