interplane.Get Omega
Read in your language

synapse

A component of the AienOS ecosystem.

Brought by drakestapleton

branch main Branches Tags History

synapse / crates / synapse-coord / tests / board_core.rs

371 lines · 12796 bytes Raw Blame History
1//! Board core (issue #83): tags, posting, addressing, subscriptions, cursors, `get`, `ack`,
2//! idempotency, restart, the index/journal agreement check and wake sockets, through the
3//! library API. Every board call that touches a planted file runs under a 5 s watchdog so a
4//! hang fails the test instead of the suite.
5
6use std::fs;
7use std::os::unix::fs::symlink;
8use std::path::{Path, PathBuf};
9use std::sync::atomic::{AtomicU32, Ordering};
10use std::sync::mpsc;
11use std::time::{Duration, Instant};
12use synapse_coord::board::{Board, BoardError, Kind, Post, Resume, Sub, Wake};
13
14static N: AtomicU32 = AtomicU32::new(0);
15
16struct Fx {
17 root: PathBuf,
18}
19impl Drop for Fx {
20 fn drop(&mut self) {
21 let _ = fs::remove_dir_all(&self.root);
22 }
23}
24
25fn fx(name: &str) -> (Fx, Board) {
26 let root = std::env::temp_dir().join(format!(
27 "sb-core-{name}-{}-{}",
28 std::process::id(),
29 N.fetch_add(1, Ordering::SeqCst)
30 ));
31 let _ = fs::remove_dir_all(&root);
32 let b = Board::init(&root).unwrap();
33 (Fx { root }, b)
34}
35
36fn watchdog<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> T {
37 let (tx, rx) = mpsc::channel();
38 std::thread::spawn(move || {
39 let _ = tx.send(f());
40 });
41 rx.recv_timeout(Duration::from_secs(5))
42 .expect("board call hung past the 5 s watchdog")
43}
44
45fn mkfifo(p: &Path) {
46 let st = std::process::Command::new("mkfifo")
47 .arg(p)
48 .status()
49 .unwrap();
50 assert!(st.success());
51}
52
53fn reg(b: &Board, session: &str, tag: &str) {
54 b.register(session, tag, None).unwrap();
55}
56
57fn post(b: &Board, session: &str, tag: &str, thread: &str, to: &[&str], text: &str) -> u64 {
58 let mut p = Post::new(
59 &b.whoami(session).unwrap(),
60 thread,
61 "lane/test",
62 Kind::Finding,
63 text,
64 );
65 assert_eq!(p.from_tag, tag);
66 p.to = to.iter().map(|s| s.to_string()).collect();
67 b.post(&p).unwrap().id
68}
69
70fn ids(batch: &synapse_coord::board::ReadBatch) -> Vec<(u64, bool)> {
71 batch
72 .events
73 .iter()
74 .map(|d| (d.event.id, d.addressed))
75 .collect()
76}
77
78#[test]
79fn tag_collision_refused_and_reregister_idempotent() {
80 let (_f, b) = fx("tag");
81 let r = b.register("s-one", "lane-a-board", None).unwrap();
82 assert!(!r.refreshed);
83 let r = b.register("s-one", "lane-a-board", None).unwrap();
84 assert!(r.refreshed, "same session re-registering is idempotent");
85 match b.register("s-two", "lane-a-board", None) {
86 Err(BoardError::TagTaken { tag, holder }) => {
87 assert_eq!(tag, "lane-a-board");
88 assert_eq!(holder, "s-one");
89 }
90 other => panic!("expected TagTaken, got {other:?}"),
91 }
92 match b.register("s-one", "other-tag", None) {
93 Err(BoardError::SessionTagged { tag, .. }) => assert_eq!(tag, "lane-a-board"),
94 other => panic!("expected SessionTagged, got {other:?}"),
95 }
96 let me = b.whoami("s-one").unwrap();
97 assert_eq!(
98 (me.tag.as_str(), me.session.as_str()),
99 ("lane-a-board", "s-one")
100 );
101 assert!(matches!(
102 b.whoami("s-two"),
103 Err(BoardError::NotRegistered { .. })
104 ));
105 for bad in ["", "../x", "a/b", ".hidden", &"x".repeat(65)] {
106 assert!(
107 matches!(
108 b.register("s-three", bad, None),
109 Err(BoardError::BadName { .. })
110 ),
111 "tag {bad:?} must be refused, not rewritten"
112 );
113 }
114 b.unregister("s-one").unwrap();
115 reg(&b, "s-two", "lane-a-board");
116}
117
118#[test]
119fn addressing_and_thread_visibility() {
120 // `to` sets addressing, not visibility: a thread subscriber sees addressed events too,
121 // unflagged; the addressees see them flagged and first.
122 let (_f, b) = fx("vis");
123 reg(&b, "sa", "alpha");
124 reg(&b, "sb", "beta");
125 reg(&b, "sc", "gamma");
126 reg(&b, "sd", "delta");
127 b.subscribe("sc", &Sub::Thread("t-83".into())).unwrap();
128 b.subscribe("sb", &Sub::Topic("lane/test".into())).unwrap();
129 let q = post(&b, "sa", "alpha", "t-83", &["beta"], "question for beta");
130 let a = post(&b, "sb", "beta", "t-83", &["alpha"], "answer for alpha");
131 let other = post(&b, "sd", "delta", "t-other", &[], "unaddressed elsewhere");
132
133 let c = b.read_since("sc", 0, 100).unwrap();
134 assert_eq!(
135 ids(&c),
136 vec![(q, false), (a, false)],
137 "gamma follows the thread"
138 );
139 assert!(!c.more);
140
141 let beta = b.read_since("sb", 0, 100).unwrap();
142 // addressed first, then subscribed (topic lane/test); own answer excluded.
143 assert_eq!(ids(&beta), vec![(q, true), (other, false)]);
144
145 let alpha = b.read_since("sa", 0, 100).unwrap();
146 assert_eq!(
147 ids(&alpha),
148 vec![(a, true)],
149 "alpha follows nothing, sees only its address"
150 );
151
152 let delta = b.read_since("sd", 0, 100).unwrap();
153 assert!(
154 delta.events.is_empty(),
155 "nobody receives a thread they did not follow"
156 );
157
158 assert!(b.get("sc", q).unwrap().is_some());
159 assert!(b.get("sd", q).unwrap().is_none(), "get respects visibility");
160 assert!(
161 b.get("sa", q).unwrap().is_none(),
162 "own post is not delivered back"
163 );
164 assert!(b.get("sa", 999).unwrap().is_none());
165
166 let mine = b.read_mine("sb", 0, 100).unwrap();
167 assert_eq!(ids(&mine), vec![(q, true)]);
168 let inbox = b.inbox("beta", 100).unwrap();
169 assert_eq!(ids(&inbox), vec![(q, true)]);
170}
171
172#[test]
173fn subscribe_unsubscribe_and_limits() {
174 let (_f, b) = fx("subs");
175 reg(&b, "sa", "alpha");
176 reg(&b, "sb", "beta");
177 b.subscribe("sb", &Sub::Topic("lane/test".into())).unwrap();
178 let s = b.subscriptions("sb").unwrap();
179 assert_eq!(s.topics, vec!["lane/test".to_string()]);
180 let ids_posted: Vec<u64> = (0..10)
181 .map(|i| post(&b, "sa", "alpha", "t", &[], &format!("e{i}")))
182 .collect();
183 let first = b.read_since("sb", 0, 4).unwrap();
184 assert_eq!(first.events.len(), 4);
185 assert!(first.more);
186 let rest = b.read_since("sb", first.through, 100).unwrap();
187 let mut all: Vec<u64> = first.events.iter().map(|d| d.event.id).collect();
188 all.extend(rest.events.iter().map(|d| d.event.id));
189 assert_eq!(all, ids_posted, "paged reads have no gap and no duplicate");
190 b.unsubscribe("sb", &Sub::Topic("lane/test".into()))
191 .unwrap();
192 post(&b, "sa", "alpha", "t", &[], "after unsubscribe");
193 assert!(b
194 .read_since("sb", rest.through, 100)
195 .unwrap()
196 .events
197 .is_empty());
198 assert!(matches!(
199 b.subscribe("sb", &Sub::Topic("../escape".into())),
200 Err(BoardError::BadName { .. })
201 ));
202}
203
204#[test]
205fn cursor_deliver_ack_resume() {
206 let (_f, b) = fx("cursor");
207 reg(&b, "sa", "alpha");
208 reg(&b, "sb", "beta");
209 let e1 = post(&b, "sa", "alpha", "t", &["beta"], "one");
210 let e2 = post(&b, "sa", "alpha", "t", &["beta"], "two");
211 assert_eq!(b.acked("sb").unwrap(), 0);
212 let d = b.deliver("sb", 100, Resume::Delivered).unwrap();
213 assert_eq!(ids(&d), vec![(e1, true), (e2, true)]);
214 assert!(b
215 .deliver("sb", 100, Resume::Delivered)
216 .unwrap()
217 .events
218 .is_empty());
219 // A crash before ack: resuming from acked hands both out again, same ids.
220 let again = b.deliver("sb", 100, Resume::Acked).unwrap();
221 assert_eq!(ids(&again), vec![(e1, true), (e2, true)]);
222 b.ack("sb", e1).unwrap();
223 assert_eq!(b.acked("sb").unwrap(), e1);
224 // idempotent at or below the cursor: no error, never moves backwards
225 b.ack("sb", e1).unwrap();
226 b.ack("sb", 0).unwrap();
227 assert_eq!(b.acked("sb").unwrap(), e1);
228 match b.ack("sb", e2 + 5) {
229 Err(BoardError::AckBeyondCommitted { id, last }) => assert_eq!((id, last), (e2 + 5, e2)),
230 other => panic!("expected AckBeyondCommitted, got {other:?}"),
231 }
232 let after_ack = b.deliver("sb", 100, Resume::Acked).unwrap();
233 assert_eq!(ids(&after_ack), vec![(e2, true)]);
234 // A new session that takes the tag over (after release) resumes the same cursor.
235 b.unregister("sb").unwrap();
236 reg(&b, "sb2", "beta");
237 assert_eq!(b.acked("sb2").unwrap(), e1);
238}
239
240#[test]
241fn addressed_events_found_via_index_after_restart() {
242 let (f, b) = fx("restart");
243 reg(&b, "sa", "alpha");
244 reg(&b, "sb", "beta");
245 let mut want = Vec::new();
246 for i in 0..5 {
247 post(&b, "sa", "alpha", "t", &[], &format!("noise {i}"));
248 want.push(post(
249 &b,
250 "sa",
251 "alpha",
252 "t",
253 &["beta"],
254 &format!("for beta {i}"),
255 ));
256 }
257 let id = b.id();
258 drop(b);
259 let b = Board::open_expecting(&f.root, id).unwrap();
260 let mine = b.read_mine("sb", 0, 100).unwrap();
261 assert_eq!(
262 mine.events.iter().map(|d| d.event.id).collect::<Vec<_>>(),
263 want
264 );
265 assert!(b.check().unwrap().ok());
266 // The read is an index read: with the inbox index gone, nothing is found by scanning
267 // the journal, and `check` names the disagreement.
268 fs::remove_file(f.root.join("inbox/beta.idx")).unwrap();
269 assert!(b.read_mine("sb", 0, 100).unwrap().events.is_empty());
270 let rep = b.check().unwrap();
271 assert!(!rep.ok());
272 assert!(
273 rep.problems
274 .iter()
275 .any(|p| p.contains("beta.idx") && p.contains("missing")),
276 "{:?}",
277 rep.problems
278 );
279}
280
281#[test]
282fn idempotency_dedup_and_conflict() {
283 let (_f, b) = fx("idem");
284 reg(&b, "sa", "alpha");
285 reg(&b, "sb", "beta");
286 let mk = |session: &str, text: &str| {
287 let mut p = Post::new(
288 &b.whoami(session).unwrap(),
289 "t",
290 "lane/test",
291 Kind::Ready,
292 text,
293 );
294 p.idem = Some("ready:t:1".into());
295 p
296 };
297 let r1 = b.post(&mk("sa", "ready")).unwrap();
298 let r2 = b.post(&mk("sa", "ready")).unwrap();
299 assert!(!r1.dedup && r2.dedup);
300 assert_eq!(r1.id, r2.id);
301 // the same body from another agent dedups to the same event too
302 let r3 = b.post(&mk("sb", "ready")).unwrap();
303 assert_eq!(r3.id, r1.id);
304 match b.post(&mk("sa", "different text")) {
305 Err(BoardError::IdempotencyConflict { existing, .. }) => assert_eq!(existing, r1.id),
306 other => panic!("expected IdempotencyConflict, got {other:?}"),
307 }
308 assert_eq!(b.bounds().unwrap().1, r1.id, "no extra event was written");
309}
310
311#[test]
312fn hostile_inbox_and_agents_files_refused() {
313 let (f, b) = fx("hostile");
314 reg(&b, "sa", "alpha");
315 post(&b, "sa", "alpha", "t", &[], "warm up");
316 // symlink planted as an addressee's inbox index
317 symlink("/dev/zero", f.root.join("inbox/beta.idx")).unwrap();
318 let b2 = Board::open(&f.root).unwrap();
319 let r = watchdog(move || {
320 let me = b2.whoami("sa").unwrap();
321 let mut p = Post::new(&me, "t", "lane/test", Kind::Finding, "to beta");
322 p.to = vec!["beta".into()];
323 b2.post(&p)
324 });
325 assert!(matches!(r, Err(BoardError::Refused { .. })), "{r:?}");
326 assert_eq!(b.bounds().unwrap().1, 1, "a refused post is not committed");
327 // FIFO planted as an agent binding
328 mkfifo(&f.root.join("agents/gamma.json"));
329 let b3 = Board::open(&f.root).unwrap();
330 let r = watchdog(move || b3.register("sg", "gamma", None));
331 assert!(matches!(r, Err(BoardError::Refused { .. })), "{r:?}");
332 let b4 = Board::open(&f.root).unwrap();
333 let r = watchdog(move || b4.whoami("sa"));
334 assert!(matches!(r, Err(BoardError::Refused { .. })), "{r:?}");
335 // FIFO planted as a reader's inbox
336 fs::remove_file(f.root.join("agents/gamma.json")).unwrap();
337 fs::remove_file(f.root.join("inbox/beta.idx")).unwrap();
338 reg(&b, "sb", "beta");
339 mkfifo(&f.root.join("inbox/beta.idx"));
340 let b5 = Board::open(&f.root).unwrap();
341 let r = watchdog(move || b5.read_mine("sb", 0, 10));
342 assert!(matches!(r, Err(BoardError::Refused { .. })), "{r:?}");
343}
344
345#[test]
346fn wake_socket_wakes_and_times_out() {
347 let (_f, b) = fx("wake");
348 reg(&b, "sa", "alpha");
349 reg(&b, "sb", "beta");
350 let w = b.watcher("sb").unwrap();
351 assert!(matches!(
352 b.watcher("sb"),
353 Err(BoardError::WatcherBusy { .. })
354 ));
355 let t = Instant::now();
356 assert_eq!(w.wait(Duration::from_millis(50)).unwrap(), Wake::TimedOut);
357 assert!(t.elapsed() < Duration::from_secs(2));
358 let id = post(&b, "sa", "alpha", "t", &["beta"], "wake up");
359 assert_eq!(w.wait(Duration::from_secs(5)).unwrap(), Wake::Woke(id));
360 drop(w);
361 // undelivered events wake at once without a datagram
362 assert_eq!(
363 b.wait("sb", Duration::from_secs(5)).unwrap(),
364 Wake::Woke(id)
365 );
366 b.deliver("sb", 100, Resume::Delivered).unwrap();
367 assert_eq!(
368 b.wait("sb", Duration::from_millis(20)).unwrap(),
369 Wake::TimedOut
370 );
371}