apalis-rtui 0.1.0-rc.1

A drop-in replacement for apalis-board: HTTP surface, live updates, and the apalis-tui dashboard
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
//! The optional-action capability builders (`docs/PLAN.md` §3.6): `RegisterReschedule`,
//! `RegisterResume`, `RegisterResumeAbandoned`, `RegisterVacuum`, `RegisterUpdate`,
//! `RegisterRegisterWorker`, and `RegisterLiveStatus`.
//!
//! Each trait's `with_*()` method is bounded only on the one `apalis_core::backend` trait it
//! needs, computed once when called, exactly like [`RegisterRoute`](crate::api::framework::RegisterRoute).
//! A backend that lacks the trait fails at `cargo check` time (`with_*()` does not compile against
//! it), never as a silent no-op or a runtime probe. `.register()`/`.register_shared()` mount the
//! always-available `/retry` and `/tasks/bulk` routes and seed a default (all `false`)
//! [`Capabilities`](apalis_rtui_types::Capabilities) entry per queue. Each `with_*()` here flips
//! the matching flag and mounts its own dedicated route.
//!
//! # Why `/retry` and bulk-retry/reschedule need a runtime hook
//!
//! `/retry` is always mounted by `register()`, bounded only on `TaskSink<T> + FetchById<T>` (the
//! bounds `register()` already requires): it can only ever perform the "push a new task with the
//! same args" fallback on its own. When `.with_reschedule()` is *also* called for that queue, a
//! true in-place reschedule becomes possible, but by then `/retry`'s route is already mounted.
//! Both axum and actix-web panic on registering the same method and path twice, so
//! `with_reschedule` cannot re-mount it with a stronger bound. Instead, `register()` gives every
//! queue a `RescheduleHook` cell, empty at first, read by `/retry` and `/tasks/bulk` at request
//! time.
//! `.with_reschedule()` fills the cell in with a closure that closes over the concrete backend
//! (known, at that call site, to implement `Reschedule`) type-erased behind `Fn(String, Duration)
//! -> ...`, so the cell's *type* never depends on which backend is behind it. `.with_resume()` and
//! `.with_update()` do the same for `/tasks/bulk`'s `resume`/`update` bulk actions via
//! `ResumeHook`/`UpdateHook`.

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;

/// Wraps an arbitrary JSON job result so `.with_live_status()` can be bounded on
/// `WaitForCompletion<LiveResult>` instead of `WaitForCompletion<B::Compact>`.
///
/// `B::Compact` is the task's encoded **input**, so it never carries an output
/// (`docs/PLAN.md` §3.6). Both
/// reference backends' blanket `WaitForCompletion<O>` impls are generic over any `O` with
/// `Result<O, String>: DeserializeOwned`, decoded with a bare `.unwrap()` that panics on a type
/// mismatch, so `WaitForCompletion<B::Compact>` would compile but panic on the first real job
/// result. `LiveResult` accepts any JSON value, so the decode can never mismatch.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LiveResult(pub serde_json::Value);

/// Registers `.with_reschedule()`: mounts `PATCH /queues/{queue}/tasks/{task_id}/reschedule` and
/// upgrades that queue's `/retry` and bulk-retry/reschedule actions to a true reschedule.
pub trait RegisterReschedule<B> {
    /// Turn on the `reschedule` capability for `queue`, bounded on `backend`'s `Reschedule` impl.
    #[must_use]
    fn with_reschedule(self, queue: impl Into<Queue>, backend: &Arc<RwLock<B>>) -> Self;
}

/// Registers `.with_resume()`: mounts `POST /queues/{queue}/tasks/{task_id}/resume` and upgrades
/// that queue's bulk-resume action.
pub trait RegisterResume<B> {
    /// Turn on the `resume_by_id` capability for `queue`, bounded on `backend`'s `ResumeById` impl.
    #[must_use]
    fn with_resume(self, queue: impl Into<Queue>, backend: &Arc<RwLock<B>>) -> Self;
}

