From 9f3031babe4d798061b5f6e81c6219c64483ba18 Mon Sep 17 00:00:00 2001 From: Cameron Wight Date: Sat, 31 Oct 2026 01:56:12 +0000 Subject: [PATCH 01/11] Design packs: a saved design and the designs it links, in one zip (#3890 K12) file.pack writes the saved design and the designs its links name into one .zip to hand on. The design goes at the top level, each of its links pointing at designs/, and each linked design under designs/, byte for byte. Packs go one level deep: a linked design's own links are listed in the reply, not followed. Only design files are copied. - A pack holds the files as saved: a design with unsaved changes or no file is refused, and the design, its file and its links are left as they were. - Every linked file is found and sized before any is read, the total within MAX_PACK_BYTES, with at most MAX_PACK_ENTRIES entries. - Entry names are made from file names: characters a file name can't hold become `_`, no name ends in a dot or a space, a name Windows keeps for a device gets `_` after its stem, and a name another entry has, case aside, is numbered (plate.sc, plate-2.sc). Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + assets/locales/pending/file-pack.json | 13 ++ crates/engine/Cargo.toml | 2 + crates/engine/src/cmd/file.rs | 2 +- crates/engine/src/cmd/file_pack.rs | 111 ++++++++++ crates/engine/src/cmd/file_pack_tests.rs | 218 ++++++++++++++++++++ crates/engine/src/cmd/mod.rs | 2 + crates/engine/src/schema/file_pack.rs | 53 +++++ crates/engine/src/schema/file_pack_tests.rs | 8 + crates/engine/src/schema/mod.rs | 1 + crates/io/src/design.rs | 2 + crates/io/src/design/pack.rs | 116 +++++++++++ crates/io/src/design/pack_tests.rs | 87 ++++++++ crates/io/src/lib.rs | 7 +- 14 files changed, 619 insertions(+), 4 deletions(-) create mode 100644 assets/locales/pending/file-pack.json create mode 100644 crates/engine/src/cmd/file_pack.rs create mode 100644 crates/engine/src/cmd/file_pack_tests.rs create mode 100644 crates/engine/src/schema/file_pack.rs create mode 100644 crates/engine/src/schema/file_pack_tests.rs create mode 100644 crates/io/src/design/pack.rs create mode 100644 crates/io/src/design/pack_tests.rs diff --git a/Cargo.lock b/Cargo.lock index e5ef73d5fbd..6af830532de 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4305,6 +4305,7 @@ dependencies = [ "thiserror 2.0.21", "toml_edit", "web-time", + "zip", ] [[package]] diff --git a/assets/locales/pending/file-pack.json b/assets/locales/pending/file-pack.json new file mode 100644 index 00000000000..659e5a6b86f --- /dev/null +++ b/assets/locales/pending/file-pack.json @@ -0,0 +1,13 @@ +{ + "en": { "cmd.file_pack": "Pack Design" }, + "ar": { "cmd.file_pack": "حزم التصميم" }, + "de": { "cmd.file_pack": "Konstruktion packen" }, + "es": { "cmd.file_pack": "Empaquetar diseño" }, + "fr": { "cmd.file_pack": "Empaqueter la conception" }, + "he": { "cmd.file_pack": "אריזת תכן" }, + "ja": { "cmd.file_pack": "デザインをパック" }, + "ko": { "cmd.file_pack": "설계 묶기" }, + "vi": { "cmd.file_pack": "Đóng gói thiết kế" }, + "zh": { "cmd.file_pack": "打包设计" }, + "zh-TW": { "cmd.file_pack": "打包設計" } +} diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 4239cc0ae80..0f8d5f0a304 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -52,6 +52,8 @@ web-time = { workspace = true } solidcraft-io = { workspace = true, features = ["trust-unknown-source"] } # Normal CI exercises profiling assertions without enabling the production feature. solidcraft-sketch = { workspace = true, features = ["solver-profiling"] } +# Packs (file.pack) are read back to check what they hold. +zip = { workspace = true } [[example]] name = "render_resource_workflow" diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index c062624bb62..0914bbffd71 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -595,7 +595,7 @@ fn save(s: &mut Session, p: &Value) -> Result { ) } -fn default_design_format(path: &str) -> &'static str { +pub(super) fn default_design_format(path: &str) -> &'static str { if std::path::Path::new(path).extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("json")) { "json" } else { "container" } } diff --git a/crates/engine/src/cmd/file_pack.rs b/crates/engine/src/cmd/file_pack.rs new file mode 100644 index 00000000000..5a62e836fac --- /dev/null +++ b/crates/engine/src/cmd/file_pack.rs @@ -0,0 +1,111 @@ +//! `file.pack` (#3890 K12): the saved design and the designs its links name, in one `.zip` to hand +//! on. The design goes at the top level with each link pointing at `designs/`, and each +//! linked design under `designs/`, byte for byte. Packs go one level deep: a linked design's own +//! links are listed in the reply, not followed. Only design files are copied. +//! +//! A pack holds the files as saved, so a design with unsaved changes or no file is refused; the +//! design, its file and its links are left as they were. Every linked file is checked before any +//! is read, and the sizes are summed before any is read, within [`solidcraft_io::MAX_PACK_BYTES`]. + +use std::path::{Path, PathBuf}; + +use serde_json::Value; +use solidcraft_io::{MAX_PACK_DESIGNS, PACK_DESIGNS, PackWriter}; + +use super::CommandSpec; +use super::design_link::{absolute, resolve}; +use crate::params::bad; +use crate::schema::file_pack::{DeeperLink, PackParams, PackResult, PackedDesign}; +use crate::schema::{TypedContract, output_schema_for}; +use crate::{EngineError, Result, Session}; + +const CMD: &str = "file.pack"; +const CONTRACT: TypedContract = TypedContract::new(); +/// The longest path taken, in bytes, as `drawing.export`'s. +const MAX_PATH_BYTES: usize = 4096; + +pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new(CMD, "Pack Design", crate::checked!("file.pack", pack)) + .any_part() + .icon("export") + .noundo() + .doc_only() + .contract(&CONTRACT) + .output(output_schema_for::) + .params("path: .zip file → {path, bytes, design, designs: [{file, entry}], deeper: [{design, path}]}. The saved design at the top level, its links pointing at designs/, and each design its links name under designs/, byte for byte, once each; a linked design's own links are listed in deeper, not followed. Refused when the design has no file or unsaved changes, or a linked file can't be read or isn't a design; at most 1 GiB in all.")]; + +fn pack(s: &mut Session, p: &Value) -> Result { + let request: PackParams = crate::schema::read(CMD, p)?; + let path = request.path; + if path.len() > MAX_PATH_BYTES || !solidcraft_io::is_pack_path(&path) { + return Err(bad(CMD, "path must be a .zip file")); + } + let io = |e: std::io::Error| EngineError::Other(e.to_string()); + solidcraft_io::vfs::check(&path).map_err(io)?; + let own = s.path.clone().ok_or_else(|| bad(CMD, "the design has no file yet: save it first"))?; + if s.is_dirty() { + return Err(bad(CMD, "the design has unsaved changes: save it first")); + } + let files = linked_files(s, &own)?; + // Every file checked from its text, then measured, before any is read. + for (file, link) in &files { + solidcraft_io::vfs::check_design_path(&file.to_string_lossy(), Some(&own)).map_err(|e| bad(CMD, format!("{link}: {e}")))?; + } + let mut total = 0u64; + for (file, link) in &files { + total = total.saturating_add(solidcraft_io::vfs::len(&file.to_string_lossy()).map_err(|e| bad(CMD, format!("{link}: {e}")))?); + } + solidcraft_io::fits_pack(total).map_err(|e| bad(CMD, e.to_string()))?; + + let mut pack = PackWriter::default(); + let (mut designs, mut deeper) = (Vec::new(), Vec::new()); + let mut doc = s.design_at(None).into_owned(); + for (file, link) in &files { + let shown = file.to_string_lossy(); + let bytes = solidcraft_io::vfs::read_design_path(&shown, Some(&own), solidcraft_io::limits::max_design_bytes()) + .map_err(|e| bad(CMD, format!("{link}: {}", solidcraft_io::limits::explain(solidcraft_io::limits::Kind::Design, e))))?; + // Only a design is copied: anything else is refused by its link alone, never quoted. + let linked = solidcraft_io::read_design(&bytes).map_err(|_| bad(CMD, format!("{link}: not a design file")))?; + let name = file.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let entry = pack.add(Some(PACK_DESIGNS), &name, &bytes).map_err(|e| bad(CMD, e.to_string()))?; + for l in doc.links.values_mut().filter(|l| absolute(&resolve(Some(&own), &l.path)) == *file) { + l.path.clone_from(&entry); + } + deeper.extend(linked.links.values().map(|l| DeeperLink { design: entry.clone(), path: l.path.clone() })); + designs.push(PackedDesign { file: shown.into_owned(), entry }); + } + let top = match super::file::default_design_format(&own) { + "json" => solidcraft_io::write_design(&doc), + _ => solidcraft_io::write_design_container(&doc).map_err(|e| bad(CMD, e.to_string()))?, + }; + let name = Path::new(&own).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let design = pack.add(None, &name, &top).map_err(|e| bad(CMD, e.to_string()))?; + let bytes = pack.finish().map_err(|e| bad(CMD, e.to_string()))?; + // Checked again just before writing, as drawing.export does. + solidcraft_io::vfs::check(&path).map_err(io)?; + solidcraft_io::write_atomic(Path::new(&path), &bytes, false).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; + let reply = PackResult { path, bytes: bytes.len(), design, designs, deeper, param_warnings: Vec::new() }; + serde_json::to_value(reply).map_err(|e| EngineError::Other(e.to_string())) +} + +/// Each file the design's links name, once, in link order, with the link that names it first +/// (as the design keeps it, for messages). The design itself is never one of them. +fn linked_files(s: &Session, own: &str) -> Result> { + let mut files: Vec<(PathBuf, String)> = Vec::new(); + for link in s.doc.links.values() { + let file = absolute(&resolve(Some(own), &link.path)); + if file == absolute(Path::new(own)) { + return Err(bad(CMD, format!("{}: a design can't be packed as its own link", link.path))); + } + if !files.iter().any(|(f, _)| *f == file) { + files.push((file, link.path.clone())); + } + } + if files.len() > MAX_PACK_DESIGNS { + return Err(bad(CMD, format!("the design links {} files; a pack holds at most {MAX_PACK_DESIGNS}", files.len()))); + } + Ok(files) +} + +#[cfg(test)] +#[path = "file_pack_tests.rs"] +mod tests; diff --git a/crates/engine/src/cmd/file_pack_tests.rs b/crates/engine/src/cmd/file_pack_tests.rs new file mode 100644 index 00000000000..72bcca11cc4 --- /dev/null +++ b/crates/engine/src/cmd/file_pack_tests.rs @@ -0,0 +1,218 @@ +use std::io::Read; +use std::path::Path; + +use serde_json::{Value, json}; + +use super::*; +use crate::schema::tests::conforms; +use crate::tests::Folder; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")) +} + +fn refused(s: &mut Session, p: Value) -> String { + s.execute(CMD, &p).err().map(|e| e.to_string()).unwrap_or_else(|| panic!("packed: {p}")) +} + +/// A box `height` mm high called Plate, saved at `path`. +fn save_box(path: &str, height: f64) { + let mut part = Session::default(); + run(&mut part, "solid.box", json!({"length": 10, "width": 20, "height": height, "body_name": "Plate"})); + run(&mut part, "file.save", json!({"path": path})); +} + +fn volume(s: &mut Session) -> f64 { + run(s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap() +} + +/// A design saved at `path` linking each of `parts`. +fn assembly(path: &str, parts: &[&str]) -> Session { + let mut s = Session::default(); + for part in parts { + run(&mut s, "component.insert_design", json!({"path": part})); + } + run(&mut s, "file.save", json!({"path": path})); + s +} + +/// Each entry of the pack at `path`, by name, unpacked into `into`. +fn unpack(path: &str, into: &Path) -> Vec<(String, Vec)> { + let mut zip = zip::ZipArchive::new(std::fs::File::open(path).unwrap()).unwrap(); + let mut entries = Vec::new(); + for i in 0..zip.len() { + let mut file = zip.by_index(i).unwrap(); + let name = file.name().unwrap().into_owned(); + let mut bytes = Vec::new(); + file.read_to_end(&mut bytes).unwrap(); + let to = into.join(&name); + std::fs::create_dir_all(to.parent().unwrap()).unwrap(); + std::fs::write(&to, &bytes).unwrap(); + entries.push((name, bytes)); + } + entries +} + +/// A pack holds the design at the top level and each design its links name once under +/// `designs/`, byte for byte; unpacked anywhere it opens with every link found and the same +/// model. The design, its file and its links are left as they were. +#[test] +fn a_pack_opens_anywhere_with_every_link_found() { + let folder = Folder::new("pack-links"); + std::fs::create_dir_all(folder.0.join("parts")).unwrap(); + std::fs::create_dir_all(folder.0.join("asm")).unwrap(); + let plate = folder.path("parts/plate.solidcraft"); + save_box(&plate, 30.0); + let case = folder.path("asm/case.solidcraft"); + // Two placements of one linked design: one file in the pack. + let mut s = assembly(&case, &[&plate, &plate]); + let (before, saved, doc) = (volume(&mut s), std::fs::read(&case).unwrap(), s.doc.clone()); + let zip = folder.path("out.zip"); + let reply = run(&mut s, CMD, json!({"path": zip})); + let schema = output_schema_for::(); + assert!(conforms(schema.as_value(), schema.as_value(), &reply), "{reply}"); + assert_eq!( + (&reply["design"], &reply["designs"][0]["entry"], &reply["deeper"]), + (&json!("case.solidcraft"), &json!("designs/plate.solidcraft"), &json!([])) + ); + assert_eq!(reply["designs"].as_array().map(Vec::len), Some(1), "{reply}"); + assert_eq!(reply["bytes"].as_u64(), Some(std::fs::metadata(&zip).unwrap().len())); + let elsewhere = Folder::new("pack-links-unpacked"); + let entries = unpack(&zip, &elsewhere.0); + let names: Vec<&str> = entries.iter().map(|(n, _)| n.as_str()).collect(); + assert_eq!(names, ["designs/plate.solidcraft", "case.solidcraft"]); + assert_eq!(entries[0].1, std::fs::read(&plate).unwrap(), "byte for byte"); + let mut opened = Session::default(); + run(&mut opened, "doc.open", json!({"path": elsewhere.path("case.solidcraft")})); + let links = run(&mut opened, "component.links", json!({})); + for link in links["links"].as_array().unwrap() { + assert_eq!(link["found"], true, "{links}"); + assert_eq!(super::absolute(Path::new(link["file"].as_str().unwrap())), super::absolute(&elsewhere.0.join("designs/plate.solidcraft"))); + } + assert!((volume(&mut opened) - before).abs() < 1e-6); + // Nothing here changed. + assert_eq!(std::fs::read(&case).unwrap(), saved); + assert!(std::sync::Arc::ptr_eq(&doc, &s.doc) && !s.is_dirty() && s.path.as_deref() == Some(case.as_str())); +} + +/// Linked files of one name are numbered apart, and a linked design's own links are listed, not +/// followed: the pack goes one level deep. +#[test] +fn names_are_numbered_apart_and_deeper_links_listed() { + let folder = Folder::new("pack-names"); + for dir in ["a", "b"] { + std::fs::create_dir_all(folder.0.join(dir)).unwrap(); + } + let (first, second, bolt) = (folder.path("a/plate.solidcraft"), folder.path("b/plate.solidcraft"), folder.path("b/bolt.solidcraft")); + save_box(&first, 30.0); + save_box(&bolt, 5.0); + assembly(&second, &[&bolt]); + let mut s = assembly(&folder.path("case.solidcraft"), &[&first, &second]); + let reply = run(&mut s, CMD, json!({"path": folder.path("case.zip")})); + let entries: Vec<&str> = reply["designs"].as_array().unwrap().iter().map(|d| d["entry"].as_str().unwrap()).collect(); + assert_eq!(entries, ["designs/plate.solidcraft", "designs/plate-2.solidcraft"]); + assert_eq!(reply["deeper"], json!([{"design": "designs/plate-2.solidcraft", "path": "bolt.solidcraft"}])); + let elsewhere = Folder::new("pack-names-unpacked"); + unpack(&folder.path("case.zip"), &elsewhere.0); + let mut opened = Session::default(); + run(&mut opened, "doc.open", json!({"path": elsewhere.path("case.solidcraft")})); + let links = run(&mut opened, "component.links", json!({})); + assert!(links["links"].as_array().unwrap().iter().all(|l| l["found"] == true), "{links}"); +} + +/// A design with no file or unsaved changes, a path that isn't a .zip, and a link to a file that +/// can't be read, a device, a network location not allowed, the design itself or anything that +/// isn't a design are refused, and nothing is written. A refused link is named by its path, never +/// by what the file holds, and one judged from its text asks nothing of the disk. +#[test] +fn what_cant_be_packed_is_refused_and_nothing_is_written() { + let folder = Folder::new("pack-refused"); + let zip = folder.path("out.zip"); + let mut s = Session::default(); + assert!(refused(&mut s, json!({"path": zip})).contains("no file yet")); + let plate = folder.path("plate.solidcraft"); + save_box(&plate, 30.0); + let case = folder.path("case.solidcraft"); + let mut s = assembly(&case, &[&plate]); + for (path, why) in [ + (json!(folder.path("out.svg")), "path must be a .zip file"), + (json!(folder.path("zip")), "path must be a .zip file"), + (json!(format!("{}.zip", "a".repeat(MAX_PATH_BYTES))), "path must be a .zip file"), + (json!(5), "path"), + ] { + let e = refused(&mut s, json!({"path": path})); + assert!(e.contains(why), "{path}: {e}"); + } + assert!(refused(&mut s, json!({})).contains("path")); + run(&mut s, "solid.box", json!({"length": 1, "width": 1, "height": 1})); + assert!(refused(&mut s, json!({"path": zip})).contains("unsaved changes")); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "file.save", json!({})); + // Not a design: refused by its link alone. + std::fs::write(&plate, "a key that must never be copied").unwrap(); + let e = refused(&mut s, json!({"path": zip})); + assert!(e.contains("not a design file") && !e.contains("never be copied"), "{e}"); + std::fs::remove_file(&plate).unwrap(); + assert!(refused(&mut s, json!({"path": zip})).contains("plate.solidcraft")); + // Links judged from their text before the disk is asked. + for (link, why) in [(r"\\server\share\plate.solidcraft", "network location"), ("NUL", "device"), (case.as_str(), "its own link")] { + let component = *s.doc.links.keys().next().unwrap(); + s.doc_mut().links.get_mut(&component).unwrap().path = link.to_string(); + run(&mut s, "file.save", json!({})); + let calls = solidcraft_io::vfs::file_calls(); + let e = refused(&mut s, json!({"path": zip})); + assert!(e.contains(why), "{link}: {e}"); + assert_eq!(solidcraft_io::vfs::file_calls(), calls, "{link}: nothing asked of the disk"); + } + // More than a pack holds in all: refused from the files' sizes, before any is read. + let big = folder.path("big.solidcraft"); + std::fs::File::create(&big).unwrap().set_len(solidcraft_io::MAX_PACK_BYTES + 1).unwrap(); + let component = *s.doc.links.keys().next().unwrap(); + s.doc_mut().links.get_mut(&component).unwrap().path = big.clone(); + run(&mut s, "file.save", json!({})); + let e = refused(&mut s, json!({"path": zip})); + assert!(e.contains("a pack holds at most 1024 MiB"), "{e}"); + std::fs::remove_file(&big).unwrap(); + assert!(!Path::new(&zip).exists()); +} + +/// A design saved as JSON goes in the pack as JSON, its link pointing into the pack. +#[test] +fn a_json_design_is_packed_as_json() { + let folder = Folder::new("pack-json"); + let plate = folder.path("plate.solidcraft"); + save_box(&plate, 30.0); + let case = folder.path("case.json"); + let mut s = assembly(&case, &[&plate]); + let zip = folder.path("out.zip"); + assert_eq!(run(&mut s, CMD, json!({"path": zip}))["design"], json!("case.json")); + let elsewhere = Folder::new("pack-json-unpacked"); + let entries = unpack(&zip, &elsewhere.0); + let top = entries.iter().find(|(name, _)| name == "case.json").map(|(_, bytes)| bytes).unwrap(); + let top: Value = serde_json::from_slice(top).unwrap(); + assert!(top.to_string().contains("designs/plate.solidcraft"), "{top}"); +} + +/// A pack carries at most `MAX_PACK_DESIGNS` linked files: one more is refused from the links alone. +#[test] +fn a_pack_carries_at_most_its_designs() { + let folder = Folder::new("pack-cap"); + let plate = folder.path("plate.solidcraft"); + save_box(&plate, 30.0); + let case = folder.path("case.solidcraft"); + let mut s = assembly(&case, &[&plate]); + let link = s.doc.links.values().next().cloned().unwrap(); + let mut files = |n: usize| { + s.doc_mut().links = (1..=n as u64) + .map(|i| { + let mut link = link.clone(); + link.path = folder.path(&format!("part-{i}.solidcraft")); + (i, link) + }) + .collect(); + linked_files(&s, &case).map(|files| files.len()).map_err(|e| e.to_string()) + }; + assert_eq!(files(MAX_PACK_DESIGNS), Ok(MAX_PACK_DESIGNS)); + let e = files(MAX_PACK_DESIGNS + 1).unwrap_err(); + assert!(e.contains("a pack holds at most 256"), "{e}"); +} diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index bb549d974f8..67a19820cef 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -64,6 +64,7 @@ pub use component_link::resolve_design_links; mod config; mod design_link; mod file; +mod file_pack; mod frame; pub(crate) mod inspect; mod interference; @@ -374,6 +375,7 @@ pub fn command_specs() -> Vec<&'static CommandSpec> { v.extend(parameters::COMMANDS.iter()); v.extend(parameter_sweep::COMMANDS.iter()); v.extend(file::COMMANDS.iter()); + v.extend(file_pack::COMMANDS.iter()); v.extend(metadata::COMMANDS.iter()); v.extend(inspect::COMMANDS.iter()); v.extend(compare::COMMANDS.iter()); diff --git a/crates/engine/src/schema/file_pack.rs b/crates/engine/src/schema/file_pack.rs new file mode 100644 index 00000000000..65ff3776e4a --- /dev/null +++ b/crates/engine/src/schema/file_pack.rs @@ -0,0 +1,53 @@ +//! Contracts and result types for `file.pack` (`cmd/file_pack.rs`, #3890 K12). + +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +/// Pack the saved design and the designs its links name into one .zip to hand on. +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +#[schemars(deny_unknown_fields)] +pub struct PackParams { + /// The .zip file to write. + pub path: String, +} + +/// A linked design in the pack. +#[derive(Debug, Serialize, JsonSchema)] +pub struct PackedDesign { + /// The file it was copied from. + pub file: String, + /// Its name in the pack, under `designs/`. + pub entry: String, +} + +/// A link a linked design makes, left out of the pack: packs go one level deep. +#[derive(Debug, Serialize, JsonSchema)] +pub struct DeeperLink { + /// The linked design that makes it, by its name in the pack. + pub design: String, + /// The link's path as that design keeps it. + pub path: String, +} + +/// What `file.pack` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct PackResult { + /// The .zip file written. + pub path: String, + /// Its size in bytes. + pub bytes: usize, + /// The design's name in the pack, at the top level. + pub design: String, + /// Each design its links name, once each, in link order. + pub designs: Vec, + /// The links those designs make, not followed. + pub deeper: Vec, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +#[cfg(test)] +#[path = "file_pack_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/file_pack_tests.rs b/crates/engine/src/schema/file_pack_tests.rs new file mode 100644 index 00000000000..c86dee39f15 --- /dev/null +++ b/crates/engine/src/schema/file_pack_tests.rs @@ -0,0 +1,8 @@ +use super::PackParams; +use crate::schema::input_schema_for; +use crate::schema::tests::assert_keys; + +#[test] +fn schemas_and_the_key_check_agree() { + assert_keys(input_schema_for::(), &["path"]); +} diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs index 4857f7eb387..e7575445a71 100644 --- a/crates/engine/src/schema/mod.rs +++ b/crates/engine/src/schema/mod.rs @@ -66,6 +66,7 @@ pub mod drawing_sheet; pub mod drawing_view; pub mod edit; pub mod features; +pub mod file_pack; pub mod inspect; pub mod render; pub mod render_lights; diff --git a/crates/io/src/design.rs b/crates/io/src/design.rs index 17290bbd0c1..6673ed1e9c6 100644 --- a/crates/io/src/design.rs +++ b/crates/io/src/design.rs @@ -7,8 +7,10 @@ use std::sync::Arc; mod drawing; mod native_cache; +mod pack; mod thumbnail; pub use native_cache::read_design_geometry; +pub use pack::{MAX_PACK_BYTES, MAX_PACK_DESIGNS, MAX_PACK_ENTRIES, PACK_DESIGNS, PackWriter, fits_pack, is_pack_path}; pub use thumbnail::{THUMBNAIL_SIZE, read_design_thumbnail, read_design_thumbnail_file}; use serde_json::{Map, Value, json}; diff --git a/crates/io/src/design/pack.rs b/crates/io/src/design/pack.rs new file mode 100644 index 00000000000..b782b7d0b49 --- /dev/null +++ b/crates/io/src/design/pack.rs @@ -0,0 +1,116 @@ +//! A design and the designs it links, packed into one `.zip` to hand on (#3890 K12): the design +//! at the top level and each linked design under [`PACK_DESIGNS`]. The pack is built in memory, +//! one file added at a time, within [`MAX_PACK_BYTES`] and [`MAX_PACK_ENTRIES`]. +//! +//! Entry names are made here from file names, never taken whole from a link: a control +//! character or one of `/ \ : < > " | ? *` becomes `_`, no name ends in `.` or a space, a name +//! Windows keeps for a device gets `_` after its stem, and a name another entry has, case aside, +//! is numbered (`plate.sc`, `plate-2.sc`). + +use std::collections::BTreeSet; +use std::io::{Cursor, Write}; + +use super::is_design_container; +use crate::{IoError, Result}; + +/// A pack's file extension. +pub const PACK_EXT: &str = "zip"; +/// The folder the linked designs go in. +pub const PACK_DESIGNS: &str = "designs"; +/// The most a pack holds in all: it is built in memory, and read back the same way. +pub const MAX_PACK_BYTES: u64 = 1 << 30; +/// The most other designs a pack carries: the files a design's links name and, once drawings +/// name files of their own, its drawings' sources, counted together. +pub const MAX_PACK_DESIGNS: usize = 256; +/// The most files a pack holds: the design and the designs it names. +pub const MAX_PACK_ENTRIES: usize = 1 + MAX_PACK_DESIGNS; + +/// Whether `path` names a pack (`.zip`, any case). +pub fn is_pack_path(path: &str) -> bool { + std::path::Path::new(path).extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case(PACK_EXT)) +} + +/// Refuse files that come to more than a pack holds. +pub fn fits_pack(bytes: u64) -> Result<()> { + if bytes > MAX_PACK_BYTES { + return Err(IoError::Invalid(format!( + "the files come to {} MiB; a pack holds at most {} MiB", + bytes.div_ceil(1 << 20), + MAX_PACK_BYTES >> 20 + ))); + } + Ok(()) +} + +/// A pack being written. Each file goes in as it is added, so only the pack and one file are +/// held at once. +pub struct PackWriter { + zip: zip::ZipWriter>>, + /// Each entry's name in lower case, to keep names apart on systems that ignore case. + names: BTreeSet, + bytes: u64, +} + +impl Default for PackWriter { + fn default() -> PackWriter { + PackWriter { zip: zip::ZipWriter::new(Cursor::new(Vec::new())), names: BTreeSet::new(), bytes: 0 } + } +} + +impl PackWriter { + /// `bytes` as the file named `name` under `folder` (`None`: the top level): the entry's name. + /// A design container is stored as it is (it is compressed already); anything else deflated. + pub fn add(&mut self, folder: Option<&str>, name: &str, bytes: &[u8]) -> Result { + if self.names.len() >= MAX_PACK_ENTRIES { + return Err(IoError::Invalid(format!("a pack holds at most {MAX_PACK_ENTRIES} files"))); + } + self.bytes = self.bytes.saturating_add(bytes.len() as u64); + fits_pack(self.bytes)?; + let entry = self.unique(folder, &entry_name(name))?; + let method = if is_design_container(bytes) { zip::CompressionMethod::Stored } else { zip::CompressionMethod::Deflated }; + let invalid = |e: zip::result::ZipError| IoError::Invalid(format!("pack: {e}")); + self.zip.start_file(entry.as_str(), zip::write::SimpleFileOptions::default().compression_method(method)).map_err(invalid)?; + self.zip.write_all(bytes).map_err(|e| IoError::Invalid(format!("pack: {e}")))?; + Ok(entry) + } + + /// The pack's bytes. + pub fn finish(self) -> Result> { + Ok(self.zip.finish().map_err(|e| IoError::Invalid(format!("pack: {e}")))?.into_inner()) + } + + /// `name` under `folder`, numbered when another entry has it, case aside. + fn unique(&mut self, folder: Option<&str>, name: &str) -> Result { + let (stem, ext) = match name.rsplit_once('.') { + Some((stem, ext)) if !stem.is_empty() => (stem, format!(".{ext}")), + _ => (name, String::new()), + }; + let candidates = std::iter::once(name.to_string()).chain((2..=MAX_PACK_ENTRIES).map(|n| format!("{stem}-{n}{ext}"))); + for candidate in candidates { + let entry = folder.map_or_else(|| candidate.clone(), |folder| format!("{folder}/{candidate}")); + if self.names.insert(entry.to_lowercase()) { + return Ok(entry); + } + } + Err(IoError::Invalid(format!("a pack holds at most {MAX_PACK_ENTRIES} files"))) + } +} + +/// `name` as an entry may have it (the module's notes), before numbering. +fn entry_name(name: &str) -> String { + let kept: String = + name.chars().map(|c| if c.is_control() || matches!(c, '/' | '\\' | ':' | '<' | '>' | '"' | '|' | '?' | '*') { '_' } else { c }).collect(); + let kept = kept.trim_end_matches([' ', '.']); + let kept = if kept.is_empty() { "file" } else { kept }; + if crate::vfs::remote(kept) != Some(crate::vfs::Remote::Device) { + return kept.to_string(); + } + match kept.split_once('.') { + Some((stem, rest)) => format!("{stem}_.{rest}"), + None => format!("{kept}_"), + } +} + +#[cfg(test)] +#[path = "pack_tests.rs"] +mod tests; diff --git a/crates/io/src/design/pack_tests.rs b/crates/io/src/design/pack_tests.rs new file mode 100644 index 00000000000..bd418385682 --- /dev/null +++ b/crates/io/src/design/pack_tests.rs @@ -0,0 +1,87 @@ +use std::io::{Cursor, Read}; + +use super::*; + +/// Each entry of `pack`: its name, how it is stored and its bytes. +fn entries(pack: &[u8]) -> Vec<(String, zip::CompressionMethod, Vec)> { + let mut zip = zip::ZipArchive::new(Cursor::new(pack)).unwrap(); + (0..zip.len()) + .map(|i| { + let mut file = zip.by_index(i).unwrap(); + let mut bytes = Vec::new(); + file.read_to_end(&mut bytes).unwrap(); + (file.name().unwrap().into_owned(), file.compression(), bytes) + }) + .collect() +} + +/// Files go in with the bytes given: a design container stored as it is, anything else +/// deflated; the top-level file and the linked designs under `designs/`. +#[test] +fn files_go_in_as_given() { + let container = b"PK\x03\x04 a design container's bytes".to_vec(); + let json = br#"{"format": "solidcraft/1"}"#.repeat(40); + let mut pack = PackWriter::default(); + assert_eq!(pack.add(None, "case.sc", &container).unwrap(), "case.sc"); + assert_eq!(pack.add(Some(PACK_DESIGNS), "plate.json", &json).unwrap(), "designs/plate.json"); + let got = entries(&pack.finish().unwrap()); + assert_eq!( + got, + [ + ("case.sc".to_string(), zip::CompressionMethod::Stored, container), + ("designs/plate.json".to_string(), zip::CompressionMethod::Deflated, json) + ] + ); +} + +/// A name another entry has, case aside, is numbered before its extension; the same bytes under +/// two names are two entries. +#[test] +fn clashing_names_are_numbered() { + let mut pack = PackWriter::default(); + let names: Vec = + ["plate.sc", "Plate.SC", "plate.sc", "plate", "PLATE"].iter().map(|n| pack.add(Some(PACK_DESIGNS), n, b"x").unwrap()).collect(); + assert_eq!(names, ["designs/plate.sc", "designs/Plate-2.SC", "designs/plate-3.sc", "designs/plate", "designs/PLATE-2"]); + // The same name at the top level is another entry. + assert_eq!(pack.add(None, "plate.sc", b"x").unwrap(), "plate.sc"); + assert_eq!(entries(&pack.finish().unwrap()).len(), 6); +} + +/// A name is made safe to unpack anywhere: no separators, drive or reserved characters, no +/// control characters, no `.` or space at the end, never empty, and never a device's name. +#[test] +fn names_are_made_safe() { + for (given, made) in [ + ("../../etc/passwd", ".._.._etc_passwd"), + (r"C:\parts\plate.sc", "C__parts_plate.sc"), + ("ac:d\"e|f?g*h.sc", "a_b_c_d_e_f_g_h.sc"), + ("tab\there\n.sc", "tab_here_.sc"), + ("plate.sc. . ", "plate.sc"), + ("", "file"), + ("...", "file"), + ("CON", "CON_"), + ("nul.sc", "nul_.sc"), + ("com1.part.sc", "com1_.part.sc"), + ("LPT9", "LPT9_"), + ("console.sc", "console.sc"), + ("プレート.sc", "プレート.sc"), + ] { + assert_eq!(entry_name(given), made, "{given:?}"); + } +} + +/// No more than MAX_PACK_ENTRIES files, and the bytes are counted as they are added: the file +/// that takes the pack past MAX_PACK_BYTES is refused. +#[test] +fn caps_hold() { + let mut pack = PackWriter::default(); + for i in 0..MAX_PACK_ENTRIES { + pack.add(Some(PACK_DESIGNS), &format!("d{i}.sc"), b"x").unwrap(); + } + let e = pack.add(Some(PACK_DESIGNS), "one-more.sc", b"x").unwrap_err().to_string(); + assert!(e.contains(&format!("at most {MAX_PACK_ENTRIES} files")), "{e}"); + assert!(fits_pack(MAX_PACK_BYTES).is_ok()); + let e = fits_pack(MAX_PACK_BYTES + 1).unwrap_err().to_string(); + assert_eq!(e, "the files come to 1025 MiB; a pack holds at most 1024 MiB"); + assert!(is_pack_path("a/b.ZIP") && is_pack_path("b.zip") && !is_pack_path("b.zip.sc") && !is_pack_path("zip")); +} diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 5ebd90fd05c..4b430db2894 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -15,9 +15,10 @@ mod dxf; mod dxf_out; pub mod formats; pub use design::{ - DesignCompression, DesignContainerReader, DesignPreview, THUMBNAIL_SIZE, is_design_container, read_design_file, read_design_geometry, - read_design_preview, read_design_thumbnail, read_design_thumbnail_file, write_design_container, write_design_container_with_cache, - write_design_container_with_compression, write_design_container_with_preview, write_design_container_with_thumbnail, + DesignCompression, DesignContainerReader, DesignPreview, MAX_PACK_BYTES, MAX_PACK_DESIGNS, MAX_PACK_ENTRIES, PACK_DESIGNS, PackWriter, + THUMBNAIL_SIZE, fits_pack, is_design_container, is_pack_path, read_design_file, read_design_geometry, read_design_preview, read_design_thumbnail, + read_design_thumbnail_file, write_design_container, write_design_container_with_cache, write_design_container_with_compression, + write_design_container_with_preview, write_design_container_with_thumbnail, }; mod legacy_dir; pub mod limits; From 2d150a366adabdfe089d1ee658d7df5547d80103 Mon Sep 17 00:00:00 2001 From: Cameron Wight Date: Wed, 11 Nov 2026 19:54:20 +0000 Subject: [PATCH 02/11] progress: claim kept alive Co-Authored-By: Claude Opus 5.5 From 834c2d64787d9a3e86abbb2815f34ae19aaf832b Mon Sep 17 00:00:00 2001 From: Cameron Wight Date: Sat, 14 Nov 2026 07:06:46 +0000 Subject: [PATCH 03/11] progress: claim kept alive Co-Authored-By: Claude Opus 5.5 From 5b129b624209a5da395a3052a07c67d314d1c414 Mon Sep 17 00:00:00 2001 From: Cameron Wight Date: Sun, 15 Nov 2026 19:39:03 +0000 Subject: [PATCH 04/11] progress: claim kept alive Co-Authored-By: Claude Opus 5.5 From 2ca5dfa595274f15605de52b71a86969143b4f70 Mon Sep 17 00:00:00 2001 From: Cameron Wight Date: Wed, 18 Nov 2026 01:15:52 +0000 Subject: [PATCH 05/11] Keepalive: work in progress continues locally (no change) Co-Authored-By: Claude Opus 5.5 From 87725f84a8fc8f1e836362576ba973fc005e88f8 Mon Sep 17 00:00:00 2001 From: Cameron Wight Date: Sat, 21 Nov 2026 06:29:49 +0000 Subject: [PATCH 06/11] keepalive Co-Authored-By: Claude Opus 5.5 From 2f384bdf07fc97dafd3507116743c4e8b2049548 Mon Sep 17 00:00:00 2001 From: Cameron Wight Date: Mon, 23 Nov 2026 05:28:13 +0000 Subject: [PATCH 07/11] keepalive Co-Authored-By: Claude Opus 5.5 From db6860a7de6604c52f9b11254ee3b89d48a437c7 Mon Sep 17 00:00:00 2001 From: Cameron Wight Date: Wed, 25 Nov 2026 10:33:50 +0000 Subject: [PATCH 08/11] progress: claim kept alive Co-Authored-By: Claude Opus 5.5 From 133d39f5f141e308e31e50333e6541918356a0f2 Mon Sep 17 00:00:00 2001 From: Cameron Wight Date: Sat, 28 Nov 2026 06:28:10 +0000 Subject: [PATCH 09/11] progress: claim kept alive Co-Authored-By: Claude Opus 5.5 From 00ed0c10f78b2186b7c947c6f2b815cbcaa350f5 Mon Sep 17 00:00:00 2001 From: Cameron Wight Date: Tue, 1 Dec 2026 07:52:01 +0000 Subject: [PATCH 10/11] progress: claim kept alive Co-Authored-By: Claude Opus 5.5 From ceddc3098d413df566f85dcb6725473490fb00b8 Mon Sep 17 00:00:00 2001 From: Cameron Wight Date: Thu, 3 Dec 2026 19:53:16 +0000 Subject: [PATCH 11/11] progress: claim kept alive Co-Authored-By: Claude Opus 5.5