appcore-filemaker 0.1.0-beta.1

Deterministic declarative document, canvas, and dataset compiler for AppCore
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
// =============================================================================
//        #######
//     ###       ###     F: patch.rs
//    ##   ## ##   ##    P: AppCore-Runtime
//         ## ##
//                       C: 2026/08/30 05:00:00 by dnettoRaw
//    ##   ## ##   ##    U: 2026/08/30 05:00:00 by dnettoRaw
//      ###########      S: 1.0.2-rc
// =============================================================================

//! Defines bounded patch contracts and behavior for this crate.

use serde::{Deserialize, Serialize};

use crate::{DocumentIr, ElementId, ElementIr, ErrorCode, FileMakerError, Length, Result, Style};

/// One immutable ordered patch batch.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Patch {
    /// Stable sequence used in provenance.
    pub sequence: u64,
    /// Operations applied atomically in order.
    pub operations: Vec<PatchOperation>,
}

/// Supported runtime mutation operation.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "op", rename_all = "snake_case")]
pub enum PatchOperation {
    /// Set literal text.
    SetText {
        /// Target ID.
        id: ElementId,
        /// New text.
        text: String,
    },
    /// Set visibility.
    SetHidden {
        /// Target ID.
        id: ElementId,
        /// Hidden state.
        hidden: bool,
    },
    /// Overlay a validated runtime style layer before layout.
    SetStyle {
        /// Target ID.
        id: ElementId,
        /// Partial style to overlay.
        style: Style,
    },
    /// Move an element.
    Move {
        /// Target ID.
        id: ElementId,
        /// New x.
        x: Length,
        /// New y.
        y: Length,
    },
    /// Resize an element.
    Resize {
        /// Target ID.
        id: ElementId,
        /// New width.
        width: Length,
        /// New height.
        height: Length,
    },
    /// Remove a node and its subtree.
    Remove {
        /// Target ID.
        id: ElementId,
    },
    /// Add a child or root node.
    Add {
        /// Optional parent ID.
        parent: Option<ElementId>,
        /// New element.
        element: ElementIr,
    },
    /// Clone a node with a new root ID.
    Clone {
        /// Source ID.
        id: ElementId,
        /// New root ID.
        new_id: ElementId,
    },
    /// Replace a node while retaining its location in source order.
    Replace {
        /// Target ID.
        id: ElementId,
        /// Replacement.
        element: ElementIr,
    },
}

/// Transactional patch executor using copy-on-write rollback semantics.
pub struct PatchTransaction<'a> {
    document: &'a mut DocumentIr,
    max_operations: usize,
}

impl<'a> PatchTransaction<'a> {
    /// Starts a transaction over a document.
    #[must_use]
    pub fn new(document: &'a mut DocumentIr, max_operations: usize) -> Self {
        Self {
            document,
            max_operations,
        }
    }

    /// Applies the complete patch or restores the exact prior document.
    pub fn apply(&mut self, patch: &Patch) -> Result<()> {
        self.apply_with_rollback_snapshot(patch).map(drop)
    }

    /// Applies a patch and returns the owned rollback snapshot on success.
    pub fn apply_with_rollback_snapshot(&mut self, patch: &Patch) -> Result<DocumentIr> {
        if patch.operations.len() > self.max_operations {
            return Err(FileMakerError::new(
                ErrorCode::LimitExceeded,
                "patch operation limit exceeded",
            ));
        }
        let original = self.document.clone();
        for operation in &patch.operations {
            if let Err(error) = apply_operation(self.document, operation, patch.sequence) {
                *self.document = original;
                return Err(error);
            }
        }
        if let Err(error) = Self::validate(self.document) {
            *self.document = original;
            return Err(error);
        }
        Ok(original)
    }

    /// Validates patch-sensitive document invariants without cloning it.
    pub fn validate(document: &DocumentIr) -> Result<()> {
        validate_document_ids(&document.elements)?;
        crate::layout_page::validate_page_layer_ir(document)
    }
}

