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
//! Framework-agnostic action functions (`docs/PLAN.md` §4.2): each is bounded on the one
//! `apalis_core::backend` trait it needs and returns a shared
//! [`ActionOutcome`](apalis_rtui_types::ActionOutcome), mirroring the existing "narrow bound per
//! function" pattern [`crate::api::push_task`]/[`crate::api::stats_by_queue`] already use.
//!
//! Every framework's route handler ([`crate::api::framework::axum`]/
//! [`crate::api::framework::actix`]) is a thin wrapper around one of these: it extracts the
//! request, calls the matching function here, and serializes the result. None of these functions
//! know about axum, actix-web, JSON extraction, or HTTP status codes.
//!
//! A single-task action returns `Ok(None)` when the task id names nothing this backend knows.
//! Its framework wrapper turns that into a 404, the same convention
//! [`crate::api::get_task_by_id`] already uses.

use std::{str::FromStr, sync::Arc, time::Duration};

use apalis_core::{
    backend::{
        Backend, BackendExt, FetchById, ResumeAbandoned, ResumeById, TaskResult, TaskSink, Update,
        Vacuum, WaitForCompletion, codec::Codec,
    },
    task::task_id::TaskId,
};
use apalis_rtui_types::{
    ActionOutcome, ApiError, BulkAction, BulkFailure, BulkOutcome, RetryMode, TaskStatusEvent,
};
use futures::StreamExt as _;
use serde::{Serialize, de::DeserializeOwned};
use tokio::sync::RwLock;

use crate::api::capability::{
    LiveResult, LiveStatusUpgrade, RescheduleUpgrade, ResumeUpgrade, UpdateUpgrade,
};

/// `POST /queues/{queue}/tasks/{task_id}/retry` (`docs/PLAN.md` §4.2), always mounted by
/// `.register()`.
///
/// Prefers `upgrade` (installed by `.with_reschedule()`, see [`crate::api::capability`]'s module
/// docs) when present: a true, in-place reschedule with no wait. Falls back to re-pushing a new
/// task carrying the same `args` otherwise. That fallback is the only thing `register()`'s own
/// bounds (`TaskSink<T> + FetchById<T>`) allow, and it is the same mechanism
/// `PUT /queues/{queue}/tasks` already exercises generically for any [`TaskSink`] backend.
///
/// # Errors
///
/// Returns [`ApiError::BackendError`] when `task_id` does not parse as `B::IdType`, when `upgrade`
/// fails, or when a backend call fails.
pub async fn retry<B, T, Compact>(
    task_id: String,
    storage: Arc<RwLock<B>>,
    upgrade: Option<RescheduleUpgrade>,
) -> Result<Option<ActionOutcome>, ApiError>
// No `Sync` on `B` and no `Send` on `T`: nothing here holds either across an await, and the
// actix `RegisterRoute` impl has to keep `apalis-board-api`'s exact bounds, which state
// neither (`docs/PLAN.md` §2.1, proven by `tests/actix_bounds.rs`). The axum handler that
// calls this needs a `Send` future and states both itself.
where
    T: Serialize + DeserializeOwned + 'static,
    B: TaskSink<T> + FetchById<T> + BackendExt + Send + 'static,
    B::Error: std::error::Error,
    B::IdType: FromStr,
    <B::IdType as FromStr>::Err: std::error::Error,
    B::Codec: Codec<T, Compact = Compact>,
    <B::Codec as Codec<T>>::Error: std::error::Error,
{
    if let Some(upgrade) = upgrade {
        let rescheduled = upgrade(task_id.clone(), Duration::ZERO).await?;
        return Ok(rescheduled.then_some(ActionOutcome::Retry {
            task_id,
            mode: RetryMode::Reschedule,
        }));
    }
    let id = TaskId::<B::IdType>::from_str(&task_id)
        .map_err(|e| ApiError::BackendError(e.to_string()))?;
    let Some(existing) = storage
        .write()
        .await
        .fetch_by_id(&id)
        .await
        .map_err(|e| ApiError::BackendError(e.to_string()))?
    else {
        return Ok(None);
    };
    storage
        .write()
        .await
        .push(existing.args)
        .await
        .map_err(|e| ApiError::BackendError(e.to_string()))?;
    Ok(Some(ActionOutcome::Retry {
        task_id,
        mode: RetryMode::NewTask,
    }))
}

