aranya-runtime 0.21.0

The Aranya core runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
//! Interfaces for graph storage.
//!
//! The [`StorageProvider`] and [`Storage`] interfaces enable high-level
//! actions on the graph. Traversing the graph is made simpler by splitting
//! its [`Command`]s into [`Segment`]s. Updating the graph is possible using
//! [`Perspective`]s, which represent a slice of state.

use alloc::{boxed::Box, string::String, vec::Vec};
use core::{fmt, ops::Deref};

use buggy::Bug;
use serde::{Deserialize, Serialize};

use crate::{Address, CmdId, Command, PolicyId, Prior};

pub mod linear;

/// Default capacity for the traversal queue.
///
/// This should be large enough to hold the maximum expected "active frontier"
/// during backward traversal, which is bounded by peer count.
pub const QUEUE_CAPACITY: usize = 512;

/// Type for the queue used in traversal operations.
///
/// Locations with the highest `max_cut` are processed first. This bounds the
/// queue size to the graph width at any given `max_cut` level, rather than
/// accumulating entries across many levels as a FIFO would.
#[derive(Debug, Default)]
pub struct TraversalQueue {
    entries: heapless::Vec<Location, QUEUE_CAPACITY>,
}

impl TraversalQueue {
    /// Create an empty traversal queue.
    pub const fn new() -> Self {
        Self {
            entries: heapless::Vec::new(),
        }
    }

    /// Clear the traversal queue.
    pub fn clear(&mut self) {
        self.entries.clear();
    }

    /// Enqueues a location.
    ///
    /// If an entry with the same segment exists, its max cut will be updated
    /// if the supplied max cut is higher.
    pub fn push(&mut self, loc: Location) -> Result<(), StorageError> {
        if let Some(prev) = self.entries.iter_mut().find(|x| x.same_segment(loc)) {
            prev.max_cut = prev.max_cut.max(loc.max_cut);
            return Ok(());
        }
        self.entries
            .push(loc)
            .map_err(|_| StorageError::TraversalQueueOverflow(QUEUE_CAPACITY))
    }

    /// Pop a location with the highest max cut.
    pub fn pop(&mut self) -> Option<Location> {
        let (i, _) = self
            .entries
            .iter()
            .enumerate()
            .max_by_key(|&(_, &loc)| loc)?;
        Some(self.entries.swap_remove(i))
    }
}

/// A queue buffer for a single graph traversal operation.
///
/// Access via [`get()`](Self::get), which clears the buffer automatically.
pub struct TraversalBuffer {
    queue: TraversalQueue,
}

impl TraversalBuffer {
    pub const fn new() -> Self {
        Self {
            queue: TraversalQueue::new(),
        }
    }

    /// Returns a cleared queue ready for use.
    pub fn get(&mut self) -> &mut TraversalQueue {
        self.queue.clear();
        &mut self.queue
    }
}

impl Default for TraversalBuffer {
    fn default() -> Self {
        Self::new()
    }
}

/// Reusable buffers for graph traversal operations.
///
/// Contains two independent queue buffers so that an outer traversal
/// (e.g. `find_needed_segments`) can maintain state in one buffer while
/// calling leaf operations (e.g. `is_ancestor`) that use the other.
pub struct TraversalBuffers {
    pub primary: TraversalBuffer,
    pub secondary: TraversalBuffer,
}

impl TraversalBuffers {
    pub const fn new() -> Self {
        Self {
            primary: TraversalBuffer::new(),
            secondary: TraversalBuffer::new(),
        }
    }
}

impl Default for TraversalBuffers {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(feature = "low-mem-usage")]
pub const MAX_COMMAND_LENGTH: usize = 400;
#[cfg(not(feature = "low-mem-usage"))]
pub const MAX_COMMAND_LENGTH: usize = 2048;

aranya_crypto::custom_id! {
    /// The ID of the graph, taken from initialization.
    pub struct GraphId;
}

#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[repr(transparent)]
pub struct SegmentIndex(pub usize);

impl fmt::Display for SegmentIndex {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.0, f)
    }
}

#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[repr(transparent)]
pub struct MaxCut(pub usize);

impl fmt::Display for MaxCut {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.0, f)
    }
}

impl MaxCut {
    /// Adds an amount to the max cut, returning `None` on overflow.
    #[must_use]
    pub fn checked_add(self, other: usize) -> Option<Self> {
        self.0.checked_add(other).map(Self)
    }

    /// Gets a max cut one lower than this, returning `None` on overflow.
    #[must_use]
    pub fn decremented(self) -> Option<Self> {
        self.0.checked_sub(1).map(Self)
    }

