crates/state/bundle/src/lib.rs 23.1 KiB 707 lines Raw
1 //! inf3r-bundle — the directory that ships one model on one target.2 //!3 //! A bundle is the unit of work, replacement, and shipping (spec section 5).4 //! This crate is the only code that knows its shape: the manifest, the five5 //! required parts, and the digest that the install gate checks. The weights in6 //! `model/` are mounted content, so nothing here reads them and the digest7 //! refuses a manifest that names them.8 //!9 //! The manifest has one key per line because the tree has no TOML parser and a10 //! bundle should not add one.11 12 use std::fmt;13 use std::fs::File;14 use std::io::Read;15 use std::path::{Component, Path, PathBuf};16 17 use inf3r_sha256::Sha256;18 19 /// The manifest at the root of every bundle directory.20 pub const MANIFEST: &str = "bundle.toml";21 22 /// The card that every bundle ships.23 const CARD: &str = "BUNDLE.md";24 25 /// The hardware profile that the bundle was built for.26 const TARGET: &str = "target.toml";27 28 /// The directory that holds one model file per served name.29 const MODELS: &str = "models";30 31 /// The mounted weights. Never tracked, never in an image, never in the digest.32 const MODEL: &str = "model";33 34 /// The runtime of a bound bundle.35 const ENGINE: &str = "engine";36 37 /// A bundle as its manifest describes it.38 #[derive(Clone, PartialEq, Eq, Debug)]39 pub struct Bundle {40     /// The pair: the path below `plugins/`.41     pub id: String,42     /// The model half of the pair.43     pub model: String,44     /// The target half of the pair.45     pub target: String,46     /// One line that says what the bundle is for.47     pub summary: String,48     /// How the engine runs.49     pub engine: EngineKind,50     /// The program that a bound engine starts, relative to the bundle root.51     pub entry: Option<PathBuf>,52     /// The words that the binder gives to the entry, with `{model}` and53     /// `{port}` left for the binder to fill.54     pub args: Vec<String>,55     /// The persistent worker protocol, when a binary engine stays resident.56     /// `jsonl` means one JSON request and one line of JSON events per job.57     pub worker: Option<String>,58     /// The process binary at the bundle root.59     pub binary: PathBuf,60     /// The files that the digest covers, relative to the bundle root.61     pub files: Vec<PathBuf>,62     /// The digest of the binary and the files, as 64 lowercase hex characters.63     pub sha256: String,64 }65 66 /// How the engine inside a bundle runs.67 #[derive(Clone, Copy, PartialEq, Eq, Debug)]68 pub enum EngineKind {69     /// The bundle owns the engine in `src/`.70     Authored,71     /// A binary in `engine/` that the binder starts.72     Binary,73     /// A service that the binder connects to.74     Http,75     /// A library in `engine/` that the entry point loads.76     Library,77 }78 79 impl EngineKind {80     /// Reads the one word that the manifest permits.81     fn parse(word: &str) -> Result<EngineKind, BundleError> {82         match word {83             "authored" => Ok(EngineKind::Authored),84             "binary" => Ok(EngineKind::Binary),85             "http" => Ok(EngineKind::Http),86             "library" => Ok(EngineKind::Library),87             other => Err(BundleError::UnknownEngine(other.to_string())),88         }89     }90 }91 92 /// One part that a bundle directory is missing or must not have.93 #[derive(Clone, PartialEq, Eq, Debug)]94 pub struct Problem {95     /// The part, as the manifest and the tree name it.96     pub part: &'static str,97     /// Why the part is wrong.98     pub why: String,99 }100 101 impl fmt::Display for Problem {102     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {103         write!(f, "{}: {}", self.part, self.why)104     }105 }106 107 /// The reason a bundle was refused.108 #[derive(Clone, PartialEq, Eq, Debug)]109 pub enum BundleError {110     /// The filesystem failed, or a named file is absent.111     Io(String),112     /// A manifest line is outside the supported subset.113     Syntax {114         /// The one-based line number.115         line: usize,116         /// What the parser found and what it expected.117         message: String,118     },119     /// A required key is absent. The value names the key.120     Missing(&'static str),121     /// A required key has no value. The value names the key.122     Empty(&'static str),123     /// The engine word is not `authored`, `binary`, `http`, or `library`.124     UnknownEngine(String),125     /// The files list names a file under `model/`.126     ModelFile(PathBuf),127     /// A path is not a normal relative path below the bundle root.128     Path {129         /// The manifest key that named it.130         key: &'static str,131         /// The path as the manifest wrote it.132         path: PathBuf,133     },134     /// The digest in the manifest is not the digest of the files.135     Mismatch {136         /// The digest that the manifest declares.137         declared: String,138         /// The digest of the files on disk.139         actual: String,140     },141 }142 143 impl fmt::Display for BundleError {144     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {145         match self {146             BundleError::Io(why) => write!(f, "{why}"),147             BundleError::Syntax { line, message } => write!(f, "line {line}: {message}"),148             BundleError::Missing(key) => write!(f, "missing {key}"),149             BundleError::Empty(key) => write!(f, "{key} is empty"),150             BundleError::UnknownEngine(word) => write!(f, "unknown engine {word}"),151             BundleError::ModelFile(path) => {152                 write!(f, "{} is under {MODEL}/", path.display())153             }154             BundleError::Path { key, path } => {155                 write!(156                     f,157                     "{key} is not a path below the bundle root: {}",158                     path.display()159                 )160             }161             BundleError::Mismatch { declared, actual } => {162                 write!(f, "digest is {actual}, not {declared}")163             }164         }165     }166 }167 168 impl std::error::Error for BundleError {}169 170 impl Bundle {171     /// Reads the manifest at `dir/bundle.toml`.172     ///173     /// An unknown key is refused instead of ignored: a manifest that names a174     /// file the installer does not copy would otherwise verify against bytes175     /// that nobody ships. A `model/` entry is refused here, so the digest176     /// cannot include weights even by accident.177     pub fn read(dir: &Path) -> Result<Bundle, BundleError> {178         let path = dir.join(MANIFEST);179         let text = std::fs::read_to_string(&path).map_err(io)?;180         parse(&text)181     }182 183     /// Every part that the directory is missing, or must not have.184     ///185     /// An empty list is a valid bundle. A problem names one part so that a186     /// reader can fix it without reading the rest of the tree.187     pub fn anatomy(&self, dir: &Path) -> Vec<Problem> {188         let mut problems = Vec::new();189         for (part, name) in [(CARD, CARD), (TARGET, TARGET)] {190             if !dir.join(name).is_file() {191                 problems.push(problem(part, format!("{name} is absent")));192             }193         }194         if !has_model_file(&dir.join(MODELS)) {195             problems.push(problem(MODELS, format!("no {MODELS}/*.toml")));196         }197         if !dir.join(MODEL).is_dir() {198             problems.push(problem(MODEL, format!("{MODEL} is not a directory")));199         }200         if !dir.join(ENGINE).is_dir() {201             problems.push(problem(ENGINE, format!("{ENGINE} is not a directory")));202         }203         let expected = format!("{}/{}", self.model, self.target);204         if self.id != expected {205             problems.push(problem("id", format!("id is {}, not {expected}", self.id)));206         }207         for file in &self.files {208             if file.starts_with(MODEL) {209                 problems.push(problem(210                     "files",211                     format!("{} is under {MODEL}/", file.display()),212                 ));213             }214         }215         problems216     }217 218     /// The digest of the binary and the files that the manifest names.219     ///220     /// The binary is first, then each file in sorted path order. Every piece221     /// contributes its relative path, its byte length, and its bytes, each with222     /// a length prefix as 8 little-endian bytes. Moving bytes from one file to223     /// another, or renaming a file, changes the digest. Files are read in224     /// bounded chunks; a large binary is never held in memory. `model/` is225     /// never read.226     pub fn digest(dir: &Path) -> Result<String, BundleError> {227         let bundle = Bundle::read(dir)?;228         bundle.digest_of(dir)229     }230 231     /// Checks that the files on disk have the digest in the manifest.232     pub fn verify(dir: &Path) -> Result<(), BundleError> {233         let bundle = Bundle::read(dir)?;234         let actual = bundle.digest_of(dir)?;235         if actual == bundle.sha256 {236             return Ok(());237         }238         Err(BundleError::Mismatch {239             declared: bundle.sha256,240             actual,241         })242     }243 244     /// Computes the digest and writes it into `sha256` in bundle.toml.245     ///246     /// Sealing is the second half of an edit: a changed file is a new bundle247     /// only after its manifest says so. Every other line stays as it was, so a248     /// comment that explains a key survives the write.249     pub fn seal(dir: &Path) -> Result<String, BundleError> {250         let path = dir.join(MANIFEST);251         let text = std::fs::read_to_string(&path).map_err(io)?;252         let mut found = false;253         for raw in text.lines() {254             let content = raw.trim();255             if content.is_empty() || content.starts_with('#') {256                 continue;257             }258             if content259                 .split_once('=')260                 .is_some_and(|(key, _)| key.trim() == "sha256")261             {262                 found = true;263                 break;264             }265         }266         if !found {267             return Err(syntax(1, "manifest has no sha256 line"));268         }269         let bundle = parse(&text)?;270         let digest = bundle.digest_of(dir)?;271         let mut sealed = String::with_capacity(text.len());272         for raw in text.lines() {273             let content = raw.trim();274             let is_sha = !content.is_empty()275                 && !content.starts_with('#')276                 && content277                     .split_once('=')278                     .is_some_and(|(key, _)| key.trim() == "sha256");279             if is_sha {280                 let before = raw.split_once('=').map_or(raw, |(left, _)| left);281                 sealed.push_str(before);282                 sealed.push_str("= \"");283                 sealed.push_str(&digest);284                 sealed.push('"');285             } else {286                 sealed.push_str(raw);287             }288             sealed.push('\n');289         }290         std::fs::write(&path, sealed).map_err(io)?;291         Ok(digest)292     }293 294     fn digest_of(&self, dir: &Path) -> Result<String, BundleError> {295         let root = dir.canonicalize().map_err(io)?;296         let model = root.join(MODEL).canonicalize().ok();297         let mut digest = Sha256::new();298         let binary = checked(&self.binary, "binary")?;299         if binary.starts_with(MODEL) {300             return Err(BundleError::ModelFile(binary));301         }302         hash_file(&mut digest, &root, &model, &binary, "binary")?;303         let mut files: Vec<&PathBuf> = self.files.iter().collect();304         files.sort();305         for file in files {306             let path = checked(file, "files")?;307             if path.starts_with(MODEL) {308                 return Err(BundleError::ModelFile(path));309             }310             hash_file(&mut digest, &root, &model, &path, "files")?;311         }312         Ok(digest.finish_hex())313     }314 }315 316 fn problem(part: &'static str, why: String) -> Problem {317     Problem { part, why }318 }319 320 fn has_model_file(dir: &Path) -> bool {321     let Ok(entries) = std::fs::read_dir(dir) else {322         return false;323     };324     entries.flatten().any(|entry| {325         entry.file_type().is_ok_and(|kind| kind.is_file())326             && entry.path().extension().is_some_and(|ext| ext == "toml")327     })328 }329 330 fn parse(text: &str) -> Result<Bundle, BundleError> {331     let mut id = None;332     let mut model = None;333     let mut target = None;334     let mut summary = None;335     let mut engine = None;336     let mut entry = None;337     let mut args = None;338     let mut worker = None;339     let mut binary = None;340     let mut files = None;341     let mut files_line = 0;342     let mut sha256 = None;343     for (index, raw) in text.lines().enumerate() {344         let line = index + 1;345         let content = raw.trim();346         if content.is_empty() || content.starts_with('#') {347             continue;348         }349         let (key, value) = content350             .split_once('=')351             .ok_or_else(|| syntax(line, "expected key = value"))?;352         let key = key.trim();353         if key == "args" {354             let parsed = parse_args(value.trim(), line)?;355             if args.replace(parsed).is_some() {356                 return Err(syntax(line, "args is given twice"));357             }358             continue;359         }360         let value = string(value.trim(), line)?;361         match key {362             "id" => put(&mut id, value, line, key)?,363             "model" => put(&mut model, value, line, key)?,364             "target" => put(&mut target, value, line, key)?,365             "summary" => put(&mut summary, value, line, key)?,366             "engine" => put(&mut engine, value, line, key)?,367             "entry" => put(&mut entry, value, line, key)?,368             "worker" => put(&mut worker, value, line, key)?,369             "binary" => put(&mut binary, value, line, key)?,370             "files" => {371                 put(&mut files, value, line, key)?;372                 files_line = line;373             }374             "sha256" => put(&mut sha256, value, line, key)?,375             other => return Err(syntax(line, format!("unknown key {other}"))),376         }377     }378 379     let id = required(id, "id")?;380     let model = required(model, "model")?;381     let target = required(target, "target")?;382     let summary = required(summary, "summary")?;383     let engine = EngineKind::parse(&required(engine, "engine")?)?;384     let binary = required(binary, "binary")?;385     let files_text = required(files, "files")?;386     let sha256 = required(sha256, "sha256")?;387     let entry = match entry {388         Some(path) if path.is_empty() => return Err(BundleError::Empty("entry")),389         Some(path) if engine == EngineKind::Http && is_url(&path) => Some(PathBuf::from(path)),390         Some(path) => {391             let path = checked(&PathBuf::from(path), "entry")?;392             if path.starts_with(MODEL) {393                 return Err(BundleError::ModelFile(path));394             }395             Some(path)396         }397         None => None,398     };399     // A bound engine cannot start without the program that it names. The file400     // itself is content: a bundle is complete without it and fails at load.401     if engine != EngineKind::Authored && entry.is_none() {402         return Err(BundleError::Missing("entry"));403     }404     if let Some(mode) = &worker {405         if mode != "jsonl" {406             return Err(syntax(1, "worker is jsonl"));407         }408         if engine != EngineKind::Binary {409             return Err(syntax(1, "worker needs the binary engine"));410         }411     }412     let args = args.unwrap_or_default();413     let mut files = Vec::new();414     for path in files_text.split(',').map(str::trim) {415         if path.is_empty() {416             return Err(syntax(files_line, "files has an empty path"));417         }418         let path = checked(&PathBuf::from(path), "files")?;419         if path.starts_with(MODEL) {420             return Err(BundleError::ModelFile(path));421         }422         files.push(path);423     }424     let binary = checked(&PathBuf::from(binary), "binary")?;425     if binary.starts_with(MODEL) {426         return Err(BundleError::ModelFile(binary));427     }428     Ok(Bundle {429         id,430         model,431         target,432         summary,433         engine,434         entry,435         args,436         worker,437         binary,438         files,439         sha256,440     })441 }442 443 fn required(value: Option<String>, key: &'static str) -> Result<String, BundleError> {444     let value = value.ok_or(BundleError::Missing(key))?;445     if value.is_empty() {446         return Err(BundleError::Empty(key));447     }448     Ok(value)449 }450 451 fn put(452     slot: &mut Option<String>,453     value: String,454     line: usize,455     key: &str,456 ) -> Result<(), BundleError> {457     if slot.replace(value).is_some() {458         return Err(syntax(line, format!("{key} is given twice")));459     }460     Ok(())461 }462 463 fn string(text: &str, line: usize) -> Result<String, BundleError> {464     let inner = text465         .strip_prefix('"')466         .and_then(|rest| rest.strip_suffix('"'))467         .ok_or_else(|| syntax(line, "value needs quotes"))?;468     if inner.contains('"') {469         return Err(syntax(line, "quoted value contains a quote"));470     }471     Ok(inner.to_string())472 }473 474 fn syntax(line: usize, message: impl Into<String>) -> BundleError {475     BundleError::Syntax {476         line,477         message: message.into(),478     }479 }480 481 fn io(why: std::io::Error) -> BundleError {482     BundleError::Io(why.to_string())483 }484 485 fn is_url(path: &str) -> bool {486     path.starts_with("http://") || path.starts_with("https://")487 }488 489 fn checked(path: &Path, key: &'static str) -> Result<PathBuf, BundleError> {490     if path.is_absolute() {491         return Err(BundleError::Path {492             key,493             path: path.to_path_buf(),494         });495     }496     let mut out = PathBuf::new();497     for part in path.components() {498         match part {499             Component::Normal(name) => out.push(name),500             Component::CurDir => {}501             Component::ParentDir => {502                 if !out.pop() {503                     return Err(BundleError::Path {504                         key,505                         path: path.to_path_buf(),506                     });507                 }508             }509             Component::RootDir | Component::Prefix(_) => {510                 return Err(BundleError::Path {511                     key,512                     path: path.to_path_buf(),513                 });514             }515         }516     }517     if out.as_os_str().is_empty() {518         return Err(BundleError::Path {519             key,520             path: path.to_path_buf(),521         });522     }523     Ok(out)524 }525 526 /// 64 KiB in one read. A larger binary is still a stream.527 const READ_CHUNK: usize = 64 * 1024;528 529 fn hash_file(530     digest: &mut Sha256,531     root: &Path,532     model: &Option<PathBuf>,533     path: &Path,534     key: &'static str,535 ) -> Result<(), BundleError> {536     let real = root.join(path).canonicalize().map_err(io)?;537     if !real.starts_with(root) {538         return Err(BundleError::Path {539             key,540             path: path.to_path_buf(),541         });542     }543     if model.as_ref().is_some_and(|model| real.starts_with(model)) {544         return Err(BundleError::ModelFile(path.to_path_buf()));545     }546     let mut file = File::open(&real).map_err(io)?;547     let len = file.metadata().map_err(io)?.len();548     let name = path.as_os_str().as_encoded_bytes();549     digest.update(&(name.len() as u64).to_le_bytes());550     digest.update(name);551     digest.update(&len.to_le_bytes());552     let mut buf = [0u8; READ_CHUNK];553     let mut read = 0u64;554     loop {555         let n = file.read(&mut buf).map_err(io)?;556         if n == 0 {557             break;558         }559         digest.update(&buf[..n]);560         read = read.wrapping_add(n as u64);561     }562     if read != len {563         return Err(BundleError::Io(format!(564             "{} changed while the digest read it",565             path.display()566         )));567     }568     Ok(())569 }570 571 fn parse_args(text: &str, line: usize) -> Result<Vec<String>, BundleError> {572     if text.starts_with('[') {573         return parse_array(text, line);574     }575     let inner = arg_string(text, line)?;576     split_words(&inner, line)577 }578 579 fn parse_array(text: &str, line: usize) -> Result<Vec<String>, BundleError> {580     let inner = text581         .strip_prefix('[')582         .and_then(|rest| rest.strip_suffix(']'))583         .ok_or_else(|| syntax(line, "args array needs closing ]"))?;584     let mut words = Vec::new();585     let mut chars = inner.chars().peekable();586     loop {587         while chars.peek().is_some_and(|c| c.is_whitespace()) {588             chars.next();589         }590         let Some(quote) = chars.next() else {591             break;592         };593         if quote != '"' && quote != '\'' {594             return Err(syntax(line, "args array needs quoted strings"));595         }596         let mut word = String::new();597         loop {598             let Some(ch) = chars.next() else {599                 return Err(syntax(line, "args array has no closing quote"));600             };601             if ch == quote {602                 break;603             }604             if ch == '\\' {605                 let Some(escaped) = chars.next() else {606                     return Err(syntax(line, "args array ends with a backslash"));607                 };608                 word.push(escaped);609             } else {610                 word.push(ch);611             }612         }613         words.push(word);614         while chars.peek().is_some_and(|c| c.is_whitespace()) {615             chars.next();616         }617         match chars.next() {618             None => break,619             Some(',') => continue,620             Some(_) => return Err(syntax(line, "args array needs a comma between strings")),621         }622     }623     Ok(words)624 }625 626 fn arg_string(text: &str, line: usize) -> Result<String, BundleError> {627     let inner = text628         .strip_prefix('"')629         .and_then(|rest| rest.strip_suffix('"'))630         .ok_or_else(|| syntax(line, "args needs quotes or an array"))?;631     let mut out = String::with_capacity(inner.len());632     let mut chars = inner.chars();633     while let Some(ch) = chars.next() {634         match ch {635             '\\' => match chars.next() {636                 Some('\\') => out.push('\\'),637                 Some('"') => out.push('"'),638                 Some(other) => {639                     out.push('\\');640                     out.push(other);641                 }642                 None => return Err(syntax(line, "args ends with a backslash")),643             },644             '"' => return Err(syntax(line, "args contains an unescaped quote")),645             other => out.push(other),646         }647     }648     Ok(out)649 }650 651 fn split_words(text: &str, line: usize) -> Result<Vec<String>, BundleError> {652     let mut words = Vec::new();653     let mut word = String::new();654     let mut quoted = false;655     let mut quote = None;656     let mut escaped = false;657     for ch in text.chars() {658         if escaped {659             word.push(ch);660             quoted = true;661             escaped = false;662             continue;663         }664         match quote {665             Some('\'') => {666                 if ch == '\'' {667                     quote = None;668                 } else {669                     word.push(ch);670                 }671             }672             Some('"') => match ch {673                 '"' => quote = None,674                 '\\' => escaped = true,675                 other => word.push(other),676             },677             Some(_) => unreachable!(),678             None => match ch {679                 '\\' => escaped = true,680                 '\'' | '"' => {681                     quote = Some(ch);682                     quoted = true;683                 }684                 other if other.is_whitespace() => {685                     if quoted {686                         words.push(std::mem::take(&mut word));687                         quoted = false;688                     }689                 }690                 other => {691                     word.push(other);692                     quoted = true;693                 }694             },695         }696     }697     if escaped {698         return Err(syntax(line, "args ends with a backslash"));699     }700     if quote.is_some() {701         return Err(syntax(line, "args has an unclosed quote"));702     }703     if quoted {704         words.push(word);705     }706     Ok(words)707 }