/// `PATCH /queues/{queue}/tasks/{task_id}/reschedule` (`docs/PLAN.md` §4.2), mounted only by
/// `.with_reschedule()`.
///
/// # Errors
///
/// Returns [`ApiError::BackendError`] when `task_id` does not parse as `B::IdType` or a backend
/// call fails.
pub async fn reschedule<B>(
    task_id: String,
    storage: Arc<RwLock<B>>,
    wait: Duration,
) -> Result<Option<ActionOutcome>, ApiError>
where
    B: apalis_core::backend::Reschedule + FetchById<<B as Backend>::Args>,
    B::Error: std::error::Error,
    B::IdType: FromStr,
    <B::IdType as FromStr>::Err: std::error::Error,
{
    Ok(reschedule_task(&task_id, storage, wait)
        .await?
        .then_some(ActionOutcome::Rescheduled { task_id }))
}

/// Shared by [`reschedule`] and the [`RescheduleUpgrade`] closures `.with_reschedule()` installs
/// for `/retry` and the bulk retry/reschedule actions: fetch the task, then reschedule it after
/// `wait`. `true` if the task existed, `false` if `task_id` named nothing this backend knows.
async fn reschedule_task<B>(
    task_id: &str,
    storage: Arc<RwLock<B>>,
    wait: Duration,
) -> Result<bool, ApiError>
where
    B: apalis_core::backend::Reschedule + FetchById<<B as Backend>::Args>,
    B::Error: std::error::Error,
    B::IdType: FromStr,
    <B::IdType as FromStr>::Err: std::error::Error,
{
    let id = TaskId::<B::IdType>::from_str(task_id)
        .map_err(|e| ApiError::BackendError(e.to_string()))?;
    let mut guard = storage.write().await;
    let Some(task) = guard
        .fetch_by_id(&id)
        .await
        .map_err(|e| ApiError::BackendError(e.to_string()))?
    else {
        return Ok(false);
    };
    guard
        .reschedule(task, wait)
        .await
        .map_err(|e| ApiError::BackendError(e.to_string()))?;
    Ok(true)
}

/// Builds the [`RescheduleUpgrade`] closure `.with_reschedule()` installs: a type-erased
/// `Fn(String, Duration) -> ...` closing over `backend`, reusable by `/retry`, `PATCH
/// .../reschedule`'s own route (via [`reschedule`] instead, for the direct call), and
/// `/tasks/bulk`.
pub(crate) fn reschedule_upgrade<B>(backend: Arc<RwLock<B>>) -> RescheduleUpgrade
where
    B: apalis_core::backend::Reschedule + FetchById<<B as Backend>::Args> + Send + Sync + 'static,
    B::Error: std::error::Error,
    B::IdType: FromStr + Send,
    <B::IdType as FromStr>::Err: std::error::Error,
{
    Arc::new(move |task_id: String, wait: Duration| {
        let storage = Arc::clone(&backend);
        Box::pin(async move { reschedule_task(&task_id, storage, wait).await })
    })
}

/// `POST /queues/{queue}/tasks/{task_id}/resume` (`docs/PLAN.md` §4.2), mounted only by
/// `.with_resume()`.
///
/// # Errors
///
/// Returns [`ApiError::BackendError`] when `task_id` does not parse as `B::IdType` or a backend
/// call fails.
pub async fn resume<B>(
    task_id: String,
    storage: Arc<RwLock<B>>,
) -> Result<Option<ActionOutcome>, ApiError>
where
    B: ResumeById,
    B::Error: std::error::Error,
    B::IdType: FromStr,
    <B::IdType as FromStr>::Err: std::error::Error,
{
    Ok(resume_task(&task_id, storage)
        .await?
        .then_some(ActionOutcome::Resumed { task_id }))
}

