feltdb 0.2.0

Embedded durable state store: an append-only log with atomic multi-record transactions, version-conditional writes, and idempotent retries
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
use crate::{
    reconcile, resolve_path, ConflictClassification, MaterializationProjection, PathComponent, StateId,
    StateRevision,
};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::{BTreeSet, HashMap};
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};

pub trait DurableObjectStore: Send + Sync + Clone + 'static {
    fn put_if_absent(&self, key: &str, value: &[u8]) -> Result<(), String>;
    fn get(&self, key: &str) -> Result<Option<Vec<u8>>, String>;
    fn delete(&self, key: &str) -> Result<bool, String>;
    fn list_prefix(&self, prefix: &str) -> Result<Vec<String>, String>;
    fn compare_and_swap(
        &self,
        key: &str,
        expected: Option<&[u8]>,
        replacement: &[u8],
    ) -> Result<bool, String>;
}

#[derive(Clone)]
pub struct LocalObjectStore {
    root: Arc<PathBuf>,
    lock: Arc<Mutex<()>>,
}

impl LocalObjectStore {
    pub fn new(root: impl AsRef<Path>) -> Result<Self, String> {
        let root = root.as_ref().to_path_buf();
        fs::create_dir_all(&root).map_err(|e| e.to_string())?;
        Ok(Self {
            root: Arc::new(root),
            lock: Arc::new(Mutex::new(())),
        })
    }

    fn path_for(&self, key: &str) -> PathBuf {
        self.root.join(encode_key(key))
    }
}

impl DurableObjectStore for LocalObjectStore {
    fn put_if_absent(&self, key: &str, value: &[u8]) -> Result<(), String> {
        let _guard = self.lock.lock().unwrap();
        let path = self.path_for(key);
        if path.exists() {
            return Ok(());
        }
        let tmp = self
            .root
            .join(format!(".tmp-{}-{}", std::process::id(), encode_key(key)));
        fs::write(&tmp, value).map_err(|e| e.to_string())?;
        match fs::rename(&tmp, &path) {
            Ok(()) => Ok(()),
            Err(_) if path.exists() => {
                let _ = fs::remove_file(&tmp);
                Ok(())
            }
            Err(e) => Err(e.to_string()),
        }
    }

    fn get(&self, key: &str) -> Result<Option<Vec<u8>>, String> {
        let path = self.path_for(key);
        match fs::read(path) {
            Ok(bytes) => Ok(Some(bytes)),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
            Err(e) => Err(e.to_string()),
        }
    }

    fn delete(&self, key: &str) -> Result<bool, String> {
        let _guard = self.lock.lock().unwrap();
        let path = self.path_for(key);
        match fs::remove_file(path) {
            Ok(()) => Ok(true),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
            Err(e) => Err(e.to_string()),
        }
    }

    fn list_prefix(&self, prefix: &str) -> Result<Vec<String>, String> {
        let entries = fs::read_dir(&*self.root).map_err(|e| e.to_string())?;
        let mut keys = Vec::new();
        for entry in entries {
            let entry = entry.map_err(|e| e.to_string())?;
            let Some(name) = entry.file_name().to_str().map(|v| v.to_string()) else {
                continue;
            };
            let key = decode_key(&name);
            if key.starts_with(prefix) {
                keys.push(key);
            }
        }
        keys.sort();
        Ok(keys)
    }

    fn compare_and_swap(
        &self,
        key: &str,
        expected: Option<&[u8]>,
        replacement: &[u8],
    ) -> Result<bool, String> {
        let _guard = self.lock.lock().unwrap();
        let path = self.path_for(key);
        let current = match fs::read(&path) {
            Ok(bytes) => Some(bytes),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
            Err(e) => return Err(e.to_string()),
        };

        let expected_matches = match (expected, current.as_deref()) {
            (None, None) => true,
            (Some(expected), Some(current)) => expected == current,
            _ => false,
        };
        if !expected_matches {
            return Ok(false);
        }

        let tmp = self
            .root
            .join(format!(".tmp-cas-{}-{}", std::process::id(), encode_key(key)));
        fs::write(&tmp, replacement).map_err(|e| e.to_string())?;
        fs::rename(tmp, path).map_err(|e| e.to_string())?;
        Ok(true)
    }
}

#[derive(Clone, Default)]
pub struct S3CompatibleBucket {
    inner: Arc<Mutex<HashMap<String, Vec<u8>>>>,
}

