use std::fmt;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use navree_contracts::{BoxError, BoxFuture, Dispatcher, Job, JobEnvelope};
use crate::batch::BatchRow;
use crate::store::Store;
use crate::{JobBatch, Queue, QueueOptions};
#[derive(Clone, Default)]
pub struct QueueFake {
recorded: Arc<Mutex<Vec<JobEnvelope>>>,
batches: Arc<Mutex<Vec<FakeBatch>>>,
}
#[derive(Clone, Debug)]
pub struct RecordedBatch {
pub batch: JobBatch,
pub jobs: Vec<JobEnvelope>,
pub then: Option<JobEnvelope>,
pub catch: Option<JobEnvelope>,
pub finally: Option<JobEnvelope>,
}
impl RecordedBatch {
pub fn name(&self) -> &str {
&self.batch.name
}
pub fn jobs_of<J: Job>(&self) -> Vec<J> {
decode_all::<J>(&self.jobs)
}
pub fn then_of<J: Job>(&self) -> Option<J> {
self.then.as_ref().and_then(decode::<J>)
}
pub fn catch_of<J: Job>(&self) -> Option<J> {
self.catch.as_ref().and_then(decode::<J>)
}
pub fn finally_of<J: Job>(&self) -> Option<J> {
self.finally.as_ref().and_then(decode::<J>)
}
}
#[derive(Clone, Debug)]
struct FakeBatch {
row: BatchRow,
jobs: Vec<JobEnvelope>,
}
fn decode<J: Job>(envelope: &JobEnvelope) -> Option<J> {
(envelope.job_type == J::NAME)
.then(|| serde_json::from_value(envelope.payload.clone()).ok())
.flatten()
}
fn decode_all<J: Job>(envelopes: &[JobEnvelope]) -> Vec<J> {
envelopes
.iter()
.filter(|e| e.job_type == J::NAME)
.map(|e| {
serde_json::from_value(e.payload.clone()).unwrap_or_else(|error| {
panic!("a recorded `{}` job does not deserialize: {error}", J::NAME)
})
})
.collect()
}
impl QueueFake {
pub fn batches(&self) -> Vec<RecordedBatch> {
self.batch_lock()
.iter()
.map(|fake| RecordedBatch {
batch: fake.row.to_batch(),
jobs: fake.jobs.clone(),
then: fake.row.callbacks.then.clone(),
catch: fake.row.callbacks.catch.clone(),
finally: fake.row.callbacks.finally.clone(),
})
.collect()
}
pub fn assert_batched(&self, pred: impl Fn(&RecordedBatch) -> bool) {
let batches = self.batches();
assert!(
batches.iter().any(pred),
"expected a matching batch to be dispatched; these were: {:?}",
batches.iter().map(RecordedBatch::name).collect::<Vec<_>>()
);
}
pub fn assert_nothing_batched(&self) {
let batches = self.batches();
assert!(
batches.is_empty(),
"expected no batch to be dispatched, these were: {:?}",
batches.iter().map(RecordedBatch::name).collect::<Vec<_>>()
);
}
pub(crate) fn record_batch(&self, row: BatchRow, jobs: Vec<JobEnvelope>) {
self.batch_lock().push(FakeBatch { row, jobs });
}
pub(crate) fn find_batch(&self, id: &str) -> Option<BatchRow> {
self.batch_lock()
.iter()
.find(|fake| fake.row.id == id)
.map(|fake| fake.row.clone())
}
pub(crate) fn batch_rows(&self, limit: usize) -> Vec<BatchRow> {
let mut rows: Vec<BatchRow> = self.batch_lock().iter().map(|f| f.row.clone()).collect();
rows.reverse();
rows.truncate(limit);
rows
}
pub(crate) fn cancel_batch(&self, id: &str, now: i64) -> Option<BatchRow> {
let mut batches = self.batch_lock();
let fake = batches.iter_mut().find(|fake| fake.row.id == id)?;
fake.row.cancel(now);
Some(fake.row.clone())
}
fn batch_lock(&self) -> MutexGuard<'_, Vec<FakeBatch>> {
self.batches.lock().unwrap_or_else(PoisonError::into_inner)
}
pub fn new() -> Self {
Self::default()
}
pub fn queue(&self) -> Queue {
Queue::new(
Store::Fake(self.clone()),
QueueOptions::default(),
None,
Vec::new(),
None,
)
}
pub fn dispatcher(&self) -> Arc<dyn Dispatcher> {
Arc::new(self.clone())
}
pub fn envelopes(&self) -> Vec<JobEnvelope> {
self.lock().clone()
}
pub fn dispatched<J: Job>(&self) -> Vec<J> {
self.lock()
.iter()
.filter(|e| e.job_type == J::NAME)
.map(|e| {
serde_json::from_value(e.payload.clone()).unwrap_or_else(|error| {
panic!("a recorded `{}` job does not deserialize: {error}", J::NAME)
})
})
.collect()
}
pub fn assert_dispatched<J: Job>(&self, pred: impl Fn(&J) -> bool) {
let jobs = self.dispatched::<J>();
assert!(
jobs.iter().any(pred),
"expected a matching `{}` job to be dispatched; {} `{}` job(s) were, and these job types: {:?}",
J::NAME,
jobs.len(),
J::NAME,
self.job_types()
);
}
pub fn assert_dispatched_times<J: Job>(&self, times: usize) {
let count = self.dispatched::<J>().len();
assert_eq!(
count,
times,
"expected `{}` to be dispatched {times} time(s), it was {count} time(s)",
J::NAME
);
}
pub fn assert_not_dispatched<J: Job>(&self) {
let count = self.dispatched::<J>().len();
assert_eq!(
count,
0,
"expected no `{}` job to be dispatched, {count} were",
J::NAME
);
}
pub fn assert_nothing_dispatched(&self) {
let types = self.job_types();
assert!(
types.is_empty(),
"expected no jobs to be dispatched, these were: {types:?}"
);
}
pub fn clear(&self) {
self.lock().clear();
self.batch_lock().clear();
}
pub(crate) fn record(&self, envelope: JobEnvelope) {
self.lock().push(envelope);
}
pub(crate) fn count_on(&self, queue: &str) -> u64 {
self.lock()
.iter()
.filter(|e| e.options.queue == queue)
.count() as u64
}
fn job_types(&self) -> Vec<String> {
self.lock().iter().map(|e| e.job_type.clone()).collect()
}
fn lock(&self) -> MutexGuard<'_, Vec<JobEnvelope>> {
self.recorded.lock().unwrap_or_else(PoisonError::into_inner)
}
}
impl Dispatcher for QueueFake {
fn dispatch_envelope(&self, env: JobEnvelope) -> BoxFuture<'_, Result<String, BoxError>> {
Box::pin(async move { Ok(self.queue().push(env).await?) })
}
}
impl fmt::Debug for QueueFake {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("QueueFake")
.field("dispatched", &self.job_types())
.finish()
}
}