aranya_runtime/client/
session.rs

1//! Ephemeral sessions for off-graph commands.
2//!
3//! See [`ClientState::session`] and [`Session`].
4//!
5//! Design discussion/docs: <https://git.spideroak-inc.com/spideroak-inc/flow3-docs/pull/53>
6
7use alloc::{
8    boxed::Box,
9    collections::{btree_map, BTreeMap},
10    string::String,
11    sync::Arc,
12    vec::Vec,
13};
14use core::{cmp::Ordering, iter::Peekable, marker::PhantomData, mem, ops::Bound};
15
16use aranya_buggy::{bug, Bug, BugExt};
17use serde::{Deserialize, Serialize};
18use yoke::{Yoke, Yokeable};
19
20use crate::{
21    Address, Checkpoint, ClientError, ClientState, Command, CommandId, CommandRecall, Engine, Fact,
22    FactPerspective, GraphId, Keys, NullSink, Perspective, Policy, PolicyId, Prior, Priority,
23    Query, QueryMut, Revertable, Segment, Sink, Storage, StorageError, StorageProvider,
24    MAX_COMMAND_LENGTH,
25};
26
27type Bytes = Box<[u8]>;
28
29/// Ephemeral session used to handle/generate off-graph commands.
30pub struct Session<SP: StorageProvider, E> {
31    /// The ID of the associated storage.
32    storage_id: GraphId,
33    /// The policy ID for the session.
34    policy_id: PolicyId,
35
36    /// The prior facts from the graph head.
37    base_facts: <SP::Storage as Storage>::FactIndex,
38    /// The log of facts in insertion order.
39    fact_log: Vec<(String, Keys, Option<Bytes>)>,
40    /// The current facts of the session, relative to `base_facts`.
41    current_facts: Arc<BTreeMap<String, BTreeMap<Keys, Option<Bytes>>>>,
42
43    /// Tag for associated engine.
44    _engine: PhantomData<E>,
45
46    head: Address,
47}
48
49struct SessionPerspective<'a, SP: StorageProvider, E, MS> {
50    session: &'a mut Session<SP, E>,
51    message_sink: &'a mut MS,
52}
53
54impl<SP: StorageProvider, E> Session<SP, E> {
55    pub(super) fn new(provider: &mut SP, storage_id: GraphId) -> Result<Self, ClientError> {
56        let storage = provider.get_storage(storage_id)?;
57        let head_loc = storage.get_head()?;
58        let seg = storage.get_segment(head_loc)?;
59        let command = seg.get_command(head_loc).assume("location must exist")?;
60
61        let base_facts = seg.facts()?;
62
63        let result = Self {
64            storage_id,
65            policy_id: seg.policy(),
66            base_facts,
67            fact_log: Vec::new(),
68            current_facts: Arc::default(),
69            _engine: PhantomData,
70            head: command.address()?,
71        };
72
73        Ok(result)
74    }
75}
76
77impl<SP: StorageProvider, E: Engine> Session<SP, E> {
78    /// Evaluate an action on the ephemeral session and generate serialized
79    /// commands, so another client can [`Session::receive`] them.
80    pub fn action<ES, MS>(
81        &mut self,
82        client: &ClientState<E, SP>,
83        effect_sink: &mut ES,
84        message_sink: &mut MS,
85        action: <E::Policy as Policy>::Action<'_>,
86    ) -> Result<(), ClientError>
87    where
88        ES: Sink<E::Effect>,
89        MS: for<'b> Sink<&'b [u8]>,
90    {
91        let policy = client.engine.get_policy(self.policy_id)?;
92
93        // Use a special perspective so we can send to the message sink.
94        let mut perspective = SessionPerspective {
95            session: self,
96            message_sink,
97        };
98        let checkpoint = perspective.checkpoint();
99        effect_sink.begin();
100
101        // Try to perform action.
102        match policy.call_action(action, &mut perspective, effect_sink) {
103            Ok(_) => {
104                // Success, commit effects
105                effect_sink.commit();
106                Ok(())
107            }
108            Err(e) => {
109                // Other error, revert all? See #513.
110                perspective.revert(checkpoint)?;
111                perspective.message_sink.rollback();
112                effect_sink.rollback();
113                Err(e.into())
114            }
115        }
116    }
117
118    /// Handle a command from another client generated by [`Session::action`].
119    ///
120    /// You do NOT need to reprocess the commands from actions generated in the
121    /// same session.
122    pub fn receive(
123        &mut self,
124        client: &ClientState<E, SP>,
125        sink: &mut impl Sink<E::Effect>,
126        command_bytes: &[u8],
127    ) -> Result<(), ClientError> {
128        let command: SessionCommand<'_> =
129            postcard::from_bytes(command_bytes).map_err(ClientError::SessionDeserialize)?;
130
131        if command.storage_id != self.storage_id {
132            bug!("ephemeral commands must be run on the same graph");
133        }
134
135        let policy = client.engine.get_policy(self.policy_id)?;
136
137        // Use a special perspective which doesn't check the head
138        let mut perspective = SessionPerspective {
139            session: self,
140            message_sink: &mut NullSink,
141        };
142
143        // Try to evaluate command.
144        sink.begin();
145        let checkpoint = perspective.checkpoint();
146        if let Err(e) = policy.call_rule(&command, &mut perspective, sink, CommandRecall::None) {
147            perspective.revert(checkpoint)?;
148            sink.rollback();
149            return Err(e.into());
150        }
151        sink.commit();
152
153        Ok(())
154    }
155}
156
157#[derive(Serialize, Deserialize)]
158/// Used for serializing session commands
159struct SessionCommand<'a> {
160    storage_id: GraphId,
161    priority: u32, // Priority::Basic
162    id: CommandId,
163    parent: Address, // Prior::Single
164    #[serde(borrow)]
165    data: &'a [u8],
166}
167
168impl Command for SessionCommand<'_> {
169    fn priority(&self) -> Priority {
170        Priority::Basic(self.priority)
171    }
172
173    fn id(&self) -> CommandId {
174        self.id
175    }
176
177    fn parent(&self) -> Prior<Address> {
178        Prior::Single(self.parent)
179    }
180
181    fn policy(&self) -> Option<&[u8]> {
182        // Session commands should never have policy?
183        None
184    }
185
186    fn bytes(&self) -> &[u8] {
187        self.data
188    }
189}
190
191impl<'sc> SessionCommand<'sc> {
192    fn from_cmd(storage_id: GraphId, command: &'sc impl Command) -> Result<Self, Bug> {
193        if command.policy().is_some() {
194            bug!("session command should have no policy")
195        }
196        Ok(SessionCommand {
197            storage_id,
198            priority: match command.priority() {
199                Priority::Basic(p) => p,
200                _ => bug!("wrong command type"),
201            },
202            id: command.id(),
203            parent: match command.parent() {
204                Prior::Single(p) => p,
205                _ => bug!("wrong command type"),
206            },
207            data: command.bytes(),
208        })
209    }
210}
211
212/// Query iterator for SessionPerspective which wraps an inner query iterator
213struct QueryIterator<I1: Iterator, I2: Iterator> {
214    prior: Peekable<I1>,
215    current: Peekable<I2>,
216}
217
218impl<I1, I2> QueryIterator<I1, I2>
219where
220    I1: Iterator<Item = Result<Fact, StorageError>>,
221    I2: Iterator<Item = (Keys, Option<Bytes>)>,
222{
223    fn new(prior: I1, current: I2) -> Self {
224        Self {
225            prior: prior.peekable(),
226            current: current.peekable(),
227        }
228    }
229}
230
231impl<I1, I2> Iterator for QueryIterator<I1, I2>
232where
233    I1: Iterator<Item = Result<Fact, StorageError>>,
234    I2: Iterator<Item = (Keys, Option<Bytes>)>,
235{
236    type Item = Result<Fact, StorageError>;
237
238    fn next(&mut self) -> Option<Self::Item> {
239        // We find the next lowest item between the two iterators,
240        // while also ensuring that newer entries overwrite older.
241        // We loop so we can skip over deleted facts.
242
243        loop {
244            let Some(new) = self.current.peek() else {
245                // If current has run out, just use prior.
246                return self.prior.next();
247            };
248            if let Some(old) = self.prior.peek() {
249                let Ok(old) = old else {
250                    // Bubble up errors as soon as possible, instead of returning `new`.
251                    return self.prior.next();
252                };
253                match new.0.cmp(&old.key) {
254                    Ordering::Equal => {
255                        // new overwrites old.
256                        let _ = self.prior.next();
257                    }
258                    Ordering::Greater => {
259                        // old comes next in sorted order.
260                        return self.prior.next();
261                    }
262                    Ordering::Less => {
263                        // new comes next in sorted order.
264                    }
265                }
266            }
267            let Some(slot) = self.current.next() else {
268                bug!("expected Some after peek")
269            };
270            if let (k, Some(v)) = slot {
271                return Some(Ok(Fact {
272                    key: k.iter().cloned().collect(),
273                    value: v,
274                }));
275            }
276        }
277    }
278}
279
280impl<SP, E, MS> FactPerspective for SessionPerspective<'_, SP, E, MS> where SP: StorageProvider {}
281
282impl<SP, E, MS> Query for SessionPerspective<'_, SP, E, MS>
283where
284    SP: StorageProvider,
285{
286    fn query(&self, name: &str, keys: &[Box<[u8]>]) -> Result<Option<Box<[u8]>>, StorageError> {
287        if let Some(slot) = self
288            .session
289            .current_facts
290            .get(name)
291            .and_then(|m| m.get(keys))
292        {
293            return Ok(slot.clone());
294        }
295        self.session.base_facts.query(name, keys)
296    }
297
298    type QueryIterator = QueryIterator<
299        <<SP::Storage as Storage>::FactIndex as Query>::QueryIterator,
300        YokeIter<PrefixIter<'static>, Arc<BTreeMap<String, BTreeMap<Keys, Option<Bytes>>>>>,
301    >;
302    fn query_prefix(
303        &self,
304        name: &str,
305        prefix: &[Box<[u8]>],
306    ) -> Result<Self::QueryIterator, StorageError> {
307        let prior = self.session.base_facts.query_prefix(name, prefix)?;
308        let current = Yoke::<PrefixIter<'static>, _>::attach_to_cart(
309            Arc::clone(&self.session.current_facts),
310            |map| match map.get(name) {
311                Some(facts) => PrefixIter::new(facts, prefix.iter().cloned().collect()),
312                None => PrefixIter::default(),
313            },
314        );
315        Ok(QueryIterator::new(prior, YokeIter::new(current)))
316    }
317}
318
319/// Iterator over matching prefix of a [`BTreeMap`].
320///
321/// Equivalent to `map.range(&prefix..).take_while(move |(k, _)| k.starts_with(prefix))`,
322/// but nameable and [`Yokeable`].
323#[derive(Default, Yokeable)]
324struct PrefixIter<'map> {
325    range: btree_map::Range<'map, Keys, Option<Bytes>>,
326    prefix: Keys,
327}
328
329impl<'map> PrefixIter<'map> {
330    fn new(map: &'map BTreeMap<Keys, Option<Bytes>>, prefix: Keys) -> Self {
331        let range =
332            map.range::<[Box<[u8]>], _>((Bound::Included(prefix.as_ref()), Bound::Unbounded));
333        Self { range, prefix }
334    }
335}
336
337impl Iterator for PrefixIter<'_> {
338    type Item = (Keys, Option<Bytes>);
339
340    fn next(&mut self) -> Option<Self::Item> {
341        self.range
342            .next()
343            .filter(|(k, _)| k.starts_with(&self.prefix))
344            .map(|(k, v)| (k.clone(), v.clone()))
345    }
346}
347
348/// Wrapper around [`Yoke`] which implements [`Iterator`].
349struct YokeIter<I: for<'a> Yokeable<'a>, C>(Option<Yoke<I, C>>);
350
351impl<I: for<'a> Yokeable<'a>, C> YokeIter<I, C> {
352    fn new(yoke: Yoke<I, C>) -> Self {
353        Self(Some(yoke))
354    }
355}
356
357impl<I, C> Iterator for YokeIter<I, C>
358where
359    I: Iterator + for<'a> Yokeable<'a>,
360    for<'a> <I as Yokeable<'a>>::Output: Iterator<Item = I::Item>,
361{
362    type Item = I::Item;
363
364    fn next(&mut self) -> Option<Self::Item> {
365        // `Yoke::map_project` is currently the only way to mutate something in a yoke and get out a value.
366        // It takes the yoke by value though, so we have to `take` it so we can own it temporarily.
367        let mut item = None;
368        self.0 = Some(self.0.take()?.map_project::<I, _>(|mut it, _| {
369            item = it.next();
370            it
371        }));
372        item
373    }
374}
375
376impl<SP: StorageProvider, E, MS> QueryMut for SessionPerspective<'_, SP, E, MS> {
377    fn insert(&mut self, name: String, keys: Keys, value: Box<[u8]>) {
378        self.session
379            .fact_log
380            .push((name.clone(), keys.clone(), Some(value.clone())));
381        Arc::make_mut(&mut self.session.current_facts)
382            .entry(name)
383            .or_default()
384            .insert(keys, Some(value));
385    }
386
387    fn delete(&mut self, name: String, keys: Keys) {
388        self.session
389            .fact_log
390            .push((name.clone(), keys.clone(), None));
391        Arc::make_mut(&mut self.session.current_facts)
392            .entry(name)
393            .or_default()
394            .insert(keys, None);
395    }
396}
397
398impl<SP, E, MS> Perspective for SessionPerspective<'_, SP, E, MS>
399where
400    SP: StorageProvider,
401    MS: for<'b> Sink<&'b [u8]>,
402{
403    fn policy(&self) -> PolicyId {
404        self.session.policy_id
405    }
406
407    fn add_command(&mut self, command: &impl Command) -> Result<usize, StorageError> {
408        let command = SessionCommand::from_cmd(self.session.storage_id, command)?;
409        self.session.head = command.address()?;
410        let mut buf = [0u8; MAX_COMMAND_LENGTH];
411        let bytes = postcard::to_slice(&command, &mut buf).assume("can serialize")?;
412        self.message_sink.consume(bytes);
413
414        Ok(0)
415    }
416
417    fn includes(&self, _id: CommandId) -> bool {
418        debug_assert!(false, "only used in transactions");
419
420        false
421    }
422
423    fn head_address(&self) -> Result<Prior<Address>, Bug> {
424        Ok(Prior::Single(self.session.head))
425    }
426}
427
428impl<SP, E, MS> Revertable for SessionPerspective<'_, SP, E, MS>
429where
430    SP: StorageProvider,
431{
432    fn checkpoint(&self) -> Checkpoint {
433        Checkpoint {
434            index: self.session.fact_log.len(),
435        }
436    }
437
438    fn revert(&mut self, checkpoint: Checkpoint) -> Result<(), Bug> {
439        if checkpoint.index == self.session.fact_log.len() {
440            return Ok(());
441        }
442
443        if checkpoint.index > self.session.fact_log.len() {
444            bug!("A checkpoint's index should always be less than or equal to the length of a session's fact log!");
445        }
446
447        self.session.fact_log.truncate(checkpoint.index);
448        // Create empty map, but reuse allocation if not shared
449        let mut facts =
450            Arc::get_mut(&mut self.session.current_facts).map_or_else(BTreeMap::new, mem::take);
451        facts.clear();
452        for (n, k, v) in self.session.fact_log.iter().cloned() {
453            facts.entry(n).or_default().insert(k, v);
454        }
455        self.session.current_facts = Arc::new(facts);
456
457        Ok(())
458    }
459}
460
461#[cfg(test)]
462mod test {
463    use super::*;
464
465    #[test]
466    fn test_query_iterator() {
467        #![allow(clippy::type_complexity)]
468
469        let prior: Vec<Result<(&[&[u8]], &[u8]), _>> = vec![
470            Ok((&[b"a"], b"a0")),
471            Ok((&[b"c"], b"c0")),
472            Ok((&[b"d"], b"d0")),
473            Ok((&[b"f"], b"f0")),
474            Err(StorageError::IoError),
475        ];
476        let current: Vec<([Box<[u8]>; 1], Option<&[u8]>)> = vec![
477            ([Box::new(*b"a")], None),
478            ([Box::new(*b"b")], Some(b"b1")),
479            ([Box::new(*b"e")], None),
480            ([Box::new(*b"j")], None),
481        ];
482        let merged: Vec<Result<(&[&[u8]], &[u8]), _>> = vec![
483            Ok((&[b"b"], b"b1")),
484            Ok((&[b"c"], b"c0")),
485            Ok((&[b"d"], b"d0")),
486            Ok((&[b"f"], b"f0")),
487            Err(StorageError::IoError),
488        ];
489
490        let got: Vec<_> = QueryIterator::new(
491            prior.into_iter().map(|r| {
492                r.map(|(k, v)| Fact {
493                    key: k.into(),
494                    value: v.into(),
495                })
496            }),
497            current
498                .into_iter()
499                .map(|(k, v)| (k.into_iter().collect(), v.map(Box::from))),
500        )
501        .collect();
502        let want: Vec<_> = merged
503            .into_iter()
504            .map(|r| {
505                r.map(|(k, v)| Fact {
506                    key: k.into(),
507                    value: v.into(),
508                })
509            })
510            .collect();
511
512        assert_eq!(got, want);
513    }
514}