use cfait::context::TestContext;
use cfait::journal::{Action, Journal};
use cfait::model::Task;
use std::collections::HashMap;
use std::sync::{Arc, Barrier};
use std::thread;
#[test]
fn test_concurrent_journal_writes() {
let ctx = Arc::new(TestContext::new());
let thread_count = 10;
let barrier = Arc::new(Barrier::new(thread_count));
let mut handles = vec![];
for i in 0..thread_count {
let b = barrier.clone();
let thread_ctx = ctx.clone();
let handle = thread::spawn(move || {
b.wait();
let mut task = Task::new(&format!("Task {}", i), &HashMap::new(), None);
task.uid = format!("uid-{}", i);
let res = Journal::push(thread_ctx.as_ref(), Action::Create(task));
assert!(res.is_ok(), "Journal push failed in thread {}", i);
});
handles.push(handle);
}
for h in handles {
h.join().unwrap();
}
let journal = Journal::load(ctx.as_ref());
assert_eq!(
journal.queue.len(),
thread_count,
"Journal should contain exactly {} items",
thread_count
);
let uids: Vec<String> = journal
.queue
.iter()
.map(|a| match a {
Action::Create(t) => t.uid.clone(),
_ => "".to_string(),
})
.collect();
for i in 0..thread_count {
assert!(
uids.contains(&format!("uid-{}", i)),
"Journal missing uid-{}",
i
);
}
}