use std::fmt;
use std::time::Duration;
use serde_json::Value;
use crate::cache::Repository;
use crate::config::cache::StoreConfig;
use crate::console::{Commands, Console, clap};
use crate::container::Inject;
use crate::queue::QueueManager;
use crate::{Error, Result};
pub(super) fn register(commands: &mut Commands) {
commands.add::<Restart>().add::<Pause>().add::<Continue>();
}
const RESTART: &str = "laravel:queue-restart";
const ALL_PAUSED: &str = "laravel:queues-paused";
const KEPT_FOR: Duration = Duration::from_secs(10 * 365 * 24 * 60 * 60);
fn paused_key(connection: &str, queue: &str) -> String {
format!("laravel:queue-paused:{connection}:{queue}")
}
#[derive(clap::Parser)]
#[command(name = "queue:restart")]
struct Restart;
#[crate::console::command]
impl Restart {
async fn handle(self, console: &mut Console) -> Result<()> {
shared_store(console)?
.put(RESTART, crate::str::uuid7().to_string(), KEPT_FOR)
.await?;
console.success("Restart signal sent.");
Ok(())
}
}
#[derive(clap::Parser)]
#[command(name = "queue:pause")]
struct Pause {
#[arg(required_unless_present = "all", conflicts_with = "all")]
queue: Option<String>,
#[arg(long)]
all: bool,
}
#[crate::console::command]
impl Pause {
async fn handle(self, manager: Inject<QueueManager>, console: &mut Console) -> Result<()> {
let paused = Paused::parse(self.queue, self.all, &manager)?;
shared_store(console)?.put(&paused.key(), true, KEPT_FOR).await?;
console.success(format!("{paused} paused."));
Ok(())
}
}
#[derive(clap::Parser)]
#[command(name = "queue:continue")]
struct Continue {
#[arg(required_unless_present = "all", conflicts_with = "all")]
queue: Option<String>,
#[arg(long)]
all: bool,
}
#[crate::console::command]
impl Continue {
async fn handle(self, manager: Inject<QueueManager>, console: &mut Console) -> Result<()> {
let paused = Paused::parse(self.queue, self.all, &manager)?;
let store = shared_store(console)?;
let resumed = store.forget(&paused.key()).await?;
if matches!(paused, Paused::All) {
console.success("All queues resumed.");
return Ok(());
}
if resumed {
console.success(format!("{paused} resumed."));
} else {
console.info(format!("{paused} isn't paused."));
}
if store.has(ALL_PAUSED).await? {
console.warn("All queues are still paused. Continue them with `queue:continue --all`.");
}
Ok(())
}
}
enum Paused {
All,
Queue { connection: String, queue: String },
}
impl Paused {
fn parse(argument: Option<String>, all: bool, manager: &QueueManager) -> Result<Self> {
let Some(argument) = argument.filter(|_| !all) else {
return Ok(Self::All);
};
let (connection, queue) = argument
.split_once(':')
.unwrap_or((manager.default_connection(), &argument));
let config = manager.connection(connection)?;
Ok(Self::Queue {
connection: connection.to_owned(),
queue: if queue.is_empty() { config.queue() } else { queue }.to_owned(),
})
}
fn key(&self) -> String {
match self {
Self::All => ALL_PAUSED.to_owned(),
Self::Queue { connection, queue } => paused_key(connection, queue),
}
}
}
impl fmt::Display for Paused {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::All => f.write_str("All queues"),
Self::Queue { connection, queue } => write!(f, "Queue `{connection}:{queue}`"),
}
}
}
fn shared_store(console: &mut Console) -> Result<Repository> {
let cache = &crate::config().cache;
match cache.stores.get(&cache.default) {
Some(StoreConfig::Discard) => {
return Err(crate::error::fail(format!(
"the default cache store `{}` keeps nothing, so no worker would see this; set `CACHE_STORE` \
to a shared store, such as `database` or `redis`",
cache.default
)));
}
Some(StoreConfig::Memory) => console.warn(format!(
"Cache store `{}` only reaches this process. Set `CACHE_STORE` to a shared store, such as `database`.",
cache.default
)),
_ => {}
}
crate::cache::manager().default_store()
}
pub(super) struct Signals {
queues: Vec<String>,
keys: Vec<String>,
started_with: Option<Value>,
paused: Vec<bool>,
}
pub(super) enum Next {
Restart,
Reserve(Vec<String>),
}
impl Signals {
pub(super) async fn new(connection: &str, queues: &[String]) -> Self {
let keys = [RESTART.to_owned(), ALL_PAUSED.to_owned()]
.into_iter()
.chain(queues.iter().map(|queue| paused_key(connection, queue)))
.collect();
let started_with = crate::cache::get::<Value>(RESTART).await.unwrap_or_else(|error| {
unreadable(&error);
None
});
Self {
queues: queues.to_vec(),
keys,
started_with,
paused: vec![false; queues.len()],
}
}
pub(super) async fn check(&mut self, console: &mut Console) -> Next {
match crate::cache::many::<Value>(&self.keys).await {
Ok(values) => {
let mut values = values.into_iter();
if values.next().flatten() != self.started_with {
return Next::Restart;
}
let all = values.next().flatten().is_some();
for ((queue, was_paused), value) in self.queues.iter().zip(&mut self.paused).zip(values) {
let paused = all || value.is_some();
if paused != *was_paused {
console.info(format!(
"Queue `{queue}` {}.",
if paused { "paused" } else { "resumed" }
));
*was_paused = paused;
}
}
}
Err(error) => unreadable(&error),
}
Next::Reserve(
self.queues
.iter()
.zip(&self.paused)
.filter(|(_, paused)| !**paused)
.map(|(queue, _)| queue.clone())
.collect(),
)
}
}
fn unreadable(error: &Error) {
crate::foundation::telemetry::logging(error, || {
tracing::warn!(
target: "laravel::queue",
%error,
"The worker couldn't read the restart signal and paused queues from the cache"
)
});
}