/// Registers `.with_resume_abandoned()`: mounts `POST /queues/{queue}/resume-abandoned`.
pub trait RegisterResumeAbandoned<B> {
    /// Turn on the `resume_abandoned` capability for `queue`, bounded on `backend`'s
    /// `ResumeAbandoned` impl.
    #[must_use]
    fn with_resume_abandoned(self, queue: impl Into<Queue>, backend: &Arc<RwLock<B>>) -> Self;
}

/// Registers `.with_vacuum()`: mounts `POST /queues/{queue}/vacuum`.
pub trait RegisterVacuum<B> {
    /// Turn on the `vacuum` capability for `queue`, bounded on `backend`'s `Vacuum` impl.
    #[must_use]
    fn with_vacuum(self, queue: impl Into<Queue>, backend: &Arc<RwLock<B>>) -> Self;
}

/// Registers `.with_update()`: mounts `PATCH /queues/{queue}/tasks/{task_id}` and upgrades that
/// queue's bulk-update action.
pub trait RegisterUpdate<B> {
    /// Turn on the `update` capability for `queue`, bounded on `backend`'s `Update` impl.
    #[must_use]
    fn with_update(self, queue: impl Into<Queue>, backend: &Arc<RwLock<B>>) -> Self;
}

/// Registers `.with_register_worker()`. Flips the `register_worker` capability flag only: no
/// route consumes it yet (`docs/PLAN.md` §4 scopes a worker-registration route to a later track).
pub trait RegisterRegisterWorker<B> {
    /// Turn on the `register_worker` capability for `queue`, bounded on `backend`'s
    /// `RegisterWorker` impl.
    #[must_use]
    fn with_register_worker(self, queue: impl Into<Queue>, backend: &Arc<RwLock<B>>) -> Self;
}

/// Registers `.with_live_status()`: flips the `live_status` capability flag and upgrades
/// `GET /queues/{queue}/tasks/{task_id}/events` (always mounted, `docs/PLAN.md` §4.4, §6.3) from
/// its tracing-derived fallback to a `WaitForCompletion<LiveResult>`-backed, backend-confirmed
/// stream.
pub trait RegisterLiveStatus<B> {
    /// Turn on the `live_status` capability for `queue`, bounded on `backend`'s
    /// `WaitForCompletion<LiveResult>` impl.
    #[must_use]
    fn with_live_status(self, queue: impl Into<Queue>, backend: &Arc<RwLock<B>>) -> Self;
}

/// A request-time boolean outcome future, boxed so `RescheduleHook`/`ResumeHook`/
/// `UpdateHook` can hold one regardless of the concrete backend behind it.
type BoolFuture = Pin<Box<dyn Future<Output = Result<bool, ApiError>> + Send>>;

/// A request-time single-event outcome future, boxed so [`LiveStatusHook`] can hold one
/// regardless of the concrete backend behind it. `None` when the task id does not parse as the
/// backend's `IdType`, or the backend's `wait_for_single` stream ends without ever yielding a
/// result.
type StatusFuture = Pin<Box<dyn Future<Output = Option<TaskStatusEvent>> + Send>>;

/// A type-erased "reschedule this task id, waiting `Duration` first" action.
pub(crate) type RescheduleUpgrade = Arc<dyn Fn(String, Duration) -> BoolFuture + Send + Sync>;
/// A type-erased "resume this task id" action.
pub(crate) type ResumeUpgrade = Arc<dyn Fn(String) -> BoolFuture + Send + Sync>;
/// A type-erased "update this task id" action.
pub(crate) type UpdateUpgrade = Arc<dyn Fn(String) -> BoolFuture + Send + Sync>;
/// A type-erased "wait for this task id to finish, backend-confirmed" action.
pub(crate) type LiveStatusUpgrade = Arc<dyn Fn(String) -> StatusFuture + Send + Sync>;

const HOOK_POISON: &str = "apalis-rtui capability hook mutex poisoned";