    /// Gets the distance between two max cuts, returning `None` on overflow.
    #[must_use]
    pub fn distance_from(self, other: Self) -> Option<usize> {
        self.0.checked_sub(other.0)
    }
}

#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Location {
    pub max_cut: MaxCut,
    pub segment: SegmentIndex,
}

impl From<(SegmentIndex, MaxCut)> for Location {
    fn from((segment, max_cut): (SegmentIndex, MaxCut)) -> Self {
        Self::new(segment, max_cut)
    }
}

impl AsRef<Self> for Location {
    fn as_ref(&self) -> &Self {
        self
    }
}

impl Location {
    pub fn new(segment: SegmentIndex, max_cut: MaxCut) -> Self {
        Self { max_cut, segment }
    }

    /// Returns true if other location is in the same segment.
    pub fn same_segment(self, other: Self) -> bool {
        self.segment == other.segment
    }
}

impl fmt::Display for Location {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}:{}", self.segment, self.max_cut)
    }
}

/// An error returned by [`Storage`] or [`StorageProvider`].
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
pub enum StorageError {
    #[error("storage already exists")]
    StorageExists,
    #[error("no such storage")]
    NoSuchStorage,
    #[error("segment index {} is out of bounds", .0.segment)]
    SegmentOutOfBounds(Location),
    #[error("max cut {} is out of bounds in segment {}", .0.max_cut, .0.segment)]
    CommandOutOfBounds(Location),
    #[error("IO error")]
    IoError,
    #[error("policy mismatch")]
    PolicyMismatch,
    #[error("cannot write an empty perspective")]
    EmptyPerspective,
    #[error("traversal queue overflow (capacity {0})")]
    TraversalQueueOverflow(usize),
    #[error("command's parents do not match the perspective head")]
    PerspectiveHeadMismatch,
    #[error(transparent)]
    Bug(#[from] Bug),
}

/// Handle to storage implementations used by the runtime.
pub trait StorageProvider {
    type Perspective: Perspective + Revertable;
    type Segment: Segment;
    type Storage: Storage<
            Segment = Self::Segment,
            Perspective = Self::Perspective,
            FactIndex = <Self::Segment as Segment>::FactIndex,
        >;

    /// Create an unrooted perspective, intended for creating a new graph.
    ///
    /// # Arguments
    ///
    /// * `policy_id` - The policy to associate with the graph.
    fn new_perspective(&mut self, policy_id: PolicyId) -> Self::Perspective;

    /// Create a new graph.
    ///
    /// # Arguments
    ///
    /// * `graph` - ID of the graph, taken from the initialization command.
    /// * `init` - Contains the data necessary to initialize the new graph.
    fn new_storage(
        &mut self,
        init: Self::Perspective,
    ) -> Result<(GraphId, &mut Self::Storage), StorageError>;

    /// Get an existing graph.
    ///
    /// # Arguments
    ///
    /// * `graph` - ID of the graph, taken from the initialization command.
    fn get_storage(&mut self, graph: GraphId) -> Result<&mut Self::Storage, StorageError>;

    /// Remove a graph.
    ///
    /// # Arguments
    ///
    /// * `graph` - ID of the graph, taken from the initialization command.
    fn remove_storage(&mut self, graph: GraphId) -> Result<(), StorageError>;

    /// Gets a list of all stored graphs by their graph ID.
    // TODO(nikki): rewrite this once we can use coroutines/generators?
    fn list_graph_ids(
        &mut self,
    ) -> Result<impl Iterator<Item = Result<GraphId, StorageError>>, StorageError>;
}

/// Represents the runtime's graph; [`Command`]s in storage have been validated
/// by an associated policy and committed to state.
pub trait Storage {
    type Perspective: Perspective + Revertable;
    type FactPerspective: FactPerspective;
    type Segment: Segment<FactIndex = Self::FactIndex>;
    type FactIndex: FactIndex;

    /// Returns the location of Command with id if it has been stored by
    /// searching from the head.
    fn get_location(
        &self,
        address: Address,
        buffer: &mut TraversalBuffer,
    ) -> Result<Option<Location>, StorageError> {
        self.get_location_from(self.get_head()?, address, buffer)
    }