async fn resume_task<B>(task_id: &str, storage: Arc<RwLock<B>>) -> Result<bool, ApiError>
where
    B: ResumeById,
    B::Error: std::error::Error,
    B::IdType: FromStr,
    <B::IdType as FromStr>::Err: std::error::Error,
{
    let id = TaskId::<B::IdType>::from_str(task_id)
        .map_err(|e| ApiError::BackendError(e.to_string()))?;
    storage
        .write()
        .await
        .resume_by_id(id)
        .await
        .map_err(|e| ApiError::BackendError(e.to_string()))
}

/// Builds the [`ResumeUpgrade`] closure `.with_resume()` installs for `/tasks/bulk`'s `resume`
/// action.
pub(crate) fn resume_upgrade<B>(backend: Arc<RwLock<B>>) -> ResumeUpgrade
where
    B: ResumeById + Send + Sync + 'static,
    B::Error: std::error::Error,
    B::IdType: FromStr + Send,
    <B::IdType as FromStr>::Err: std::error::Error,
{
    Arc::new(move |task_id: String| {
        let storage = Arc::clone(&backend);
        Box::pin(async move { resume_task(&task_id, storage).await })
    })
}

/// `POST /queues/{queue}/resume-abandoned` (`docs/PLAN.md` §4.2), mounted only by
/// `.with_resume_abandoned()`. No task id in or out.
///
/// # Errors
///
/// Returns [`ApiError::BackendError`] when the backend call fails.
pub async fn resume_abandoned<B>(storage: Arc<RwLock<B>>) -> Result<ActionOutcome, ApiError>
where
    B: ResumeAbandoned,
    B::Error: std::error::Error,
{
    let count = storage
        .write()
        .await
        .resume_abandoned()
        .await
        .map_err(|e| ApiError::BackendError(e.to_string()))?;
    Ok(ActionOutcome::ResumedAbandoned {
        count: Some(u64::try_from(count).unwrap_or(u64::MAX)),
    })
}

/// `POST /queues/{queue}/vacuum` (`docs/PLAN.md` §4.2), mounted only by `.with_vacuum()`.
///
/// # Errors
///
/// Returns [`ApiError::BackendError`] when the backend call fails.
pub async fn vacuum<B>(storage: Arc<RwLock<B>>) -> Result<ActionOutcome, ApiError>
where
    B: Vacuum,
    B::Error: std::error::Error,
{
    let count = storage
        .write()
        .await
        .vacuum()
        .await
        .map_err(|e| ApiError::BackendError(e.to_string()))?;
    Ok(ActionOutcome::Vacuumed {
        count: Some(u64::try_from(count).unwrap_or(u64::MAX)),
    })
}

/// `PATCH /queues/{queue}/tasks/{task_id}` (`docs/PLAN.md` §4.2), mounted only by
/// `.with_update()`.
///
/// `priority`/`meta` are accepted for wire-contract completeness (they round-trip through
/// [`apalis_rtui_types::UpdateRequest`]) and are not applied here. `Backend::Context` is opaque
/// beyond `Default`, so nothing in `apalis-core` lets a backend-agnostic function place a
/// `priority`/`meta` value inside it. Only a backend-specific `Update` implementation, with its
/// own knowledge of its `Context`'s shape, could. This still fetches the task and calls
/// [`Update::update`] on it unchanged, which proves the route is reachable and correctly gated.
/// `docs/PLAN.md` §4.5 notes zero reference-backend `Update` implementors today, so no published
/// backend loses anything this deviation could otherwise have given it.
///
/// # Errors
///
/// Returns [`ApiError::BackendError`] when `task_id` does not parse as `B::IdType` or a backend
/// call fails.
pub async fn update<B>(
    task_id: String,
    storage: Arc<RwLock<B>>,
    _priority: Option<i32>,
    _meta: Option<serde_json::Value>,
) -> Result<Option<ActionOutcome>, ApiError>
where
    B: Update + FetchById<<B as Backend>::Args>,
    B::Error: std::error::Error,
    B::IdType: FromStr,
    <B::IdType as FromStr>::Err: std::error::Error,
{
    Ok(update_task(&task_id, storage)
        .await?
        .then_some(ActionOutcome::Updated { task_id }))
}