/// The `.expect()` message every `ApiBuilder::state` lock site (builder methods and route
/// handlers alike) uses.
pub(crate) const STATE_POISON: &str = "apalis-rtui: ApiBuilder capability state mutex poisoned";

/// A shared, request-time-mutable slot for one optional upgrade action of type `F`.
/// `.register()`/`.register_shared()` create one per queue, empty. The matching `.with_*()`
/// builder fills it in afterward, once the concrete backend's stronger trait bound is known. See
/// the module docs for why this indirection exists.
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()
    }
}

/// The cell `/retry`, `PATCH .../reschedule`'s bulk-action counterpart, and `/tasks/bulk` read to
/// find a true reschedule for a queue, when one is available.
pub(crate) type RescheduleHook = Hook<RescheduleUpgrade>;
/// The cell `/tasks/bulk`'s `resume` action reads.
pub(crate) type ResumeHook = Hook<ResumeUpgrade>;
/// The cell `/tasks/bulk`'s `update` action reads.
pub(crate) type UpdateHook = Hook<UpdateUpgrade>;
/// The cell `GET .../tasks/{task_id}/events` reads to find a backend-confirmed live-status
/// stream for a queue, when one is available (`docs/PLAN.md` §6.3).
pub(crate) type LiveStatusHook = Hook<LiveStatusUpgrade>;

/// How many `task_id -> queue` entries [`SharedState::record_task_queue`] keeps before evicting
/// the oldest one, oldest-insertion-first. This is a FIFO, so a repeatedly re-fetched old task
/// does not postpone its own eviction the way a true LRU would.
/// Bounds the index's memory on a long-running server
/// regardless of how many distinct tasks it has ever served, at the cost of forgetting a queue
/// mapping for a task nobody has looked up by id in a while. See [`SharedState`]'s docs for the
/// mechanism this index feeds.
const TASK_QUEUE_INDEX_CAPACITY: usize = 10_000;

/// A small, FIFO-bounded `task_id -> queue` index (`docs/PLAN.md` §6.2's "task_id→queue map").
#[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);
            }
        }
    }

    // Only read by `crate::api::sse::ring`'s tracing-derived event pipeline, which is itself
    // built only under the `events` feature. Recording still happens unconditionally (see
    // `SharedState::record_task_queue`'s call site): a build without `events` pays a small,
    // harmless bit of bookkeeping it never reads back.
    #[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)
    }
}