fn apply_operation(
    document: &mut DocumentIr,
    operation: &PatchOperation,
    sequence: u64,
) -> Result<()> {
    match operation {
        PatchOperation::SetText { id, text } => mutate(document, id, sequence, |element| {
            element.text = Some(text.clone());
        }),
        PatchOperation::SetHidden { id, hidden } => {
            mutate(document, id, sequence, |element| element.hidden = *hidden)
        }
        PatchOperation::SetStyle { id, style } => {
            style.validate()?;
            mutate(document, id, sequence, |element| {
                element.style.overlay(style)
            })
        }
        PatchOperation::Move { id, x, y } => mutate(document, id, sequence, |element| {
            element.geometry.x = Some(*x);
            element.geometry.y = Some(*y);
            element.geometry.align_x = None;
            element.geometry.align_y = None;
            element.geometry.anchors.clear();
        }),
        PatchOperation::Resize { id, width, height } => mutate(document, id, sequence, |element| {
            element.geometry.width = Some(*width);
            element.geometry.height = Some(*height);
            element.geometry.constraints = crate::LayoutConstraints::default();
        }),
        PatchOperation::Remove { id } => remove(&mut document.elements, id),
        PatchOperation::Add { parent, element } => {
            add(document, parent.as_ref(), element.clone(), sequence)
        }
        PatchOperation::Clone { id, new_id } => clone_element(document, id, new_id, sequence),
        PatchOperation::Replace { id, element } => {
            replace(&mut document.elements, id, element.clone(), sequence)
        }
    }
}

fn mutate(
    document: &mut DocumentIr,
    id: &ElementId,
    sequence: u64,
    action: impl FnOnce(&mut ElementIr),
) -> Result<()> {
    let element = find_mut(&mut document.elements, id)
        .ok_or_else(|| patch_error("patch target was not found"))?;
    ensure_unlocked(element)?;
    action(element);
    element.provenance.patches.push(sequence);
    Ok(())
}

fn add(
    document: &mut DocumentIr,
    parent: Option<&ElementId>,
    mut element: ElementIr,
    sequence: u64,
) -> Result<()> {
    if find(&document.elements, &element.id).is_some() {
        return Err(patch_error("added element ID already exists"));
    }
    element.provenance.patches.push(sequence);
    if let Some(parent) = parent {
        let parent = find_mut(&mut document.elements, parent)
            .ok_or_else(|| patch_error("add parent was not found"))?;
        ensure_unlocked(parent)?;
        parent.children.push(element);
    } else {
        document.elements.push(element);
    }
    Ok(())
}

fn clone_element(
    document: &mut DocumentIr,
    id: &ElementId,
    new_id: &ElementId,
    sequence: u64,
) -> Result<()> {
    if find(&document.elements, new_id).is_some() {
        return Err(patch_error("clone ID already exists"));
    }
    let mut cloned = find(&document.elements, id)
        .ok_or_else(|| patch_error("clone source was not found"))?
        .clone();
    ensure_unlocked(&cloned)?;
    remap_clone_ids(&mut cloned, id.as_str(), new_id.as_str())?;
    cloned.provenance.patches.push(sequence);
    document.elements.push(cloned);
    Ok(())
}

fn remove(elements: &mut Vec<ElementIr>, id: &ElementId) -> Result<()> {
    let target = find(elements, id).ok_or_else(|| patch_error("remove target was not found"))?;
    ensure_subtree_unlocked(target)?;
    remove_unchecked(elements, id);
    Ok(())
}

fn remove_unchecked(elements: &mut Vec<ElementIr>, id: &ElementId) -> bool {
    if let Some(position) = elements.iter().position(|element| &element.id == id) {
        elements.remove(position);
        return true;
    }
    for element in elements {
        if remove_unchecked(&mut element.children, id) {
            return true;
        }
    }
    false
}

fn replace(
    elements: &mut [ElementIr],
    id: &ElementId,
    mut replacement: ElementIr,
    sequence: u64,
) -> Result<()> {
    let target = find(elements, id).ok_or_else(|| patch_error("replace target was not found"))?;
    ensure_subtree_unlocked(target)?;
    if target.page_placement != replacement.page_placement {
        return Err(patch_error("replace cannot change page-layer ownership"));
    }
    if replace_unchecked(elements, id, &mut replacement, sequence) {
        Ok(())
    } else {
        Err(patch_error("replace target was not found"))
    }
}

fn replace_unchecked(
    elements: &mut [ElementIr],
    id: &ElementId,
    replacement: &mut ElementIr,
    sequence: u64,
) -> bool {
    for element in elements {
        if &element.id == id {
            replacement.provenance.patches.push(sequence);
            *element = replacement.clone();
            return true;
        }
        if replace_unchecked(&mut element.children, id, replacement, sequence) {
            return true;
        }
    }
    false
}

fn find<'a>(elements: &'a [ElementIr], id: &ElementId) -> Option<&'a ElementIr> {
    for element in elements {
        if &element.id == id {
            return Some(element);
        }
        if let Some(found) = find(&element.children, id) {
            return Some(found);
        }
    }
    None
}

