Skip to main content

fasm_storage/flatdir/
layout.rs

1//! The exact row layouts of the flat directory layout.
2//!
3//! This module holds the layout constants and the builders that turn a
4//! directory node, a segment name, or an allocated prefix into the raw
5//! row keys and regions the layout operates on. Every row form replicates
6//! what the FoundationDB directory layer (`DirectoryLayer::default()`)
7//! writes into a real FoundationDB keyspace:
8//!
9//! | Row | Key | Value |
10//! |-----|-----|-------|
11//! | version | [`VERSION_KEY`] | 12 bytes: major, minor, patch as little-endian `u32` (1.0.0) |
12//! | HCA counter | [`COUNTERS_BASE`] ‖ packed `i64` window start | 8-byte little-endian allocation count |
13//! | HCA recent | [`RECENT_BASE`] ‖ packed `i64` candidate | empty |
14//! | child | [`child_key`]: node ‖ `i64(0)` ‖ STRING(segment) | the child's allocated prefix (raw bytes) |
15//! | layer | [`layer_key`]: node ‖ BYTES("layer") | layer bytes (always empty in this layout) |
16//! | data | allocated prefix ‖ key | the value |
17//!
18//! Key regions by first byte:
19//!
20//! | First byte | Content |
21//! |---|---|
22//! | `0x00`–`0xFD` | Data keys: an allocated prefix ‖ key |
23//! | `0xFE` | Directory nodes: [`NODE_PREFIX`] ‖ BYTES(allocated prefix), each holding its child rows and layer row; the version key and the HCA counter/recent rows live under the root node in this region |
24//! | `0xFF` | Reserved (empty forever) |
25//!
26//! Allocated prefixes are packed `i64`s: prefix-free (no one is a
27//! byte-prefix of another) and always starting `0x0c..=0x1c`, so a data
28//! key needs no separator byte and no data key can collide with another
29//! directory's data keys, the meta region, or the reserved region.
30//!
31//! The `0xFE`/`0xFF` node and reserved regions, and the content range
32//! `0x00..0xFE`, match `DirectoryLayer::default()` exactly (its
33//! `DEFAULT_NODE_PREFIX` is `0xFE`, its content subspace is the whole
34//! keyspace).
35
36use core::ops::Bound;
37
38use crate::flatdir::tuple::{CODE_BYTES, pack_bytes, pack_i64, pack_string};
39use crate::keyspace::next_prefix;
40
41/// The raw first byte of every directory-node key.
42pub const NODE_PREFIX: &[u8] = &[0xFE];
43/// The reserved first byte: no row of this layout starts with it.
44pub const RESERVED_BYTE: u8 = 0xFF;
45
46/// The root node: `NODE_PREFIX ‖ BYTES([0xFE])` — verbatim from the layer
47/// constructor (`root_node = node_subspace.subspace(&node_subspace.bytes())`
48/// with the default node prefix `0xFE`).
49pub const ROOT_NODE: &[u8] = &[0xFE, 0x01, 0xFE, 0x00];
50
51/// The HCA subspace: root node ‖ BYTES("hca") — `DEFAULT_HCA_PREFIX` is a
52/// byte string in the layer's own code.
53pub const HCA_SUBSPACE: &[u8] = &[0xFE, 0x01, 0xFE, 0x00, 0x01, b'h', b'c', b'a', 0x00];
54
55/// HCA counters subspace: HCA ‖ INT(0).
56pub const COUNTERS_BASE: &[u8] = &[0xFE, 0x01, 0xFE, 0x00, 0x01, b'h', b'c', b'a', 0x00, 0x14];
57
58/// HCA recents subspace: HCA ‖ INT(1).
59pub const RECENT_BASE: &[u8] = &[
60    0xFE, 0x01, 0xFE, 0x00, 0x01, b'h', b'c', b'a', 0x00, 0x15, 0x01,
61];
62
63/// The version key: root node ‖ BYTES("version").
64pub const VERSION_KEY: &[u8] = &[
65    0xFE, 0x01, 0xFE, 0x00, 0x01, b'v', b'e', b'r', b's', b'i', b'o', b'n', 0x00,
66];
67
68/// The layer-row tag: a node's layer row is `node ‖ BYTES("layer")`.
69pub const LAYER_TAG: &[u8] = &[CODE_BYTES, b'l', b'a', b'y', b'e', b'r', 0x00];
70
71/// The version this layout writes and reads: 1.0.0 as three little-endian
72/// `u32`s.
73pub const LAYOUT_VERSION: &[u8] = &[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
74
75/// Parse a version value: three little-endian `u32`s (major, minor,
76/// patch). `None` when the value is shorter than 12 bytes (trailing bytes
77/// beyond 12 are tolerated, matching the layer's `len < 12` check).
78pub fn parse_version(value: &[u8]) -> Option<(u32, u32, u32)> {
79    if value.len() < 12 {
80        return None;
81    }
82    Some((
83        u32::from_le_bytes(value[0..4].try_into().ok()?),
84        u32::from_le_bytes(value[4..8].try_into().ok()?),
85        u32::from_le_bytes(value[8..12].try_into().ok()?),
86    ))
87}
88
89/// The fasm root directory maps to the layer path starting with this
90/// segment; every fasm directory path is `[ROOT_PATH_SEGMENT] ‖ dir`.
91/// The segment is valid UTF-8 and contains a NUL, which no user segment
92/// validation would reject but which keeps the anchor unforgeable from a
93/// single user path level. The fdb backend shares this constant, so the
94/// flat layout and the native layer agree on the anchor mapping.
95pub const ROOT_PATH_SEGMENT: &str = "\0fasm-storage";
96
97/// The node subspace of an allocated prefix: `NODE_PREFIX ‖ BYTES(prefix)`.
98pub fn node_subspace(prefix: &[u8]) -> Vec<u8> {
99    let mut node = NODE_PREFIX.to_vec();
100    node.extend_from_slice(&pack_bytes(prefix));
101    node
102}
103
104/// The child-row key under `node` for segment `name` (UTF-8):
105/// `node ‖ INT(0) ‖ STRING(name)`.
106pub fn child_key(node: &[u8], name: &str) -> Vec<u8> {
107    let mut key = node.to_vec();
108    key.extend_from_slice(&pack_i64(0));
109    key.extend_from_slice(&pack_string(name));
110    key
111}
112
113/// The layer-row key of a node: `node ‖ BYTES("layer")`.
114pub fn layer_key(node: &[u8]) -> Vec<u8> {
115    let mut key = node.to_vec();
116    key.extend_from_slice(LAYER_TAG);
117    key
118}
119
120/// The HCA counter key for a window start: `COUNTERS_BASE ‖ INT(start)`.
121pub fn counter_key(window_start: i64) -> Vec<u8> {
122    let mut key = COUNTERS_BASE.to_vec();
123    key.extend_from_slice(&pack_i64(window_start));
124    key
125}
126
127/// The HCA recent key for a candidate: `RECENT_BASE ‖ INT(candidate)`.
128pub fn recent_key(candidate: i64) -> Vec<u8> {
129    let mut key = RECENT_BASE.to_vec();
130    key.extend_from_slice(&pack_i64(candidate));
131    key
132}
133
134/// The raw keyspace range of a node's own rows (children rows + layer
135/// row): `[node ‖ 0x00, node ‖ 0xFF]` inclusive at both ends, expressed
136/// with the flat engine's half-open end.
137pub fn node_key_range(node: &[u8]) -> (Bound<Vec<u8>>, Bound<Vec<u8>>) {
138    let start = {
139        let mut k = node.to_vec();
140        k.push(0x00);
141        k
142    };
143    let mut end = node.to_vec();
144    end.push(0xFF);
145    end.push(0x00);
146    (Bound::Included(start), Bound::Excluded(end))
147}
148
149/// The raw keyspace range of a node's child rows:
150/// `[node ‖ INT(0) ‖ 0x00, node ‖ INT(0) ‖ 0xFF]` inclusive at both ends.
151pub fn children_key_range(node: &[u8]) -> (Bound<Vec<u8>>, Bound<Vec<u8>>) {
152    let base = {
153        let mut k = node.to_vec();
154        k.extend_from_slice(&pack_i64(0));
155        k
156    };
157    let start = {
158        let mut k = base.clone();
159        k.push(0x00);
160        k
161    };
162    let mut end = base;
163    end.push(0xFF);
164    end.push(0x00);
165    (Bound::Included(start), Bound::Excluded(end))
166}
167
168/// The raw keyspace range of a directory's data:
169/// `[prefix, strinc(prefix))`, where `strinc` is the FoundationDB
170/// successor (increment the last non-`0xFF` byte, drop trailing `0xFF`s)
171/// — exactly the crate's [`next_prefix`], pinned by test.
172///
173/// An allocated prefix (a packed `i64`) never ends in `0xFF` at its last
174/// non-`0xFF` position in a way that makes `strinc` fail: `next_prefix`
175/// returns `Some` for every packed `i64`.
176pub fn data_region(prefix: &[u8]) -> (Bound<Vec<u8>>, Bound<Vec<u8>>) {
177    let end = next_prefix(prefix).expect(
178        "next_prefix fails only on an all-0xFF input; allocated prefixes start 0x0c..=0x1c",
179    );
180    (Bound::Included(prefix.to_vec()), Bound::Excluded(end))
181}
182
183#[cfg(test)]
184mod tests {
185    use super::*;
186    use crate::flatdir::tuple::{unpack_child_name, unpack_i64_full};
187
188    #[test]
189    fn the_constants_are_the_layer_row_bytes() {
190        // Pinned from the `foundationdb` crate's default layer:
191        // node prefix 0xFE, root node = 0xFE || BYTES(0xFE), hca/version/
192        // layer tags as byte strings, counters/recents as INT subspace.
193        assert_eq!(node_subspace(&[0xFE]), ROOT_NODE.to_vec());
194        assert_eq!(
195            HCA_SUBSPACE,
196            &[0xFE, 0x01, 0xFE, 0x00, 0x01, b'h', b'c', b'a', 0x00]
197        );
198        assert_eq!(COUNTERS_BASE[..HCA_SUBSPACE.len()], HCA_SUBSPACE[..]);
199        assert_eq!(RECENT_BASE[..HCA_SUBSPACE.len()], HCA_SUBSPACE[..]);
200        assert_eq!(VERSION_KEY[..ROOT_NODE.len()], ROOT_NODE[..]);
201        assert_eq!(parse_version(LAYOUT_VERSION), Some((1, 0, 0)));
202        // Version key and HCA rows sit under the root node; data and the
203        // reserved region are disjoint.
204        assert!(VERSION_KEY.starts_with(ROOT_NODE));
205        assert!(COUNTERS_BASE.starts_with(ROOT_NODE));
206        assert!(RECENT_BASE.starts_with(ROOT_NODE));
207        // The allocated-prefix data range (first byte 0x0c..=0x1c) never
208        // touches the 0xFE node region or the 0xFF reserved region.
209        for v in [0i64, 1, 255, 256, -1, i64::MAX] {
210            let p = pack_i64(v);
211            assert!((0x0c..=0x1c).contains(&p[0]), "{v}");
212            let (start, end) = data_region(&p);
213            match (start, end) {
214                (Bound::Included(s), Bound::Excluded(e)) => {
215                    // Both ends of the data region stay below the 0xFE
216                    // node region: the prefix starts 0x0c..=0x1c and
217                    // `next_prefix` only increments within that band.
218                    assert!(s[0] < 0xFE && e[0] < 0xFE);
219                }
220                _ => panic!("data_region must be Included/Excluded"),
221            }
222        }
223    }
224
225    #[test]
226    fn strinc_is_next_prefix() {
227        // The layout's region end is FDB's `strinc`; the crate's
228        // property-tested `next_prefix` is that function.
229        for v in [0i64, 1, 254, 255, 256, 65534, 65535, 65536, 1_000_000] {
230            let p = pack_i64(v);
231            let (start, end) = data_region(&p);
232            match end {
233                Bound::Excluded(e) => assert_eq!(Some(e), next_prefix(&p)),
234                _ => panic!(),
235            }
236            assert_eq!(start, Bound::Included(p));
237        }
238        // Region arithmetic: [prefix, strinc(prefix)) holds exactly the
239        // keys prefix || k, and the end is the successor of the whole
240        // prefix block.
241        let p = pack_i64(255); // [0x15, 0xFF] - ends in 0xFF.
242        let (start, end) = data_region(&p);
243        assert_eq!(
244            (start, end),
245            (Bound::Included(p.clone()), Bound::Excluded(vec![0x16]))
246        );
247        for k in [
248            b"".as_slice(),
249            b"k".as_slice(),
250            b"k\0".as_slice(),
251            &[0xFF][..],
252        ] {
253            let mut raw = p.clone();
254            raw.extend_from_slice(k);
255            assert!(
256                raw.as_slice() >= p.as_slice() && raw.as_slice() < [0x16].as_slice(),
257                "key {k:?}"
258            );
259        }
260    }
261
262    #[test]
263    fn child_key_round_trips() {
264        for name in ["a", "hca", "version", "\u{00d4}\0"] {
265            let key = child_key(ROOT_NODE, name);
266            let rel = &key[ROOT_NODE.len()..];
267            assert_eq!(unpack_child_name(rel), Some(name.to_string()));
268        }
269        // The children range holds the child rows and nothing else from
270        // other row kinds: the layer row sits outside it.
271        let (s, e) = children_key_range(ROOT_NODE);
272        match (s, e) {
273            (Bound::Included(s), Bound::Excluded(e)) => {
274                let ck = child_key(ROOT_NODE, "a");
275                assert!(ck >= s && ck < e);
276                let lk = layer_key(ROOT_NODE);
277                assert!(
278                    lk < s || lk >= e,
279                    "layer row must sit outside the children range"
280                );
281            }
282            _ => panic!(),
283        }
284    }
285
286    #[test]
287    fn node_range_holds_child_and_layer_rows() {
288        let node = node_subspace(&[0x15, 0x01]);
289        let (s, e) = node_key_range(&node);
290        match (s, e) {
291            (Bound::Included(s), Bound::Excluded(e)) => {
292                let ck = child_key(&node, "x");
293                assert!(ck >= s && ck < e);
294                let lk = layer_key(&node);
295                assert!(lk >= s && lk < e);
296            }
297            _ => panic!(),
298        }
299    }
300
301    #[test]
302    fn hca_keys_decode() {
303        for (start, key) in [
304            (0i64, counter_key(0)),
305            (64, counter_key(64)),
306            (-7, counter_key(-7)),
307        ] {
308            assert_eq!(unpack_i64_full(&key[COUNTERS_BASE.len()..]), Some(start));
309        }
310        for (cand, key) in [(0i64, recent_key(0)), (4096, recent_key(4096))] {
311            assert_eq!(unpack_i64_full(&key[RECENT_BASE.len()..]), Some(cand));
312        }
313    }
314}