/// Every queue's default-`false` [`Capabilities`](apalis_rtui_types::Capabilities) entry, the
/// four hook maps keyed the same way, and the `task_id -> queue` index the SSE ring buffer
/// (`crate::api::sse::ring`) consults to fill `TaskStatusEvent::queue`, all live behind one
/// shared, lockable value so `.register()`, every `.with_*()`, and the `GET /capabilities` route
/// agree on one source of truth regardless of call order.
///
/// # `task_id -> queue`: mechanism and limits
///
/// A tracing span carries only `task_id`/`attempt` (`docs/research/00-ground-truth.md` §3,
/// confirmed against `apalis-1.0.0-rc.9`'s own `TraceLayer`), never a queue name, so
/// `crate::api::sse::ring` cannot recover `queue` from the frame it derives a `TaskStatusEvent`
/// from. Instead, `GET /queues/{queue}/tasks/{task_id}` (always mounted, the route the TUI's task
/// detail screen already calls before it ever subscribes to that task's live status) records the
/// mapping here on every successful lookup. A task id nobody has fetched by id yet reports
/// `queue: ""` on its status events until it is: `?task_id=` filtering still works regardless
/// (task ids are unique on their own), only the `queue` field and an unrelated `?queue=` filter
/// are affected, and only until the first `GET .../tasks/{task_id}` for that id.
#[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 {
    /// Seed `queue`'s default (all-`false`) [`Capabilities`](apalis_rtui_types::Capabilities)
    /// entry and a matching set of empty hook cells. Idempotent: registering the same queue name
    /// twice keeps the first entry and cells (an already-flipped flag or already-filled hook is
    /// never reset).
    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();
    }

    /// The reschedule-upgrade cell for `queue`, if [`SharedState::register_queue`] has already
    /// been called for it.
    pub(crate) fn reschedule_hook(&self, queue: &str) -> Option<RescheduleHook> {
        self.reschedule_hooks.get(queue).cloned()
    }

    /// The resume-upgrade cell for `queue`, if [`SharedState::register_queue`] has already been
    /// called for it.
    pub(crate) fn resume_hook(&self, queue: &str) -> Option<ResumeHook> {
        self.resume_hooks.get(queue).cloned()
    }

    /// The update-upgrade cell for `queue`, if [`SharedState::register_queue`] has already been
    /// called for it.
    pub(crate) fn update_hook(&self, queue: &str) -> Option<UpdateHook> {
        self.update_hooks.get(queue).cloned()
    }

    /// The live-status-upgrade cell for `queue`, if [`SharedState::register_queue`] has already
    /// been called for it.
    pub(crate) fn live_status_hook(&self, queue: &str) -> Option<LiveStatusHook> {
        self.live_status_hooks.get(queue).cloned()
    }

    /// Record that `task_id` belongs to `queue`, consulted later by
    /// [`SharedState::queue_for_task`]. See the struct docs for when this is called and what it
    /// means for a task never recorded this way.
    pub(crate) fn record_task_queue(&mut self, task_id: &str, queue: &str) {
        self.task_queue.record(task_id, queue);
    }

    /// The queue `task_id` was last recorded under, if any. See the struct docs for the
    /// mechanism and its limits.
    // Only read by `crate::api::sse::ring`, built under the `events` feature; see
    // `TaskQueueIndex::get`'s own note.
    #[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)
    }
}

/// Reject a `.with_*()` call naming a queue that no `.register()`/`.register_shared()` call has
/// mounted (`docs/PLAN.md` §3.6).
///
/// Every `.with_*()` takes its queue as free-form text, so a typo used to create a second,
/// phantom entry: `GET /capabilities` grew a queue with no routes behind it, the real queue's
/// hook cell stayed empty, and `/retry` quietly fell back to pushing a new task. Nothing failed
/// and nothing was logged. This is a startup configuration error of the same class as
/// [`validate_queue_name`], so it fails the same way, once, at build time.
///
/// # Panics
///
/// Panics with a message naming the builder and the unknown queue.
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"
    );
}

/// Reject an empty queue name or one containing `/`, `?`, `#`, whitespace, or a control character
/// (`docs/PLAN.md` §7.6). Called once per queue, at `.register()`/`.register_shared()` time. It
/// catches a configuration error once at startup, never on a request.
///
/// # Panics
///
/// Panics with a message naming the offending queue and character when the name is empty or
/// contains a disallowed character.
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:?}");
    }
}

/// The characters percent-encoded in a queue name once it is interpolated into a route path,
/// beyond what [`validate_queue_name`] already rejects outright (`docs/PLAN.md` §7.6, §4.2).
// Only reached by the axum route wiring: actix percent-decodes a request path before matching
// it, so its patterns carry the queue name decoded (see `framework::actix::register_shared`).
#[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'~');

/// Percent-encode `queue` for interpolation into an axum route path. See
/// [`QUEUE_PATH_ENCODE_SET`] for why actix has no equivalent call.
#[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()
}

/// The double-submit-cookie check `.require_csrf_token(true)` gates every mutating route behind
/// (`docs/PLAN.md` §7.8): the request must carry both a `csrf_token` cookie and a matching
/// `x-csrf-token` header. Framework-agnostic so the axum and actix-web middleware share one rule.
#[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");
    }

    // Braces open a dynamic segment in an actix `ResourceDef` pattern, where the decoded queue
    // name is interpolated verbatim.
    #[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")
        );
    }
}