    /// Returns the location of Command with id by searching from the given location.
    ///
    /// See `aranya-docs/docs/graph-traversal.md` for the traversal algorithm specification.
    fn get_location_from(
        &self,
        start: Location,
        address: Address,
        buffer: &mut TraversalBuffer,
    ) -> Result<Option<Location>, StorageError> {
        if start.max_cut < address.max_cut {
            return Ok(None);
        }

        let queue = buffer.get();
        queue.push(start)?;

        while let Some(loc) = queue.pop() {
            debug_assert!(
                loc.max_cut >= address.max_cut,
                "Invariant: we only enqueue locations with at least the target max cut"
            );

            // Must load segment
            let segment = self.get_segment(loc)?;

            // Search commands in this segment.
            if let Some(found) = segment.get_by_address(address) {
                return Ok(Some(found));
            }

            // Try to use skip list to jump directly backward.
            // Skip list is sorted by max_cut ascending, so the first entry
            // with max_cut >= target has the lowest valid max_cut, jumping
            // furthest back in the graph.
            if let Some(&skip) = segment
                .skip_list()
                .iter()
                .find(|skip| skip.max_cut >= address.max_cut)
            {
                queue.push(skip)?;
            } else {
                // No valid skip - add prior locations to queue
                for prior in segment.prior() {
                    if prior.max_cut >= address.max_cut {
                        queue.push(prior)?;
                    }
                }
            }
        }
        Ok(None)
    }

    /// Returns the address of the command at the given location.
    ///
    /// By default, this fetches the segment, then the command, then the address.
    fn get_command_address(&self, location: Location) -> Result<Address, StorageError> {
        let segment = self.get_segment(location)?;
        let command = segment
            .get_command(location)
            .ok_or(StorageError::CommandOutOfBounds(location))?;
        let address = command.address()?;
        Ok(address)
    }

    /// Returns a linear perspective at the given location.
    fn get_linear_perspective(&self, parent: Location) -> Result<Self::Perspective, StorageError>;

    /// Returns a fact perspective at the given location, intended for evaluating braids.
    /// The fact perspective will include the facts of the command at the given location.
    fn get_fact_perspective(&self, first: Location) -> Result<Self::FactPerspective, StorageError>;

    /// Returns a merge perspective based on the given locations with the braid as prior facts.
    fn new_merge_perspective(
        &self,
        left: Location,
        right: Location,
        last_common_ancestor: Location,
        policy_id: PolicyId,
        braid: Self::FactIndex,
    ) -> Result<Self::Perspective, StorageError>;

    /// Returns the segment at the given location.
    fn get_segment(&self, location: Location) -> Result<Self::Segment, StorageError>;

    /// Returns the location of head of the graph.
    fn get_head(&self) -> Result<Location, StorageError>;

    /// Returns the address of the head of the graph.
    fn get_head_address(&self) -> Result<Address, StorageError> {
        self.get_command_address(self.get_head()?)
    }

    /// Sets the given segment as the head of the graph.
    ///
    /// The given segment must be a descendant of the current graph head.
    /// Implementations may rely on this for correctness, but not for safety.
    fn commit(&mut self, segment: Self::Segment) -> Result<(), StorageError>;

    /// Writes the given perspective to a segment.
    fn write(&mut self, perspective: Self::Perspective) -> Result<Self::Segment, StorageError>;

    /// Writes the given fact perspective to a fact index.
    fn write_facts(
        &mut self,
        fact_perspective: Self::FactPerspective,
    ) -> Result<Self::FactIndex, StorageError>;

    /// Determine whether the given location is an ancestor of the given segment.
    fn is_ancestor(
        &self,
        search_location: Location,
        segment: &Self::Segment,
        buffer: &mut TraversalBuffer,
    ) -> Result<bool, StorageError> {
        let queue = buffer.get();

        // Try to use skip list to jump directly backward.
        // Skip list is sorted by max_cut ascending, so first valid skip
        // jumps as far back as possible.
        if let Some(&skip) = segment
            .skip_list()
            .iter()
            .find(|skip| skip.max_cut >= search_location.max_cut)
        {
            queue.push(skip)?;
        } else {
            // No valid skip - add prior locations to queue
            for prior in segment.prior() {
                if prior.max_cut >= search_location.max_cut {
                    queue.push(prior)?;
                }
            }
        }

        while let Some(loc) = queue.pop() {
            debug_assert!(
                loc.max_cut >= search_location.max_cut,
                "Invariant: we only enqueue locations with at least the target max cut"
            );

            // Must load segment
            let segment = self.get_segment(loc)?;

            // Search commands in this segment.
            if segment.get_command(search_location).is_some() {
                return Ok(true);
            }

            // Try to use skip list to jump directly backward.
            // Skip list is sorted by max_cut ascending, so the first entry
            // with max_cut >= target has the lowest valid max_cut, jumping
            // furthest back in the graph.
            if let Some(&skip) = segment
                .skip_list()
                .iter()
                .find(|skip| skip.max_cut >= search_location.max_cut)
            {
                queue.push(skip)?;
            } else {
                // No valid skip - add prior locations to queue
                for prior in segment.prior() {
                    if prior.max_cut >= search_location.max_cut {
                        queue.push(prior)?;
                    }
                }
            }
        }
        Ok(false)
    }
}

/// A segment is a nonempty sequence of commands persisted to storage.
///
/// A segment can be one of three types. This might be encoded in a future version of the API.
/// * init   - This segment is the first segment of the graph and begins with an init command.
/// * linear - This segment has a single prior command and is simply a sequence of linear commands.
/// * merge  - This segment merges two other segments and thus begins with a merge command. A merge
///   segment has a braid as it's prior facts.
///
/// Each command past the first must have the parent of the previous command in the segment.
pub trait Segment {
    type FactIndex: FactIndex;
    type Command<'a>: Command
    where
        Self: 'a;

