Skip to main content

ifc_model/mutation/
transaction.rs

1//! Validate a batch of edits, then apply it as a unit.
2//!
3//! # Why the direct edit methods are not enough
4//!
5//! [`Model::set_attribute`], [`Model::retype`] and [`Model::remove`] each do
6//! one thing correctly and immediately. That is right for a codec and wrong
7//! for an author: `remove` is documented to leave every reference to the
8//! removed entity dangling, so deleting a storey that walls still reference
9//! produces a file that parses and is wrong.
10//!
11//! A transaction closes that gap without changing the primitives. It collects
12//! edits, checks them against a PROJECTED view of the model -- what would
13//! exist if the whole batch applied -- and only then writes.
14//!
15//! # Atomicity without an undo log
16//!
17//! Every failure mode is decided during preflight. Once preflight returns
18//! clean, apply consists of map inserts, slot writes and map removals against
19//! entities already proven to exist. None of those can fail, so there is
20//! nothing to roll back and no half-applied state to observe.
21//!
22//! That is a stronger guarantee than "we rolled back on error", because a
23//! rollback path is itself code that can be wrong and is exercised only on
24//! failure. Here the failure path never touches the model at all.
25//!
26//! # Projection is what makes co-dependent edits expressible
27//!
28//! Checking each edit against the CURRENT model would reject a transaction
29//! that creates an entity and references it in the same batch, and would
30//! accept one that removes an entity another edit still points at. Both
31//! answers are wrong. Validating against the projected end state gets both
32//! right, and is the reason "delete a storey and re-parent its walls" is a
33//! single atomic edit rather than a sequence with a broken middle.
34//!
35//! # Undo
36//!
37//! [`Transaction::commit_reversible`] also returns an [`Inverse`] that
38//! restores the model exactly. The inverse is recorded by the model's own
39//! primitive writes, not derived from the staged edits, so file order,
40//! type-index order and the next free id come back too. See
41//! [`Inverse`] and [`History`](crate::History).
42//!
43//! ```
44//! use ifc_model::{Entity, Model, Transaction, Value};
45//!
46//! let mut model = Model::new();
47//! let storey = model.push(Entity::new("IFCBUILDINGSTOREY", vec![]));
48//!
49//! // A wall that references the storey.
50//! let mut tx = Transaction::new(&model);
51//! let wall = tx.create(Entity::new("IFCWALL", vec![Value::Ref(storey)]));
52//! tx.commit(&mut model).expect("the storey exists");
53//!
54//! // Removing the storey alone is refused: the wall still points at it.
55//! let mut tx = Transaction::new(&model);
56//! tx.remove(storey);
57//! assert!(tx.commit(&mut model).is_err());
58//!
59//! // Removing both together is fine -- nothing survives to dangle.
60//! let mut tx = Transaction::new(&model);
61//! tx.remove(storey);
62//! tx.remove(wall);
63//! assert!(tx.commit(&mut model).is_ok());
64//! ```
65
66use std::collections::BTreeMap;
67
68use ahash::{AHashMap, AHashSet};
69
70use crate::entity::Entity;
71use crate::header::Header;
72use crate::index::ReverseIndex;
73use crate::model::Model;
74use crate::mutation::conflict::Conflict;
75use crate::mutation::inverse::Inverse;
76use crate::value::{EntityId, Value};
77
78/// One staged change.
79///
80/// Deliberately structural: there is no `set_name` or `set_material` here.
81/// Domain-shaped authoring belongs in the crate that owns the domain, built
82/// on top of these operations -- otherwise every schema concept leaks into
83/// the model layer, which is the boundary this crate exists to hold.
84#[derive(Debug, Clone, PartialEq)]
85pub enum Edit {
86    /// Create an entity under a reserved id.
87    Create {
88        /// The id reserved for it by [`Transaction::create`].
89        id: EntityId,
90        /// The entity to store.
91        entity: Entity,
92    },
93    /// Replace one positional attribute.
94    SetAttribute {
95        /// The entity to edit.
96        id: EntityId,
97        /// Attribute slot.
98        slot: usize,
99        /// New value.
100        value: Value,
101    },
102    /// Change an entity's type name, keeping its id and attributes.
103    Retype {
104        /// The entity to retype.
105        id: EntityId,
106        /// The new type name.
107        type_name: std::sync::Arc<str>,
108    },
109    /// Delete an entity.
110    Remove {
111        /// The entity to delete.
112        id: EntityId,
113    },
114}
115
116/// A batch of edits, validated together and applied as a unit.
117///
118/// Opened against a model snapshot and carrying that snapshot's revision, so
119/// a commit against a model that has since changed is refused rather than
120/// applied to state the caller never saw.
121#[derive(Debug, Clone)]
122pub struct Transaction {
123    revision: u64,
124    next_id: u64,
125    edits: Vec<Edit>,
126    /// A header replacement. Not an [`Edit`] variant: `Edit` is matched
127    /// exhaustively downstream.
128    header: Option<Header>,
129    /// Record shortenings, applied after the edits and before the header.
130    /// Not an [`Edit`] variant either, for the same reason as `header`.
131    truncations: BTreeMap<EntityId, usize>,
132}
133
134impl Transaction {
135    /// Open a transaction against a model.
136    #[must_use]
137    pub fn new(model: &Model) -> Self {
138        Self {
139            revision: model.revision(),
140            next_id: model.next_id().0,
141            edits: Vec::new(),
142            header: None,
143            truncations: BTreeMap::new(),
144        }
145    }
146
147    /// The model revision this transaction was opened against.
148    #[must_use]
149    pub fn revision(&self) -> u64 {
150        self.revision
151    }
152
153    /// The staged edits, in the order they were added. Truncations are not
154    /// edits: see [`Transaction::truncations`].
155    #[must_use]
156    pub fn edits(&self) -> &[Edit] {
157        &self.edits
158    }
159
160    /// Whether anything is staged.
161    #[must_use]
162    pub fn is_empty(&self) -> bool {
163        self.edits.is_empty() && self.header.is_none() && self.truncations.is_empty()
164    }
165
166    /// Number of staged edits; truncations and the header are not counted.
167    #[must_use]
168    pub fn len(&self) -> usize {
169        self.edits.len()
170    }
171
172    /// Stage a new entity, returning the id reserved for it.
173    ///
174    /// The id is allocated from the transaction, not the model, so several
175    /// creates in one batch cannot collide and the caller can reference a
176    /// newly created entity from another edit in the same transaction before
177    /// anything is written.
178    pub fn create(&mut self, entity: Entity) -> EntityId {
179        #[cfg(feature = "authored-dump")]
180        crate::authored_dump::record(&entity.type_name, "create");
181        let id = EntityId(self.next_id);
182        self.next_id += 1;
183        self.edits.push(Edit::Create { id, entity });
184        id
185    }
186
187    /// Stage an already-constructed edit.
188    ///
189    /// [`Transaction::create`] allocates ids and is what an author should
190    /// use. This exists for replaying a batch that was built elsewhere --
191    /// deserialized, or produced by another process -- where the edit list
192    /// is data rather than a sequence of calls. Preflight checks it exactly
193    /// the same way, so a replayed batch cannot bypass validation.
194    pub fn stage(&mut self, edit: Edit) -> &mut Self {
195        if let Edit::Create { id, .. } = &edit {
196            // Keep the allocator ahead of any id staged this way, so a later
197            // `create` cannot hand out an id this batch already occupies.
198            self.next_id = self.next_id.max(id.0 + 1);
199        }
200        self.edits.push(edit);
201        self
202    }
203
204    /// Stage an attribute write.
205    pub fn set_attribute(&mut self, id: EntityId, slot: usize, value: Value) -> &mut Self {
206        self.edits.push(Edit::SetAttribute { id, slot, value });
207        self
208    }
209
210    /// Stage a type change.
211    pub fn retype(&mut self, id: EntityId, type_name: impl Into<std::sync::Arc<str>>) -> &mut Self {
212        self.edits.push(Edit::Retype {
213            id,
214            type_name: type_name.into(),
215        });
216        self
217    }
218
219    /// Stage a removal.
220    pub fn remove(&mut self, id: EntityId) -> &mut Self {
221        self.edits.push(Edit::Remove { id });
222        self
223    }
224
225    /// Stage a replacement of the file header, applied after the edits.
226    pub fn set_header(&mut self, header: Header) -> &mut Self {
227        self.header = Some(header);
228        self
229    }
230
231    /// Stage shortening `id`'s record to its first `len` attributes, applied
232    /// after every edit and before the header. Staging `id` again replaces
233    /// the length.
234    ///
235    /// The record may be one the batch creates. A `len` at or past the
236    /// record's length at that point drops nothing. A [`Edit::SetAttribute`]
237    /// at a slot of `len` or more is refused
238    /// ([`Conflict::WriteBeyondTruncation`]); references held only in dropped
239    /// slots do not keep a removed entity alive.
240    pub fn truncate(&mut self, id: EntityId, len: usize) -> &mut Self {
241        self.truncations.insert(id, len);
242        self
243    }
244
245    /// The staged truncations as `(id, len)`, in ascending id.
246    pub fn truncations(&self) -> impl Iterator<Item = (EntityId, usize)> + '_ {
247        self.truncations.iter().map(|(id, len)| (*id, *len))
248    }
249
250    /// The staged header replacement, if any.
251    #[must_use]
252    pub fn header(&self) -> Option<&Header> {
253        self.header.as_ref()
254    }
255
256    /// Check every edit without touching the model.
257    ///
258    /// Returns every conflict found rather than the first: an author fixing a
259    /// batch wants the whole list, and stopping at the first turns one review
260    /// into N round trips.
261    ///
262    /// Conflicts are ordered by the edit that produced them, so the report
263    /// reads in the order the caller wrote the batch.
264    #[must_use]
265    pub fn preflight(&self, model: &Model) -> Vec<Conflict> {
266        let mut conflicts = Vec::new();
267
268        if model.revision() != self.revision {
269            conflicts.push(Conflict::StaleRevision {
270                expected: self.revision,
271                found: model.revision(),
272            });
273            // Every other check would be computed against a model the caller
274            // never saw, so the results would be noise. Report the one fact
275            // that matters and stop.
276            return conflicts;
277        }
278
279        // --- project the end state -------------------------------------
280        let mut created: AHashMap<EntityId, &Entity> = AHashMap::new();
281        let mut removed: AHashSet<EntityId> = AHashSet::new();
282        // Slot writes, keyed by entity then slot: a later edit to the same
283        // slot wins, matching apply order.
284        let mut writes: AHashMap<EntityId, AHashMap<usize, &Value>> = AHashMap::new();
285
286        for edit in &self.edits {
287            match edit {
288                Edit::Create { id, entity } => {
289                    created.insert(*id, entity);
290                    removed.remove(id);
291                }
292                Edit::Remove { id } => {
293                    removed.insert(*id);
294                }
295                Edit::SetAttribute { id, slot, value } => {
296                    writes.entry(*id).or_default().insert(*slot, value);
297                }
298                Edit::Retype { .. } => {}
299            }
300        }
301
302        let exists = |id: EntityId| -> bool {
303            !removed.contains(&id) && (created.contains_key(&id) || model.get(id).is_some())
304        };
305
306        // --- per-edit checks -------------------------------------------
307        for (index, edit) in self.edits.iter().enumerate() {
308            match edit {
309                Edit::Create { id, entity } => {
310                    if model.get(*id).is_some() {
311                        conflicts.push(Conflict::IdAlreadyExists {
312                            edit: index,
313                            id: *id,
314                        });
315                    }
316                    let kept = self.truncations.get(id).copied().unwrap_or(usize::MAX);
317                    for (slot, attribute) in entity.attributes.iter().enumerate() {
318                        // A dropped slot is never stored.
319                        if slot >= kept {
320                            break;
321                        }
322                        // A slot overwritten later in the same batch is not
323                        // what will be stored, so checking it would reject a
324                        // batch that is actually coherent.
325                        if writes.get(id).is_some_and(|w| w.contains_key(&slot)) {
326                            continue;
327                        }
328                        check_refs(attribute, index, *id, slot, &exists, &mut conflicts);
329                    }
330                }
331                Edit::SetAttribute { id, slot, value } => {
332                    if !exists(*id) {
333                        conflicts.push(Conflict::MissingTarget {
334                            edit: index,
335                            id: *id,
336                        });
337                        continue;
338                    }
339                    if let Some(&len) = self.truncations.get(id) {
340                        if *slot >= len {
341                            conflicts.push(Conflict::WriteBeyondTruncation {
342                                edit: index,
343                                id: *id,
344                                slot: *slot,
345                                len,
346                            });
347                            continue;
348                        }
349                    }
350                    // Only the winning write for a slot is checked; an earlier
351                    // superseded one never reaches the model.
352                    if writes
353                        .get(id)
354                        .and_then(|w| w.get(slot))
355                        .is_some_and(|winner| !std::ptr::eq(*winner, value))
356                    {
357                        continue;
358                    }
359                    check_refs(value, index, *id, *slot, &exists, &mut conflicts);
360                }
361                Edit::Retype { id, .. } => {
362                    if !exists(*id) {
363                        conflicts.push(Conflict::MissingTarget {
364                            edit: index,
365                            id: *id,
366                        });
367                    }
368                }
369                Edit::Remove { id } => {
370                    if model.get(*id).is_none() && !created.contains_key(id) {
371                        conflicts.push(Conflict::MissingTarget {
372                            edit: index,
373                            id: *id,
374                        });
375                    }
376                }
377            }
378        }
379
380        // --- removals must not orphan surviving references --------------
381        //
382        // Built once for the whole batch rather than per removal: the index is
383        // a single scan, and a batch deleting a hundred entities would
384        // otherwise rescan the model a hundred times. A model that already
385        // keeps its index is not scanned at all.
386        if self.edits.iter().any(|e| matches!(e, Edit::Remove { .. })) {
387            // The model's own index when something built it: no scan.
388            let temporary;
389            let index = match model.reverse_index_if_built() {
390                Some(index) => index,
391                None => {
392                    temporary = ReverseIndex::build(model);
393                    &temporary
394                }
395            };
396            // Staging the same removal twice is one problem, not two: report
397            // it against the first occurrence only.
398            let mut reported: AHashSet<EntityId> = AHashSet::new();
399            for (position, edit) in self.edits.iter().enumerate() {
400                let Edit::Remove { id } = edit else { continue };
401                if !reported.insert(*id) {
402                    continue;
403                }
404                for referrer in index.referrers(*id) {
405                    // A referrer that is itself going away cannot dangle.
406                    if removed.contains(&referrer.from) {
407                        continue;
408                    }
409                    // A slot the referrer's truncation drops holds nothing.
410                    if self
411                        .truncations
412                        .get(&referrer.from)
413                        .is_some_and(|len| referrer.slot >= *len)
414                    {
415                        continue;
416                    }
417                    // A slot being rewritten in this batch is governed by the
418                    // new value, which the per-edit check already validated.
419                    if writes
420                        .get(&referrer.from)
421                        .is_some_and(|w| w.contains_key(&referrer.slot))
422                    {
423                        continue;
424                    }
425                    conflicts.push(Conflict::RemovalWouldDangle {
426                        edit: position,
427                        removed: *id,
428                        referrer: referrer.from,
429                        slot: referrer.slot,
430                    });
431                }
432            }
433        }
434
435        // --- a truncation needs a record to shorten ----------------------
436        for id in self.truncations.keys() {
437            if !exists(*id) {
438                conflicts.push(Conflict::TruncationMissingTarget { id: *id });
439            }
440        }
441
442        conflicts
443    }
444
445    /// Validate and apply, or report every conflict and change nothing.
446    ///
447    /// On `Err` the model is untouched: preflight runs to completion before
448    /// the first write, so a rejected transaction cannot leave partial state.
449    pub fn commit(self, model: &mut Model) -> Result<Applied, Vec<Conflict>> {
450        let conflicts = self.preflight(model);
451        if !conflicts.is_empty() {
452            return Err(conflicts);
453        }
454
455        let mut applied = Applied {
456            created: Vec::new(),
457            removed: Vec::new(),
458            revision: 0,
459        };
460
461        for edit in self.edits {
462            match edit {
463                Edit::Create { id, entity } => {
464                    model.insert(id, entity);
465                    applied.created.push(id);
466                }
467                Edit::SetAttribute { id, slot, value } => {
468                    // Preflight proved the entity exists.
469                    model.set_attribute(id, slot, value);
470                }
471                Edit::Retype { id, type_name } => {
472                    model.retype(id, type_name);
473                }
474                Edit::Remove { id } => {
475                    if let Some(entity) = model.remove(id) {
476                        applied.removed.push((id, entity));
477                    }
478                }
479            }
480        }
481
482        // Preflight proved every target exists.
483        for (id, len) in self.truncations {
484            model.truncate_attributes(id, len);
485        }
486
487        if let Some(header) = self.header {
488            *model.header_mut() = header;
489        }
490
491        applied.revision = model.revision();
492        Ok(applied)
493    }
494
495    /// [`Transaction::commit`], also returning the [`Inverse`] that restores
496    /// the model exactly. A refused commit changes nothing and returns the
497    /// conflicts only.
498    pub fn commit_reversible(self, model: &mut Model) -> Result<(Applied, Inverse), Vec<Conflict>> {
499        let (result, inverse) = Inverse::record(model, |model| self.commit(model));
500        result.map(|applied| (applied, inverse))
501    }
502}
503
504/// What a committed transaction did.
505#[derive(Debug, Clone, PartialEq)]
506#[non_exhaustive]
507pub struct Applied {
508    /// Ids created, in commit order.
509    pub created: Vec<EntityId>,
510    /// Entities removed, with their contents.
511    ///
512    /// Returned rather than dropped so a caller can undo, log, or re-file
513    /// them. A delete that silently discards the payload makes an editor's
514    /// undo stack impossible to build.
515    pub removed: Vec<(EntityId, Entity)>,
516    /// The model revision after the commit.
517    pub revision: u64,
518}
519
520/// Record a conflict for every reference in `value` that will not resolve.
521fn check_refs(
522    value: &Value,
523    edit: usize,
524    from: EntityId,
525    slot: usize,
526    exists: &impl Fn(EntityId) -> bool,
527    conflicts: &mut Vec<Conflict>,
528) {
529    value.for_each_ref(&mut |target| {
530        if !exists(target) {
531            conflicts.push(Conflict::DanglingReference {
532                edit,
533                from,
534                slot,
535                target,
536            });
537        }
538    });
539}