use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::fmt;
use std::future::Future;
use std::marker::PhantomData;
use futures_util::future::BoxFuture;
use serde::Serialize;
use serde::de::DeserializeOwned;
pub use serde_json::{Map, Value};
use crate::Result;
#[diagnostic::on_unimplemented(
message = "`{Self}` can't be stored on the queue",
label = "expected a type that derives `laravel::queue::Queueable`",
note = "add `#[derive(laravel::queue::Queueable)]` to `{Self}`"
)]
pub trait Queueable: Send + Sync + Sized + 'static {
#[doc(hidden)]
fn __store(&self, rows: &mut ModelRows) -> Result<Value>;
#[doc(hidden)]
fn __assemble(stored: Value, rows: &ModelRows) -> Result<Self>;
#[doc(hidden)]
fn __restore(stored: Value) -> impl Future<Output = Result<Self>> + Send;
}
#[doc(hidden)]
pub type Collect<T> = fn(Value, &mut ModelRows) -> Result<Pending<T>>;
#[doc(hidden)]
pub fn __assemble<T>(stored: Value, collect: Collect<T>, rows: &ModelRows) -> Result<T> {
Ok(collect(stored, &mut ModelRows::new())?.finish(rows))
}
#[doc(hidden)]
pub async fn __restore<T>(stored: Value, collect: Collect<T>) -> Result<T> {
let mut rows = ModelRows::new();
let pending = collect(stored, &mut rows)?;
rows.load().await?;
Ok(pending.finish(&rows))
}
#[doc(hidden)]
#[macro_export]
macro_rules! __serde_queueable {
($ty:ty $(, $param:ident: $bound:path)?) => {
impl$(<$param: $bound>)? $crate::queue::Queueable for $ty
where
Self: ::serde::Serialize + ::serde::de::DeserializeOwned + Send + Sync,
{
fn __store(&self, _: &mut $crate::queue::__queueable::ModelRows) -> $crate::Result<::serde_json::Value> {
Ok(::serde_json::to_value(self)?)
}
fn __assemble(
stored: ::serde_json::Value,
_: &$crate::queue::__queueable::ModelRows,
) -> $crate::Result<Self> {
::serde_json::from_value(stored).map_err($crate::queue::__queueable::__undecodable)
}
async fn __restore(stored: ::serde_json::Value) -> $crate::Result<Self> {
::serde_json::from_value(stored).map_err($crate::queue::__queueable::__undecodable)
}
}
};
}
#[doc(hidden)]
pub use crate::__serde_queueable as serde_queueable;
pub use laravel_rust_queue_macros::Queueable;
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub struct MissingModels {
model: &'static str,
keys: Vec<String>,
}
impl MissingModels {
#[must_use]
pub const fn model(&self) -> &'static str {
self.model
}
#[must_use]
pub fn keys(&self) -> &[String] {
&self.keys
}
}
impl fmt::Display for MissingModels {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let keys = self
.keys
.iter()
.map(|key| format!("`{key}`"))
.collect::<Vec<_>>()
.join(", ");
let noun = if self.keys.len() == 1 { "key" } else { "keys" };
write!(f, "no `{}` has the {noun} {keys} any more", self.model)
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{0}")]
pub(crate) struct Undecodable(pub(crate) String);
#[doc(hidden)]
pub fn __undecodable(message: impl fmt::Display) -> crate::Error {
Undecodable(message.to_string()).into()
}
#[doc(hidden)]
#[derive(Debug)]
pub struct Fields(Map<String, Value>);
impl Fields {
pub fn object(stored: Value) -> Result<Self> {
match stored {
Value::Object(fields) => Ok(Self(fields)),
other => Err(__undecodable(format!("expected an object, found {other}"))),
}
}
pub fn array(stored: Value, len: usize) -> Result<Self> {
match stored {
Value::Array(values) if values.len() == len => Ok(Self(
values
.into_iter()
.enumerate()
.map(|(index, value)| (index.to_string(), value))
.collect(),
)),
other => Err(__undecodable(format!(
"expected an array of {len} values, found {other}"
))),
}
}
pub fn take(&mut self, name: &str) -> Option<Value> {
self.0.remove(name)
}
pub fn take_any(&mut self, names: &[&str]) -> Option<Value> {
names.iter().find_map(|name| self.take(name))
}
}
#[doc(hidden)]
pub struct Field<T>(PhantomData<fn() -> T>);
impl<T> Field<T> {
#[must_use]
pub const fn new() -> Self {
Self(PhantomData)
}
}
impl<T> fmt::Debug for Field<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Field")
}
}
impl<T> Default for Field<T> {
fn default() -> Self {
Self::new()
}
}
#[doc(hidden)]
pub struct Pending<T>(PendingValue<T>);
impl<T> fmt::Debug for Pending<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Pending")
}
}
enum PendingValue<T> {
Ready(T),
Models(Box<dyn FnOnce(&ModelRows) -> T + Send>),
}
impl<T> Pending<T> {
pub const fn ready(value: T) -> Self {
Self(PendingValue::Ready(value))
}
pub fn map<U>(self, map: impl FnOnce(T) -> U + Send + 'static) -> Pending<U>
where
T: 'static,
{
match self.0 {
PendingValue::Ready(value) => Pending::ready(map(value)),
PendingValue::Models(finish) => Pending::models(move |rows| map(finish(rows))),
}
}
pub fn models(finish: impl FnOnce(&ModelRows) -> T + Send + 'static) -> Self {
Self(PendingValue::Models(Box::new(finish)))
}
pub fn finish(self, rows: &ModelRows) -> T {
match self.0 {
PendingValue::Ready(value) => value,
PendingValue::Models(finish) => finish(rows),
}
}
}
#[doc(hidden)]
pub trait ModelField<T> {
fn store(&self, value: &T, name: &str, rows: &mut ModelRows) -> Result<Value>;
fn collect(&self, stored: Option<Value>, name: &str, rows: &mut ModelRows) -> Result<Pending<T>>;
fn kind(&self) -> ModelKind {
ModelKind
}
}
#[doc(hidden)]
pub trait SerdeField<T> {
fn store(&self, value: &T, name: &str, rows: &mut ModelRows) -> Result<Value>;
fn collect(&self, stored: Option<Value>, name: &str, rows: &mut ModelRows) -> Result<Pending<T>>;
fn kind(&self) -> SerdeKind {
SerdeKind
}
}
#[doc(hidden)]
#[derive(Debug, Clone, Copy)]
pub struct ModelKind;
#[doc(hidden)]
#[derive(Debug, Clone, Copy)]
pub struct SerdeKind;
#[doc(hidden)]
#[diagnostic::on_unimplemented(
message = "the model field of type `{T}` can't take `#[serde(default)]`, because a model has no default",
label = "this field holds a model",
note = "make the field an `Option<{T}>`, which is `None` when the job doesn't store it"
)]
pub trait DefaultKind<T> {
fn default_value(self) -> T;
}
impl<T: Default> DefaultKind<T> for SerdeKind {
fn default_value(self) -> T {
T::default()
}
}
#[doc(hidden)]
#[diagnostic::on_unimplemented(
message = "the model field of type `{T}` can't take `#[serde(default = \"..\")]`",
label = "this field holds models",
note = "a model field defaults only to `None` or an empty `Vec`: use `#[serde(default)]` on an `Option` or a `Vec`"
)]
pub trait DefaultWith<T> {}
impl<T> DefaultWith<T> for SerdeKind {}
#[doc(hidden)]
pub fn __default<T, K: DefaultKind<T>>(kind: K) -> Pending<T> {
Pending::ready(kind.default_value())
}
#[doc(hidden)]
pub fn __default_with<T, K: DefaultWith<T>>(_: K, default: fn() -> T) -> Pending<T> {
Pending::ready(default())
}
impl<T: Serialize + DeserializeOwned> SerdeField<T> for &Field<T> {
fn store(&self, value: &T, name: &str, _: &mut ModelRows) -> Result<Value> {
serde_json::to_value(value).map_err(|error| __undecodable(format!("field `{name}`: {error}")))
}
fn collect(&self, stored: Option<Value>, name: &str, _: &mut ModelRows) -> Result<Pending<T>> {
let value = match stored {
Some(stored) => {
serde_json::from_value(stored).map_err(|error| __undecodable(format!("field `{name}`: {error}")))
}
None => serde_json::from_value(Value::Null).map_err(|_| __undecodable(format!("missing field `{name}`"))),
};
value.map(|value| Pending(PendingValue::Ready(value)))
}
}
#[doc(hidden)]
#[derive(Default)]
pub struct ModelRows {
groups: Vec<Box<dyn Group>>,
#[cfg_attr(not(feature = "database"), expect(dead_code, reason = "only models restore rows"))]
index: HashMap<TypeId, usize>,
}
impl fmt::Debug for ModelRows {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ModelRows").field("groups", &self.groups.len()).finish()
}
}
impl ModelRows {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub async fn load(&mut self) -> Result<()> {
for group in &mut self.groups {
group.load().await?;
}
Ok(())
}
#[cfg_attr(not(feature = "database"), expect(dead_code, reason = "only models restore rows"))]
pub(crate) fn group<G: Group + Default>(&mut self) -> &mut G {
let groups = &mut self.groups;
let index = *self.index.entry(TypeId::of::<G>()).or_insert_with(|| {
groups.push(Box::new(G::default()));
groups.len() - 1
});
let group: &mut dyn Any = &mut *self.groups[index];
group
.downcast_mut()
.expect("the index maps each group's type to its group")
}
#[cfg_attr(not(feature = "database"), expect(dead_code, reason = "only models restore rows"))]
pub(crate) fn loaded<G: Group>(&self) -> &G {
let index = self.index[&TypeId::of::<G>()];
let group: &dyn Any = &*self.groups[index];
group
.downcast_ref()
.expect("the index maps each group's type to its group")
}
}
pub(crate) trait Group: Any + Send + Sync {
fn load(&mut self) -> BoxFuture<'_, Result<()>>;
}
impl MissingModels {
#[cfg_attr(not(feature = "database"), expect(dead_code, reason = "only models restore rows"))]
pub(crate) const fn new(model: &'static str, keys: Vec<String>) -> Self {
Self { model, keys }
}
}
pub fn restore_error(kind: &str, name: &str, error: crate::Error) -> crate::Error {
match error.downcast_ref::<Undecodable>() {
Some(Undecodable(message)) => Undecodable(format!("the {kind} `{name}` couldn't be decoded: {message}")).into(),
None => error,
}
}
pub fn store<Q: Queueable>(kind: &str, name: &str, value: &Q, rows: &mut ModelRows) -> Result<Value> {
value
.__store(rows)
.map_err(|error| match error.downcast_ref::<Undecodable>() {
Some(Undecodable(message)) => {
crate::error::fail(format!("the {kind} `{name}` couldn't be encoded: {message}"))
}
None => error,
})
}