#[derive(Clone)]
pub struct S3CompatibleObjectStore {
    bucket: S3CompatibleBucket,
}

impl S3CompatibleObjectStore {
    pub fn new(bucket: S3CompatibleBucket) -> Self {
        Self { bucket }
    }
}

impl DurableObjectStore for S3CompatibleObjectStore {
    fn put_if_absent(&self, key: &str, value: &[u8]) -> Result<(), String> {
        self.bucket
            .inner
            .lock()
            .unwrap()
            .entry(key.to_string())
            .or_insert_with(|| value.to_vec());
        Ok(())
    }

    fn get(&self, key: &str) -> Result<Option<Vec<u8>>, String> {
        Ok(self.bucket.inner.lock().unwrap().get(key).cloned())
    }

    fn delete(&self, key: &str) -> Result<bool, String> {
        Ok(self.bucket.inner.lock().unwrap().remove(key).is_some())
    }

    fn list_prefix(&self, prefix: &str) -> Result<Vec<String>, String> {
        let mut keys = self
            .bucket
            .inner
            .lock()
            .unwrap()
            .keys()
            .filter(|k| k.starts_with(prefix))
            .cloned()
            .collect::<Vec<_>>();
        keys.sort();
        Ok(keys)
    }

    fn compare_and_swap(
        &self,
        key: &str,
        expected: Option<&[u8]>,
        replacement: &[u8],
    ) -> Result<bool, String> {
        let mut guard = self.bucket.inner.lock().unwrap();
        let current = guard.get(key).map(|bytes| bytes.as_slice());
        let expected_matches = match (expected, current) {
            (None, None) => true,
            (Some(expected), Some(current)) => expected == current,
            _ => false,
        };
        if !expected_matches {
            return Ok(false);
        }
        guard.insert(key.to_string(), replacement.to_vec());
        Ok(true)
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DurableRef {
    pub namespace: String,
    pub name: String,
    pub target: StateId,
    pub version: u64,
    pub authority: String,
}

#[derive(Clone)]
pub struct VersionedObjectSubstrate<S: DurableObjectStore> {
    store: S,
    cache: Arc<Mutex<HashMap<String, Vec<u8>>>>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
struct RevisionRecord {
    revision: StateRevision,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SubstrateError {
    NotFound(String),
    Conflict(String),
    Storage(String),
    Invalid(String),
}

impl std::fmt::Display for SubstrateError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SubstrateError::NotFound(v) => write!(f, "{v}"),
            SubstrateError::Conflict(v) => write!(f, "{v}"),
            SubstrateError::Storage(v) => write!(f, "{v}"),
            SubstrateError::Invalid(v) => write!(f, "{v}"),
        }
    }
}

impl std::error::Error for SubstrateError {}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct Reachability {
    pub revisions: Vec<StateId>,
    pub objects: Vec<StateId>,
}

impl<S: DurableObjectStore> VersionedObjectSubstrate<S> {
    pub fn new(store: S) -> Self {
        Self {
            store,
            cache: Arc::new(Mutex::new(HashMap::new())),
        }
    }

    pub fn clear_cache(&self) {
        self.cache.lock().unwrap().clear();
    }

    pub fn store_object(&self, content: &str) -> Result<StateId, SubstrateError> {
        let id = StateId::compute(content);
        let key = object_key(&id);
        self.store
            .put_if_absent(&key, content.as_bytes())
            .map_err(SubstrateError::Storage)?;
        self.cache
            .lock()
            .unwrap()
            .insert(key, content.as_bytes().to_vec());
        Ok(id)
    }

    pub fn get_object(&self, id: &StateId) -> Result<String, SubstrateError> {
        let key = object_key(id);
        // durable backend is authoritative; cache is advisory only
        let Some(bytes) = self.store.get(&key).map_err(SubstrateError::Storage)? else {
            self.cache.lock().unwrap().remove(&key);
            return Err(SubstrateError::NotFound(format!("object {} not found", id.as_hex())));
        };
        self.cache.lock().unwrap().insert(key, bytes.clone());
        String::from_utf8(bytes)
            .map_err(|e| SubstrateError::Invalid(format!("object is not utf8: {e}")))
    }

