Skip to main content

ic_storage/runtime/directory_model/
mod.rs

1//! Owned named-allocation directory and durable extent validation.
2
3#[cfg(test)]
4mod tests;
5
6mod format;
7pub(super) mod leases;
8mod persistence;
9
10use crate::{StableKey, hash};
11use serde::{Deserialize, Serialize};
12use std::collections::{BTreeMap, BTreeSet};
13
14const MAX_METADATA_ARENAS: usize = 128;
15const FRAME: &[u8] = b"ICDIRS02";
16
17///
18/// StorageConfig
19/// Resource ceilings checked when creating, opening and extending the directory.
20/// Physical page accounting includes retained metadata and abandoned tails.
21///
22
23#[derive(Clone, Copy, Debug)]
24pub struct StorageConfig {
25    /// Maximum retained named allocations, including currently omitted names.
26    pub allocations: usize,
27    /// Maximum total data extents across every allocation.
28    pub extents: usize,
29    /// Maximum physical backing extent, in 64 KiB Wasm pages.
30    pub pages: u64,
31    /// Encoding and decoding budgets for each directory snapshot.
32    pub directory_bytes: usize,
33}
34
35impl Default for StorageConfig {
36    fn default() -> Self {
37        Self {
38            allocations: 4_096,
39            extents: 16_384,
40            pages: 1_048_576,
41            directory_bytes: 4 * 1024 * 1024,
42        }
43    }
44}
45
46///
47/// AllocationId
48/// Opaque durable identity assigned by the directory. It grants no access.
49///
50
51#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
52pub struct AllocationId(u64);
53
54impl AllocationId {
55    /// Opaque diagnostic identity; callers cannot choose an allocation ID.
56    #[must_use]
57    pub const fn get(self) -> u64 {
58        self.0
59    }
60}
61
62///
63/// Extent
64/// A contiguous range of physical backing pages.
65///
66
67#[derive(Clone, Debug, Eq, PartialEq)]
68struct Extent {
69    start: u64,
70    pub pages: u64,
71}
72
73///
74/// Entry
75/// The stable key, identity and logical extent order for one named allocation.
76///
77
78#[derive(Clone, Debug, Eq, PartialEq)]
79struct Entry {
80    id: AllocationId,
81    key: StableKey,
82    // Logical page order is explicit; physical ranges need not be contiguous.
83    extents: Vec<Extent>,
84}
85
86///
87/// Image
88/// The committed directory generation and its allocation and metadata extents.
89///
90
91#[derive(Clone, Debug, Eq, PartialEq)]
92struct Image {
93    generation: u64,
94    next_id: u64,
95    // High-water mark, including space reserved for directory persistence.
96    next_page: u64,
97    // Reserved snapshot arenas, including the active arena. Never application data.
98    metadata: Vec<Extent>,
99    entries: Vec<Entry>,
100}
101
102/// Directory validation, custody and backing failures.
103#[derive(Debug, thiserror::Error)]
104pub enum Error {
105    /// Logical page count overflowed before any backing access.
106    /// allocation page count overflow.
107    #[error("allocation page count overflow")]
108    ArithmeticOverflow,
109    /// directory budget exceeded.
110    #[error("directory budget exceeded")]
111    Budget,
112    /// invalid directory: {0}.
113    #[error("invalid directory: {0}")]
114    Invalid(&'static str),
115    /// allocation already has a live lease.
116    #[error("allocation already has a live lease")]
117    AlreadyOpen,
118    /// access exceeds allocation bounds.
119    #[error("access exceeds allocation bounds")]
120    Bounds,
121    /// backing already has a live owner.
122    #[error("backing already has a live owner")]
123    AlreadyClaimed,
124    /// allocation does not exist.
125    #[error("allocation does not exist")]
126    Missing,
127    /// prepared directory belongs to a stale generation.
128    #[error("prepared directory belongs to a stale generation")]
129    Stale,
130    /// backing growth refused.
131    #[error("backing growth refused")]
132    Growth,
133    /// directory owner is poisoned after interrupted backing IO.
134    #[error("directory owner is poisoned after interrupted backing IO")]
135    Poisoned,
136}
137
138#[derive(Clone, Debug)]
139struct Directory {
140    image: Image,
141    by_key: BTreeMap<StableKey, AllocationId>,
142    by_id: BTreeMap<AllocationId, usize>,
143    // Derived only from validated extents; never persisted as a second authority.
144    logical_ends: Vec<Vec<u64>>,
145    budget: StorageConfig,
146    data_start: u64,
147}
148
149///
150/// Prepared
151/// A candidate owns all tentative changes. Preparation never mutates its base.
152///
153
154#[derive(Debug)]
155struct Prepared {
156    base: Image,
157    candidate: Directory,
158}
159
160impl Directory {
161    fn empty(budget: StorageConfig, data_start: u64) -> Result<Self, Error> {
162        Self::validate(
163            Image {
164                generation: 0,
165                next_id: 1,
166                next_page: data_start,
167                metadata: vec![],
168                entries: vec![],
169            },
170            budget,
171            data_start,
172        )
173    }
174
175    fn validate(image: Image, budget: StorageConfig, data_start: u64) -> Result<Self, Error> {
176        if image.entries.len() > budget.allocations || image.next_page > budget.pages {
177            return Err(Error::Budget);
178        }
179        if data_start == 0 || image.next_page < data_start || image.next_id == 0 {
180            return Err(Error::Invalid("root boundary or identity watermark"));
181        }
182        let mut by_key = BTreeMap::new();
183        let mut by_id = BTreeMap::new();
184        if image.metadata.len() > MAX_METADATA_ARENAS {
185            return Err(Error::Budget);
186        }
187        let mut ranges = Vec::new();
188        for extent in &image.metadata {
189            let end = extent
190                .start
191                .checked_add(extent.pages)
192                .ok_or(Error::Budget)?;
193            if extent.pages == 0 || extent.start < data_start || end > image.next_page {
194                return Err(Error::Invalid("metadata arena outside backing"));
195            }
196            ranges.push((extent.start, end));
197        }
198        let mut data_extents = 0;
199        let mut previous = None;
200        for (index, entry) in image.entries.iter().enumerate() {
201            if entry.id.0 == 0
202                || entry.id.0 >= image.next_id
203                || previous.is_some_and(|id| id >= entry.id)
204            {
205                return Err(Error::Invalid("noncanonical allocation identities"));
206            }
207            previous = Some(entry.id);
208            if by_key.insert(entry.key.clone(), entry.id).is_some() {
209                return Err(Error::Invalid("duplicate stable key"));
210            }
211            by_id.insert(entry.id, index);
212            if entry.extents.len() > budget.extents.saturating_sub(data_extents) {
213                return Err(Error::Budget);
214            }
215            data_extents += entry.extents.len();
216
217            for extent in &entry.extents {
218                let end = extent
219                    .start
220                    .checked_add(extent.pages)
221                    .ok_or(Error::Invalid("extent overflow"))?;
222                if extent.pages == 0 || extent.start < data_start || end > image.next_page {
223                    return Err(Error::Invalid("extent outside data region"));
224                }
225                ranges.push((extent.start, end));
226            }
227        }
228        ranges.sort_unstable();
229        if ranges.windows(2).any(|pair| pair[0].1 > pair[1].0) {
230            return Err(Error::Invalid("overlapping physical extents"));
231        }
232        let logical_ends = image
233            .entries
234            .iter()
235            .map(|entry| {
236                let mut total = 0;
237
238                entry
239                    .extents
240                    .iter()
241                    .map(|extent| {
242                        // Disjoint ranges fit within the admitted physical watermark.
243                        total += extent.pages;
244
245                        total
246                    })
247                    .collect()
248            })
249            .collect();
250
251        Ok(Self {
252            image,
253            by_key,
254            by_id,
255            logical_ends,
256            budget,
257            data_start,
258        })
259    }
260
261    fn decode(bytes: &[u8], budget: StorageConfig, data_start: u64) -> Result<Self, Error> {
262        if bytes.len() > budget.directory_bytes {
263            return Err(Error::Budget);
264        }
265        let payload = bytes
266            .strip_prefix(FRAME)
267            .ok_or(Error::Invalid("directory frame"))?;
268        let image = format::decode(payload, budget)?;
269
270        Self::validate(image, budget, data_start)
271    }
272
273    fn encode(&self) -> Result<Vec<u8>, Error> {
274        format::encode(&self.image, self.budget.directory_bytes)
275    }
276
277    fn prepare(
278        &self,
279        keys: Vec<StableKey>,
280        growth: &[(AllocationId, u64)],
281    ) -> Result<Prepared, Error> {
282        let mut image = self.image.clone();
283        let keys: BTreeSet<_> = keys.into_iter().collect();
284        for key in keys {
285            if self.by_key.contains_key(&key) {
286                continue;
287            }
288            if image.entries.len() >= self.budget.allocations {
289                return Err(Error::Budget);
290            }
291            let id = AllocationId(image.next_id);
292            image.next_id = image.next_id.checked_add(1).ok_or(Error::Budget)?;
293            image.entries.push(Entry {
294                id,
295                key,
296                extents: vec![],
297            });
298        }
299        for &(id, pages) in growth {
300            // Growth applies only to bindings already present in the base.
301            let index = *self.by_id.get(&id).ok_or(Error::Missing)?;
302            if pages == 0 {
303                continue;
304            }
305            let start = image.next_page;
306            image.next_page = start.checked_add(pages).ok_or(Error::Budget)?;
307
308            if let Some(last) = image.entries[index].extents.last_mut()
309                && last.start + last.pages == start
310            {
311                last.pages += pages;
312            } else {
313                image.entries[index].extents.push(Extent { start, pages });
314            }
315        }
316        image.generation = image.generation.checked_add(1).ok_or(Error::Budget)?;
317        let candidate = Self::validate(image, self.budget, self.data_start)?;
318
319        Ok(Prepared {
320            base: self.image.clone(),
321            candidate,
322        })
323    }
324
325    fn page_span(&self, id: AllocationId, logical: u64) -> Option<(u64, u64)> {
326        let index = *self.by_id.get(&id)?;
327        let ends = &self.logical_ends[index];
328        let slot = ends.partition_point(|&end| end <= logical);
329        let extent = self.image.entries[index].extents.get(slot)?;
330        let start = if slot == 0 { 0 } else { ends[slot - 1] };
331
332        Some((extent.start + logical - start, ends[slot] - logical))
333    }
334}