aranya_runtime/storage/
mod.rs

1//! Interfaces for graph storage.
2//!
3//! The [`StorageProvider`] and [`Storage`] interfaces enable high-level
4//! actions on the graph. Traversing the graph is made simpler by splitting
5//! its [`Command`]s into [`Segment`]s. Updating the graph is possible using
6//! [`Perspective`]s, which represent a slice of state.
7
8use alloc::{boxed::Box, string::String, vec::Vec};
9use core::{fmt, ops::Deref};
10
11use buggy::{Bug, BugExt};
12use serde::{Deserialize, Serialize};
13
14use crate::{Address, Command, CommandId, PolicyId, Prior};
15
16pub mod linear;
17pub mod memory;
18
19/// The maximum size of a serialized message
20pub const MAX_COMMAND_LENGTH: usize = 2048;
21
22aranya_crypto::custom_id! {
23    /// The ID of the graph, taken from initialization.
24    pub struct GraphId;
25}
26
27#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
28pub struct Location {
29    pub segment: usize,
30    pub command: usize,
31}
32
33impl From<(usize, usize)> for Location {
34    fn from((segment, command): (usize, usize)) -> Self {
35        Self::new(segment, command)
36    }
37}
38
39impl AsRef<Location> for Location {
40    fn as_ref(&self) -> &Location {
41        self
42    }
43}
44
45impl Location {
46    pub fn new(segment: usize, command: usize) -> Location {
47        Location { segment, command }
48    }
49
50    /// If this is not the first command in a segment, return a location
51    /// pointing to the previous command.
52    #[must_use]
53    pub fn previous(mut self) -> Option<Self> {
54        if let Some(n) = usize::checked_sub(self.command, 1) {
55            self.command = n;
56            Some(self)
57        } else {
58            None
59        }
60    }
61
62    /// Returns true if other location is in the same segment.
63    pub fn same_segment(self, other: Location) -> bool {
64        self.segment == other.segment
65    }
66}
67
68impl fmt::Display for Location {
69    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70        write!(f, "{}:{}", self.segment, self.command)
71    }
72}
73
74/// An error returned by [`Storage`] or [`StorageProvider`].
75#[derive(Debug, PartialEq, Eq, thiserror::Error)]
76pub enum StorageError {
77    #[error("storage already exists")]
78    StorageExists,
79    #[error("no such storage")]
80    NoSuchStorage,
81    #[error("segment index {} is out of bounds", .0.segment)]
82    SegmentOutOfBounds(Location),
83    #[error("command index {} is out of bounds in segment {}", .0.command, .0.segment)]
84    CommandOutOfBounds(Location),
85    #[error("IO error")]
86    IoError,
87    #[error("not a merge command")]
88    NotMerge,
89    #[error("command with id {0} not found")]
90    NoSuchId(CommandId),
91    #[error("policy mismatch")]
92    PolicyMismatch,
93    #[error("cannot write an empty perspective")]
94    EmptyPerspective,
95    #[error("segment must be a descendant of the head for commit")]
96    HeadNotAncestor,
97    #[error("command's parents do not match the perspective head")]
98    PerspectiveHeadMismatch,
99    #[error(transparent)]
100    Bug(#[from] Bug),
101}
102
103/// Handle to storage implementations used by the runtime.
104pub trait StorageProvider {
105    type Perspective: Perspective + Revertable;
106    type Segment: Segment;
107    type Storage: Storage<
108            Segment = Self::Segment,
109            Perspective = Self::Perspective,
110            FactIndex = <Self::Segment as Segment>::FactIndex,
111        >;
112
113    /// Create an unrooted perspective, intended for creating a new graph.
114    ///
115    /// # Arguments
116    ///
117    /// * `policy_id` - The policy to associate with the graph.
118    fn new_perspective(&mut self, policy_id: PolicyId) -> Self::Perspective;
119
120    /// Create a new graph.
121    ///
122    /// # Arguments
123    ///
124    /// * `graph` - ID of the graph, taken from the initialization command.
125    /// * `init` - Contains the data necessary to initialize the new graph.
126    fn new_storage(
127        &mut self,
128        init: Self::Perspective,
129    ) -> Result<(GraphId, &mut Self::Storage), StorageError>;
130
131    /// Get an existing graph.
132    ///
133    /// # Arguments
134    ///
135    /// * `graph` - ID of the graph, taken from the initialization command.
136    fn get_storage(&mut self, graph: GraphId) -> Result<&mut Self::Storage, StorageError>;
137
138    /// Remove a graph.
139    ///
140    /// # Arguments
141    ///
142    /// * `graph` - ID of the graph, taken from the initialization command.
143    fn remove_storage(&mut self, graph: GraphId) -> Result<(), StorageError>;
144
145    /// Gets a list of all stored graphs by their graph ID.
146    // TODO(nikki): rewrite this once we can use coroutines/generators?
147    fn list_graph_ids(
148        &mut self,
149    ) -> Result<impl Iterator<Item = Result<GraphId, StorageError>>, StorageError>;
150}
151
152/// Represents the runtime's graph; [`Command`]s in storage have been validated
153/// by an associated policy and committed to state.
154pub trait Storage {
155    type Perspective: Perspective + Revertable;
156    type FactPerspective: FactPerspective;
157    type Segment: Segment<FactIndex = Self::FactIndex>;
158    type FactIndex: FactIndex;
159
160    /// Returns the location of Command with id if it has been stored by
161    /// searching from the head.
162    fn get_location(&self, address: Address) -> Result<Option<Location>, StorageError> {
163        self.get_location_from(self.get_head()?, address)
164    }
165
166    /// Returns the location of Command with id by searching from the given location.
167    fn get_location_from(
168        &self,
169        start: Location,
170        address: Address,
171    ) -> Result<Option<Location>, StorageError> {
172        let mut queue = Vec::new();
173        queue.push(start);
174        'outer: while let Some(loc) = queue.pop() {
175            let head = self.get_segment(loc)?;
176            if address.max_cut > head.longest_max_cut()? {
177                continue;
178            }
179            if let Some(loc) = head.get_from_max_cut(address.max_cut)? {
180                let command = head.get_command(loc).assume("command must exist")?;
181                if command.id() == address.id {
182                    return Ok(Some(loc));
183                }
184            }
185            // Assumes skip list is sorted in ascending order.
186            // We always want to skip as close to the root as possible.
187            for (skip, max_cut) in head.skip_list() {
188                if max_cut >= &address.max_cut {
189                    queue.push(*skip);
190                    continue 'outer;
191                }
192            }
193            queue.extend(head.prior());
194        }
195        Ok(None)
196    }
197
198    /// Returns the CommandId of the command at the location.
199    fn get_command_id(&self, location: Location) -> Result<CommandId, StorageError>;
200
201    /// Returns a linear perspective at the given location.
202    fn get_linear_perspective(
203        &self,
204        parent: Location,
205    ) -> Result<Option<Self::Perspective>, StorageError>;
206
207    /// Returns a fact perspective at the given location, intended for evaluating braids.
208    /// The fact perspective will include the facts of the command at the given location.
209    fn get_fact_perspective(&self, first: Location) -> Result<Self::FactPerspective, StorageError>;
210
211    /// Returns a merge perspective based on the given locations with the braid as prior facts.
212    fn new_merge_perspective(
213        &self,
214        left: Location,
215        right: Location,
216        last_common_ancestor: (Location, usize),
217        policy_id: PolicyId,
218        braid: Self::FactIndex,
219    ) -> Result<Option<Self::Perspective>, StorageError>;
220
221    /// Returns the segment at the given location.
222    fn get_segment(&self, location: Location) -> Result<Self::Segment, StorageError>;
223
224    /// Returns the head of the graph.
225    fn get_head(&self) -> Result<Location, StorageError>;
226
227    /// Sets the given segment as the head of the graph.  Returns an error if
228    /// the current head is not an ancestor of the provided segment.
229    fn commit(&mut self, segment: Self::Segment) -> Result<(), StorageError>;
230
231    /// Writes the given perspective to a segment.
232    fn write(&mut self, perspective: Self::Perspective) -> Result<Self::Segment, StorageError>;
233
234    /// Writes the given fact perspective to a fact index.
235    fn write_facts(
236        &mut self,
237        fact_perspective: Self::FactPerspective,
238    ) -> Result<Self::FactIndex, StorageError>;
239
240    /// Determine whether the given location is an ancestor of the given segment.
241    fn is_ancestor(
242        &self,
243        search_location: Location,
244        segment: &Self::Segment,
245    ) -> Result<bool, StorageError> {
246        let mut queue = Vec::new();
247        queue.extend(segment.prior());
248        let segment = self.get_segment(search_location)?;
249        let address = segment
250            .get_command(search_location)
251            .assume("location must exist")?
252            .address()?;
253        'outer: while let Some(location) = queue.pop() {
254            if location.segment == search_location.segment
255                && location.command >= search_location.command
256            {
257                return Ok(true);
258            }
259            let segment = self.get_segment(location)?;
260            if address.max_cut > segment.longest_max_cut()? {
261                continue;
262            }
263            for (skip, max_cut) in segment.skip_list() {
264                if max_cut >= &address.max_cut {
265                    queue.push(*skip);
266                    continue 'outer;
267                }
268            }
269            queue.extend(segment.prior());
270        }
271        Ok(false)
272    }
273}
274
275type MaxCut = usize;
276
277/// A segment is a nonempty sequence of commands persisted to storage.
278///
279/// A segment can be one of three types. This might be encoded in a future version of the API.
280/// * init   - This segment is the first segment of the graph and begins with an init command.
281/// * linear - This segment has a single prior command and is simply a sequence of linear commands.
282/// * merge  - This segment merges two other segments and thus begins with a merge command.
283///            A merge segment has a braid as it's prior facts.
284///
285/// Each command past the first must have the parent of the previous command in the segment.
286pub trait Segment {
287    type FactIndex: FactIndex;
288    type Command<'a>: Command
289    where
290        Self: 'a;
291
292    /// Returns the head of the segment.
293    fn head(&self) -> Result<Self::Command<'_>, StorageError>;
294
295    /// Returns the first Command in the segment.
296    fn first(&self) -> Self::Command<'_>;
297
298    /// Returns the location of the head of the segment.
299    fn head_location(&self) -> Location;
300
301    /// Returns the location of the first command.
302    fn first_location(&self) -> Location;
303
304    /// Returns true if the segment contains the location.
305    fn contains(&self, location: Location) -> bool;
306
307    /// Returns the id for the policy used for this segment.
308    fn policy(&self) -> PolicyId;
309
310    /// Returns the prior segments for this segment.
311    fn prior(&self) -> Prior<Location>;
312
313    /// Returns the command at the given location.
314    fn get_command(&self, location: Location) -> Option<Self::Command<'_>>;
315
316    /// Returns the command with the given max cut from within this segment.
317    fn get_from_max_cut(&self, max_cut: usize) -> Result<Option<Location>, StorageError>;
318
319    /// Returns an iterator of commands starting at the given location.
320    fn get_from(&self, location: Location) -> Vec<Self::Command<'_>>;
321
322    /// Get the fact index associated with this segment.
323    fn facts(&self) -> Result<Self::FactIndex, StorageError>;
324
325    fn contains_any<I>(&self, locations: I) -> bool
326    where
327        I: IntoIterator,
328        I::Item: AsRef<Location>,
329    {
330        locations
331            .into_iter()
332            .any(|loc| self.contains(*loc.as_ref()))
333    }
334
335    /// The shortest max cut for this segment.
336    ///
337    /// This will always the max cut of the first command in the segment.
338    fn shortest_max_cut(&self) -> MaxCut;
339
340    /// The longest max cut for this segment.
341    ///
342    /// This will always be the max cut of the last command in the segment.
343    fn longest_max_cut(&self) -> Result<MaxCut, StorageError>;
344
345    /// The skip list is a series of locations that can be safely jumped to
346    /// when searching for a location. As long as the max cut of the location
347    /// you're jumping to is greater than or equal to the location you're
348    /// searching for you can jump to it and be guaranteed not to miss
349    /// the location you're searching for.
350    ///
351    /// For merge commands the last location in the skip list is the least
352    /// common ancestor.
353    fn skip_list(&self) -> &[(Location, MaxCut)];
354}
355
356/// An index of facts in storage.
357pub trait FactIndex: Query {}
358
359/// A perspective is essentially a mutable, in-memory version of a [`Segment`],
360/// with the same three types.
361pub trait Perspective: FactPerspective {
362    /// Returns the id for the policy used for this perspective.
363    fn policy(&self) -> PolicyId;
364
365    /// Adds the given command to the head of the perspective. The command's
366    /// parent must be the head of the perspective.
367    fn add_command(&mut self, command: &impl Command) -> Result<usize, StorageError>;
368
369    /// Returns true if the perspective contains a command with the given ID.
370    fn includes(&self, id: CommandId) -> bool;
371
372    /// Returns the head address in the perspective, if it exists
373    fn head_address(&self) -> Result<Prior<Address>, Bug>;
374}
375
376/// A fact perspective is essentially a mutable, in-memory version of a [`FactIndex`].
377pub trait FactPerspective: QueryMut {}
378
379/// A revertable perspective can make checkpoints and be reverted such that the
380/// state of the perspective matches that when the checkpoint was created.
381pub trait Revertable {
382    /// Create a checkpoint which can be used to revert the perspective.
383    fn checkpoint(&self) -> Checkpoint;
384
385    /// Revert the perspective to the state it was at when the checkpoint was created.
386    fn revert(&mut self, checkpoint: Checkpoint) -> Result<(), Bug>;
387}
388
389/// A checkpoint used to revert perspectives.
390pub struct Checkpoint {
391    /// An index interpreted by a given `Revertable` implementation to revert to a prior point.
392    pub index: usize,
393}
394
395/// Can be queried to look up facts.
396///
397/// Facts are labeled by a name, which are generally a bounded set of human-readable strings determined in advance.
398///
399/// Within a name, facts are an association of compound keys to values. The facts are keyed by a compound key
400/// `(k_1, k_2, ..., k_n)`, where each `k` is a sequence of bytes. The fact value is also a sequence of bytes.
401pub trait Query {
402    /// Look up a named fact by an exact match of the compound key.
403    fn query(&self, name: &str, keys: &[Box<[u8]>]) -> Result<Option<Box<[u8]>>, StorageError>;
404
405    /// Iterator for [`Query::query_prefix`].
406    type QueryIterator: Iterator<Item = Result<Fact, StorageError>>;
407
408    /// Look up all named facts that begin with the prefix of keys, in sorted key order.
409    ///
410    /// The `prefix` is a partial compound key `(k_1, k_2, ..., k_n)`, where each `k` is a sequence of bytes.
411    /// This returns all facts under the name with keys such that `prefix` is equal to a prefix of the fact's keys.
412    fn query_prefix(
413        &self,
414        name: &str,
415        prefix: &[Box<[u8]>],
416    ) -> Result<Self::QueryIterator, StorageError>;
417}
418
419/// A fact with a key and value.
420#[derive(Debug, PartialEq, Eq)]
421pub struct Fact {
422    /// The sequence of keys.
423    pub key: Keys,
424    /// The bytes of the value.
425    pub value: Box<[u8]>,
426}
427
428/// Can mutate facts by inserting and deleting them.
429///
430/// See [`Query`] for details on the nature of facts.
431pub trait QueryMut: Query {
432    /// Insert a fact labeled by a name, with a given compound key and a value.
433    ///
434    /// This fact can later be looked up by [`Query`] methods, using the name and keys.
435    fn insert(&mut self, name: String, keys: Keys, value: Box<[u8]>);
436
437    /// Delete any fact associated to the compound key, under the given name.
438    fn delete(&mut self, name: String, keys: Keys);
439}
440
441/// A sequence of byte-based keys, used for facts.
442#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
443pub struct Keys(Box<[Box<[u8]>]>);
444
445impl Deref for Keys {
446    type Target = [Box<[u8]>];
447    fn deref(&self) -> &[Box<[u8]>] {
448        self.0.as_ref()
449    }
450}
451
452impl AsRef<[Box<[u8]>]> for Keys {
453    fn as_ref(&self) -> &[Box<[u8]>] {
454        self.0.as_ref()
455    }
456}
457
458impl core::borrow::Borrow<[Box<[u8]>]> for Keys {
459    fn borrow(&self) -> &[Box<[u8]>] {
460        self.0.as_ref()
461    }
462}
463
464impl From<&[&[u8]]> for Keys {
465    fn from(value: &[&[u8]]) -> Self {
466        value.iter().copied().collect()
467    }
468}
469
470impl Keys {
471    fn starts_with(&self, prefix: &[Box<[u8]>]) -> bool {
472        self.as_ref().starts_with(prefix)
473    }
474}
475
476impl<B: Into<Box<[u8]>>> FromIterator<B> for Keys {
477    fn from_iter<T: IntoIterator<Item = B>>(iter: T) -> Self {
478        Self(iter.into_iter().map(Into::into).collect())
479    }
480}
481
482// TODO: Fix and enable
483// #[cfg(test)]
484// mod tests;