async fn update_task<B>(task_id: &str, storage: Arc<RwLock<B>>) -> Result<bool, ApiError>
where
    B: Update + FetchById<<B as Backend>::Args>,
    B::Error: std::error::Error,
    B::IdType: FromStr,
    <B::IdType as FromStr>::Err: std::error::Error,
{
    let id = TaskId::<B::IdType>::from_str(task_id)
        .map_err(|e| ApiError::BackendError(e.to_string()))?;
    let mut guard = storage.write().await;
    let Some(task) = guard
        .fetch_by_id(&id)
        .await
        .map_err(|e| ApiError::BackendError(e.to_string()))?
    else {
        return Ok(false);
    };
    guard
        .update(task)
        .await
        .map_err(|e| ApiError::BackendError(e.to_string()))?;
    Ok(true)
}

/// Builds the [`UpdateUpgrade`] closure `.with_update()` installs for `/tasks/bulk`'s `update`
/// action.
pub(crate) fn update_upgrade<B>(backend: Arc<RwLock<B>>) -> UpdateUpgrade
where
    B: Update + FetchById<<B as Backend>::Args> + Send + Sync + 'static,
    B::Error: std::error::Error,
    B::IdType: FromStr + Send,
    <B::IdType as FromStr>::Err: std::error::Error,
{
    Arc::new(move |task_id: String| {
        let storage = Arc::clone(&backend);
        Box::pin(async move { update_task(&task_id, storage).await })
    })
}

/// Builds the [`LiveStatusUpgrade`] closure `.with_live_status()` installs for
/// `GET /queues/{queue}/tasks/{task_id}/events` (`docs/PLAN.md` §6.3): wait for `task_id` to
/// reach a terminal status on `backend` directly, instead of inferring one from the tracing
/// pipeline. `backend`'s `wait_for_single` stream yields at most one [`TaskResult`]. This takes
/// that one item, or `None` if the id does not parse or the stream ends without ever yielding.
///
/// Only the `.read().await` that fetches the stream is held across an await point, never the
/// (potentially long, until the task finishes) wait itself.
/// `WaitForCompletion::ResultStream: 'static` means `wait_for_single`'s returned stream owns
/// whatever it needs instead of borrowing `backend`, so the read guard is dropped the moment the
/// stream is obtained, before this ever polls it. A `.with_live_status()` watcher never blocks
/// this queue's writers for however long a task takes to finish.
///
/// The resulting event's `attempt` is always `0`: [`TaskResult`] carries no attempt number, only
/// a final status and result, unlike the tracing-derived path (`crate::api::sse::ring`), which
/// reads the real attempt straight off the span. Documented here since this is the one place that
/// gap is introduced.
pub(crate) fn live_status_upgrade<B>(queue: String, backend: Arc<RwLock<B>>) -> LiveStatusUpgrade
where
    B: WaitForCompletion<LiveResult> + BackendExt + Send + Sync + 'static,
    B::Error: std::error::Error,
    B::IdType: FromStr + Send + Sync,
    <B::IdType as FromStr>::Err: std::error::Error,
{
    Arc::new(move |task_id: String| {
        let queue = queue.clone();
        let backend = Arc::clone(&backend);
        Box::pin(async move {
            let id = TaskId::<B::IdType>::from_str(&task_id).ok()?;
            let mut stream = Box::pin(backend.read().await.wait_for_single(id));
            let result = stream.next().await?.ok()?;
            Some(task_result_to_event(task_id, queue, result))
        })
    })
}