    /// Returns the segment's index.
    fn index(&self) -> SegmentIndex;

    /// Returns the ID of the head of the segment.
    fn head_id(&self) -> CmdId;

    /// Returns the id for the policy used for this segment.
    fn policy(&self) -> PolicyId;

    /// Returns the prior segments for this segment.
    fn prior(&self) -> Prior<Location>;

    /// Returns the command at the given location.
    fn get_command(&self, location: Location) -> Option<Self::Command<'_>>;

    /// Get the fact index associated with this segment.
    fn facts(&self) -> Result<Self::FactIndex, StorageError>;

    /// The shortest max cut for this segment.
    ///
    /// This will always the max cut of the first command in the segment.
    fn shortest_max_cut(&self) -> MaxCut;

    /// The longest max cut for this segment.
    ///
    /// This will always be the max cut of the last command in the segment.
    fn longest_max_cut(&self) -> Result<MaxCut, StorageError>;

    /// The skip list is a series of locations that can be safely jumped to
    /// when searching for a location. As long as the max cut of the location
    /// you're jumping to is greater than or equal to the location you're
    /// searching for you can jump to it and be guaranteed not to miss
    /// the location you're searching for.
    ///
    /// For merge commands the last location in the skip list is the least
    /// common ancestor.
    fn skip_list(&self) -> &[Location];

    /// Returns an iterator of commands starting at the given location.
    fn get_from(&self, location: Location) -> Vec<Self::Command<'_>> {
        let segment = location.segment;
        core::iter::successors(Some(location.max_cut), |max_cut| max_cut.checked_add(1))
            .map_while(|max_cut| self.get_command(Location { max_cut, segment }))
            .collect()
    }

    /// Returns the location of the command with the given address from within this segment.
    fn get_by_address(&self, address: Address) -> Option<Location> {
        let loc = Location::new(self.index(), address.max_cut);
        let cmd = self.get_command(loc)?;
        if cmd.id() != address.id {
            return None;
        }
        Some(loc)
    }

    /// Returns the location of the first command.
    fn first_location(&self) -> Location {
        Location {
            max_cut: self.shortest_max_cut(),
            segment: self.index(),
        }
    }

    /// Returns the location of the head of the segment.
    fn head_location(&self) -> Result<Location, StorageError> {
        Ok(Location {
            max_cut: self.longest_max_cut()?,
            segment: self.index(),
        })
    }

    /// Returns the address of the head of the segment.
    fn head_address(&self) -> Result<Address, StorageError> {
        Ok(Address {
            id: self.head_id(),
            max_cut: self.longest_max_cut()?,
        })
    }

    /// Walks a location toward init if it would still point within this segment.
    #[must_use]
    fn previous(&self, mut location: Location) -> Option<Location> {
        debug_assert_eq!(location.segment, self.index());
        if location.max_cut <= self.shortest_max_cut() {
            return None;
        }
        location.max_cut = location.max_cut.decremented()?;
        Some(location)
    }
}

/// An index of facts in storage.
pub trait FactIndex: Query {}

/// A perspective is essentially a mutable, in-memory version of a [`Segment`],
/// with the same three types.
pub trait Perspective: FactPerspective {
    /// Returns the id for the policy used for this perspective.
    fn policy(&self) -> PolicyId;

    /// Adds the given command to the head of the perspective. The command's
    /// parent must be the head of the perspective.
    fn add_command(&mut self, command: &impl Command) -> Result<usize, StorageError>;

    /// Returns true if the perspective contains a command with the given ID.
    fn includes(&self, id: CmdId) -> bool;

    /// Returns the head address in the perspective, if it exists
    fn head_address(&self) -> Result<Prior<Address>, Bug>;
}

/// A fact perspective is essentially a mutable, in-memory version of a [`FactIndex`].
pub trait FactPerspective: QueryMut {}

