use std::collections::{BTreeMap, BTreeSet};
use crate::content::{BlobId, ContentStore, Storage};
use crate::model::{
AtomId, ChangeAtom, Content, CopyRecord, Flag, ImportProvenance, Ir, LossBoundary,
MetadataClaims, PathOp, RefRecord, SourceIdentity, TransformRecord,
};
use crate::status::EpistemicStatus;
use crate::{Error, Result};
#[derive(Debug, Clone)]
pub struct AtomDraft {
pub parents: Vec<AtomId>,
pub ops: Vec<PathOp>,
pub copies: Vec<CopyRecord>,
pub metadata: MetadataClaims,
pub source: SourceIdentity,
pub status: EpistemicStatus,
}
pub(crate) const DEFAULT_MAX_IR_OPS: usize = 200_000_000;
#[derive(Debug)]
pub struct IrBuilder {
content: ContentStore,
atoms: Vec<ChangeAtom>,
known: BTreeSet<AtomId>,
refs: Vec<RefRecord>,
provenance: ImportProvenance,
loss: LossBoundary,
flags: Vec<Flag>,
transforms: Vec<TransformRecord>,
max_ops: usize,
total_ops: usize,
}
impl IrBuilder {
#[must_use]
pub fn new(provenance: ImportProvenance) -> Self {
Self {
content: ContentStore::new(),
atoms: Vec::new(),
known: BTreeSet::new(),
refs: Vec::new(),
provenance,
loss: LossBoundary::default(),
flags: Vec::new(),
transforms: Vec::new(),
max_ops: DEFAULT_MAX_IR_OPS,
total_ops: 0,
}
}
pub fn with_storage(provenance: ImportProvenance, storage: &Storage) -> Result<Self> {
Ok(Self {
content: ContentStore::for_storage(storage)?,
atoms: Vec::new(),
known: BTreeSet::new(),
refs: Vec::new(),
provenance,
loss: LossBoundary::default(),
flags: Vec::new(),
transforms: Vec::new(),
max_ops: DEFAULT_MAX_IR_OPS,
total_ops: 0,
})
}
#[cfg(test)]
pub(crate) fn with_max_ops_for_test(mut self, max_ops: usize) -> Self {
self.max_ops = max_ops;
self
}
pub fn add_blob(&mut self, bytes: Vec<u8>) -> Result<BlobId> {
self.content.insert(bytes)
}
pub fn blob(&self, id: &BlobId) -> Result<Option<Vec<u8>>> {
self.content.get(id)
}
pub fn add_atom(&mut self, draft: AtomDraft) -> Result<AtomId> {
let mut ops = draft.ops;
let next_total = self.total_ops.saturating_add(ops.len());
if next_total > self.max_ops {
return Err(Error::ResourceLimit {
what: "the path-operation total in this artifact".to_string(),
ceiling: format!("{} operations", self.max_ops),
});
}
self.total_ops = next_total;
ops.sort_by(|a, b| a.path().cmp(b.path()));
for (a, b) in ops.iter().zip(ops.iter().skip(1)) {
if a.path() == b.path() {
return Err(Error::Invariant(format!(
"two ops on one path in one atom: {:?}",
a.path()
)));
}
}
for op in &ops {
if let Some(Content::Submodule { commit }) = op.content() {
if commit.len() != 20 && commit.len() != 32 {
return Err(Error::Invariant(format!(
"a submodule's commit id is {} bytes at {:?}, must be 20 or 32",
commit.len(),
op.path()
)));
}
}
}
let mut copies = draft.copies;
copies.sort_by(|a, b| (&a.to, &a.from, a.from_atom).cmp(&(&b.to, &b.from, b.from_atom)));
for (a, b) in copies.iter().zip(copies.iter().skip(1)) {
if (&a.to, &a.from, a.from_atom) == (&b.to, &b.from, b.from_atom) {
return Err(Error::Invariant(format!(
"two copy records with the same (to, from, from_atom): ({:?}, {:?}, {})",
a.to, a.from, a.from_atom
)));
}
}
for copy in &copies {
if !self.known.contains(©.from_atom) {
return Err(Error::Invariant(format!(
"copy of {:?} names from_atom {} which was not already added",
copy.from, copy.from_atom
)));
}
}
let mut atom = ChangeAtom {
id: AtomId([0u8; 32]),
parents: draft.parents,
ops,
copies,
metadata: draft.metadata,
source: draft.source,
status: draft.status,
};
atom.id = atom.compute_id();
let id = atom.id;
self.known.insert(id);
self.atoms.push(atom);
Ok(id)
}
pub fn add_ref(&mut self, record: RefRecord) -> Result<()> {
if !self.known.contains(&record.target) {
return Err(Error::Invariant(format!(
"ref {:?} targets unknown atom {}",
record.name, record.target
)));
}
self.refs.push(record);
Ok(())
}
pub fn set_loss(&mut self, loss: LossBoundary) {
self.loss = loss;
}
pub fn add_flag(&mut self, flag: Flag) {
self.flags.push(flag);
}
pub fn add_transform(&mut self, record: TransformRecord) -> usize {
let step = self.transforms.len();
self.transforms.push(record);
step
}
pub fn finish(self) -> Result<Ir> {
let ordered = topo_order(&self.atoms)?;
let mut refs = self.refs;
refs.sort_by(|a, b| (&a.name, a.kind.variant()).cmp(&(&b.name, b.kind.variant())));
if let Some((a, _)) = refs
.iter()
.zip(refs.iter().skip(1))
.find(|(a, b)| (&a.name, a.kind.variant()) == (&b.name, b.kind.variant()))
{
return Err(Error::Invariant(format!(
"two refs named {:?} of one kind",
a.name
)));
}
if self.transforms.len() > 64 {
return Err(Error::Invariant(
"more than 64 transform records".to_string(),
));
}
let mut loss = self.loss;
loss.dropped.sort_by(|a, b| {
(a.class.variant(), a.step, &a.what).cmp(&(b.class.variant(), b.step, &b.what))
});
if let Some((a, _)) = loss
.dropped
.iter()
.zip(loss.dropped.iter().skip(1))
.find(|(a, b)| {
(a.class.variant(), a.step, &a.what) == (b.class.variant(), b.step, &b.what)
})
{
return Err(Error::Invariant(format!(
"two drops of one class/step with the same `what`: {:?}",
a.what
)));
}
let mut flags = self.flags;
flags.sort_by(|a, b| (a.kind.variant(), &a.what).cmp(&(b.kind.variant(), &b.what)));
if let Some((a, _)) = flags
.iter()
.zip(flags.iter().skip(1))
.find(|(a, b)| (a.kind.variant(), &a.what) == (b.kind.variant(), &b.what))
{
return Err(Error::Invariant(format!(
"two flags of one kind with the same `what`: {:?}",
a.what
)));
}
let referenced: BTreeSet<BlobId> = ordered
.iter()
.flat_map(|a| a.ops.iter())
.filter_map(|op| match op.content() {
Some(Content::Blob { blob, .. }) => Some(*blob),
Some(Content::Submodule { .. }) | None => None,
})
.collect();
let mut content = self.content;
content.retain(|id| referenced.contains(id));
Ok(Ir {
atoms: ordered,
refs,
provenance: self.provenance,
loss,
flags,
content,
transforms: self.transforms,
})
}
}
pub(crate) fn canonical_order_ids(atoms: &[ChangeAtom]) -> Option<Vec<AtomId>> {
let by_id: BTreeMap<AtomId, &ChangeAtom> = atoms.iter().map(|a| (a.id, a)).collect();
let mut indegree: BTreeMap<AtomId, usize> = atoms.iter().map(|a| (a.id, 0usize)).collect();
let mut children: BTreeMap<AtomId, Vec<AtomId>> = BTreeMap::new();
for a in atoms {
for p in &a.parents {
if by_id.contains_key(p) {
children.entry(*p).or_default().push(a.id);
if let Some(d) = indegree.get_mut(&a.id) {
*d += 1;
}
}
}
}
let mut ready: BTreeSet<(Vec<u8>, AtomId)> = BTreeSet::new();
for a in atoms {
if indegree.get(&a.id).copied().unwrap_or(0) == 0 {
ready.insert((a.source.atom_id.clone(), a.id));
}
}
let mut out: Vec<AtomId> = Vec::with_capacity(atoms.len());
while let Some(key) = ready.iter().next().cloned() {
ready.remove(&key);
let id = key.1;
out.push(id);
if let Some(kids) = children.get(&id) {
for kid in kids {
if let Some(d) = indegree.get_mut(kid) {
*d = d.saturating_sub(1);
if *d == 0 {
if let Some(k) = by_id.get(kid) {
ready.insert((k.source.atom_id.clone(), *kid));
}
}
}
}
}
}
if out.len() != atoms.len() {
return None;
}
Some(out)
}
fn topo_order(atoms: &[ChangeAtom]) -> Result<Vec<ChangeAtom>> {
let order = canonical_order_ids(atoms).ok_or_else(|| {
Error::Invariant("atom graph contains a cycle (source history must be acyclic)".to_string())
})?;
let mut by_id: BTreeMap<AtomId, ChangeAtom> =
atoms.iter().cloned().map(|a| (a.id, a)).collect();
Ok(order
.into_iter()
.filter_map(|id| by_id.remove(&id))
.collect())
}
#[cfg(test)]
mod tests;