    pub fn create_revision(
        &self,
        resource: &str,
        content: String,
        parent: Option<StateId>,
        authority: String,
    ) -> Result<StateRevision, SubstrateError> {
        let parent_revision = if let Some(parent_id) = parent {
            Some(self.get_revision(&parent_id)?)
        } else {
            None
        };
        let revision = match parent_revision {
            Some(parent_revision) => {
                if parent_revision.resource != resource {
                    return Err(SubstrateError::Invalid(
                        "parent belongs to another resource".to_string(),
                    ));
                }
                StateRevision::child(content, &parent_revision, authority)
            }
            None => StateRevision::initial(resource.to_string(), content, authority),
        };
        let _ = self.store_object(&revision.content)?;
        self.persist_revision(&revision)?;
        Ok(revision)
    }

    pub fn get_revision(&self, id: &StateId) -> Result<StateRevision, SubstrateError> {
        let Some(bytes) = self
            .store
            .get(&revision_key(id))
            .map_err(SubstrateError::Storage)?
        else {
            return Err(SubstrateError::NotFound(format!("revision {} not found", id)));
        };
        let record: RevisionRecord =
            serde_json::from_slice(&bytes).map_err(|e| SubstrateError::Invalid(e.to_string()))?;
        let _ = self.get_object(&record.revision.content_id)?;
        Ok(record.revision)
    }

    pub fn list_revisions(&self) -> Result<Vec<StateRevision>, SubstrateError> {
        let keys = self
            .store
            .list_prefix("revision:")
            .map_err(SubstrateError::Storage)?;
        let mut revisions = keys
            .into_iter()
            .map(|key| {
                self.store
                    .get(&key)
                    .map_err(SubstrateError::Storage)?
                    .ok_or_else(|| SubstrateError::NotFound(format!("missing revision key {key}")))
                    .and_then(|bytes| {
                        serde_json::from_slice::<RevisionRecord>(&bytes)
                            .map(|record| record.revision)
                            .map_err(|e| SubstrateError::Invalid(e.to_string()))
                    })
            })
            .collect::<Result<Vec<_>, _>>()?;
        revisions.sort_by(|one, two| one.id.as_hex().cmp(two.id.as_hex()));
        Ok(revisions)
    }

    pub fn create_ref(
        &self,
        namespace: &str,
        name: &str,
        target: StateId,
        authority: String,
    ) -> Result<DurableRef, SubstrateError> {
        let _ = self.get_revision(&target)?;
        let reference = DurableRef {
            namespace: namespace.to_string(),
            name: name.to_string(),
            target,
            version: 1,
            authority,
        };
        let bytes = serde_json::to_vec(&reference)
            .map_err(|e| SubstrateError::Invalid(e.to_string()))?;
        let inserted = self
            .store
            .compare_and_swap(&ref_key(namespace, name), None, &bytes)
            .map_err(SubstrateError::Storage)?;
        if !inserted {
            return Err(SubstrateError::Conflict("ref already exists".to_string()));
        }
        Ok(reference)
    }

    pub fn get_ref(&self, namespace: &str, name: &str) -> Result<Option<DurableRef>, SubstrateError> {
        let Some(bytes) = self
            .store
            .get(&ref_key(namespace, name))
            .map_err(SubstrateError::Storage)?
        else {
            return Ok(None);
        };
        let reference =
            serde_json::from_slice(&bytes).map_err(|e| SubstrateError::Invalid(e.to_string()))?;
        Ok(Some(reference))
    }

    pub fn cas_move_ref(
        &self,
        namespace: &str,
        name: &str,
        expected_version: u64,
        target: StateId,
        authority: String,
    ) -> Result<DurableRef, SubstrateError> {
        let _ = self.get_revision(&target)?;
        let Some(current) = self.get_ref(namespace, name)? else {
            return Err(SubstrateError::NotFound("ref not found".to_string()));
        };
        if current.version != expected_version {
            return Err(SubstrateError::Conflict(format!(
                "stale version {}, current {}",
                expected_version, current.version
            )));
        }

        let next = DurableRef {
            version: current.version + 1,
            target,
            authority,
            ..current.clone()
        };
        let current_bytes =
            serde_json::to_vec(&current).map_err(|e| SubstrateError::Invalid(e.to_string()))?;
        let next_bytes =
            serde_json::to_vec(&next).map_err(|e| SubstrateError::Invalid(e.to_string()))?;
        let applied = self
            .store
            .compare_and_swap(&ref_key(namespace, name), Some(&current_bytes), &next_bytes)
            .map_err(SubstrateError::Storage)?;
        if !applied {
            return Err(SubstrateError::Conflict("concurrent ref update".to_string()));
        }
        Ok(next)
    }