fn find_mut<'a>(elements: &'a mut [ElementIr], id: &ElementId) -> Option<&'a mut ElementIr> {
    for element in elements {
        if &element.id == id {
            return Some(element);
        }
        if let Some(found) = find_mut(&mut element.children, id) {
            return Some(found);
        }
    }
    None
}

fn ensure_unlocked(element: &ElementIr) -> Result<()> {
    if element.locked {
        Err(
            FileMakerError::new(ErrorCode::PatchLocked, "element is locked")
                .at(element.id.as_str()),
        )
    } else {
        Ok(())
    }
}

fn ensure_subtree_unlocked(root: &ElementIr) -> Result<()> {
    let mut stack = vec![root];
    while let Some(element) = stack.pop() {
        ensure_unlocked(element)?;
        stack.extend(element.children.iter().rev());
    }
    Ok(())
}

fn remap_clone_ids(element: &mut ElementIr, old_root: &str, new_root: &str) -> Result<()> {
    let current = element.id.as_str();
    let suffix = current.strip_prefix(old_root).unwrap_or(current);
    element.id = ElementId::new(format!("{new_root}{suffix}"))?;
    for child in &mut element.children {
        remap_clone_ids(child, old_root, new_root)?;
    }
    Ok(())
}

fn validate_document_ids(elements: &[ElementIr]) -> Result<()> {
    let mut ids = std::collections::BTreeSet::new();
    let mut stack: Vec<&ElementIr> = elements.iter().collect();
    while let Some(element) = stack.pop() {
        if !ids.insert(element.id.as_str()) {
            return Err(patch_error(format!(
                "patch produced duplicate element ID `{}`",
                element.id.as_str()
            )));
        }
        stack.extend(&element.children);
    }
    Ok(())
}

fn patch_error(message: impl Into<String>) -> FileMakerError {
    FileMakerError::new(ErrorCode::PatchInvalid, message)
}

#[cfg(test)]
mod operation_log_tests {
    use std::collections::BTreeMap;

    use super::*;
    use crate::{Compiler, DataValue, OperationLog};

    fn document() -> DocumentIr {
        let yaml = br"filemaker: '1.0'
model: canvas
id: log
page: { width: 10pt, height: 10pt }
elements: [{ id: node, type: rect, width: 2pt, height: 2pt }]
";
        let compiler = Compiler::builder().build().unwrap();
        let template = compiler.compile_template_yaml(yaml).unwrap();
        compiler
            .bind(&template, &DataValue::Object(BTreeMap::new()), &[])
            .unwrap()
    }

    fn visibility_patch(sequence: u64, hidden: bool) -> Patch {
        Patch {
            sequence,
            operations: vec![PatchOperation::SetHidden {
                id: ElementId::new("node").unwrap(),
                hidden,
            }],
        }
    }

    #[test]
    fn successful_patches_can_be_undone_and_redone() {
        let mut document = document();
        let patch = visibility_patch(1, true);
        let mut log = OperationLog::new(2).unwrap();
        log.apply(&mut document, &patch, 4).unwrap();
        assert!(document.elements[0].hidden);
        log.undo(&mut document).unwrap();
        assert!(!document.elements[0].hidden);
        log.redo(&mut document).unwrap();
        assert!(document.elements[0].hidden);
    }

    #[test]
    fn rejects_a_snapshot_before_mutating_the_document() {
        let mut document = document();
        let original = document.clone();
        let mut log = OperationLog::new_bounded(2, 1).unwrap();
        let error = log
            .apply(&mut document, &visibility_patch(1, true), 4)
            .unwrap_err();
        assert_eq!(error.code(), ErrorCode::LimitExceeded);
        assert_eq!(document, original);
        assert_eq!(log.used_bytes(), 0);
    }

    #[test]
    fn evicts_old_snapshots_to_honor_the_aggregate_byte_budget() {
        let mut document = document();
        let original_bytes = crate::memory::serialized_size(&document).unwrap();
        let mut changed = document.clone();
        PatchTransaction::new(&mut changed, 1)
            .apply(&visibility_patch(1, true))
            .unwrap();
        let changed_bytes = crate::memory::serialized_size(&changed).unwrap();
        let mut log = OperationLog::new_bounded(4, original_bytes.max(changed_bytes)).unwrap();
        log.apply(&mut document, &visibility_patch(1, true), 1)
            .unwrap();
        log.apply(&mut document, &visibility_patch(2, false), 1)
            .unwrap();
        assert_eq!(log.undo_len(), 1);
        assert!(log.used_bytes() <= log.max_bytes());
    }
}