use std::{
collections::{BTreeMap, HashMap, VecDeque},
fmt,
future::Future,
pin::Pin,
sync::{Arc, Mutex},
time::Duration,
};
use apalis_core::backend::queue::Queue;
use apalis_rtui_types::{ApiError, TaskStatusEvent};
use serde::{Deserialize, Serialize};
use tokio::sync::RwLock;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LiveResult(pub serde_json::Value);
pub trait RegisterReschedule<B> {
#[must_use]
fn with_reschedule(self, queue: impl Into<Queue>, backend: &Arc<RwLock<B>>) -> Self;
}
pub trait RegisterResume<B> {
#[must_use]
fn with_resume(self, queue: impl Into<Queue>, backend: &Arc<RwLock<B>>) -> Self;
}
pub trait RegisterResumeAbandoned<B> {
#[must_use]
fn with_resume_abandoned(self, queue: impl Into<Queue>, backend: &Arc<RwLock<B>>) -> Self;
}
pub trait RegisterVacuum<B> {
#[must_use]
fn with_vacuum(self, queue: impl Into<Queue>, backend: &Arc<RwLock<B>>) -> Self;
}
pub trait RegisterUpdate<B> {
#[must_use]
fn with_update(self, queue: impl Into<Queue>, backend: &Arc<RwLock<B>>) -> Self;
}
pub trait RegisterRegisterWorker<B> {
#[must_use]
fn with_register_worker(self, queue: impl Into<Queue>, backend: &Arc<RwLock<B>>) -> Self;
}
pub trait RegisterLiveStatus<B> {
#[must_use]
fn with_live_status(self, queue: impl Into<Queue>, backend: &Arc<RwLock<B>>) -> Self;
}
type BoolFuture = Pin<Box<dyn Future<Output = Result<bool, ApiError>> + Send>>;
type StatusFuture = Pin<Box<dyn Future<Output = Option<TaskStatusEvent>> + Send>>;
pub(crate) type RescheduleUpgrade = Arc<dyn Fn(String, Duration) -> BoolFuture + Send + Sync>;
pub(crate) type ResumeUpgrade = Arc<dyn Fn(String) -> BoolFuture + Send + Sync>;
pub(crate) type UpdateUpgrade = Arc<dyn Fn(String) -> BoolFuture + Send + Sync>;
pub(crate) type LiveStatusUpgrade = Arc<dyn Fn(String) -> StatusFuture + Send + Sync>;
const HOOK_POISON: &str = "apalis-rtui capability hook mutex poisoned";
pub(crate) const STATE_POISON: &str = "apalis-rtui: ApiBuilder capability state mutex poisoned";
pub(crate) struct Hook<F>(Arc<Mutex<Option<F>>>);
impl<F> Clone for Hook<F> {
fn clone(&self) -> Self {
Self(Arc::clone(&self.0))
}
}
impl<F> Default for Hook<F> {
fn default() -> Self {
Self(Arc::new(Mutex::new(None)))
}
}
impl<F> fmt::Debug for Hook<F> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let filled = self.0.lock().expect(HOOK_POISON).is_some();
f.debug_struct("Hook").field("filled", &filled).finish()
}
}
impl<F: Clone> Hook<F> {
pub(crate) fn set(&self, value: F) {
*self.0.lock().expect(HOOK_POISON) = Some(value);
}
pub(crate) fn get(&self) -> Option<F> {
self.0.lock().expect(HOOK_POISON).clone()
}
}
pub(crate) type RescheduleHook = Hook<RescheduleUpgrade>;
pub(crate) type ResumeHook = Hook<ResumeUpgrade>;
pub(crate) type UpdateHook = Hook<UpdateUpgrade>;
pub(crate) type LiveStatusHook = Hook<LiveStatusUpgrade>;
const TASK_QUEUE_INDEX_CAPACITY: usize = 10_000;
#[derive(Debug, Default)]
struct TaskQueueIndex {
queue_by_task: HashMap<String, String>,
insertion_order: VecDeque<String>,
}
impl TaskQueueIndex {
fn record(&mut self, task_id: &str, queue: &str) {
if self
.queue_by_task
.insert(task_id.to_owned(), queue.to_owned())
.is_none()
{
self.insertion_order.push_back(task_id.to_owned());
if self.insertion_order.len() > TASK_QUEUE_INDEX_CAPACITY
&& let Some(evicted) = self.insertion_order.pop_front()
{
self.queue_by_task.remove(&evicted);
}
}
}
#[cfg_attr(not(feature = "events"), allow(dead_code))]
fn get(&self, task_id: &str) -> Option<&str> {
self.queue_by_task.get(task_id).map(String::as_str)
}
}
#[derive(Debug, Default)]
pub(crate) struct SharedState {
pub(crate) capabilities: apalis_rtui_types::CapabilityMap,
reschedule_hooks: BTreeMap<String, RescheduleHook>,
resume_hooks: BTreeMap<String, ResumeHook>,
update_hooks: BTreeMap<String, UpdateHook>,
live_status_hooks: BTreeMap<String, LiveStatusHook>,
task_queue: TaskQueueIndex,
}
impl SharedState {
pub(crate) fn register_queue(&mut self, queue: &str) {
self.capabilities.entry(queue.to_owned()).or_default();
self.reschedule_hooks.entry(queue.to_owned()).or_default();
self.resume_hooks.entry(queue.to_owned()).or_default();
self.update_hooks.entry(queue.to_owned()).or_default();
self.live_status_hooks.entry(queue.to_owned()).or_default();
}
pub(crate) fn reschedule_hook(&self, queue: &str) -> Option<RescheduleHook> {
self.reschedule_hooks.get(queue).cloned()
}
pub(crate) fn resume_hook(&self, queue: &str) -> Option<ResumeHook> {
self.resume_hooks.get(queue).cloned()
}
pub(crate) fn update_hook(&self, queue: &str) -> Option<UpdateHook> {
self.update_hooks.get(queue).cloned()
}
pub(crate) fn live_status_hook(&self, queue: &str) -> Option<LiveStatusHook> {
self.live_status_hooks.get(queue).cloned()
}
pub(crate) fn record_task_queue(&mut self, task_id: &str, queue: &str) {
self.task_queue.record(task_id, queue);
}
#[cfg_attr(not(feature = "events"), allow(dead_code))]
pub(crate) fn queue_for_task(&self, task_id: &str) -> Option<&str> {
self.task_queue.get(task_id)
}
}
pub(crate) fn assert_queue_registered(state: &SharedState, queue: &str, builder: &str) {
assert!(
state.capabilities.contains_key(queue),
"apalis-rtui: .{builder}({queue:?}) names a queue that was never registered; call \
.register() or .register_shared() with that queue's backend first"
);
}
pub(crate) fn validate_queue_name(name: &str) {
assert!(
!name.is_empty(),
"apalis-rtui: a queue name must not be empty"
);
if let Some(bad) = name
.chars()
.find(|c| matches!(c, '/' | '?' | '#' | '{' | '}') || c.is_whitespace() || c.is_control())
{
panic!("apalis-rtui: queue name {name:?} must not contain {bad:?}");
}
}
#[cfg_attr(not(feature = "axum"), allow(dead_code))]
const QUEUE_PATH_ENCODE_SET: &percent_encoding::AsciiSet = &percent_encoding::NON_ALPHANUMERIC
.remove(b'-')
.remove(b'_')
.remove(b'.')
.remove(b'~');
#[cfg_attr(not(feature = "axum"), allow(dead_code))]
pub(crate) fn percent_encode_queue(queue: &Queue) -> String {
percent_encoding::utf8_percent_encode(queue.as_ref(), QUEUE_PATH_ENCODE_SET).to_string()
}
#[must_use]
pub(crate) fn csrf_token_ok(cookie_header: Option<&str>, csrf_header: Option<&str>) -> bool {
let Some(csrf_header) = csrf_header else {
return false;
};
let Some(cookie_header) = cookie_header else {
return false;
};
cookie_header
.split(';')
.filter_map(|pair| pair.trim().split_once('='))
.any(|(name, value)| name == "csrf_token" && value == csrf_header)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn validate_queue_name_accepts_ordinary_names() {
validate_queue_name("emails");
validate_queue_name("emails-2");
validate_queue_name("émails");
}
#[test]
#[should_panic(expected = "must not be empty")]
fn validate_queue_name_rejects_empty() {
validate_queue_name("");
}
#[test]
#[should_panic(expected = "must not contain")]
fn validate_queue_name_rejects_slash() {
validate_queue_name("emails/urgent");
}
#[test]
#[should_panic(expected = "must not contain")]
fn validate_queue_name_rejects_braces() {
validate_queue_name("emails{urgent}");
}
#[test]
#[should_panic(expected = "must not contain")]
fn validate_queue_name_rejects_whitespace() {
validate_queue_name("emails urgent");
}
#[test]
fn percent_encode_queue_escapes_reserved_characters() {
let queue = Queue::from("emails&urgent");
assert_eq!(percent_encode_queue(&queue), "emails%26urgent");
}
#[test]
fn percent_encode_queue_leaves_ordinary_names_untouched() {
let queue = Queue::from("emails-2");
assert_eq!(percent_encode_queue(&queue), "emails-2");
}
#[test]
fn csrf_token_ok_requires_matching_cookie_and_header() {
assert!(csrf_token_ok(Some("csrf_token=abc"), Some("abc")));
assert!(csrf_token_ok(
Some("session=1; csrf_token=abc; other=2"),
Some("abc")
));
assert!(!csrf_token_ok(Some("csrf_token=abc"), Some("xyz")));
assert!(!csrf_token_ok(None, Some("abc")));
assert!(!csrf_token_ok(Some("csrf_token=abc"), None));
}
#[tokio::test]
async fn hook_starts_empty_and_reports_once_set() {
let hook: Hook<Arc<str>> = Hook::default();
assert!(hook.get().is_none());
hook.set(Arc::from("filled"));
assert_eq!(hook.get().as_deref(), Some("filled"));
}
#[test]
fn shared_state_queue_for_task_is_none_until_recorded() {
let mut state = SharedState::default();
assert_eq!(state.queue_for_task("t1"), None);
state.record_task_queue("t1", "emails");
assert_eq!(state.queue_for_task("t1"), Some("emails"));
}
#[test]
fn shared_state_queue_for_task_keeps_the_latest_recording() {
let mut state = SharedState::default();
state.record_task_queue("t1", "emails");
state.record_task_queue("t1", "notifications");
assert_eq!(state.queue_for_task("t1"), Some("notifications"));
}
#[test]
fn task_queue_index_evicts_the_oldest_entry_once_over_capacity() {
let mut index = TaskQueueIndex::default();
for i in 0..=TASK_QUEUE_INDEX_CAPACITY {
index.record(&format!("t{i}"), "emails");
}
assert_eq!(
index.get("t0"),
None,
"the first-ever entry should have been evicted"
);
assert_eq!(index.get("t1"), Some("emails"));
assert_eq!(
index.get(&format!("t{TASK_QUEUE_INDEX_CAPACITY}")),
Some("emails")
);
}
}