Skip to main content

ic_storage/adapter/
region.rs

1//! Operation-local collection access within a retained allocation region.
2use super::{Memory, Storable};
3use crate::{
4    DefaultMemoryImpl, RuntimeGrowError, RuntimeMemory, WASM_PAGE_SIZE_BYTES as PAGE_BYTES,
5    substrate,
6};
7use std::{
8    marker::PhantomData,
9    ops::{Range, RangeBounds},
10    rc::Rc,
11};
12
13const MAX_PAGES: u64 = 4_194_304;
14
15/// Failure to reserve a governed region's virtual extent, before any writes.
16#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
17pub enum RegionGrowError {
18    /// The requested relative extent exceeds the selected region.
19    #[error("requested region extent {minimum} exceeds {maximum} pages")]
20    LimitExceeded {
21        /// Requested relative page count.
22        minimum: u64,
23        /// Maximum relative page count.
24        maximum: u64,
25    },
26    /// Storage refused to grow the containing allocation.
27    #[error("{0}")]
28    Runtime(#[source] RuntimeGrowError),
29}
30
31///
32/// BTreeMapRegion
33/// A B-tree view inside one existing, governed allocation lease.
34///
35/// The caller retains its `Rc<RuntimeMemory>` for disjoint application frames.
36/// Each collection operation loads the current upstream root and allocator;
37/// multiple views may interleave operations without retaining stale roots.
38/// Key scans return owned snapshots, so no cached tree or iterator escapes.
39/// Applications own namespace bounds, codec admission and recovery policy.
40///
41/// Construction performs no IO. Inspect retained framing with [`Self::read`]
42/// before calling collection operations, which retain upstream load/panic
43/// contracts. Only [`Self::initialize`] creates a tree, and only in an empty
44/// region. No method reinitializes nonempty memory or exports raw backing.
45/// As with ordinary collections, callers must not reenter collection access
46/// from a codec or mutate the tree's bytes through their retained lease.
47///
48
49pub struct BTreeMapRegion<K: Storable + Ord + Clone, V: Storable, M: Memory = DefaultMemoryImpl> {
50    memory: RegionMemory<M>,
51    record: PhantomData<(K, V)>,
52}
53
54impl<K: Storable + Ord + Clone, V: Storable, M: Memory> BTreeMapRegion<K, V, M> {
55    /// Select an absolute, half-open range of 65,536-byte allocation pages.
56    ///
57    /// Retains the same allocation lease; no allocation or collection is opened.
58    /// Other owners of the `Rc` may access disjoint frames in that allocation.
59    /// Drop every view and the caller's last `Rc` before reopening the lease.
60    ///
61    /// # Panics
62    /// Panics unless `pages.start < pages.end <= 4_194_304`.
63    #[must_use]
64    pub fn new(memory: Rc<RuntimeMemory<M>>, pages: Range<u64>) -> Self {
65        assert!(pages.start < pages.end && pages.end <= MAX_PAGES);
66
67        Self {
68            memory: RegionMemory { memory, pages },
69            record: PhantomData,
70        }
71    }
72
73    /// Return the currently allocated relative extent in Wasm pages.
74    #[must_use]
75    pub fn allocated_pages(&self) -> u64 {
76        (&self.memory).size()
77    }
78
79    /// Read relative bytes for the application's retained-framing admission.
80    ///
81    /// # Panics
82    /// Panics before IO if the complete read exceeds the allocated region.
83    /// An empty read is valid at the region's end, but not beyond it.
84    pub fn read(&self, offset: u64, dst: &mut [u8]) {
85        (&self.memory).read(offset, dst);
86    }
87
88    /// Create an upstream tree only when the selected region has zero pages.
89    ///
90    /// Call before reserving extra pages. Retained trees need no initialization:
91    /// admit their framing and use the operations directly.
92    ///
93    /// # Panics
94    /// Panics without writing if the region is nonempty. Empty-region creation
95    /// retains upstream growth and panic contracts.
96    pub fn initialize(&mut self) {
97        assert_eq!(self.allocated_pages(), 0, "region is already nonempty");
98        substrate::BTreeMap::<K, V, _>::new(&self.memory);
99    }
100
101    /// Reserve an absolute relative extent without promising entry capacity.
102    ///
103    /// # Errors
104    /// Returns a region-limit or Storage growth error without changing bytes
105    /// or allocation accounting. A satisfied request performs no growth or IO.
106    /// Callers own byte/page budgets and must qualify them for their codecs.
107    /// Mutations retain upstream failure semantics; this is not a transaction
108    /// around an insert that later runs out of space or panics in a codec.
109    pub fn reserve_pages(&mut self, minimum: u64) -> Result<(), RegionGrowError> {
110        self.memory.reserve_pages(minimum)
111    }
112
113    /// Read a record using the current retained root.
114    pub fn get(&self, key: &K) -> Option<V> {
115        self.current_map().get(key)
116    }
117
118    /// Insert using the current retained root and upstream mutation semantics.
119    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
120        self.current_map().insert(key, value)
121    }
122
123    /// Remove using the current retained root and upstream mutation semantics.
124    pub fn remove(&mut self, key: &K) -> Option<V> {
125        self.current_map().remove(key)
126    }
127
128    /// Return the current tree's record count across all namespaces.
129    #[must_use]
130    pub fn len(&self) -> u64 {
131        self.current_map().len()
132    }
133
134    /// Return whether the current tree has no records.
135    #[must_use]
136    pub fn is_empty(&self) -> bool {
137        self.current_map().is_empty()
138    }
139
140    /// Snapshot ordered keys within the caller's namespace/range bounds.
141    ///
142    /// The scan completes before returning; the iterator retains owned keys,
143    /// with no collection cache, memory handle or borrow across later mutations.
144    pub fn keys_range(&self, bounds: impl RangeBounds<K>) -> std::vec::IntoIter<K> {
145        self.keys_range_limited(bounds, usize::MAX)
146    }
147
148    /// Snapshot at most `limit` ordered keys, stopping iteration at that bound.
149    ///
150    /// Unlike `keys_range(bounds).take(limit)`, this bounds collection work before
151    /// allocating the snapshot. Zero returns without loading the tree. Resume
152    /// with an excluded last key; intervening mutations are visible to each call.
153    /// The limit bounds key count, not encoded bytes or instruction cost.
154    pub fn keys_range_limited(
155        &self,
156        bounds: impl RangeBounds<K>,
157        limit: usize,
158    ) -> std::vec::IntoIter<K> {
159        if limit == 0 {
160            return Vec::new().into_iter();
161        }
162
163        self.current_map()
164            .keys_range(bounds)
165            .take(limit)
166            .collect::<Vec<_>>()
167            .into_iter()
168    }
169
170    fn current_map(&self) -> substrate::BTreeMap<K, V, &RegionMemory<M>> {
171        substrate::BTreeMap::load(&self.memory)
172    }
173}
174
175///
176/// RegionMemory
177/// Private bounded IO over an admitted lease. Upstream RestrictedMemory does not
178/// bound reads/writes and may overgrow an absent region; enforce both here.
179///
180
181struct RegionMemory<M: Memory> {
182    memory: Rc<RuntimeMemory<M>>,
183    pages: Range<u64>,
184}
185
186impl<M: Memory> RegionMemory<M> {
187    fn reserve_pages(&self, minimum: u64) -> Result<(), RegionGrowError> {
188        let maximum = self.pages.end - self.pages.start;
189        if minimum > maximum {
190            return Err(RegionGrowError::LimitExceeded { minimum, maximum });
191        }
192        if minimum > self.size() {
193            let additional = self.pages.start + minimum - self.memory.size();
194            self.memory
195                .as_ref()
196                .grow(additional)
197                .map_err(RegionGrowError::Runtime)?;
198        }
199
200        Ok(())
201    }
202
203    fn check_io(&self, offset: u64, count: usize) {
204        let extent = self.size() * PAGE_BYTES;
205        assert!(offset <= extent && count as u64 <= extent - offset);
206    }
207}
208
209impl<M: Memory> Memory for &RegionMemory<M> {
210    fn size(&self) -> u64 {
211        self.memory.size().clamp(self.pages.start, self.pages.end) - self.pages.start
212    }
213
214    fn grow(&self, delta: u64) -> i64 {
215        let previous = self.size();
216        let Some(minimum) = previous.checked_add(delta) else {
217            return -1;
218        };
219
220        if self.reserve_pages(minimum).is_ok() {
221            // The selected range is bounded by MAX_PAGES.
222            i64::try_from(previous).unwrap()
223        } else {
224            -1
225        }
226    }
227
228    fn read(&self, offset: u64, dst: &mut [u8]) {
229        self.check_io(offset, dst.len());
230
231        if !dst.is_empty() {
232            self.memory
233                .read(self.pages.start * PAGE_BYTES + offset, dst);
234        }
235    }
236
237    fn write(&self, offset: u64, src: &[u8]) {
238        self.check_io(offset, src.len());
239
240        if !src.is_empty() {
241            self.memory
242                .write(self.pages.start * PAGE_BYTES + offset, src);
243        }
244    }
245}