use std::sync::{Arc, LazyLock, Mutex, PoisonError};
use std::time::{Duration, UNIX_EPOCH};
use super::{Driver, LEASE, QueueSizes, Reservation, ReservedJob};
use crate::config::queue::RedisQueue;
use crate::error::Result;
use crate::redis::client::Script;
use crate::redis::client::aio::MultiplexedConnection;
use crate::redis::{Commands, Connection, RedisManager};
const BULK_JOBS: usize = 1000;
const BLOCK_SLACK: Duration = Duration::from_secs(5);
const KEYS: &str = r"
local available, delayed, reserved = KEYS[1], KEYS[2], KEYS[3]
local payloads, attempts, notify = KEYS[4], KEYS[5], KEYS[6]
";
static PUSH: LazyLock<Script> = LazyLock::new(|| {
script(
r"
local id = ARGV[1]
redis.call('hset', payloads, id, ARGV[2])
if ARGV[3] then
redis.call('zadd', delayed, ARGV[3], id)
else
redis.call('rpush', available, id)
redis.call('rpush', notify, 1)
end
",
)
});
static BULK: LazyLock<Script> = LazyLock::new(|| {
script(
r"
for i = 1, #ARGV, 2 do
redis.call('hset', payloads, ARGV[i], ARGV[i + 1])
redis.call('rpush', available, ARGV[i])
redis.call('rpush', notify, 1)
end
",
)
});
static SIZES: LazyLock<Script> = LazyLock::new(|| {
script(
r"
local due = redis.call('zcount', delayed, '-inf', ARGV[1])
local lapsed = redis.call('zcount', reserved, '-inf', ARGV[1])
local first = redis.call('lindex', available, 0)
return {
redis.call('llen', available) + due + lapsed,
redis.call('zcard', delayed) - due,
redis.call('zcard', reserved) - lapsed,
first and redis.call('hget', payloads, first) or false,
}
",
)
});
static RESERVE: LazyLock<Script> = LazyLock::new(|| {
script(
r"
-- A hundred at a time, so a large delayed dispatch coming due doesn't block the server...
local due = redis.call('zrangebyscore', delayed, '-inf', ARGV[1], 'limit', 0, 100)
if #due > 0 then
redis.call('zremrangebyrank', delayed, 0, #due - 1)
for _, id in ipairs(due) do
redis.call('rpush', available, id)
redis.call('rpush', notify, 1)
end
end
local id = redis.call('zrangebyscore', reserved, '-inf', ARGV[1], 'limit', 0, 1)[1]
if id then
if ARGV[3] == '0' and redis.call('llen', available) > redis.call('llen', notify) then
redis.call('rpush', notify, 1)
end
else
id = redis.call('lpop', available)
if not id then
redis.call('del', notify)
return false
end
if ARGV[3] ~= '0' then
redis.call('lpop', notify)
end
end
redis.call('zadd', reserved, ARGV[2], id)
return {id, redis.call('hincrby', attempts, id, 1), redis.call('hget', payloads, id)}
",
)
});
const OWNED: &str = r"
if redis.call('hget', attempts, ARGV[1]) ~= ARGV[2] or not redis.call('zscore', reserved, ARGV[1]) then
return 0
end
";
static RENEW: LazyLock<Script> = LazyLock::new(|| {
owned_script(
r"
redis.call('zadd', reserved, ARGV[3], ARGV[1])
return 1
",
)
});
static DELETE: LazyLock<Script> = LazyLock::new(|| {
owned_script(
r"
redis.call('zrem', reserved, ARGV[1])
redis.call('hdel', payloads, ARGV[1])
redis.call('hdel', attempts, ARGV[1])
return 1
",
)
});
static RELEASE: LazyLock<Script> = LazyLock::new(|| {
owned_script(
r"
redis.call('zrem', reserved, ARGV[1])
if ARGV[3] then
redis.call('zadd', delayed, ARGV[3], ARGV[1])
else
redis.call('rpush', available, ARGV[1])
redis.call('rpush', notify, 1)
end
return 1
",
)
});
static CLEAR: LazyLock<Script> = LazyLock::new(|| {
script(
r"
local count = redis.call('llen', available) + redis.call('zcard', delayed) + redis.call('zcard', reserved)
redis.call('del', available, delayed, reserved, payloads, attempts, notify)
return count
",
)
});
fn script(body: &str) -> Script {
Script::new(&format!("{KEYS}{body}"))
}
fn owned_script(body: &str) -> Script {
Script::new(&format!("{KEYS}{OWNED}{body}"))
}
pub(crate) struct RedisDriver {
redis: Arc<RedisManager>,
connection: String,
block_for: Option<Duration>,
blocking: Mutex<Option<MultiplexedConnection>>,
}
impl RedisDriver {
pub(crate) fn new(redis: Arc<RedisManager>, config: &RedisQueue) -> Self {
Self {
redis,
connection: config.connection.clone(),
block_for: config
.block_for
.map(Duration::from)
.filter(|block_for| !block_for.is_zero()),
blocking: Mutex::new(None),
}
}
fn connection(&self) -> Result<Connection> {
self.redis.connection(&self.connection)
}
async fn take(&self, connection: &Connection, queues: &[String], woken: Option<&str>) -> Result<Option<RedisJob>> {
for queue in queues {
let now = unix_millis();
let pop_notify = u8::from(woken != Some(key(queue, ":notify").as_str()));
let reserved: Option<(String, u32, String)> = RESERVE
.key(&keys(queue))
.arg(now)
.arg(now.saturating_add(millis(LEASE)))
.arg(pop_notify)
.invoke_async(&mut connection.clone())
.await?;
if let Some((id, attempts, payload)) = reserved {
return Ok(Some(RedisJob {
connection: connection.clone(),
queue: queue.clone(),
id,
attempts,
payload,
}));
}
}
Ok(None)
}
async fn wait(&self, queues: &[String], block_for: Duration) -> Result<Option<String>> {
let taken = self.blocking.lock().unwrap_or_else(PoisonError::into_inner).take();
let mut blocking = match taken {
Some(blocking) => blocking,
None => self.connection()?.dedicated().await?,
};
let notify: Vec<String> = queues.iter().map(|queue| key(queue, ":notify")).collect();
let notified: Option<[String; 2]> =
tokio::time::timeout(block_for + BLOCK_SLACK, blocking.blpop(notify, block_for.as_secs_f64()))
.await
.map_err(|_| {
crate::error::fail(format!(
"Redis connection `{}` didn't answer `BLPOP` in time",
self.connection
))
})??;
*self.blocking.lock().unwrap_or_else(PoisonError::into_inner) = Some(blocking);
Ok(notified.map(|[notify, _]| notify))
}
}
impl Driver for RedisDriver {
type Job = RedisJob;
async fn push(&self, queue: &str, payload: String, delay: Duration) -> Result<()> {
let mut push = PUSH.key(&keys(queue));
push.arg(crate::str::uuid7().to_string()).arg(payload);
if !delay.is_zero() {
push.arg(unix_millis().saturating_add(millis(delay)));
}
let () = push.invoke_async(&mut self.connection()?).await?;
Ok(())
}
async fn reserve(&self, queues: &[String]) -> Result<Option<RedisJob>> {
if queues.is_empty() {
return Ok(None);
}
let connection = self.connection()?;
if let Some(job) = self.take(&connection, queues, None).await? {
return Ok(Some(job));
}
let Some(block_for) = self.block_for else {
return Ok(None);
};
let Some(notify) = self.wait(queues, block_for).await? else {
return Ok(None);
};
let job = self.take(&connection, queues, Some(¬ify)).await?;
if job.as_ref().is_some_and(|job| key(&job.queue, ":notify") != notify) {
let () = crate::redis::client::cmd("RPUSH")
.arg(notify)
.arg(1)
.query_async(&mut connection.clone())
.await?;
}
Ok(job)
}
async fn clear(&self, queue: &str) -> Result<u64> {
Ok(CLEAR.key(&keys(queue)).invoke_async(&mut self.connection()?).await?)
}
async fn bulk(&self, queue: &str, payloads: Vec<String>) -> Result<()> {
let mut connection = self.connection()?;
let keys = keys(queue);
for chunk in payloads.chunks(BULK_JOBS) {
let mut bulk = BULK.key(&keys);
for payload in chunk {
bulk.arg(crate::str::uuid7().to_string()).arg(payload);
}
let () = bulk.invoke_async(&mut connection).await?;
}
Ok(())
}
async fn sizes(&self, queue: &str) -> Result<Option<QueueSizes>> {
let (pending, delayed, reserved, first): (u64, u64, u64, Option<String>) = SIZES
.key(&keys(queue))
.arg(unix_millis())
.invoke_async(&mut self.connection()?)
.await?;
Ok(Some(QueueSizes {
pending,
delayed,
reserved,
oldest_pending: first.as_deref().and_then(dispatched_at),
approximate: false,
}))
}
}
fn dispatched_at(payload: &str) -> Option<jiff::Timestamp> {
#[derive(serde::Deserialize)]
struct Dispatched {
dispatched_at: i64,
}
let dispatched: Dispatched = serde_json::from_str(payload).ok()?;
jiff::Timestamp::from_second(dispatched.dispatched_at).ok()
}
pub(crate) struct RedisJob {
connection: Connection,
queue: String,
id: String,
attempts: u32,
payload: String,
}
impl RedisJob {
async fn run_owned(&self, script: &Script, extra: Option<u64>) -> Result<Reservation> {
let mut invocation = script.key(&keys(&self.queue));
invocation.arg(&self.id).arg(self.attempts).arg(extra);
let owned: bool = invocation.invoke_async(&mut self.connection.clone()).await?;
Ok(Reservation::held_if(owned))
}
}
impl ReservedJob for RedisJob {
fn queue(&self) -> &str {
&self.queue
}
fn payload(&self) -> &str {
&self.payload
}
fn attempts(&self) -> u32 {
self.attempts
}
async fn renew(&self) -> Result<Reservation> {
self.run_owned(&RENEW, Some(unix_millis().saturating_add(millis(LEASE))))
.await
}
async fn delete(&self) -> Result<Reservation> {
self.run_owned(&DELETE, None).await
}
async fn release(&self, delay: Duration) -> Result<Reservation> {
let available_at = (!delay.is_zero()).then(|| unix_millis().saturating_add(millis(delay)));
self.run_owned(&RELEASE, available_at).await
}
}
fn keys(queue: &str) -> [String; 6] {
["", ":delayed", ":reserved", ":payloads", ":attempts", ":notify"].map(|suffix| key(queue, suffix))
}
fn key(queue: &str, suffix: &str) -> String {
format!("queues:{{{queue}}}{suffix}")
}
fn unix_millis() -> u64 {
millis(
crate::clock::system_now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default(),
)
}
fn millis(duration: Duration) -> u64 {
u64::try_from(duration.as_nanos().div_ceil(1_000_000)).unwrap_or(u64::MAX)
}