Skip to main content

sim_lib_journal/
memory.rs

1// SPDX-License-Identifier: MPL-2.0
2// This Source Code Form is subject to the terms of the Mozilla Public
3// License, v. 2.0. If a copy of the MPL was not distributed with this
4// file, You can obtain one at https://mozilla.org/MPL/2.0/.
5
6use crate::{
7    Admission, AdmissionDisposition, CommitAction, GuardedAdmission, JournalBackend, JournalError,
8    JournalHead, JournalObject, Lease, StoredDatumRef, StoredState,
9};
10use sim_kernel::{ContentId, Datum};
11use std::sync::{Mutex, PoisonError};
12
13#[derive(Default)]
14struct Inner {
15    fence: u64,
16    state: StoredState,
17}
18
19/// Deterministic law-reference backend. It is deliberately not durable.
20#[derive(Default)]
21pub struct MemoryBackend {
22    admission: Mutex<()>,
23    inner: Mutex<Inner>,
24}
25
26impl MemoryBackend {
27    pub fn new() -> Self {
28        Self::default()
29    }
30    fn commit_admission(&self, admission: Admission) -> Result<GuardedAdmission, JournalError> {
31        let mut inner = self
32            .inner
33            .lock()
34            .map_err(|_: PoisonError<_>| JournalError::Backend("memory lock poisoned".into()))?;
35        if admission.fence != inner.fence {
36            return Err(JournalError::StaleLease);
37        }
38        if admission.expected != inner.state.head {
39            // A caller may retry an exactly committed batch after losing its
40            // acknowledgement. This is the sole stale-head exception.
41            let exact = admission
42                .entries
43                .iter()
44                .all(|entry| inner.state.entries.get(&entry.sequence) == Some(entry))
45                && !admission.entries.is_empty();
46            if exact {
47                return Ok(GuardedAdmission {
48                    head: inner.state.head.clone().ok_or(JournalError::WrongHead)?,
49                    disposition: AdmissionDisposition::AlreadyCommittedActionNotInvoked,
50                });
51            }
52            if admission
53                .entries
54                .iter()
55                .any(|entry| inner.state.entries.contains_key(&entry.sequence))
56            {
57                return Err(JournalError::ConflictingDelivery);
58            }
59            return Err(JournalError::WrongHead);
60        }
61        for object in admission.objects {
62            match inner.state.objects.get(&object.id) {
63                Some(bytes) if bytes != &object.bytes => {
64                    return Err(JournalError::ConflictingObject);
65                }
66                Some(_) => {}
67                None => {
68                    inner
69                        .state
70                        .datums
71                        .insert(object.id.clone(), object.datum().clone());
72                    inner.state.objects.insert(object.id, object.bytes);
73                }
74            }
75        }
76        for entry in admission.entries {
77            match inner.state.entries.get(&entry.sequence) {
78                Some(existing) if existing == &entry => {}
79                Some(_) => return Err(JournalError::ConflictingDelivery),
80                None => {
81                    inner.state.entries.insert(entry.sequence, entry);
82                }
83            }
84        }
85        let entry = inner
86            .state
87            .entries
88            .last_key_value()
89            .ok_or(JournalError::EmptyBatch)?
90            .1;
91        let head = JournalHead {
92            sequence: entry.sequence,
93            entry: entry.id.clone(),
94        };
95        inner.state.head = Some(head.clone());
96        Ok(GuardedAdmission {
97            head,
98            disposition: AdmissionDisposition::CommittedActionInvoked,
99        })
100    }
101}
102
103impl JournalBackend for MemoryBackend {
104    fn acquire_lease(&self) -> Result<Lease, JournalError> {
105        let _guard = self
106            .admission
107            .lock()
108            .map_err(|_| JournalError::Backend("memory admission lock poisoned".into()))?;
109        let mut inner = self
110            .inner
111            .lock()
112            .map_err(|_: PoisonError<_>| JournalError::Backend("memory lock poisoned".into()))?;
113        inner.fence = inner
114            .fence
115            .checked_add(1)
116            .ok_or_else(|| JournalError::Backend("fence exhausted".into()))?;
117        Ok(Lease { fence: inner.fence })
118    }
119    fn read_state(&self) -> Result<StoredState, JournalError> {
120        Ok(self
121            .inner
122            .lock()
123            .map_err(|_: PoisonError<_>| JournalError::Backend("memory lock poisoned".into()))?
124            .state
125            .clone())
126    }
127    fn admit(&self, admission: Admission) -> Result<JournalHead, JournalError> {
128        self.admit_then(admission, &mut || {})
129            .map(|result| result.head)
130    }
131
132    fn admit_then(
133        &self,
134        admission: Admission,
135        action: &mut dyn CommitAction,
136    ) -> Result<GuardedAdmission, JournalError> {
137        let _guard = self
138            .admission
139            .lock()
140            .map_err(|_| JournalError::Backend("memory admission lock poisoned".into()))?;
141        let result = self.commit_admission(admission)?;
142        if result.disposition == AdmissionDisposition::CommittedActionInvoked {
143            action.after_commit();
144        }
145        Ok(result)
146    }
147
148    fn put_datum(&self, object: JournalObject) -> Result<StoredDatumRef, JournalError> {
149        object.verify()?;
150        let storage_bytes = object.storage_bytes()?;
151        let reference = StoredDatumRef {
152            meaning: object.id.clone(),
153            storage: crate::object::storage_id(&storage_bytes),
154        };
155        let mut inner = self
156            .inner
157            .lock()
158            .map_err(|_: PoisonError<_>| JournalError::Backend("memory lock poisoned".into()))?;
159        match inner.state.datums.get(&object.id) {
160            Some(value) => {
161                let existing = JournalObject::from_datum(value.clone())?;
162                if existing.id != object.id || existing.bytes != object.bytes {
163                    return Err(JournalError::ConflictingObject);
164                }
165            }
166            None => {
167                let datum = object.datum().clone();
168                inner.state.objects.insert(object.id.clone(), object.bytes);
169                inner.state.datums.insert(object.id, datum);
170            }
171        }
172        Ok(reference)
173    }
174
175    fn get_datum(&self, meaning: &ContentId) -> Result<Datum, JournalError> {
176        self.inner
177            .lock()
178            .map_err(|_: PoisonError<_>| JournalError::Backend("memory lock poisoned".into()))?
179            .state
180            .datums
181            .get(meaning)
182            .cloned()
183            .ok_or_else(|| JournalError::MissingSemanticObject(meaning.clone()))
184    }
185
186    fn rebuild_datum_index(&self) -> Result<Vec<StoredDatumRef>, JournalError> {
187        let inner = self
188            .inner
189            .lock()
190            .map_err(|_: PoisonError<_>| JournalError::Backend("memory lock poisoned".into()))?;
191        inner
192            .state
193            .datums
194            .iter()
195            .map(|(meaning, datum)| {
196                let object = JournalObject::from_datum(datum.clone())?;
197                let bytes = object.storage_bytes()?;
198                Ok(StoredDatumRef {
199                    meaning: meaning.clone(),
200                    storage: crate::object::storage_id(&bytes),
201                })
202            })
203            .collect()
204    }
205}