use super::QueueManagerInternals as _;
use std::any::type_name;
use std::collections::HashSet;
use std::fmt;
use std::ops::Deref;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::Duration;
use serde_json::Value;
use super::batch::{BatchId, BatchSpec};
use super::callback::{Callback, EncodedCallback};
use super::chain::Link;
use super::payload::Payload;
use super::queueable::ModelRows;
use super::{Job, JobId, QueueManager, Queueable};
use crate::context::{Context, Internals};
use crate::testing::fake_stack::{FakeGuard, FakeStack};
use crate::time::ExactDuration;
#[track_caller]
pub fn fake() -> QueueFake {
let manager = QueueManager::of(Context::expect("laravel::queue::fake()").services());
QueueFake {
recording: manager.fakes.push(),
}
}
#[must_use = "bind the queue fake to a name, as in `let queue = queue::fake();`, because dropping it restores dispatch, and `let _ = ..` drops it straight away"]
pub struct QueueFake {
recording: FakeGuard<Recording>,
}
impl QueueFake {
#[must_use = "keep the selected queue fake alive while exercising the application"]
pub fn only<J: Job>(self) -> Self {
self.recording
.state()
.only
.get_or_insert_with(HashSet::new)
.insert(J::NAME);
self
}
#[must_use = "keep the selected queue fake alive while exercising the application"]
pub fn except<J: Job>(self) -> Self {
self.recording.state().except.insert(J::NAME);
self
}
pub fn pushed<J: Job>(&self) -> Vec<Pushed<J>> {
let records: Vec<Record> = self
.recording
.state()
.records
.iter()
.filter(|record| record.payload.job == J::NAME)
.cloned()
.collect();
records
.into_iter()
.map(|record| Pushed {
job: dispatched::<J>(&record.payload.dispatched, record.payload.data, "job"),
id: record.payload.id,
connection: record.connection,
queue: record.queue,
delay: record.delay,
chain: JobList(record.payload.chain.jobs),
catch: CallbackList(record.payload.chain.catch),
})
.collect()
}
#[track_caller]
pub fn assert_pushed<J: Job>(&self) -> &Self {
assert!(
self.count::<J>() > 0,
"expected job `{}` to be pushed at least once; recorded jobs: {:?}",
type_name::<J>(),
self.recorded_names(),
);
self
}
#[track_caller]
pub fn assert_pushed_where<J: Job>(&self, predicate: impl Fn(&Pushed<J>) -> bool) -> &Self {
let jobs = self.pushed::<J>();
assert!(
jobs.iter().any(&predicate),
"expected job `{}` matching the predicate; recorded {} job(s) of this type",
type_name::<J>(),
jobs.len(),
);
self
}
#[track_caller]
pub fn assert_pushed_times<J: Job>(&self, expected: usize) -> &Self {
let actual = self.count::<J>();
assert_eq!(
actual,
expected,
"expected job `{}` to be pushed {expected} time(s), but recorded {actual}",
type_name::<J>(),
);
self
}
#[track_caller]
pub fn assert_not_pushed<J: Job>(&self) -> &Self {
self.assert_pushed_times::<J>(0)
}
#[track_caller]
pub fn assert_not_pushed_where<J: Job>(&self, predicate: impl Fn(&Pushed<J>) -> bool) -> &Self {
let jobs = self.pushed::<J>();
let matching = jobs.iter().filter(|job| predicate(job)).count();
assert!(
matching == 0,
"unexpected job `{}` matching the predicate: {matching} of {} recorded job(s) of this type match",
type_name::<J>(),
jobs.len(),
);
self
}
#[track_caller]
pub fn assert_chained<C: JobTypes>(&self) -> &Self {
let expected = C::names();
let (first, rest) = expected.split_first().expect("a tuple of job types has at least one");
let chains = self.chains(first);
assert!(
chains.iter().any(|chain| chain == rest),
"expected job `{first}` to be pushed with the chain {rest:?}; recorded chains of `{first}`: {chains:?}",
);
self
}
#[track_caller]
pub fn assert_pushed_without_chain<J: Job>(&self) -> &Self {
let chains = self.chains(J::NAME);
assert!(
chains.iter().any(Vec::is_empty),
"expected job `{}` to be pushed without a chain; recorded chains of `{}`: {chains:?}",
type_name::<J>(),
J::NAME,
);
self
}
fn chains(&self, name: &str) -> Vec<Vec<String>> {
self.recording
.state()
.records
.iter()
.filter(|record| record.payload.job == name)
.map(|record| {
record
.payload
.chain
.jobs
.iter()
.map(|link| link.name().to_owned())
.collect()
})
.collect()
}
pub fn batches(&self) -> Vec<PushedBatch> {
self.recording
.state()
.batches
.iter()
.map(|batch| PushedBatch(batch.spec.clone()))
.collect()
}
#[track_caller]
pub fn assert_batched(&self, predicate: impl Fn(&PushedBatch) -> bool) -> &Self {
let batches = self.batches();
assert!(
batches.iter().any(predicate),
"expected a batch matching the predicate; recorded {} batch(es)",
batches.len(),
);
self
}
#[track_caller]
pub fn assert_batch_count(&self, expected: usize) -> &Self {
let actual = self.recording.state().batches.len();
assert_eq!(
actual, expected,
"expected {expected} batch(es) to be dispatched, but recorded {actual}"
);
self
}
#[track_caller]
pub fn assert_nothing_batched(&self) -> &Self {
let batches: Vec<Vec<String>> = self
.batches()
.iter()
.map(|batch| batch.jobs().names().into_iter().map(str::to_owned).collect())
.collect();
assert!(
batches.is_empty(),
"expected no batches to be dispatched; recorded batches of: {batches:?}"
);
self
}
#[track_caller]
pub fn assert_nothing_pushed(&self) -> &Self {
let names = self.recorded_names();
assert!(
names.is_empty(),
"expected no jobs to be pushed; recorded jobs: {names:?}"
);
self
}
fn count<J: Job>(&self) -> usize {
self.recording
.state()
.records
.iter()
.filter(|record| record.payload.job == J::NAME)
.count()
}
fn recorded_names(&self) -> Vec<String> {
self.recording
.state()
.records
.iter()
.map(|record| record.payload.job.clone())
.collect()
}
}
impl fmt::Debug for QueueFake {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("QueueFake")
.field("recorded_jobs", &self.recorded_names())
.finish_non_exhaustive()
}
}
#[derive(Debug)]
pub struct Pushed<J> {
job: Arc<J>,
id: JobId,
connection: String,
queue: String,
delay: Duration,
chain: JobList,
catch: CallbackList,
}
impl<J> Clone for Pushed<J> {
fn clone(&self) -> Self {
Self {
job: Arc::clone(&self.job),
id: self.id,
connection: self.connection.clone(),
queue: self.queue.clone(),
delay: self.delay,
chain: self.chain.clone(),
catch: self.catch.clone(),
}
}
}
impl<J> Pushed<J> {
pub fn job(&self) -> &J {
&self.job
}
pub const fn id(&self) -> JobId {
self.id
}
pub fn connection(&self) -> &str {
&self.connection
}
pub fn queue(&self) -> &str {
&self.queue
}
pub fn delay(&self) -> ExactDuration {
self.delay.into()
}
pub const fn chain(&self) -> &JobList {
&self.chain
}
pub const fn chain_catch(&self) -> &CallbackList {
&self.catch
}
}
#[derive(Debug, Clone, Default)]
pub struct JobList(Vec<Link>);
impl JobList {
#[doc(hidden)]
pub const fn new(jobs: Vec<Link>) -> Self {
Self(jobs)
}
#[must_use]
pub fn len(&self) -> usize {
self.0.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
#[must_use]
pub fn names(&self) -> Vec<&str> {
self.0.iter().map(Link::name).collect()
}
#[must_use]
pub fn get<J: Job>(&self, index: usize) -> Option<Arc<J>> {
let Some(Link::Job(job)) = self.0.get(index) else {
return None;
};
if job.job != J::NAME {
return None;
}
Some(dispatched(&job.dispatched, job.data.clone(), "chained job"))
}
#[must_use]
pub fn batch(&self, index: usize) -> Option<PushedBatch> {
match self.0.get(index)? {
Link::Batch { batch } => Some(PushedBatch((**batch).clone())),
Link::Job(_) => None,
}
}
}
#[derive(Debug, Clone, Default)]
pub struct CallbackList(Vec<EncodedCallback>);
impl CallbackList {
#[must_use]
pub fn len(&self) -> usize {
self.0.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
#[must_use]
pub fn names(&self) -> Vec<&str> {
self.0.iter().map(|callback| callback.callback.as_str()).collect()
}
#[must_use]
pub fn get<C: Callback>(&self, index: usize) -> Option<Arc<C>> {
let callback = self.0.get(index).filter(|callback| callback.callback == C::NAME)?;
Some(dispatched(&callback.dispatched, callback.data.clone(), "callback"))
}
}
#[derive(Debug, Clone)]
pub struct PushedBatch(BatchSpec);
impl PushedBatch {
#[must_use]
pub const fn id(&self) -> BatchId {
self.0.id
}
#[must_use]
pub fn name(&self) -> Option<&str> {
self.0.name.as_deref()
}
#[must_use]
pub fn jobs(&self) -> JobList {
JobList(
self.0
.jobs
.iter()
.filter_map(|chain| chain.jobs.first().cloned())
.collect(),
)
}
#[must_use]
pub fn chain(&self, index: usize) -> JobList {
JobList(
self.0
.jobs
.get(index)
.map(|chain| chain.jobs.iter().skip(1).cloned().collect())
.unwrap_or_default(),
)
}
#[must_use]
pub fn then(&self) -> CallbackList {
CallbackList(self.0.options.then.clone())
}
#[must_use]
pub fn catch(&self) -> CallbackList {
CallbackList(self.0.options.catch.clone())
}
#[must_use]
pub fn finally(&self) -> CallbackList {
CallbackList(self.0.options.finally.clone())
}
#[must_use]
pub const fn allows_failures(&self) -> bool {
self.0.options.allow_failures
}
#[must_use]
pub fn connection(&self) -> Option<&str> {
self.0.options.connection.as_deref()
}
#[must_use]
pub fn queue(&self) -> Option<&str> {
self.0.options.queue.as_deref()
}
}
pub trait JobTypes {
#[doc(hidden)]
fn names() -> Vec<&'static str>;
}
impl<J: Job> JobTypes for J {
fn names() -> Vec<&'static str> {
vec![J::NAME]
}
}
macro_rules! job_types {
($($name:ident),+) => {
impl<$($name: Job),+> JobTypes for ($($name,)+) {
fn names() -> Vec<&'static str> {
vec![$($name::NAME),+]
}
}
};
}
job_types!(A);
job_types!(A, B);
job_types!(A, B, C);
job_types!(A, B, C, D);
job_types!(A, B, C, D, E);
job_types!(A, B, C, D, E, F);
job_types!(A, B, C, D, E, F, G);
job_types!(A, B, C, D, E, F, G, H);
impl<J> Deref for Pushed<J> {
type Target = J;
fn deref(&self) -> &J {
&self.job
}
}
#[derive(Clone, Default)]
pub(crate) struct Dispatched(Option<Arc<ModelRows>>);
impl Dispatched {
pub(crate) fn new(rows: ModelRows) -> Self {
Self(Some(Arc::new(rows)))
}
}
impl PartialEq for Dispatched {
fn eq(&self, _: &Self) -> bool {
true
}
}
impl fmt::Debug for Dispatched {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Dispatched")
}
}
fn dispatched<Q: Queueable>(dispatched: &Dispatched, data: Value, kind: &str) -> Arc<Q> {
let rows = dispatched
.0
.as_deref()
.unwrap_or_else(|| panic!("the {kind} `{}` wasn't recorded by a queue fake", type_name::<Q>()));
match Q::__assemble(data, rows) {
Ok(value) => Arc::new(value),
Err(error) => panic!(
"the {kind} `{}` couldn't be decoded from its payload: {error}",
type_name::<Q>()
),
}
}
#[derive(Debug, Default)]
pub(crate) struct Fakes(FakeStack<Recording>);
impl std::ops::Deref for Fakes {
type Target = FakeStack<Recording>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl Fakes {
pub(super) fn record(&self, payload: &Payload, connection: &str, queue: &str, delay: Duration) -> bool {
let Some(recording) = self.active() else {
return false;
};
let mut state = recording.state();
if !state.selects(&payload.job) {
return false;
}
state.records.push(Record {
payload: payload.clone(),
connection: connection.to_owned(),
queue: queue.to_owned(),
delay,
});
true
}
pub(super) fn record_batch(&self, batch: &BatchSpec) -> bool {
let Some(recording) = self.active() else {
return false;
};
recording.state().batches.push(RecordedBatch {
spec: batch.clone(),
cancelled: false,
});
true
}
pub(super) fn find_batch(&self, id: BatchId) -> Option<(BatchSpec, bool)> {
self.recordings().iter().find_map(|recording| {
let state = recording.state();
let batch = state.batches.iter().find(|batch| batch.spec.id == id)?;
Some((batch.spec.clone(), batch.cancelled))
})
}
pub(super) fn cancel_batch(&self, id: BatchId) -> bool {
self.recordings().iter().any(|recording| {
let mut state = recording.state();
let Some(batch) = state.batches.iter_mut().find(|batch| batch.spec.id == id) else {
return false;
};
batch.cancelled = true;
true
})
}
}
#[derive(Default)]
pub(crate) struct Recording(Mutex<State>);
impl Recording {
fn state(&self) -> MutexGuard<'_, State> {
self.0.lock().unwrap_or_else(PoisonError::into_inner)
}
}
#[derive(Default)]
struct State {
only: Option<HashSet<&'static str>>,
except: HashSet<&'static str>,
records: Vec<Record>,
batches: Vec<RecordedBatch>,
}
struct RecordedBatch {
spec: BatchSpec,
cancelled: bool,
}
impl State {
fn selects(&self, job: &str) -> bool {
!self.except.contains(job) && self.only.as_ref().is_none_or(|jobs| jobs.contains(job))
}
}
#[derive(Clone)]
struct Record {
payload: Payload,
connection: String,
queue: String,
delay: Duration,
}