fcproj-format: split and reassemble project bins and items (#3517)

Co-authored-by: whatever-industries <77seventy77@users.noreply.github.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-11-26 20:14:49 +01:00
1 parent 39c7c75c52
commit 0ebc5915b0
3 files changed
+218

No files matched your search

+2
View File
@@ -1,6 +1,8 @@
//! FilmCraft `.fcproj` JSON envelope, version detection and historical migrations.
//! Project and editor-view types are supplied by the caller.
#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))]
pub mod records;
use serde::{Deserialize, Serialize};
use serde_json::Value;
/// The `format` tag written in every envelope.
+138
View File
@@ -0,0 +1,138 @@
//! Reversible record boundaries for a FilmCraft project. A bin owns an ordered list of
//! references; each project item (including a sequence) has one payload. Fields outside
//! those boundaries stay in their original JSON objects, including editor and extension data.
//!
//! These types describe logical records, independent of directory names, hashing, and commits.
use crate::{FormatError, MIGRATIONS, check_supported, detect_bytes, migrate_with};
use serde::Deserialize;
use serde_json::{Map, Value};
use std::collections::BTreeMap;
type Result<T> = std::result::Result<T, FormatError>;
type Payloads = BTreeMap<u64, Value>;
// Reassembly follows links between separately supplied records, outside the JSON parser's
// recursion limit. A repeated or cyclic bin is also rejected on its second visit.
const MAX_BIN_DEPTH: usize = 64;
/// The envelope carries the root bin ID and a complete inventory of item IDs, including
/// items outside any bin. The map keys are persisted project IDs, never display names.
#[derive(Debug)]
pub struct ProjectRecords {
pub envelope: Value,
pub bins: BTreeMap<u64, Value>,
pub items: BTreeMap<u64, Value>,
}
fn corrupt(message: impl Into<String>) -> FormatError {
FormatError::Corrupt(message.into())
}
fn object_id(value: &Value) -> Result<u64> {
value.get("id").and_then(Value::as_u64).ok_or_else(|| corrupt("record lacks an unsigned id"))
}
fn children(bin: &mut Value, depth: usize) -> Result<&mut Vec<Value>> {
if depth > MAX_BIN_DEPTH {
return Err(corrupt("bin nesting exceeds the supported depth"));
}
bin.get_mut("children").and_then(Value::as_array_mut).ok_or_else(|| corrupt("bin lacks children"))
}
// Only nested bins change representation. Item references retain their original position.
fn nested_or_item<'a>(child: &'a mut Value, items: &Payloads) -> Result<Option<&'a mut Value>> {
let entry = child.as_object_mut().filter(|o| o.len() == 1).ok_or_else(|| corrupt("invalid bin entry"))?;
if let Some(item) = entry.get("Item") {
let id = item.as_u64().ok_or_else(|| corrupt("invalid item reference"))?;
if !items.contains_key(&id) {
return Err(corrupt(format!("bin references missing item {id}")));
}
Ok(None)
} else {
entry.get_mut("Bin").map(Some).ok_or_else(|| corrupt("unknown bin entry"))
}
}
fn split_bin(mut bin: Value, bins: &mut Payloads, items: &Payloads, depth: usize) -> Result<u64> {
let id = object_id(&bin)?;
for child in children(&mut bin, depth)? {
if let Some(nested) = nested_or_item(child, items)? {
*nested = Value::from(split_bin(nested.take(), bins, items, depth + 1)?);
}
}
if bins.insert(id, bin).is_some() {
return Err(corrupt(format!("duplicate bin id {id}")));
}
Ok(id)
}
fn join_bin(reference: &Value, bins: &mut Payloads, items: &Payloads, depth: usize) -> Result<Value> {
let id = reference.as_u64().ok_or_else(|| corrupt("invalid bin reference"))?;
let mut bin = bins.remove(&id).ok_or_else(|| corrupt(format!("missing or repeated bin {id}")))?;
if object_id(&bin)? != id {
return Err(corrupt(format!("bin payload does not match id {id}")));
}
for child in children(&mut bin, depth)? {
if let Some(nested) = nested_or_item(child, items)? {
*nested = join_bin(nested, bins, items, depth + 1)?;
}
}
Ok(bin)
}
impl ProjectRecords {
/// Split supported project bytes, applying the same historical migrations as the
/// ordinary reader. Callers reading from storage must bound input size before parsing.
pub fn split(bytes: &[u8]) -> Result<Self> {
let version = detect_bytes(bytes)?;
let doc = serde_json::from_slice(bytes).map_err(|e| corrupt(e.to_string()))?;
let mut envelope = migrate_with(MIGRATIONS, doc, version)?;
let project = envelope.get_mut("project").and_then(Value::as_object_mut).ok_or_else(|| corrupt("missing project"))?;
let Some(Value::Object(payloads)) = project.remove("items") else { return Err(corrupt("missing project items")) };
let mut items = Payloads::new();
let mut inventory = Vec::with_capacity(payloads.len());
for (key, value) in payloads {
let id = object_id(&value)?;
if id.to_string() != key {
return Err(corrupt(format!("item key does not match id {id}")));
}
items.insert(id, value);
inventory.push(Value::from(id));
}
project.insert("items".into(), Value::Array(inventory));
let root = project.get_mut("root").ok_or_else(|| corrupt("missing root bin"))?;
let mut bins = Payloads::new();
*root = Value::from(split_bin(root.take(), &mut bins, &items, 0)?);
Ok(Self { envelope, bins, items })
}
/// Reassemble a complete set, refusing missing, extra or misidentified payloads.
/// A successful result preserves the migrated document as JSON, including unknown
/// fields; the application still validates timeline and media semantics on load.
pub fn into_document(mut self) -> Result<Value> {
let probe = crate::Probe::deserialize(&self.envelope).map_err(|e| corrupt(e.to_string()))?;
check_supported(crate::probe_version(&probe)?)?;
let project = self.envelope.get_mut("project").and_then(Value::as_object_mut).ok_or_else(|| corrupt("missing project"))?;
let root = project.get_mut("root").ok_or_else(|| corrupt("missing root bin"))?;
*root = join_bin(root, &mut self.bins, &self.items, 0)?;
if !self.bins.is_empty() {
return Err(corrupt("unreferenced bin payload"));
}
let Some(Value::Array(ids)) = project.remove("items") else { return Err(corrupt("missing item inventory")) };
let mut items = Map::new();
for key in ids {
let id = key.as_u64().ok_or_else(|| corrupt("invalid item inventory entry"))?;
let item = self.items.remove(&id).ok_or_else(|| corrupt(format!("missing or repeated item {id}")))?;
if object_id(&item)? != id {
return Err(corrupt(format!("item payload does not match id {id}")));
}
items.insert(id.to_string(), item);
}
if !self.items.is_empty() {
return Err(corrupt("unreferenced item payload"));
}
project.insert("items".into(), Value::Object(items));
Ok(self.envelope)
}
}
+78
View File
@@ -0,0 +1,78 @@
//! Original, generated project fragments exercise record ownership and preservation.
use craft_fcproj_format::{FormatError, MIGRATIONS, SCHEMA_VERSION, migrate_with, records::ProjectRecords};
use serde_json::{Value, json};
fn project() -> Value {
json!({
"format": "filmcraft.project", "schema_version": SCHEMA_VERSION, "view": {"tabs":[12]},
"generator": "test", "extra": [null, {}],
"project": {
"root": {"id":0,"name":"Cut","children":[
{"Item":12},{"Bin":{"id":19,"name":"Cut","children":[{"Item":4}]}}
]},
"items": {
"4":{"id":4,"media":{"path":"../offline/shot.mov"},"label":"A"},
"12":{"id":12,"sequence":{"nested":[4],"duration":123}},
"9":{"id":9,"name":"Unfiled","extra":{}}
},
"next_id":20, "transcripts":{}, "new_project_field":{"value":null}
}
})
}
fn split(doc: &Value) -> ProjectRecords {
ProjectRecords::split(&serde_json::to_vec(doc).unwrap()).unwrap()
}
#[test]
fn changing_one_sequence_preserves_all_other_records_and_the_view() {
let original = project();
let mut changed = original.clone();
changed["project"]["items"]["12"]["sequence"]["duration"] = json!(124);
let before = split(&original);
let after = split(&changed);
assert_eq!(before.envelope, after.envelope);
assert_eq!(before.bins, after.bins);
assert_eq!(before.items.keys().filter(|id| before.items[id] != after.items[id]).copied().collect::<Vec<_>>(), [12]);
assert_eq!(before.into_document().unwrap(), original);
assert_eq!(after.into_document().unwrap(), changed);
}
#[test]
fn legacy_uses_the_same_migrations_and_future_versions_are_refused() {
let mut bare = project()["project"].take();
bare["version"] = json!(1);
assert_eq!(split(&bare).into_document().unwrap(), migrate_with(MIGRATIONS, bare, 1).unwrap());
let mut doc = project();
doc["schema_version"] = json!(SCHEMA_VERSION + 1);
assert!(matches!(ProjectRecords::split(&serde_json::to_vec(&doc).unwrap()), Err(FormatError::TooNew { .. })));
}
#[test]
fn incomplete_or_conflicting_records_cannot_be_reassembled() {
let make = || split(&project());
let mut missing = make();
missing.items.remove(&9); // Unfiled; a bin traversal alone cannot detect the lost item.
assert!(missing.into_document().is_err());
let mut extra = make();
extra.items.insert(11, json!({"id":11}));
assert!(extra.into_document().is_err());
let mut cycle = make();
cycle.bins.get_mut(&19).unwrap()["children"] = json!([{"Bin":0}]);
assert!(cycle.into_document().is_err());
let mut mismatch = make();
mismatch.items.get_mut(&4).unwrap()["id"] = json!(19);
assert!(mismatch.into_document().is_err());
let mut detached = make();
detached.bins.get_mut(&0).unwrap()["children"] = json!([]);
assert!(detached.into_document().is_err());
}
#[test]
fn conversion_refuses_ambiguous_bins_and_dangling_membership() {
let mut doc = project();
doc["project"]["root"]["children"][1]["Bin"]["id"] = json!(0);
assert!(ProjectRecords::split(&serde_json::to_vec(&doc).unwrap()).is_err());
doc["project"]["root"]["children"] = json!([{"Item":100}]);
assert!(ProjectRecords::split(&serde_json::to_vec(&doc).unwrap()).is_err());
}