/// A revertable perspective can make checkpoints and be reverted such that the
/// state of the perspective matches that when the checkpoint was created.
pub trait Revertable {
    /// Create a checkpoint which can be used to revert the perspective.
    fn checkpoint(&self) -> Checkpoint;

    /// Revert the perspective to the state it was at when the checkpoint was created.
    fn revert(&mut self, checkpoint: Checkpoint) -> Result<(), Bug>;
}

/// A checkpoint used to revert perspectives.
pub struct Checkpoint {
    /// An index interpreted by a given `Revertable` implementation to revert to a prior point.
    pub index: usize,
}

/// Can be queried to look up facts.
///
/// Facts are labeled by a name, which are generally a bounded set of human-readable strings determined in advance.
///
/// Within a name, facts are an association of compound keys to values. The facts are keyed by a compound key
/// `(k_1, k_2, ..., k_n)`, where each `k` is a sequence of bytes. The fact value is also a sequence of bytes.
pub trait Query {
    /// Look up a named fact by an exact match of the compound key.
    fn query(&self, name: &str, keys: &[Box<[u8]>]) -> Result<Option<Box<[u8]>>, StorageError>;

    /// Iterator for [`Query::query_prefix`].
    type QueryIterator: Iterator<Item = Result<Fact, StorageError>>;

    /// Look up all named facts that begin with the prefix of keys, in sorted key order.
    ///
    /// The `prefix` is a partial compound key `(k_1, k_2, ..., k_n)`, where each `k` is a sequence of bytes.
    /// This returns all facts under the name with keys such that `prefix` is equal to a prefix of the fact's keys.
    fn query_prefix(
        &self,
        name: &str,
        prefix: &[Box<[u8]>],
    ) -> Result<Self::QueryIterator, StorageError>;
}

/// A fact with a key and value.
#[derive(Debug, PartialEq, Eq)]
pub struct Fact {
    /// The sequence of keys.
    pub key: Keys,
    /// The bytes of the value.
    pub value: Box<[u8]>,
}

/// Can mutate facts by inserting and deleting them.
///
/// See [`Query`] for details on the nature of facts.
pub trait QueryMut: Query {
    /// Insert a fact labeled by a name, with a given compound key and a value.
    ///
    /// This fact can later be looked up by [`Query`] methods, using the name and keys.
    fn insert(&mut self, name: String, keys: Keys, value: Box<[u8]>);

    /// Delete any fact associated to the compound key, under the given name.
    fn delete(&mut self, name: String, keys: Keys);
}

// TODO(jdygert): Expose this?
#[cfg(all(test, feature = "graphviz"))]
pub(crate) trait FactIndexExtra {
    fn name(&self) -> String;
    fn prior(&self) -> Result<Option<Self>, StorageError>
    where
        Self: Sized;
}

/// A sequence of byte-based keys, used for facts.
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Keys(Box<[Box<[u8]>]>);

impl Deref for Keys {
    type Target = [Box<[u8]>];
    fn deref(&self) -> &[Box<[u8]>] {
        self.0.as_ref()
    }
}

impl AsRef<[Box<[u8]>]> for Keys {
    fn as_ref(&self) -> &[Box<[u8]>] {
        self.0.as_ref()
    }
}

impl core::borrow::Borrow<[Box<[u8]>]> for Keys {
    fn borrow(&self) -> &[Box<[u8]>] {
        self.0.as_ref()
    }
}

impl From<&[&[u8]]> for Keys {
    fn from(value: &[&[u8]]) -> Self {
        value.iter().copied().collect()
    }
}

impl Keys {
    fn starts_with(&self, prefix: &[Box<[u8]>]) -> bool {
        self.as_ref().starts_with(prefix)
    }
}

impl<B: Into<Box<[u8]>>> FromIterator<B> for Keys {
    fn from_iter<T: IntoIterator<Item = B>>(iter: T) -> Self {
        Self(iter.into_iter().map(Into::into).collect())
    }
}

#[cfg(test)]
mod queue_tests {
    use super::*;

    fn loc(seg: usize, mc: usize) -> Location {
        Location::new(SegmentIndex(seg), MaxCut(mc))
    }

    #[test]
    fn test_queue_overflow_returns_error() {
        let mut queue = TraversalQueue::new();
        // Fill to capacity
        for i in 0..QUEUE_CAPACITY {
            queue.push(loc(i, i)).unwrap();
        }
        // Next push should fail with TraversalQueueOverflow
        let result = queue
            .push(loc(999, 999))
            .expect_err("expected push_queue to fail");
        assert_eq!(result, StorageError::TraversalQueueOverflow(QUEUE_CAPACITY));
    }
}