happenstance_sync_testkit/restore_suite.rs
1//! The restore rules, their one enumeration, and the two emitters.
2//!
3//! Private: what a caller reaches is [`restore_rules`], re-exported at the
4//! crate root, and the macros, which `#[macro_export]` puts there regardless.
5
6/// The restore rules. See the [crate documentation](crate) for what each
7/// covers.
8///
9/// Each rule is an async function taking `impl AsyncFn() -> F` — how to make a
10/// [`RestoreFixture`](crate::RestoreFixture), as in the other families — and returning
11/// `Result<RuleOutcome, Violation>`. No rule decodes a payload (SY-35): an
12/// event is compared whole, and found by its type.
13pub mod restore_rules {
14 use alloc::collections::BTreeMap;
15 use alloc::collections::btree_map::Entry;
16 use alloc::format;
17 use alloc::vec::Vec;
18 use core::slice;
19
20 use happenstance_core::{Event, EventId, EventType};
21 use happenstance_sync::{ReplicatedEvent, SyncPeer, Waiting};
22 use happenstance_testkit::RuleOutcome;
23
24 use crate::RestoreFixture;
25 use crate::violation::{Violation, ensure};
26
27 /// The clause every rule here reports under.
28 const VT_6: &str = "VT-6";
29
30 /// The most pulls the rule makes before it decides the peer will never
31 /// say it has caught up: a peer that loops fails rather than hangs (H-13).
32 const MAX_PULLS: usize = 64;
33
34 /// Written before the backup: the restore brings it back.
35 const KEPT: EventType = EventType::from_static("KeptByTheBackup");
36 /// Written after the backup: the restore takes it away, and the identity
37 /// it was issued is the one a store that keeps its identity issues again.
38 const LOST: EventType = EventType::from_static("LostToTheRestore");
39 /// Written after the restore and the documented procedure.
40 const WRITTEN_AFTER: EventType = EventType::from_static("WrittenAfterTheRestore");
41
42 /// VT-6: a restored store does not issue an `EventId` it already issued
43 /// for a different event.
44 ///
45 /// The rule writes one event, takes a backup, writes a second, and pulls
46 /// the peer's whole log. Then it restores the backup, which takes every
47 /// step the adapter documents for after a restore (VT-6's re-mint on a
48 /// mint-once adapter), connects a fresh peer, writes a third event, and
49 /// pulls the whole log again. No identity may name one event in the first
50 /// pull and a different event in the second, or two events in either.
51 ///
52 /// It then checks that the restore was one: the first event is back
53 /// under the identity it was issued, the second is gone, and the third is
54 /// there. A fixture whose restore did nothing would otherwise pass for a
55 /// store that never reissues. No position is compared: an identity is
56 /// matched whole, against what the peer itself handed back.
57 ///
58 /// # Rejects
59 ///
60 /// The adapter VT-6's `Rejects:` line names: one that keys its
61 /// `StoreId` on the device, or keeps the one a migration minted, and so
62 /// after a restore hands Monday's identities to new events. Every peer that
63 /// pulled the lost event dedupes the new one away as already seen. The same
64 /// sequence with the documented re-mint left out is the negative control:
65 /// `tests/wrong_restores.rs` holds the device-keyed peer, a restore that
66 /// restores nothing, and a store that stamps its current incarnation on
67 /// every event it reads back, so a re-mint rewrites the history it
68 /// restored; `happenstance-postgres` runs its own store with the re-mint
69 /// skipped.
70 ///
71 /// # Errors
72 ///
73 /// A [`Violation`] of VT-6 if the fixture cannot write, back up or
74 /// restore; if a pull fails or never ends; if one identity names two
75 /// events; or if the restore did not bring back the backup.
76 pub async fn restored_peer_does_not_reissue_identities<F: RestoreFixture>(
77 open: impl AsyncFn() -> F,
78 ) -> Result<RuleOutcome, Violation> {
79 let fixture = open().await;
80 let (kept, lost, written_after) = (
81 one_event(KEPT)?,
82 one_event(LOST)?,
83 one_event(WRITTEN_AFTER)?,
84 );
85
86 fixture.append_local(slice::from_ref(&kept)).await?;
87 fixture.back_up().await?;
88 fixture.append_local(slice::from_ref(&lost)).await?;
89 let before = whole_log(&fixture.connect().await, "before the restore").await?;
90 let kept_id = issued(&before, &kept, "before the restore")?;
91 issued(&before, &lost, "before the restore")?;
92
93 fixture.restore().await?;
94 fixture
95 .append_local(slice::from_ref(&written_after))
96 .await?;
97 let after = whole_log(&fixture.connect().await, "after the restore").await?;
98
99 no_identity_names_two_events(&before, &after)?;
100 let restored_id = issued(&after, &kept, "after the restore")?;
101 ensure(restored_id == kept_id, VT_6, || {
102 format!(
103 "the event the backup held came back as {restored_id}, not the {kept_id} it was \
104 issued: the restore did not keep the identities it restored (VT-5), so a peer \
105 that pulled it takes it again as a new fact"
106 )
107 })?;
108 ensure(!after.iter().any(|event| event.event == lost), VT_6, || {
109 "the event written after the backup is still there after the restore: the fixture's \
110 restore did not put the storage back, so nothing was restored for the rule to judge"
111 .into()
112 })?;
113 issued(&after, &written_after, "after the restore")?;
114 Ok(RuleOutcome::Ran)
115 }
116
117 /// An event of `event_type` with a payload no other event of the rule
118 /// carries: its own type's name, as opaque bytes.
119 ///
120 /// `Event::new` cannot refuse an `EventType` already built; the error is
121 /// mapped rather than unwrapped all the same.
122 fn one_event(event_type: EventType) -> Result<Event, Violation> {
123 let data = event_type.as_str().as_bytes().to_vec();
124 Event::new(event_type, data).map_err(|error| {
125 Violation::new(VT_6, format!("the rule's own event is invalid: {error}"))
126 })
127 }
128
129 /// Every event `peer` hands back from the start, following its tokens.
130 async fn whole_log<P: SyncPeer>(
131 peer: &P,
132 when: &str,
133 ) -> Result<Vec<ReplicatedEvent>, Violation> {
134 let mut events = Vec::new();
135 let mut from: Option<P::Resume> = None;
136 for _ in 0..MAX_PULLS {
137 let pulled = peer.pull(from.as_ref()).await.map_err(|error| {
138 Violation::new(VT_6, format!("a pull {when} was refused: {error}"))
139 })?;
140 events.extend(
141 pulled
142 .batch
143 .groups
144 .into_iter()
145 .flat_map(|group| group.events),
146 );
147 if pulled.waiting == Waiting::Nothing {
148 return Ok(events);
149 }
150 from = Some(pulled.resume);
151 }
152 Err(Violation::new(
153 VT_6,
154 format!("the peer {when} never said nothing was waiting in {MAX_PULLS} pulls"),
155 ))
156 }
157
158 /// The identity the one event in `log` equal to `event` carries.
159 fn issued(log: &[ReplicatedEvent], event: &Event, when: &str) -> Result<EventId, Violation> {
160 let mut found = log.iter().filter(|held| held.event == *event);
161 match (found.next(), found.next()) {
162 (Some(held), None) => Ok(held.id),
163 (None, _) => Err(Violation::new(
164 VT_6,
165 format!(
166 "the rule's local `{}` event is not in the log the peer handed back {when}",
167 event.event_type()
168 ),
169 )),
170 (Some(first), Some(second)) => Err(Violation::new(
171 VT_6,
172 format!(
173 "the rule's one local `{}` event came back twice {when}, as {} and {}",
174 event.event_type(),
175 first.id,
176 second.id
177 ),
178 )),
179 }
180 }
181
182 /// No identity names one event in `before` and another in `after`, or two
183 /// events within either.
184 fn no_identity_names_two_events(
185 before: &[ReplicatedEvent],
186 after: &[ReplicatedEvent],
187 ) -> Result<(), Violation> {
188 let mut named: BTreeMap<EventId, &Event> = BTreeMap::new();
189 for held in before.iter().chain(after) {
190 match named.entry(held.id) {
191 Entry::Vacant(slot) => {
192 slot.insert(&held.event);
193 }
194 Entry::Occupied(slot) => ensure(*slot.get() == &held.event, VT_6, || {
195 format!(
196 "the store issued {} to a `{}` event and again to a `{}` event: after a \
197 restore it reissued an identity it had already given away, and every \
198 peer that holds the first will drop the second as already seen",
199 held.id,
200 slot.get().event_type(),
201 held.event.event_type()
202 )
203 })?,
204 }
205 }
206 Ok(())
207 }
208}
209
210/// Hands the complete restore rule set to `$callback`.
211///
212/// This family's single enumeration. `$callback` is the path of a macro that
213/// accepts a comma-separated list of identifiers, and it is invoked once, with
214/// every rule in [`restore_rules`].
215///
216/// # Examples
217///
218/// ```
219/// macro_rules! rule_names {
220/// ($($name:ident),* $(,)?) => { [ $( stringify!($name) ),* ] };
221/// }
222///
223/// let names = happenstance_sync_testkit::for_each_restore_rule!(rule_names);
224/// assert!(names.contains(&"restored_peer_does_not_reissue_identities"));
225/// ```
226#[macro_export]
227macro_rules! for_each_restore_rule {
228 // Raw token trees, for the reason `for_each_sync_peer_rule!` records.
229 ($($callback:tt)+) => {
230 $($callback)+! {
231 // --- A restore does not reissue an identity (VT-6) --------------
232 restored_peer_does_not_reissue_identities,
233 }
234 };
235}
236
237/// Emits one `#[tokio::test]` per restore rule.
238///
239/// The caller's crate needs `tokio` with `macros` and `rt` in its
240/// `dev-dependencies`. The default emitter of
241/// [`restore_conformance!`](crate::restore_conformance).
242#[macro_export]
243macro_rules! emit_restore_tokio {
244 ($($name:ident),* $(,)?) => {
245 $(
246 #[tokio::test]
247 async fn $name() -> ::core::result::Result<(), $crate::Violation> {
248 $crate::__private::restore_rules::$name(__restore_fixture)
249 .await?
250 .report(::core::stringify!($name));
251 Ok(())
252 }
253 )*
254 };
255}
256
257/// Emits one plain `#[test]` per restore rule, driven by
258/// [`happenstance_testkit::block_on`]: no runtime and no `Send` bound.
259#[macro_export]
260macro_rules! emit_restore_blocking {
261 ($($name:ident),* $(,)?) => {
262 $(
263 #[test]
264 fn $name() -> ::core::result::Result<(), $crate::Violation> {
265 $crate::__private::block_on(
266 $crate::__private::restore_rules::$name(__restore_fixture),
267 )?
268 .report(::core::stringify!($name));
269 Ok(())
270 }
271 )*
272 };
273}
274
275/// Expands to a `[&str; N]` of the rule names, for the orphan meta-test.
276#[cfg(test)]
277macro_rules! restore_rule_names {
278 ($($name:ident),* $(,)?) => { [ $( ::core::stringify!($name) ),* ] };
279}
280
281/// No rule exists without appearing in the enumeration, and none is
282/// enumerated without existing: `no_orphan_sync_rules`, one family over, over
283/// the same four-space prefix `cargo xtask spec-trace` reads.
284#[cfg(test)]
285#[test]
286fn no_orphan_restore_rules() {
287 const SOURCE: &str = include_str!("restore_suite.rs");
288 const PREFIX: &str = " pub async fn ";
289 let declared: Vec<&str> = SOURCE
290 .lines()
291 .filter_map(|line| line.strip_prefix(PREFIX))
292 .filter_map(|rest| {
293 rest.split(|c: char| !c.is_alphanumeric() && c != '_')
294 .next()
295 })
296 .collect();
297 let mut registered = crate::for_each_restore_rule!(restore_rule_names).to_vec();
298
299 assert!(
300 !declared.is_empty(),
301 "the source scan matched no rule at all"
302 );
303 let mut declared = declared;
304 declared.sort_unstable();
305 registered.sort_unstable();
306 assert_eq!(
307 declared, registered,
308 "the rules declared in `restore_suite.rs` and the rules `for_each_restore_rule!` \
309 enumerates must be the same set"
310 );
311}