    pub fn delete_ref(
        &self,
        namespace: &str,
        name: &str,
        expected_version: Option<u64>,
    ) -> Result<(), SubstrateError> {
        if let Some(expected) = expected_version {
            let Some(reference) = self.get_ref(namespace, name)? else {
                return Err(SubstrateError::NotFound("ref not found".to_string()));
            };
            if reference.version != expected {
                return Err(SubstrateError::Conflict("stale ref delete".to_string()));
            }
        }
        let deleted = self
            .store
            .delete(&ref_key(namespace, name))
            .map_err(SubstrateError::Storage)?;
        if !deleted {
            return Err(SubstrateError::NotFound("ref not found".to_string()));
        }
        Ok(())
    }

    pub fn list_refs(&self, namespace: Option<&str>) -> Result<Vec<DurableRef>, SubstrateError> {
        let keys = self
            .store
            .list_prefix("ref:")
            .map_err(SubstrateError::Storage)?;
        let mut refs = Vec::new();
        for key in keys {
            let Some(bytes) = self.store.get(&key).map_err(SubstrateError::Storage)? else {
                continue;
            };
            let reference: DurableRef =
                serde_json::from_slice(&bytes).map_err(|e| SubstrateError::Invalid(e.to_string()))?;
            if namespace.is_none_or(|scope| scope == reference.namespace) {
                refs.push(reference);
            }
        }
        refs.sort_by(|one, two| {
            one.namespace
                .cmp(&two.namespace)
                .then_with(|| one.name.cmp(&two.name))
        });
        Ok(refs)
    }

    pub fn materialize(
        &self,
        revision_id: &StateId,
        projection: &MaterializationProjection,
    ) -> Result<Value, SubstrateError> {
        let revision = self.get_revision(revision_id)?;
        let source: Value = serde_json::from_str(&revision.content)
            .map_err(|e| SubstrateError::Invalid(format!("unparseable json: {e}")))?;

        if projection.is_full() {
            return Ok(source);
        }

        let mut paths = projection.paths.clone();
        paths.sort();
        paths.dedup();
        if paths
            .windows(2)
            .any(|pair| path_overlap(&pair[0], &pair[1]))
        {
            return Err(SubstrateError::Invalid(
                "overlapping projection paths".to_string(),
            ));
        }

        let mut projected = Value::Object(serde_json::Map::new());
        for path in paths {
            let value = resolve_path(&source, &path)
                .cloned()
                .ok_or_else(|| SubstrateError::NotFound(format!("path missing: {path:?}")))?;
            assign_projection(&mut projected, &path, value)?;
        }
        Ok(projected)
    }

    pub fn conflict_classification(
        &self,
        base: &StateId,
        left: &StateId,
        right: &StateId,
    ) -> Result<ConflictClassification, SubstrateError> {
        let base = self.get_revision(base)?;
        let left = self.get_revision(left)?;
        let right = self.get_revision(right)?;
        Ok(ConflictClassification::classify(&base, &left, &right))
    }

    pub fn reconcile(
        &self,
        base: &StateId,
        left: &StateId,
        right: &StateId,
        authority: &str,
    ) -> Result<StateRevision, SubstrateError> {
        let base_revision = self.get_revision(base)?;
        let left_revision = self.get_revision(left)?;
        let right_revision = self.get_revision(right)?;
        let plan = crate::ReconciliationPlan::new(
            left_revision.id.clone(),
            right_revision.id.clone(),
            base_revision.id.clone(),
            true,
        );
        let reconciled = reconcile(
            &base_revision,
            &left_revision,
            &right_revision,
            &plan,
            authority.to_string(),
        )
        .map_err(SubstrateError::Invalid)?;
        self.persist_revision(&reconciled.materialized_state)?;
        let _ = self.store_object(&reconciled.materialized_state.content)?;
        Ok(reconciled.materialized_state)
    }