/// Shared by [`live_status_upgrade`]'s closure: turn a backend-confirmed [`TaskResult`] into the
/// same [`TaskStatusEvent`] shape the tracing-derived path produces.
fn task_result_to_event<Id>(
    task_id: String,
    queue: String,
    result: TaskResult<LiveResult, Id>,
) -> TaskStatusEvent {
    let status = result.status.to_string();
    let result = Some(match result.result {
        Ok(LiveResult(value)) => value.to_string(),
        Err(message) => message,
    });
    TaskStatusEvent {
        task_id,
        queue,
        status,
        attempt: 0,
        done_in_ms: None,
        result,
    }
}

/// `POST /queues/{queue}/tasks/bulk` (`docs/PLAN.md` §4.2), always mounted by `.register()`.
///
/// Applies `request.action` to every id in `request.task_ids`, sequentially, against the same
/// write guard. The batch is not atomic. That matches the spike's own multi-task loop. Each id's
/// outcome lands in [`BulkOutcome::succeeded`] or [`BulkOutcome::failed`]. A request naming ids
/// this queue's backend cannot resolve, or an action this queue never registered
/// (`reschedule`/`resume`/`update` without the matching `.with_*()` call), fails that one id and
/// leaves the rest of the request alone.
pub async fn bulk<B, T, Compact>(
    request: apalis_rtui_types::BulkRequest,
    storage: Arc<RwLock<B>>,
    reschedule: Option<RescheduleUpgrade>,
    resume: Option<ResumeUpgrade>,
    update: Option<UpdateUpgrade>,
) -> BulkOutcome
// No `Sync` on `B` and no `Send` on `T`: nothing here holds either across an await, and the
// actix `RegisterRoute` impl has to keep `apalis-board-api`'s exact bounds, which state
// neither (`docs/PLAN.md` §2.1, proven by `tests/actix_bounds.rs`). The axum handler that
// calls this needs a `Send` future and states both itself.
where
    T: Serialize + DeserializeOwned + 'static,
    B: TaskSink<T> + FetchById<T> + BackendExt + Send + 'static,
    B::Error: std::error::Error,
    B::IdType: FromStr,
    <B::IdType as FromStr>::Err: std::error::Error,
    B::Codec: Codec<T, Compact = Compact>,
    <B::Codec as Codec<T>>::Error: std::error::Error,
{
    let wait = Duration::from_secs(request.wait_secs.unwrap_or(0));
    let mut succeeded = Vec::new();
    let mut failed = Vec::new();
    for id in request.task_ids {
        let outcome: Result<bool, String> = match request.action {
            BulkAction::Retry => {
                retry::<B, T, Compact>(id.clone(), Arc::clone(&storage), reschedule.clone())
                    .await
                    .map(|found| found.is_some())
                    .map_err(|e| e.to_string())
            }
            BulkAction::Reschedule => match &reschedule {
                Some(hook) => hook(id.clone(), wait).await.map_err(|e| e.to_string()),
                None => Err("reschedule not registered for this queue".to_owned()),
            },
            BulkAction::Resume => match &resume {
                Some(hook) => hook(id.clone()).await.map_err(|e| e.to_string()),
                None => Err("resume not registered for this queue".to_owned()),
            },
            BulkAction::Update => match &update {
                Some(hook) => hook(id.clone()).await.map_err(|e| e.to_string()),
                None => Err("update not registered for this queue".to_owned()),
            },
        };
        match outcome {
            Ok(true) => succeeded.push(id),
            Ok(false) => failed.push(BulkFailure {
                id,
                error: "no task with that id".to_owned(),
            }),
            Err(error) => failed.push(BulkFailure { id, error }),
        }
    }
    BulkOutcome { succeeded, failed }
}