Skip to main content

fasm_storage/flatdir/
ops.rs

1//! The directory operations over a [`RawKv`] view: the version check,
2//! node lookup, lazy creation, child listing, and recursive removal.
3//!
4//! Each function ports the corresponding `DirectoryLayer` algorithm
5//! (pinned `foundationdb-0.11.0`) onto the flat layout's row forms. The
6//! flat single-writer view makes the layer's transactional structure
7//! trivial: every operation below is one flat transaction; FDB's
8//! version-vector and conflict-range machinery has no flat analogue.
9//!
10//! Paths are the layer's paths — `&[&[u8]]` of segments, UTF-8 enforced
11//! by the caller at the fasm API boundary (`validate_dir`) and re-checked
12//! here where a segment is packed as a string element.
13
14use core::ops::Bound;
15
16use rand::RngExt;
17
18use crate::flatdir::error::FlatError;
19use crate::flatdir::hca::{allocate, allocate_async};
20use crate::flatdir::layout::{
21    COUNTERS_BASE, LAYER_TAG, LAYOUT_VERSION, NODE_PREFIX, RECENT_BASE, ROOT_NODE, VERSION_KEY,
22    child_key, children_key_range, data_region, layer_key, node_key_range, node_subspace,
23    parse_version,
24};
25use crate::flatdir::tuple::{self, unpack_child_name, unpack_i64_full};
26use crate::keyspace::next_prefix;
27use crate::maybe_send::MaybeSend;
28use crate::rawkv::{AsyncRawKv, RawKv};
29use crate::stream::KvPair;
30
31/// Convert an owned bound pair into references (the `RawKv` bound type).
32pub(crate) fn bounds_ref(b: &(Bound<Vec<u8>>, Bound<Vec<u8>>)) -> (Bound<&[u8]>, Bound<&[u8]>) {
33    (bound_ref1(&b.0), bound_ref1(&b.1))
34}
35
36fn bound_ref1(b: &Bound<Vec<u8>>) -> Bound<&[u8]> {
37    match b {
38        Bound::Unbounded => Bound::Unbounded,
39        Bound::Included(v) => Bound::Included(v.as_slice()),
40        Bound::Excluded(v) => Bound::Excluded(v.as_slice()),
41    }
42}
43
44/// Validate the raw value stored at [`VERSION_KEY`].
45///
46/// Returns `Ok(true)` when a compatible version row is present, `Ok(false)`
47/// when the row is absent (fresh store), and `Err(FlatError::Foreign)` when
48/// the value is malformed or names a version this layout does not read.
49fn validate_version_value<E>(value: Option<&[u8]>) -> Result<bool, FlatError<E>> {
50    match value {
51        None => Ok(false),
52        Some(v) => match parse_version(v) {
53            None => Err(FlatError::Foreign),
54            Some((major, minor, _)) => {
55                if major > 1 || minor > 0 {
56                    Err(FlatError::Foreign)
57                } else {
58                    Ok(true)
59                }
60            }
61        },
62    }
63}
64
65fn node_containing_range(prefix: &[u8]) -> (Vec<u8>, Vec<u8>) {
66    let mut key_after = prefix.to_vec();
67    key_after.push(0);
68    let range_end = {
69        let mut k = NODE_PREFIX.to_vec();
70        k.extend_from_slice(&tuple::pack_bytes(&key_after));
71        k
72    };
73    let mut scan_start = NODE_PREFIX.to_vec();
74    scan_start.push(0);
75    (scan_start, range_end)
76}
77
78fn prev_node_contains_prefix(row: &KvPair, prefix: &[u8]) -> bool {
79    let rel = &row.key[NODE_PREFIX.len()..];
80    tuple::first_element_payload(rel).is_some_and(|prev| prefix.starts_with(&prev))
81}
82
83fn node_subspace_probe_range(prefix: &[u8]) -> (Vec<u8>, Vec<u8>) {
84    let ns_start = {
85        let mut k = NODE_PREFIX.to_vec();
86        k.extend_from_slice(&tuple::pack_bytes(prefix));
87        k
88    };
89    let ns_end = {
90        let mut k = NODE_PREFIX.to_vec();
91        k.extend_from_slice(&tuple::pack_bytes(&next_prefix(prefix).expect(
92            "next_prefix fails only on all-0xFF; allocated prefixes start 0x0c..=0x1c",
93        )));
94        k
95    };
96    (ns_start, ns_end)
97}
98
99fn prefix_data_probe_range(prefix: &[u8]) -> (Vec<u8>, Vec<u8>) {
100    let mut start = prefix.to_vec();
101    start.push(0x00);
102    let mut end = prefix.to_vec();
103    end.push(0xFF);
104    end.push(0x00);
105    (start, end)
106}
107
108fn unpack_child_rows<E>(node: &[u8], rows: &[KvPair]) -> Result<Vec<String>, FlatError<E>> {
109    let mut names = Vec::with_capacity(rows.len());
110    for row in rows {
111        let key = &row.key;
112        if !key.starts_with(node) {
113            return Err(FlatError::Corrupt);
114        }
115        let rel = &key[node.len()..];
116        names.push(unpack_child_name(rel).ok_or(FlatError::Corrupt)?);
117    }
118    names.sort();
119    Ok(names)
120}
121
122fn validate_scanned_rows<E>(
123    node_rows: &[KvPair],
124    data_rows_scan: &[KvPair],
125) -> Result<(usize, usize), FlatError<E>> {
126    let mut data_rows = 0usize;
127    let mut child_rows = 0usize;
128    let mut layer_rows: std::collections::BTreeSet<Vec<u8>> = std::collections::BTreeSet::new();
129    let mut child_targets: std::collections::BTreeSet<Vec<u8>> = std::collections::BTreeSet::new();
130    let mut all_live: std::collections::BTreeSet<Vec<u8>> = std::collections::BTreeSet::new();
131
132    for row in node_rows {
133        let key = &row.key;
134        let value = &row.value;
135        if key == VERSION_KEY {
136            let (major, minor, _patch) = parse_version(value).ok_or(FlatError::Foreign)?;
137            if major > 1 || minor > 0 {
138                // The same gate as `check_version_read`: a foreign
139                // version row is not a healthy layout, even when it
140                // parses.
141                return Err(FlatError::Foreign);
142            }
143            continue;
144        }
145        if key.starts_with(COUNTERS_BASE) {
146            unpack_i64_full(&key[COUNTERS_BASE.len()..]).ok_or(FlatError::Corrupt)?;
147            if value.len() != 8 {
148                return Err(FlatError::Corrupt);
149            }
150            continue;
151        }
152        if key.starts_with(RECENT_BASE) {
153            unpack_i64_full(&key[RECENT_BASE.len()..]).ok_or(FlatError::Corrupt)?;
154            if !value.is_empty() {
155                return Err(FlatError::Corrupt);
156            }
157            continue;
158        }
159        // A node row: NODE_PREFIX ‖ BYTES(P) ‖ row. The root node's P is
160        // the reserved byte [0xFE] (not an HCA allocation); every other
161        // node's P is a packed i64. A key that does not start with the
162        // node prefix is not a node row: foreign content.
163        if !key.starts_with(NODE_PREFIX) {
164            return Err(FlatError::Foreign);
165        }
166        let rel = &key[NODE_PREFIX.len()..];
167        let (escaped, row_rel) = split_node_row(rel).ok_or(FlatError::Foreign)?;
168        // `split_node_row` returns the escaped payload for the row-offset
169        // arithmetic; the prefix itself must be unescaped before
170        // unpacking — a packed prefix whose big-endian payload contains a
171        // `0x00` byte (e.g. 256, 512, 65536) escapes to `0x00 0xFF`
172        // inside the node key.
173        let prefix: Vec<u8> = if escaped == [0xFE] {
174            vec![0xFE]
175        } else {
176            let raw_prefix = tuple::first_element_payload(rel).ok_or(FlatError::Foreign)?;
177            unpack_i64_full(&raw_prefix)
178                .map(tuple::pack_i64)
179                .ok_or(FlatError::Corrupt)?
180        };
181        // The BYTES element re-packs canonically: a node row's leading
182        // element is the canonical packing of P.
183        let expected_node = node_subspace(&prefix);
184        if key.len() < expected_node.len() || !key.starts_with(&expected_node) {
185            return Err(FlatError::Corrupt);
186        }
187        if row_rel == LAYER_TAG {
188            if !value.is_empty() {
189                return Err(FlatError::Corrupt);
190            }
191            layer_rows.insert(prefix.clone());
192            all_live.insert(prefix);
193            continue;
194        }
195        // A child row: INT(0) ‖ STRING(name), value = child prefix.
196        let _name = unpack_child_name(row_rel).ok_or(FlatError::Corrupt)?;
197        let child_prefix = unpack_i64_full(value)
198            .map(tuple::pack_i64)
199            .ok_or(FlatError::Corrupt)?;
200        child_rows += 1;
201        all_live.insert(prefix);
202        all_live.insert(child_prefix.clone());
203        child_targets.insert(child_prefix);
204    }
205    // Every node that is a child's target must have its layer row.
206    for target in &child_targets {
207        if !layer_rows.contains(target) {
208            return Err(FlatError::Corrupt);
209        }
210    }
211    for row in data_rows_scan {
212        let key = &row.key;
213        let Some(p) = data_key_prefix(key) else {
214            return Err(FlatError::Foreign);
215        };
216        if !all_live.contains(p) {
217            return Err(FlatError::Corrupt);
218        }
219        data_rows += 1;
220    }
221    Ok((data_rows, child_rows))
222}
223
224/// Read and enforce the store's version row (the layer's `check_version`,
225/// verbatim):
226///
227/// * missing → fresh: succeed, and write the version row iff
228///   `allow_create` (lazy initialisation — the first create writes it);
229/// * present → must parse as a 12-byte version; a newer major (or a
230///   read-only newer minor — this layout has no read-only mode, so it
231///   fails closed) is [`FlatError::Foreign`]; a malformed value is
232///   [`FlatError::Foreign`] (the layer calls it "incorrect version
233///   length").
234pub fn check_version<R: RawKv>(raw: &mut R, allow_create: bool) -> Result<(), FlatError<R::Error>> {
235    let present = validate_version_value(raw.get(VERSION_KEY)?.as_deref())?;
236    if allow_create && !present {
237        // The fresh-store branch: the layer's `initialize_directory`
238        // (1.0.0, little-endian).
239        raw.insert(VERSION_KEY, LAYOUT_VERSION)?;
240    }
241    Ok(())
242}
243
244/// The read-only half of [`check_version`]: enforce the version row
245/// without writing it. Read operations pay this one point read per
246/// call (the layer's per-entry-point cost).
247pub fn check_version_read<R: RawKv>(raw: &R) -> Result<(), FlatError<R::Error>> {
248    validate_version_value(raw.get(VERSION_KEY)?.as_deref())?;
249    Ok(())
250}
251
252/// Find the allocated prefix of the node at `path` (the layer's `find`,
253/// verbatim): walk from the root node; a missing child row stops the walk
254/// with `Ok(None)` — missing parents are not errors.
255///
256/// An empty path is the layer's root: it always exists, and its
257/// "prefix" is the node prefix itself (never used as a data prefix — the
258/// fasm mapping always carries the anchor segment).
259pub fn find<R: RawKv>(raw: &R, path: &[&[u8]]) -> Result<Option<Vec<u8>>, FlatError<R::Error>> {
260    if path.is_empty() {
261        return Ok(Some(NODE_PREFIX.to_vec()));
262    }
263    let mut node = ROOT_NODE.to_vec();
264    let mut prefix = NODE_PREFIX.to_vec();
265    for seg in path {
266        let name = core::str::from_utf8(seg).map_err(|_| FlatError::Corrupt)?;
267        let key = child_key(&node, name);
268        let Some(value) = raw.get(&key)? else {
269            return Ok(None);
270        };
271        // The value is the child's allocated prefix (a packed i64); a
272        // malformed value is a corrupt node row.
273        if unpack_i64_full(&value).is_none() {
274            return Err(FlatError::Corrupt);
275        }
276        node = node_subspace(&value);
277        prefix = value;
278    }
279    Ok(Some(prefix))
280}
281
282/// The raw key that owns a data key (the layer's `node_containing_key`):
283/// for a data key `P ‖ k`, the prefix `P` is the packed `i64` at the
284/// front of the key.
285///
286/// Returns the prefix (`P`), or `None` when the key is not a data key
287/// with a well-formed allocated prefix at its front (meta keys, foreign
288/// content, reserved-region rows).
289pub fn data_key_prefix(key: &[u8]) -> Option<&[u8]> {
290    if key.is_empty() {
291        return None;
292    }
293    // A packed i64 first byte is 0x0c..=0x1c; anything else (0x00..0x0b,
294    // 0x1d..=0xff) is not a data key.
295    match key[0] {
296        0x0c..=0x1c => {
297            let n = (key[0] as i8 - 0x14).unsigned_abs() as usize;
298            let len = 1 + n;
299            if key.len() < len {
300                return None;
301            }
302            let packed = &key[..len];
303            unpack_i64_full(packed)?;
304            Some(packed)
305        }
306        _ => None,
307    }
308}
309
310/// Whether an allocated prefix is free (the layer's `is_prefix_free`,
311/// verbatim): the prefix is free when (a) no existing node's child rows
312/// could own a key in the prefix's data region — checked by the
313/// `node_containing_key` reverse scan over the node region, and (b) the
314/// prefix's own node subspace holds no rows.
315///
316/// Both checks hold for every HCA-allocated prefix; a violation here is
317/// an allocator-invariant failure ([`FlatError::Corrupt`]), reported by
318/// the caller.
319pub fn is_prefix_free<R: RawKv>(raw: &R, prefix: &[u8]) -> Result<bool, FlatError<R::Error>> {
320    if prefix.is_empty() {
321        return Ok(false);
322    }
323    if prefix.starts_with(NODE_PREFIX) {
324        return Ok(false);
325    }
326    // (a) node_containing_key: the largest node row strictly below the
327    // candidate's position in the node region. FDB reverse-scans with
328    // limit 1; the flat view scans ascending and takes the last.
329    {
330        let (scan_start, range_end) = node_containing_range(prefix);
331        let rows = raw.scan(
332            Bound::Included(scan_start.as_slice()),
333            Bound::Excluded(range_end.as_slice()),
334            true,
335        )?;
336        if let Some(row) = rows.last()
337            && prev_node_contains_prefix(row, prefix)
338        {
339            return Ok(false);
340        }
341    }
342    // (b) the candidate's own node subspace must be empty, over the
343    // layer's exact range [BYTES(P), BYTES(strinc(P))).
344    {
345        let (ns_start, ns_end) = node_subspace_probe_range(prefix);
346        let rows = raw.scan(
347            Bound::Included(ns_start.as_slice()),
348            Bound::Excluded(ns_end.as_slice()),
349            true,
350        )?;
351        Ok(rows.is_empty())
352    }
353}
354
355/// The `get_prefix` range probe: whether the candidate's data region
356/// `[prefix ‖ 0x00, prefix ‖ 0xFF]` holds any row (verbatim: a limit-1
357/// range read; the flat view counts).
358pub fn prefix_data_region_occupied<R: RawKv>(
359    raw: &R,
360    prefix: &[u8],
361) -> Result<bool, FlatError<R::Error>> {
362    let (start, end) = prefix_data_probe_range(prefix);
363    Ok(!raw
364        .scan(
365            Bound::Included(start.as_slice()),
366            Bound::Excluded(end.as_slice()),
367            true,
368        )?
369        .is_empty())
370}
371
372/// Open (and optionally create) the directory at `path`, returning its
373/// allocated prefix.
374///
375/// This composes the layer's `create_or_open_internal` + `create_internal`
376/// over the flat view: version check (read mode), the node walk
377/// (`find`), and on creation — the version check (create mode, which
378/// lazily writes the version row on a fresh store), the HCA allocation,
379/// the two prefix-freedom checks, the lazy parent creation, and the
380/// child-row + layer-row writes.
381pub fn create_or_open<R: RawKv, RNG: RngExt>(
382    raw: &mut R,
383    path: &[&[u8]],
384    allow_create: bool,
385    rng: &mut RNG,
386) -> Result<Option<Vec<u8>>, FlatError<R::Error>> {
387    check_version(raw, false)?;
388    if let Some(prefix) = find(raw, path)? {
389        return Ok(Some(prefix));
390    }
391    if !allow_create {
392        return Ok(None);
393    }
394    // create_internal (verbatim order): version check with creation,
395    // allocation, both prefix checks, parent creation, row writes.
396    check_version(raw, true)?;
397    let new_prefix = tuple::pack_i64(allocate(raw, rng)?);
398    if prefix_data_region_occupied(raw, &new_prefix)? {
399        // PrefixNotEmpty: the allocator produced a used prefix — an
400        // invariant failure, not a retryable one.
401        return Err(FlatError::Corrupt);
402    }
403    if !is_prefix_free(raw, &new_prefix)? {
404        return Err(FlatError::Corrupt);
405    }
406    let (last, parent_path) = path
407        .split_last()
408        .expect("find said the path is missing; it is non-empty");
409    let parent_node = if parent_path.is_empty() {
410        ROOT_NODE.to_vec()
411    } else {
412        // get_parent_node (verbatim): the parent is opened (created)
413        // lazily — intermediate nodes appear only on demand.
414        let parent_prefix =
415            create_or_open(raw, parent_path, true, rng)?.expect("the parent path was just created");
416        node_subspace(&parent_prefix)
417    };
418    let name = core::str::from_utf8(last).map_err(|_| FlatError::Corrupt)?;
419    raw.insert(&child_key(&parent_node, name), &new_prefix)?;
420    raw.insert(&layer_key(&node_subspace(&new_prefix)), &[])?;
421    Ok(Some(new_prefix))
422}
423
424/// List the immediate children of the directory with allocated prefix
425/// `prefix`, sorted by name (the layer's `list`).
426pub fn list_children<R: RawKv>(raw: &R, prefix: &[u8]) -> Result<Vec<String>, FlatError<R::Error>> {
427    let node = node_subspace(prefix);
428    let r = children_key_range(&node);
429    let (s, e) = bounds_ref(&r);
430    let rows = raw.scan(s, e, true)?;
431    unpack_child_rows(&node, &rows)
432}
433
434/// Remove the directory at `path` and its entire subtree (the layer's
435/// `remove_internal` + `remove_recursive` + `remove_from_parent`,
436/// verbatim operation order): recurse into every child, clear the
437/// directory's data region, clear the node's own rows, then delete the
438/// child row in the (re-found) parent, tolerating a missing parent.
439///
440/// `Ok(false)` when the path does not exist. An empty path is the layer
441/// root and is not removable; the fasm mapping never passes one (the
442/// fasm root directory is rejected before reaching this function).
443pub fn remove_dir<R: RawKv>(raw: &mut R, path: &[&[u8]]) -> Result<bool, FlatError<R::Error>> {
444    check_version(raw, true)?;
445    if path.is_empty() {
446        // CannotModifyRootDirectory (the layer): unreachable in the fasm
447        // mapping; a precondition violation, not a structural fault.
448        return Err(FlatError::Corrupt);
449    }
450    let Some(prefix) = find(raw, path)? else {
451        return Ok(false);
452    };
453    remove_recursive(raw, &prefix)?;
454    // remove_from_parent (verbatim): re-resolve the parent and tolerate
455    // its absence. `find` of the empty path answers the root node, so a
456    // single-segment path clears the child row the layer holds under the
457    // root node — the same row the create path wrote.
458    let (last, parent_path) = path.split_last().expect("empty path rejected above");
459    if let Some(parent_prefix) = find(raw, parent_path)? {
460        let name = core::str::from_utf8(last).map_err(|_| FlatError::Corrupt)?;
461        let parent_node = node_subspace(&parent_prefix);
462        raw.delete(&child_key(&parent_node, name))?;
463    }
464    Ok(true)
465}
466
467/// The recursive removal of a directory node (verbatim): scan the
468/// children subspace, recurse into each child (deepest-first via the
469/// recursion), then clear the data region, then the node's own rows.
470fn remove_recursive<R: RawKv>(raw: &mut R, prefix: &[u8]) -> Result<(), FlatError<R::Error>> {
471    let node = node_subspace(prefix);
472    let r = children_key_range(&node);
473    let (s, e) = bounds_ref(&r);
474    let rows = raw.scan(s, e, true)?;
475    for row in &rows {
476        // The child row's value is the child's allocated prefix (packed
477        // i64); a malformed value is corrupt structure.
478        if unpack_i64_full(&row.value).is_none() {
479            return Err(FlatError::Corrupt);
480        }
481        remove_recursive(raw, &row.value)?;
482    }
483    let dr = data_region(prefix);
484    let (ds, de) = bounds_ref(&dr);
485    raw.clear_range(ds, de)?;
486    let nr = node_key_range(&node);
487    let (ns, ne) = bounds_ref(&nr);
488    raw.clear_range(ns, ne)?;
489    Ok(())
490}
491
492/// A whole-store walk that validates every row against the layout.
493///
494/// Every row must classify into exactly one kind (version, HCA
495/// counter, HCA recent, node row, data row) with well-formed fields;
496/// every node that is referenced as a child must have its layer row;
497/// every data key must resolve to such a live directory. Returns the
498/// counted (data rows, child rows); `Err(FlatError::Corrupt)` on a
499/// malformed row, `Err(FlatError::Foreign)` on content the layout does
500/// not own (a row that classifies into no kind).
501pub fn validate<R: RawKv>(raw: &R) -> Result<(usize, usize), FlatError<R::Error>> {
502    let mut node_scan_start = NODE_PREFIX.to_vec();
503    node_scan_start.push(0);
504    // Unbounded end: the walk also covers node keys at or above
505    // `[FE FF 00]` and the `0xFF` reserved region, so a foreign row
506    // anywhere in the store is caught, not just below `0xFF`.
507    let node_rows = raw.scan(
508        Bound::Included(node_scan_start.as_slice()),
509        Bound::Unbounded,
510        true,
511    )?;
512    // The data region: every key below the node region must be a data
513    // key resolving to a live directory. The unbounded start also covers
514    // the empty key, which no data key can be.
515    let data_end = vec![NODE_PREFIX[0], 0x00];
516    let data_rows_scan = raw.scan(Bound::Unbounded, Bound::Excluded(data_end.as_slice()), true)?;
517    validate_scanned_rows(&node_rows, &data_rows_scan)
518}
519
520// -- asynchronous counterparts over AsyncRawKv -----------------------------
521
522/// Asynchronous counterpart to [`check_version`].
523pub async fn check_version_async<R: AsyncRawKv>(
524    raw: &mut R,
525    allow_create: bool,
526) -> Result<(), FlatError<R::Error>> {
527    let present = validate_version_value(raw.get(VERSION_KEY).await?.as_deref())?;
528    if allow_create && !present {
529        raw.insert(VERSION_KEY, LAYOUT_VERSION).await?;
530    }
531    Ok(())
532}
533
534/// Asynchronous counterpart to [`check_version_read`].
535pub async fn check_version_read_async<R: AsyncRawKv>(raw: &R) -> Result<(), FlatError<R::Error>> {
536    validate_version_value(raw.get(VERSION_KEY).await?.as_deref())?;
537    Ok(())
538}
539
540/// Asynchronous counterpart to [`find`].
541pub async fn find_async<R: AsyncRawKv>(
542    raw: &R,
543    path: &[&[u8]],
544) -> Result<Option<Vec<u8>>, FlatError<R::Error>> {
545    if path.is_empty() {
546        return Ok(Some(NODE_PREFIX.to_vec()));
547    }
548    let mut node = ROOT_NODE.to_vec();
549    let mut prefix = NODE_PREFIX.to_vec();
550    for seg in path {
551        let name = core::str::from_utf8(seg).map_err(|_| FlatError::Corrupt)?;
552        let key = child_key(&node, name);
553        let Some(value) = raw.get(&key).await? else {
554            return Ok(None);
555        };
556        if unpack_i64_full(&value).is_none() {
557            return Err(FlatError::Corrupt);
558        }
559        node = node_subspace(&value);
560        prefix = value;
561    }
562    Ok(Some(prefix))
563}
564
565/// Asynchronous counterpart to [`is_prefix_free`], using bounded limit-1 scans.
566pub async fn is_prefix_free_async<R: AsyncRawKv>(
567    raw: &R,
568    prefix: &[u8],
569) -> Result<bool, FlatError<R::Error>> {
570    if prefix.is_empty() || prefix.starts_with(NODE_PREFIX) {
571        return Ok(false);
572    }
573    {
574        let (scan_start, range_end) = node_containing_range(prefix);
575        let rows = raw
576            .scan(
577                Bound::Included(scan_start.as_slice()),
578                Bound::Excluded(range_end.as_slice()),
579                false,
580                Some(1),
581            )
582            .await?;
583        if let Some(row) = rows.first()
584            && prev_node_contains_prefix(row, prefix)
585        {
586            return Ok(false);
587        }
588    }
589    {
590        let (ns_start, ns_end) = node_subspace_probe_range(prefix);
591        let rows = raw
592            .scan(
593                Bound::Included(ns_start.as_slice()),
594                Bound::Excluded(ns_end.as_slice()),
595                true,
596                Some(1),
597            )
598            .await?;
599        Ok(rows.is_empty())
600    }
601}
602
603/// Asynchronous counterpart to [`prefix_data_region_occupied`], using a limit-1 scan.
604pub async fn prefix_data_region_occupied_async<R: AsyncRawKv>(
605    raw: &R,
606    prefix: &[u8],
607) -> Result<bool, FlatError<R::Error>> {
608    let (start, end) = prefix_data_probe_range(prefix);
609    Ok(!raw
610        .scan(
611            Bound::Included(start.as_slice()),
612            Bound::Excluded(end.as_slice()),
613            true,
614            Some(1),
615        )
616        .await?
617        .is_empty())
618}
619
620/// Asynchronous counterpart to [`create_or_open`].
621///
622/// Uses an explicit stack so deep paths neither allocate boxed recursive
623/// futures nor depend on call-stack depth, while preserving the layer's exact
624/// allocation and row-write order.
625pub async fn create_or_open_async<R: AsyncRawKv, RNG: RngExt + MaybeSend>(
626    raw: &mut R,
627    path: &[&[u8]],
628    allow_create: bool,
629    rng: &mut RNG,
630) -> Result<Option<Vec<u8>>, FlatError<R::Error>> {
631    check_version_async(raw, false).await?;
632    if let Some(prefix) = find_async(raw, path).await? {
633        return Ok(Some(prefix));
634    }
635    if !allow_create {
636        return Ok(None);
637    }
638
639    let mut pending: Vec<(&str, Vec<u8>)> = Vec::new();
640    let mut current_path = path;
641    let mut parent_node = loop {
642        check_version_async(raw, true).await?;
643        let new_prefix = tuple::pack_i64(allocate_async(raw, rng).await?);
644        if prefix_data_region_occupied_async(raw, &new_prefix).await? {
645            return Err(FlatError::Corrupt);
646        }
647        if !is_prefix_free_async(raw, &new_prefix).await? {
648            return Err(FlatError::Corrupt);
649        }
650        let (last, parent_path) = current_path
651            .split_last()
652            .expect("find said the path is missing; it is non-empty");
653        let name = core::str::from_utf8(last).map_err(|_| FlatError::Corrupt)?;
654        pending.push((name, new_prefix));
655
656        if parent_path.is_empty() {
657            break ROOT_NODE.to_vec();
658        }
659        check_version_async(raw, false).await?;
660        if let Some(parent_prefix) = find_async(raw, parent_path).await? {
661            break node_subspace(&parent_prefix);
662        }
663        current_path = parent_path;
664    };
665
666    let mut target_prefix = Vec::new();
667    while let Some((name, new_prefix)) = pending.pop() {
668        raw.insert(&child_key(&parent_node, name), &new_prefix)
669            .await?;
670        let child_node = node_subspace(&new_prefix);
671        raw.insert(&layer_key(&child_node), &[]).await?;
672        parent_node = child_node;
673        target_prefix = new_prefix;
674    }
675    Ok(Some(target_prefix))
676}
677
678/// Asynchronous counterpart to [`list_children`].
679pub async fn list_children_async<R: AsyncRawKv>(
680    raw: &R,
681    prefix: &[u8],
682) -> Result<Vec<String>, FlatError<R::Error>> {
683    let node = node_subspace(prefix);
684    let r = children_key_range(&node);
685    let (s, e) = bounds_ref(&r);
686    let rows = raw.scan(s, e, true, None).await?;
687    unpack_child_rows(&node, &rows)
688}
689
690/// Asynchronous counterpart to [`remove_dir`].
691pub async fn remove_dir_async<R: AsyncRawKv>(
692    raw: &mut R,
693    path: &[&[u8]],
694) -> Result<bool, FlatError<R::Error>> {
695    check_version_async(raw, true).await?;
696    if path.is_empty() {
697        return Err(FlatError::Corrupt);
698    }
699    let Some(prefix) = find_async(raw, path).await? else {
700        return Ok(false);
701    };
702    remove_recursive_async(raw, &prefix).await?;
703    let (last, parent_path) = path.split_last().expect("empty path rejected above");
704    if let Some(parent_prefix) = find_async(raw, parent_path).await? {
705        let name = core::str::from_utf8(last).map_err(|_| FlatError::Corrupt)?;
706        let parent_node = node_subspace(&parent_prefix);
707        raw.delete(&child_key(&parent_node, name)).await?;
708    }
709    Ok(true)
710}
711
712async fn remove_recursive_async<R: AsyncRawKv>(
713    raw: &mut R,
714    prefix: &[u8],
715) -> Result<(), FlatError<R::Error>> {
716    enum Frame {
717        Expand(Vec<u8>),
718        Clear(Vec<u8>),
719    }
720
721    let mut stack = vec![Frame::Expand(prefix.to_vec())];
722    while let Some(frame) = stack.pop() {
723        match frame {
724            Frame::Expand(prefix) => {
725                let node = node_subspace(&prefix);
726                let r = children_key_range(&node);
727                let (s, e) = bounds_ref(&r);
728                let rows = raw.scan(s, e, true, None).await?;
729                for row in &rows {
730                    if unpack_i64_full(&row.value).is_none() {
731                        return Err(FlatError::Corrupt);
732                    }
733                }
734                stack.push(Frame::Clear(prefix));
735                for row in rows.into_iter().rev() {
736                    stack.push(Frame::Expand(row.value));
737                }
738            }
739            Frame::Clear(prefix) => {
740                let node = node_subspace(&prefix);
741                let dr = data_region(&prefix);
742                let (ds, de) = bounds_ref(&dr);
743                raw.clear_range(ds, de).await?;
744                let nr = node_key_range(&node);
745                let (ns, ne) = bounds_ref(&nr);
746                raw.clear_range(ns, ne).await?;
747            }
748        }
749    }
750    Ok(())
751}
752
753/// Asynchronous counterpart to [`validate`].
754pub async fn validate_async<R: AsyncRawKv>(raw: &R) -> Result<(usize, usize), FlatError<R::Error>> {
755    let mut node_scan_start = NODE_PREFIX.to_vec();
756    node_scan_start.push(0);
757    let node_rows = raw
758        .scan(
759            Bound::Included(node_scan_start.as_slice()),
760            Bound::Unbounded,
761            true,
762            None,
763        )
764        .await?;
765    let data_end = vec![NODE_PREFIX[0], 0x00];
766    let data_rows_scan = raw
767        .scan(
768            Bound::Unbounded,
769            Bound::Excluded(data_end.as_slice()),
770            true,
771            None,
772        )
773        .await?;
774    validate_scanned_rows(&node_rows, &data_rows_scan)
775}
776
777/// Split a node-region relative key into (escaped BYTES payload, row
778/// remainder). The relative key is `[code] ‖ escaped ‖ [00] ‖ row`;
779/// `first_bytes_element` returns the escaped payload (escapes included,
780/// terminator excluded), so the row starts after the terminator.
781fn split_node_row(rel: &[u8]) -> Option<(&[u8], &[u8])> {
782    let escaped = tuple::first_bytes_element(rel)?;
783    let row_start = 1 + escaped.len() + 1; // code + escaped + terminator
784    if rel.len() < row_start {
785        return None;
786    }
787    Some((escaped, &rel[row_start..]))
788}
789
790#[cfg(test)]
791mod tests {
792    use super::*;
793    use crate::flatdir::hca::Lcg;
794    use crate::flatengine::Mem;
795
796    /// Create the directory `dir` (fasm path form) under the anchor,
797    /// returning its allocated prefix.
798    fn create<R: RawKv, RNG: RngExt>(
799        raw: &mut R,
800        rng: &mut RNG,
801        dir: &[&str],
802    ) -> Result<Vec<u8>, FlatError<R::Error>> {
803        let segs = path_refs(dir);
804        create_or_open(raw, &as_refs(&segs), true, rng).map(|p| p.expect("created"))
805    }
806
807    /// The layer path for a fasm directory, owned: the anchor segment
808    /// plus the directory segments.
809    fn path_refs(dir: &[&str]) -> Vec<Vec<u8>> {
810        let mut v: Vec<Vec<u8>> = vec![
811            crate::flatdir::layout::ROOT_PATH_SEGMENT
812                .as_bytes()
813                .to_vec(),
814        ];
815        for d in dir {
816            v.push(d.as_bytes().to_vec());
817        }
818        v
819    }
820
821    /// Borrow the owned segments as the `&[&[u8]]` form the ops take.
822    fn as_refs(segs: &[Vec<u8>]) -> Vec<&[u8]> {
823        segs.iter().map(|s| s.as_slice()).collect()
824    }
825
826    /// Resolve (without creating) the directory `dir`.
827    fn resolve<R: RawKv, RNG: RngExt>(
828        raw: &mut R,
829        rng: &mut RNG,
830        dir: &[&str],
831    ) -> Result<Option<Vec<u8>>, FlatError<R::Error>> {
832        let segs = path_refs(dir);
833        create_or_open(raw, &as_refs(&segs), false, rng)
834    }
835
836    fn open_anchor<R: RawKv, RNG: RngExt>(
837        raw: &mut R,
838        rng: &mut RNG,
839    ) -> Result<Vec<u8>, FlatError<R::Error>> {
840        resolve(raw, rng, &[]).map(|p| p.expect("anchor exists"))
841    }
842
843    #[test]
844    fn a_fresh_store_is_fresh_until_the_first_create() {
845        let mut raw = Mem::default();
846        // Reads on a fresh store succeed (verbatim FDB): find is None,
847        // the version row is absent.
848        let segs = path_refs(&[]);
849        assert_eq!(find(&raw, &as_refs(&segs)).unwrap(), None);
850        assert_eq!(raw.get(VERSION_KEY).unwrap(), None);
851        // The first create writes the version row, the anchor node's
852        // layer row, and the HCA rows.
853        let prefix = create(&mut raw, &mut Lcg::new(1), &[]).unwrap();
854        assert_eq!(raw.get(VERSION_KEY).unwrap(), Some(LAYOUT_VERSION.to_vec()));
855        let anchor_node = node_subspace(&prefix);
856        assert!(raw.get(&layer_key(&anchor_node)).unwrap().is_some());
857        // The fasm root now exists (its anchor node row is present).
858        assert_eq!(open_anchor(&mut raw, &mut Lcg::new(2)).unwrap(), prefix);
859    }
860
861    #[test]
862    fn create_builds_the_node_tree_lazy() {
863        let mut raw = Mem::default();
864        let mut rng = Lcg::new(3);
865        let a = create(&mut raw, &mut rng, &["a"]).unwrap();
866        let ab = create(&mut raw, &mut rng, &["a", "b"]).unwrap();
867        let abc = create(&mut raw, &mut rng, &["a", "b", "c"]).unwrap();
868        assert!(!a.is_empty() && !ab.is_empty() && !abc.is_empty());
869        assert_ne!(a, ab);
870        assert_ne!(ab, abc);
871        // Every node has its layer row.
872        for p in [&a, &ab, &abc] {
873            let node = node_subspace(p);
874            assert!(raw.get(&layer_key(&node)).unwrap().is_some());
875        }
876        // Reopening finds the same prefixes (no re-allocation).
877        assert_eq!(
878            resolve(&mut raw, &mut Lcg::new(99), &["a"]).unwrap(),
879            Some(a)
880        );
881        assert_eq!(
882            resolve(&mut raw, &mut Lcg::new(99), &["a", "b", "c"]).unwrap(),
883            Some(abc)
884        );
885    }
886
887    #[test]
888    fn list_children_is_sorted_and_exact() {
889        let mut raw = Mem::default();
890        let mut rng = Lcg::new(4);
891        for name in ["c", "a", "b", "A", "aa"] {
892            create(&mut raw, &mut rng, &[name]).unwrap();
893        }
894        let root = open_anchor(&mut raw, &mut Lcg::new(5)).unwrap();
895        let names = list_children(&raw, &root).unwrap();
896        assert_eq!(names, vec!["A", "a", "aa", "b", "c"]);
897        // An empty directory lists empty (no error).
898        let empty = create(&mut raw, &mut rng, &["empty"]).unwrap();
899        assert!(list_children(&raw, &empty).unwrap().is_empty());
900    }
901
902    #[test]
903    fn remove_deletes_the_whole_subtree() {
904        let mut raw = Mem::default();
905        let mut rng = Lcg::new(5);
906        let a = create(&mut raw, &mut rng, &["a"]).unwrap();
907        let ab = create(&mut raw, &mut rng, &["a", "b"]).unwrap();
908        let ac = create(&mut raw, &mut rng, &["a", "c"]).unwrap();
909        // A data row under each leaf (the data key is prefix || key).
910        let data = |p: &[u8]| {
911            let mut k = p.to_vec();
912            k.extend_from_slice(b"key");
913            k
914        };
915        raw.insert(&data(&a), b"v1").unwrap();
916        raw.insert(&data(&ab), b"v2").unwrap();
917        raw.insert(&data(&ac), b"v3").unwrap();
918
919        assert!(remove_dir(&mut raw, &as_refs(&path_refs(&["a"]))).unwrap());
920        // The whole subtree is gone: layer rows and data rows.
921        for p in [&a, &ab, &ac] {
922            let node = node_subspace(p);
923            assert_eq!(raw.get(&layer_key(&node)).unwrap(), None);
924        }
925        assert_eq!(raw.get(&data(&a)).unwrap(), None);
926        assert_eq!(raw.get(&data(&ab)).unwrap(), None);
927        assert_eq!(raw.get(&data(&ac)).unwrap(), None);
928        // The parent's child row is deleted.
929        let root = open_anchor(&mut raw, &mut Lcg::new(6)).unwrap();
930        assert!(list_children(&raw, &root).unwrap().is_empty());
931        // Removing a missing directory is Ok(false).
932        assert!(!remove_dir(&mut raw, &as_refs(&path_refs(&["a"]))).unwrap());
933        // The store still validates.
934        assert!(validate(&raw).is_ok());
935    }
936
937    #[test]
938    fn remove_tolerates_a_missing_parent() {
939        let mut raw = Mem::default();
940        let mut rng = Lcg::new(6);
941        let _a = create(&mut raw, &mut rng, &["a"]).unwrap();
942        let _ab = create(&mut raw, &mut rng, &["a", "b"]).unwrap();
943        // Removing "a" clears the "a/b" subtree with it; removing "a/b"
944        // afterwards fails the walk at "a" and is Ok(false), not an
945        // error.
946        assert!(remove_dir(&mut raw, &as_refs(&path_refs(&["a"]))).unwrap());
947        assert!(!remove_dir(&mut raw, &as_refs(&path_refs(&["a", "b"]))).unwrap());
948        assert!(validate(&raw).is_ok());
949    }
950
951    #[test]
952    fn a_foreign_version_fails_closed() {
953        let mut raw = Mem::default();
954        // major = 2: newer than this layout reads.
955        let mut v = [0u8; 12];
956        v[0..4].copy_from_slice(&2u32.to_le_bytes());
957        raw.insert(VERSION_KEY, &v).unwrap();
958        let mut rng = Lcg::new(1);
959        let segs = path_refs(&["a"]);
960        assert_eq!(
961            create_or_open(&mut raw, &as_refs(&segs), true, &mut rng).unwrap_err(),
962            FlatError::Foreign
963        );
964        // minor > 0: a same-major foreign store (the read-only rule).
965        let mut raw = Mem::default();
966        let mut v = [0u8; 12];
967        v[0..4].copy_from_slice(&1u32.to_le_bytes());
968        v[4..8].copy_from_slice(&1u32.to_le_bytes());
969        raw.insert(VERSION_KEY, &v).unwrap();
970        let mut rng = Lcg::new(3);
971        let segs = path_refs(&["a"]);
972        assert_eq!(
973            create_or_open(&mut raw, &as_refs(&segs), true, &mut rng).unwrap_err(),
974            FlatError::Foreign
975        );
976        // A short version value is Foreign (incorrect version length).
977        let mut raw = Mem::default();
978        raw.insert(VERSION_KEY, &[1, 0]).unwrap();
979        let mut rng = Lcg::new(2);
980        let segs = path_refs(&["a"]);
981        assert_eq!(
982            create_or_open(&mut raw, &as_refs(&segs), true, &mut rng).unwrap_err(),
983            FlatError::Foreign
984        );
985    }
986
987    #[test]
988    fn an_allocated_prefix_is_not_free() {
989        let mut raw = Mem::default();
990        let mut rng = Lcg::new(1);
991        let p = create(&mut raw, &mut rng, &[]).unwrap();
992        // The layer row occupies the prefix's own node subspace: an
993        // allocated prefix is never free for a new allocation.
994        assert!(!is_prefix_free(&raw, &p).unwrap());
995        // A candidate inside the node region (0xFE ...) is never free
996        // either.
997        assert!(!is_prefix_free(&raw, &[0xFE, 0x01, 0x7F]).unwrap());
998    }
999
1000    #[test]
1001    fn validate_walks_a_populated_store() {
1002        let mut raw = Mem::default();
1003        let mut rng = Lcg::new(11);
1004        for name in ["x", "y"] {
1005            create(&mut raw, &mut rng, &[name]).unwrap();
1006        }
1007        let x = resolve(&mut raw, &mut Lcg::new(12), &["x"])
1008            .unwrap()
1009            .unwrap();
1010        let mut dk = x;
1011        dk.extend_from_slice(b"some-key");
1012        raw.insert(&dk, b"some-value").unwrap();
1013        let (data_rows, child_rows) = validate(&raw).unwrap();
1014        assert_eq!(data_rows, 1);
1015        assert!(child_rows >= 2);
1016    }
1017
1018    #[test]
1019    fn validate_rejects_unknown_content() {
1020        let mut raw = Mem::default();
1021        let mut rng = Lcg::new(12);
1022        let _ = create(&mut raw, &mut rng, &[]).unwrap();
1023        // A row in the data region that does not start with a packed i64.
1024        raw.insert(&[0x03, 0x00], b"foreign").unwrap();
1025        assert_eq!(validate(&raw).unwrap_err(), FlatError::Foreign);
1026    }
1027
1028    #[test]
1029    fn two_stores_same_ops_resolve_the_same_paths() {
1030        // The structural equivalence invariant (the determinism
1031        // invariant's replacement): two stores, same operation
1032        // sequence, may allocate different prefixes (allocation is
1033        // random) but must resolve every path to a working node with
1034        // the same data.
1035        let mut s1 = Mem::default();
1036        let mut s2 = Mem::default();
1037        let mut r1 = Lcg::new(101);
1038        let mut r2 = Lcg::new(202);
1039        for name in ["a", "b", "c"] {
1040            create(&mut s1, &mut r1, &[name]).unwrap();
1041            create(&mut s2, &mut r2, &[name]).unwrap();
1042        }
1043        for name in ["a", "b", "c"] {
1044            let p1 = resolve(&mut s1, &mut r1, &[name]).unwrap().unwrap();
1045            let p2 = resolve(&mut s2, &mut r2, &[name]).unwrap().unwrap();
1046            // A data row under each store's own prefix: same data,
1047            // different raw keys (different prefixes).
1048            let mut k1 = p1;
1049            k1.extend_from_slice(b"k");
1050            let mut k2 = p2;
1051            k2.extend_from_slice(b"k");
1052            s1.insert(&k1, b"v").unwrap();
1053            s2.insert(&k2, b"v").unwrap();
1054            assert_eq!(s1.get(&k1).unwrap(), Some(b"v".to_vec()));
1055            assert_eq!(s2.get(&k2).unwrap(), Some(b"v".to_vec()));
1056            // Both stores validate.
1057            assert!(validate(&s1).is_ok());
1058            assert!(validate(&s2).is_ok());
1059        }
1060    }
1061
1062    /// Validate a healthy store after 129 allocations: three full HCA
1063    /// windows, advanced counter/recent rows, and 129 nodes.
1064    #[test]
1065    fn validate_passes_on_a_healthy_store_past_the_first_hca_window() {
1066        let mut raw = Mem::default();
1067        let mut rng = Lcg::new(7);
1068        for i in 0..129 {
1069            let name = format!("d{i}");
1070            create(&mut raw, &mut rng, &[name.as_str()]).expect("create the directory");
1071        }
1072        validate(&raw).expect("a healthy store must validate");
1073    }
1074
1075    /// A node key whose prefix's packed form contains a `0x00` byte
1076    /// carries that byte escaped (`0x00 0xFF`) inside the BYTES
1077    /// element: prefix 256 packs as `[0x16, 0x01, 0x00]`, so the node
1078    /// key's escaped payload is `[0x16, 0x01, 0x00, 0xFF]`. The walk
1079    /// must unescape the payload before unpacking the prefix — a
1080    /// healthy store validates.
1081    #[test]
1082    fn validate_unescapes_a_node_prefix_with_an_embedded_zero() {
1083        let prefix = tuple::pack_i64(256);
1084        let node = node_subspace(&prefix);
1085        let mut raw = Mem::default();
1086        // The version row (1.0.0), the node's layer row, and a child
1087        // row targeting the node from the root node.
1088        let version = [1u32.to_le_bytes(), 0u32.to_le_bytes(), 0u32.to_le_bytes()].concat();
1089        raw.insert(VERSION_KEY, &version).unwrap();
1090        raw.insert(&layer_key(&node), b"").unwrap();
1091        raw.insert(&child_key(ROOT_NODE, "d"), &prefix).unwrap();
1092        validate(&raw).expect("a healthy store must validate");
1093    }
1094}