    pub fn reachability(&self) -> Result<Reachability, SubstrateError> {
        let refs = self.list_refs(None)?;
        let mut revision_ids = BTreeSet::new();
        let mut object_ids = BTreeSet::new();
        let mut stack = refs.into_iter().map(|reference| reference.target).collect::<Vec<_>>();
        while let Some(revision_id) = stack.pop() {
            if !revision_ids.insert(revision_id.clone()) {
                continue;
            }
            let revision = self.get_revision(&revision_id)?;
            object_ids.insert(revision.content_id.clone());
            if let Some(parent) = revision.parent_id {
                stack.push(parent);
            }
        }
        Ok(Reachability {
            revisions: revision_ids.into_iter().collect(),
            objects: object_ids.into_iter().collect(),
        })
    }

    pub fn collect_unreachable(&self) -> Result<Reachability, SubstrateError> {
        let reachable = self.reachability()?;
        let keep_revisions: BTreeSet<_> = reachable.revisions.iter().cloned().collect();
        let keep_objects: BTreeSet<_> = reachable.objects.iter().cloned().collect();

        for revision in self.list_revisions()? {
            if !keep_revisions.contains(&revision.id) {
                self.store
                    .delete(&revision_key(&revision.id))
                    .map_err(SubstrateError::Storage)?;
            }
        }

        for key in self
            .store
            .list_prefix("object:")
            .map_err(SubstrateError::Storage)?
        {
            if let Some(id_hex) = key.strip_prefix("object:") {
                let id = StateId::from_hex(id_hex.to_string());
                if !keep_objects.contains(&id) {
                    self.store.delete(&key).map_err(SubstrateError::Storage)?;
                }
            }
        }
        self.reachability()
    }

    fn persist_revision(&self, revision: &StateRevision) -> Result<(), SubstrateError> {
        let record = RevisionRecord {
            revision: revision.clone(),
        };
        let bytes = serde_json::to_vec(&record)
            .map_err(|e| SubstrateError::Invalid(format!("serialize revision: {e}")))?;
        self.store
            .put_if_absent(&revision_key(&revision.id), &bytes)
            .map_err(SubstrateError::Storage)
    }
}

fn revision_key(id: &StateId) -> String {
    format!("revision:{}", id.as_hex())
}

fn object_key(id: &StateId) -> String {
    format!("object:{}", id.as_hex())
}

fn ref_key(namespace: &str, name: &str) -> String {
    format!("ref:{}:{}", encode_key(namespace), encode_key(name))
}

fn encode_key(value: &str) -> String {
    value
        .replace('%', "%25")
        .replace(':', "%3A")
        .replace('/', "%2F")
}

fn decode_key(value: &str) -> String {
    value
        .replace("%2F", "/")
        .replace("%3A", ":")
        .replace("%25", "%")
}

fn path_overlap(one: &[PathComponent], two: &[PathComponent]) -> bool {
    one == two
        || (one.len() < two.len() && two.starts_with(one))
        || (two.len() < one.len() && one.starts_with(two))
}

fn assign_projection(state: &mut Value, path: &[PathComponent], value: Value) -> Result<(), SubstrateError> {
    let Some((last, prefix)) = path.split_last() else {
        *state = value;
        return Ok(());
    };

    let mut current = state;
    for component in prefix {
        match component {
            PathComponent::Key(key) => {
                if current.is_null() {
                    *current = Value::Object(serde_json::Map::new());
                }
                let Some(object) = current.as_object_mut() else {
                    return Err(SubstrateError::Invalid("projection path type mismatch".to_string()));
                };
                current = object.entry(key.clone()).or_insert(Value::Null);
            }
            PathComponent::Index(index) => {
                if current.is_null() {
                    *current = Value::Array(Vec::new());
                }
                let Some(array) = current.as_array_mut() else {
                    return Err(SubstrateError::Invalid("projection path type mismatch".to_string()));
                };
                while array.len() <= *index {
                    array.push(Value::Null);
                }
                current = &mut array[*index];
            }
        }
    }

    match last {
        PathComponent::Key(key) => {
            if current.is_null() {
                *current = Value::Object(serde_json::Map::new());
            }
            let Some(object) = current.as_object_mut() else {
                return Err(SubstrateError::Invalid("projection terminal mismatch".to_string()));
            };
            object.insert(key.clone(), value);
            Ok(())
        }
        PathComponent::Index(index) => {
            if current.is_null() {
                *current = Value::Array(Vec::new());
            }
            let Some(array) = current.as_array_mut() else {
                return Err(SubstrateError::Invalid("projection terminal mismatch".to_string()));
            };
            while array.len() <= *index {
                array.push(Value::Null);
            }
            array[*index] = value;
            Ok(())
        }
    }
}