happenstance_sync_testkit/restore_fixture.rs
1//! What an adapter hands the restore family, and the reference implementation
2//! of it.
3
4use alloc::format;
5use alloc::sync::Arc;
6use alloc::vec::Vec;
7use core::cell::RefCell;
8use core::future::Future;
9use core::num::NonZeroUsize;
10
11use happenstance_core::{Event, SendEventStore, SequencePosition};
12use happenstance_sync::{
13 EventGroup, IngestGroup, MemoryIngestStore, SendIngestStore, SendWriteGroupStore,
14 StoreSyncPeer, Waiting,
15};
16
17use crate::ingest_fixture::MemoryIngestHandle;
18use crate::violation::{Violation, ensure};
19
20/// The clause every failure of a restore fixture is reported under: the one
21/// rule that asked for it.
22const VT_6: &str = "VT-6";
23
24/// One isolated far side whose storage can be backed up and restored, and a
25/// way to reach it.
26///
27/// One fixture instance is one isolated backing store, and each
28/// [`connect`](Self::connect) is one peer onto it: the other families'
29/// contract. What this family adds is the operator's half of the store's life:
30/// a writer of the store's **own** events, a backup and a restore. A peer port
31/// has none of the three, so the fixture supplies them.
32///
33/// # Why a trait of its own
34///
35/// Not a capability on [`SyncFixture`](crate::SyncFixture): a peer that issues
36/// no identity of its own, such as `happenstance_sync::MemorySyncPeer`, which
37/// holds only what it was pushed, has nothing a restore could reissue, and
38/// every rule of that family is held against peers built on it. Here the three
39/// methods are required, so mounting the family is the declaration that the
40/// store can be restored.
41///
42/// # No `Send`, on purpose
43///
44/// Bounded on the bare [`SyncPeer`](happenstance_sync::SyncPeer), as
45/// [`SyncFixture`](crate::SyncFixture) is, so a `!Send` peer is a valid
46/// fixture.
47///
48/// # Errors
49///
50/// Every method but `connect` returns a [`Violation`] of VT-6 when the fixture
51/// cannot do what it was asked. That is the fixture's own failure, reported
52/// under the clause of the rule that asked, as SY-36's provocations are.
53pub trait RestoreFixture {
54 /// The peer adapter under test.
55 type Peer: happenstance_sync::SyncPeer;
56
57 /// A fresh peer onto this fixture's store, as a process started now would
58 /// open one.
59 ///
60 /// An implementation in test code may panic when the environment cannot
61 /// connect, as the other families' fixtures do.
62 fn connect(&self) -> impl Future<Output = Self::Peer>;
63
64 /// Appends `events` to the store as one local write, as the store's own
65 /// writer would: each event takes an identity the store mints.
66 ///
67 /// # Errors
68 ///
69 /// A [`Violation`] of VT-6 if the store refuses the write.
70 fn append_local(&self, events: &[Event]) -> impl Future<Output = Result<(), Violation>>;
71
72 /// Takes a backup of the store's storage as it stands now: everything a
73 /// point-in-time restore to this moment would bring back, the store's
74 /// identity among it.
75 ///
76 /// # Errors
77 ///
78 /// A [`Violation`] of VT-6 if the backup cannot be taken.
79 fn back_up(&self) -> impl Future<Output = Result<(), Violation>>;
80
81 /// Puts the store's storage back to the last [`back_up`](Self::back_up),
82 /// as an operator's restore would, and then takes **every step the adapter
83 /// documents a deployment must take after a restore**.
84 ///
85 /// For an adapter that mints its identity once, that is VT-6's re-mint,
86 /// run the way its documentation says to run it. An adapter that detects a
87 /// restore, or mints on every open, documents no step, and does nothing
88 /// here past the restore itself. The rule drops every peer it connected
89 /// before it asks for the restore, and connects a fresh one after it, as a
90 /// deployment stops its writers first and restarts what held the store.
91 ///
92 /// # Errors
93 ///
94 /// A [`Violation`] of VT-6 if there is no backup to restore, or the
95 /// restore or a documented step fails.
96 fn restore(&self) -> impl Future<Output = Result<(), Violation>>;
97}
98
99/// The most groups one page of a [`MemoryRestoreFixture`] backup reads.
100const BACKUP_PAGE: NonZeroUsize = NonZeroUsize::MIN.saturating_add(127);
101
102/// The most pages a [`MemoryRestoreFixture`] backup reads before it reports
103/// the store as one that never ends (H-13). Far above anything a rule writes.
104const MAX_BACKUP_PAGES: usize = 1_024;
105
106/// The reference [`RestoreFixture`]: a
107/// [`StoreSyncPeer`] over a [`MemoryIngestStore`].
108///
109/// The in-memory peer that issues identities of its own. `MemorySyncPeer`
110/// issues none, so it is not this family's reference; a store peer over the
111/// in-memory oracle is the far side every networked peer in this workspace
112/// stands in front of.
113///
114/// # How it restores
115///
116/// A backup reads the store's write groups whole: every event with its
117/// identity, its recorded time and its group's guard. A restore builds a
118/// **fresh** [`MemoryIngestStore`], with an incarnation of its own, and
119/// ingests the backed-up groups into it. Ingest keeps an origin's identity and
120/// time (VT-5, VT-9), so the restored log holds every backed-up event as it
121/// was, at the positions it held; the fresh incarnation is the re-mint. The
122/// in-memory store can do no other: it refuses a claim on its own identity it
123/// does not hold (SY-38), so a restore under the old identity cannot be built
124/// from its public API at all.
125#[derive(Debug, Default)]
126pub struct MemoryRestoreFixture {
127 /// The store a peer connected now reaches. Swapped by a restore, so a
128 /// `RefCell`: the fixture is used from one task, and no borrow outlives the
129 /// statement that takes it.
130 store: RefCell<Arc<MemoryIngestStore>>,
131 /// The groups the last backup read, taken by the restore that uses them.
132 backup: RefCell<Option<Vec<EventGroup>>>,
133}
134
135impl MemoryRestoreFixture {
136 /// A fixture over a fresh in-memory store.
137 #[must_use]
138 pub fn new() -> Self {
139 Self::default()
140 }
141
142 /// The store a peer connected now reaches.
143 fn current(&self) -> Arc<MemoryIngestStore> {
144 Arc::clone(&self.store.borrow())
145 }
146}
147
148impl RestoreFixture for MemoryRestoreFixture {
149 type Peer = StoreSyncPeer<MemoryIngestHandle, MemoryIngestHandle>;
150
151 fn connect(&self) -> impl Future<Output = Self::Peer> {
152 let store = self.current();
153 core::future::ready(StoreSyncPeer::new(
154 MemoryIngestHandle::over(Arc::clone(&store)),
155 MemoryIngestHandle::over(store),
156 ))
157 }
158
159 async fn append_local(&self, events: &[Event]) -> Result<(), Violation> {
160 let store = self.current();
161 SendEventStore::append(&*store, events, None)
162 .await
163 .map(drop)
164 .map_err(|error| {
165 Violation::new(
166 VT_6,
167 format!("the in-memory store refused a local append: {error}"),
168 )
169 })
170 }
171
172 async fn back_up(&self) -> Result<(), Violation> {
173 let groups = every_group(&self.current()).await?;
174 self.backup.replace(Some(groups));
175 Ok(())
176 }
177
178 async fn restore(&self) -> Result<(), Violation> {
179 let groups = self.backup.take().ok_or_else(|| {
180 Violation::new(VT_6, "the fixture was asked to restore before any backup")
181 })?;
182 let restored = MemoryIngestStore::new();
183 let ingest: Vec<IngestGroup<'_>> = groups
184 .iter()
185 .map(|group| IngestGroup::new(&group.events, &[]).with_guard(group.guard.as_ref()))
186 .collect();
187 let ingested = SendIngestStore::ingest(&restored, &ingest)
188 .await
189 .map_err(|error| {
190 Violation::new(
191 VT_6,
192 format!("the restored store refused the backup: {error}"),
193 )
194 })?;
195 let backed_up: usize = groups.iter().map(|group| group.events.len()).sum();
196 ensure(ingested.appended == backed_up, VT_6, || {
197 format!(
198 "the restored store took {} of the {backed_up} backed-up events",
199 ingested.appended
200 )
201 })?;
202 self.store.replace(Arc::new(restored));
203 Ok(())
204 }
205}
206
207/// Every write group `store` holds, read page by page, as a push carries them.
208async fn every_group(store: &MemoryIngestStore) -> Result<Vec<EventGroup>, Violation> {
209 let mut groups = Vec::new();
210 let mut after: Option<SequencePosition> = None;
211 for _ in 0..MAX_BACKUP_PAGES {
212 let page = SendWriteGroupStore::read_groups(store, after, BACKUP_PAGE)
213 .await
214 .map_err(|error| {
215 Violation::new(
216 VT_6,
217 format!("the in-memory store's groups did not read: {error}"),
218 )
219 })?;
220 let waiting = page.waiting;
221 after = page.groups.last().map(happenstance_sync::WriteGroup::first);
222 groups.extend(page.groups.into_iter().map(EventGroup::from));
223 if waiting == Waiting::Nothing || after.is_none() {
224 return Ok(groups);
225 }
226 }
227 Err(Violation::new(
228 VT_6,
229 format!("the in-memory store's groups ran past {MAX_BACKUP_PAGES} pages"),
230 ))
231}