Skip to main content

apalis_rtui_types/
lib.rs

1//! Wire types shared between `apalis-rtui`'s HTTP surface, TUI backend, and testkit.
2//!
3//! This crate re-exports the `apalis-board-types` wire contract byte-identically and adds
4//! the wire-side types `apalis-rtui` needs beyond it. It carries no HTTP framework, no
5//! `apalis-core` dependency, and no runtime, so the server, the native dashboard, and the wasm
6//! dashboard all share one definition of every JSON shape. Repository:
7//! <https://github.com/ngriaznov/apalis-rtui>.
8//!
9//! ## Re-exported from `apalis-board-types`
10//!
11//! [`LogEntry`], [`LogLevel`], [`LineEntry`], [`EntryType`], [`ResultEntry`], [`Entry`], [`Span`],
12//! [`ApiError`], and the [`config`] module are the exact types a consumer already holding
13//! `apalis-board-types` has. A value built against one crate deserializes and compares equal
14//! against the other: same struct, same `TypeId`, not a lookalike.
15//!
16//! ## New in this crate
17//!
18//! [`Capabilities`] and [`CapabilityMap`] describe which optional backend actions a queue
19//! supports. [`RetryMode`], [`ActionOutcome`], [`BulkAction`], [`BulkRequest`], [`BulkFailure`],
20//! and [`BulkOutcome`] cover the request/response shapes of the action routes. [`TaskStatusEvent`]
21//! is the `task-status` SSE event shape, and [`ActivityBucket`] is one minute of its
22//! `GET /events/activity` rollup. [`RescheduleRequest`] and [`UpdateRequest`] are request bodies
23//! for the reschedule and update actions.
24//!
25//! ## `wire`
26//!
27//! The [`wire`] module holds hand-written, `apalis-core`-free mirrors of the `QueueInfo`,
28//! `RunningWorker`, `Statistic`, and `Task` JSON shapes, re-exported at the crate root so both
29//! `apalis-rtui` and `apalis-tui` (including its wasm32 build) share one definition. See the
30//! module's own docs for why log frames reuse [`LogEntry`]/[`Span`] instead of a third copy.
31
32#![forbid(unsafe_code)]
33#![warn(missing_docs)]
34#![warn(unreachable_pub)]
35#![warn(missing_debug_implementations)]
36
37use std::collections::BTreeMap;
38
39use serde::{Deserialize, Serialize};
40
41pub use apalis_board_types::config;
42pub use apalis_board_types::*;
43
44pub mod wire;
45pub use wire::{LogFrameExt, Parts, QueueInfo, RunningWorker, Statistic, TaskJson};
46
47/// Which optional actions a queue's registered backend supports.
48///
49/// Computed once when a backend is registered (`.register()`/`.with_*()`), then served as a
50/// plain map so a client can grey or hide a control without probing the action route itself.
51///
52/// # Examples
53///
54/// ```
55/// use apalis_rtui_types::Capabilities;
56///
57/// let caps = Capabilities {
58///     vacuum: true,
59///     ..Capabilities::default()
60/// };
61/// let json = serde_json::to_string(&caps).unwrap();
62/// assert_eq!(
63///     json,
64///     r#"{"reschedule":false,"resume_by_id":false,"resume_abandoned":false,"vacuum":true,"update":false,"register_worker":false,"live_status":false}"#
65/// );
66/// ```
67#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
68pub struct Capabilities {
69    /// The backend implements `Reschedule`, so `PATCH .../reschedule` is wired.
70    pub reschedule: bool,
71    /// The backend implements `ResumeById`, so `POST .../resume` is wired.
72    pub resume_by_id: bool,
73    /// The backend implements `ResumeAbandoned`, so `POST .../resume-abandoned` is wired.
74    pub resume_abandoned: bool,
75    /// The backend implements `Vacuum`, so `POST .../vacuum` is wired.
76    pub vacuum: bool,
77    /// The backend implements `Update`, so `PATCH .../tasks/{task_id}` is wired.
78    pub update: bool,
79    /// The backend implements `RegisterWorker`.
80    pub register_worker: bool,
81    /// The backend implements `WaitForCompletion<LiveResult>`, so the per-task completion
82    /// stream is backend-confirmed instead of tracing-derived.
83    pub live_status: bool,
84}
85
86/// One [`Capabilities`] entry per queue name, as served by `GET /capabilities`.
87pub type CapabilityMap = BTreeMap<String, Capabilities>;
88
89/// How a retry action was carried out.
90///
91/// A backend without `Reschedule` still accepts a retry request: it re-pushes a new task with
92/// the same arguments instead. `mode` tells the caller which one happened, so a client never
93/// labels a re-push as a true reschedule.
94#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
95#[serde(rename_all = "snake_case")]
96pub enum RetryMode {
97    /// The backend implements `Reschedule`: the existing task was rescheduled in place.
98    Reschedule,
99    /// The backend lacks `Reschedule`: a new task carrying the same arguments was pushed.
100    NewTask,
101}
102
103/// The result of a single action route.
104///
105/// Serialized with an internal `outcome` tag naming the variant in `snake_case`, each variant's
106/// own fields flattened next to it. For example a successful retry serializes as:
107///
108/// ```json
109/// {"outcome": "retry", "task_id": "01K7...", "mode": "reschedule"}
110/// ```
111///
112/// # Examples
113///
114/// ```
115/// use apalis_rtui_types::{ActionOutcome, RetryMode};
116///
117/// let outcome = ActionOutcome::Retry {
118///     task_id: "01K7EXAMPLE".to_owned(),
119///     mode: RetryMode::NewTask,
120/// };
121/// let json = serde_json::to_string(&outcome).unwrap();
122/// assert_eq!(
123///     json,
124///     r#"{"outcome":"retry","task_id":"01K7EXAMPLE","mode":"new_task"}"#
125/// );
126/// ```
127#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
128#[serde(tag = "outcome", rename_all = "snake_case")]
129pub enum ActionOutcome {
130    /// A retry was carried out, either as a true reschedule or as a fresh push. See
131    /// [`RetryMode`].
132    Retry {
133        /// The id of the task the retry acted on.
134        task_id: String,
135        /// Which mechanism the retry used.
136        mode: RetryMode,
137    },
138    /// A task was rescheduled to run again after a delay.
139    Rescheduled {
140        /// The id of the rescheduled task.
141        task_id: String,
142    },
143    /// A task was resumed by id.
144    Resumed {
145        /// The id of the resumed task.
146        task_id: String,
147    },
148    /// Abandoned tasks for a queue were resumed in bulk.
149    ResumedAbandoned {
150        /// How many tasks were resumed, when the backend reports a count.
151        count: Option<u64>,
152    },
153    /// Stale or orphaned rows were vacuumed from a queue.
154    Vacuumed {
155        /// How many rows were vacuumed, when the backend reports a count.
156        count: Option<u64>,
157    },
158    /// A task's priority and/or metadata was updated.
159    Updated {
160        /// The id of the updated task.
161        task_id: String,
162    },
163}
164
165/// Which action a bulk request applies to every listed task id.
166#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
167#[serde(rename_all = "snake_case")]
168pub enum BulkAction {
169    /// Retry every listed task, see [`ActionOutcome::Retry`].
170    Retry,
171    /// Reschedule every listed task, see [`ActionOutcome::Rescheduled`].
172    Reschedule,
173    /// Resume every listed task by id, see [`ActionOutcome::Resumed`].
174    Resume,
175    /// Update every listed task, see [`ActionOutcome::Updated`].
176    Update,
177}
178
179/// The body of `POST /queues/{queue}/tasks/bulk`.
180///
181/// # Examples
182///
183/// ```
184/// use apalis_rtui_types::{BulkAction, BulkRequest};
185///
186/// let request = BulkRequest {
187///     task_ids: vec!["a".to_owned(), "b".to_owned()],
188///     action: BulkAction::Retry,
189///     wait_secs: None,
190/// };
191/// let json = serde_json::to_string(&request).unwrap();
192/// let back: BulkRequest = serde_json::from_str(&json).unwrap();
193/// assert_eq!(back, request);
194/// ```
195#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
196pub struct BulkRequest {
197    /// The task ids the action applies to.
198    pub task_ids: Vec<String>,
199    /// Which action to apply to every id.
200    pub action: BulkAction,
201    /// The reschedule delay, when `action` is [`BulkAction::Reschedule`]. Ignored otherwise.
202    pub wait_secs: Option<u64>,
203}
204
205/// One failed entry in a [`BulkOutcome`].
206#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
207pub struct BulkFailure {
208    /// The task id the action failed for.
209    pub id: String,
210    /// The error message the backend returned for this id.
211    pub error: String,
212}
213
214/// The result of a bulk action: every id sequentially attempted, split by outcome.
215///
216/// A bulk request is not atomic. Partial failure is an expected, steady-state result, not an
217/// error condition for the whole request.
218///
219/// # Examples
220///
221/// ```
222/// use apalis_rtui_types::{BulkFailure, BulkOutcome};
223///
224/// let outcome = BulkOutcome {
225///     succeeded: vec!["a".to_owned()],
226///     failed: vec![BulkFailure {
227///         id: "b".to_owned(),
228///         error: "not found".to_owned(),
229///     }],
230/// };
231/// let json = serde_json::to_string(&outcome).unwrap();
232/// let back: BulkOutcome = serde_json::from_str(&json).unwrap();
233/// assert_eq!(back, outcome);
234/// ```
235#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
236pub struct BulkOutcome {
237    /// Task ids the action succeeded for.
238    pub succeeded: Vec<String>,
239    /// Task ids the action failed for, each with its error message.
240    pub failed: Vec<BulkFailure>,
241}
242
243/// A `task-status` event on the `/events/status` SSE stream.
244///
245/// A brand-new, `apalis-rtui`-owned event shape with no wire-compatibility obligation to
246/// upstream. Unlike [`Span`], which carries no queue name, `queue` is included here so a
247/// server-side `?queue=` filter is possible instead of a client-side one.
248///
249/// # Examples
250///
251/// ```
252/// use apalis_rtui_types::TaskStatusEvent;
253///
254/// let event = TaskStatusEvent {
255///     task_id: "01K7EXAMPLE".to_owned(),
256///     queue: "Emails".to_owned(),
257///     status: "Failed".to_owned(),
258///     attempt: 3,
259///     done_in_ms: Some(3200),
260///     result: Some("timed out".to_owned()),
261/// };
262/// let json = serde_json::to_string(&event).unwrap();
263/// let back: TaskStatusEvent = serde_json::from_str(&json).unwrap();
264/// assert_eq!(back, event);
265/// ```
266#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
267pub struct TaskStatusEvent {
268    /// The id of the task the event is about.
269    pub task_id: String,
270    /// The queue the task runs on.
271    pub queue: String,
272    /// The task's status after this event (for example `"Failed"`, `"Done"`, `"Running"`).
273    pub status: String,
274    /// The attempt number this event reflects.
275    pub attempt: u32,
276    /// How long the attempt took to finish, in milliseconds, once it finishes.
277    pub done_in_ms: Option<u64>,
278    /// The task's result payload, once it finishes.
279    pub result: Option<String>,
280}
281
282/// One minute-bucket of `task.start`/`task.done`/`task.failed` counts, as served by
283/// `GET /events/activity` (`docs/PLAN.md` ยง6.2).
284///
285/// A tracing span carries no wall-clock precision beyond the log line's own timestamp, and the
286/// activity series only ever needs minute granularity, so `minute_epoch` is Unix epoch seconds
287/// truncated to the minute rather than an RFC3339 string: cheaper to compute on the server, and a
288/// client renders it however it likes.
289///
290/// # Examples
291///
292/// ```
293/// use apalis_rtui_types::ActivityBucket;
294///
295/// let bucket = ActivityBucket {
296///     minute_epoch: 1_700_000_040,
297///     start: 3,
298///     done: 2,
299///     failed: 1,
300/// };
301/// let json = serde_json::to_string(&bucket).unwrap();
302/// let back: ActivityBucket = serde_json::from_str(&json).unwrap();
303/// assert_eq!(back, bucket);
304/// ```
305#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
306pub struct ActivityBucket {
307    /// Unix epoch seconds, truncated to the minute this bucket covers.
308    pub minute_epoch: i64,
309    /// `task.start` events observed in this minute.
310    pub start: u64,
311    /// `task.done` events observed in this minute.
312    pub done: u64,
313    /// `task.failed` events observed in this minute.
314    pub failed: u64,
315}
316
317/// The body of `PATCH /queues/{queue}/tasks/{task_id}/reschedule`.
318#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
319pub struct RescheduleRequest {
320    /// How many seconds from now to reschedule the task for.
321    pub wait_secs: u64,
322}
323
324/// The body of `PATCH /queues/{queue}/tasks/{task_id}`.
325///
326/// # Examples
327///
328/// ```
329/// use apalis_rtui_types::UpdateRequest;
330///
331/// let request = UpdateRequest {
332///     priority: Some(5),
333///     meta: None,
334/// };
335/// let json = serde_json::to_string(&request).unwrap();
336/// let back: UpdateRequest = serde_json::from_str(&json).unwrap();
337/// assert_eq!(back, request);
338/// ```
339#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
340pub struct UpdateRequest {
341    /// The task's new priority, when changed.
342    pub priority: Option<i32>,
343    /// The task's new metadata, when changed.
344    pub meta: Option<serde_json::Value>,
345}
346
347#[cfg(test)]
348mod tests {
349    use super::*;
350
351    #[test]
352    fn capabilities_round_trip() {
353        let caps = Capabilities {
354            reschedule: true,
355            resume_by_id: false,
356            resume_abandoned: true,
357            vacuum: false,
358            update: true,
359            register_worker: false,
360            live_status: true,
361        };
362        let json = serde_json::to_string(&caps).expect("Capabilities serializes");
363        let back: Capabilities = serde_json::from_str(&json).expect("Capabilities deserializes");
364        assert_eq!(back, caps);
365    }
366
367    #[test]
368    fn capability_map_round_trip() {
369        let mut map = CapabilityMap::new();
370        map.insert("Emails".to_owned(), Capabilities::default());
371        let json = serde_json::to_string(&map).expect("CapabilityMap serializes");
372        let back: CapabilityMap = serde_json::from_str(&json).expect("CapabilityMap deserializes");
373        assert_eq!(back, map);
374    }
375
376    #[test]
377    fn retry_mode_serializes_snake_case() {
378        assert_eq!(
379            serde_json::to_string(&RetryMode::Reschedule).expect("serializes"),
380            "\"reschedule\""
381        );
382        assert_eq!(
383            serde_json::to_string(&RetryMode::NewTask).expect("serializes"),
384            "\"new_task\""
385        );
386        let back: RetryMode = serde_json::from_str("\"new_task\"").expect("deserializes");
387        assert_eq!(back, RetryMode::NewTask);
388    }
389
390    #[test]
391    fn action_outcome_round_trip_every_variant() {
392        let variants = [
393            ActionOutcome::Retry {
394                task_id: "t1".to_owned(),
395                mode: RetryMode::Reschedule,
396            },
397            ActionOutcome::Rescheduled {
398                task_id: "t2".to_owned(),
399            },
400            ActionOutcome::Resumed {
401                task_id: "t3".to_owned(),
402            },
403            ActionOutcome::ResumedAbandoned { count: Some(4) },
404            ActionOutcome::Vacuumed { count: None },
405            ActionOutcome::Updated {
406                task_id: "t4".to_owned(),
407            },
408        ];
409        for outcome in variants {
410            let json = serde_json::to_string(&outcome).expect("ActionOutcome serializes");
411            let back: ActionOutcome =
412                serde_json::from_str(&json).expect("ActionOutcome deserializes");
413            assert_eq!(back, outcome);
414        }
415    }
416
417    #[test]
418    fn action_outcome_tag_shape() {
419        let outcome = ActionOutcome::Vacuumed { count: Some(7) };
420        let json = serde_json::to_string(&outcome).expect("serializes");
421        assert_eq!(json, r#"{"outcome":"vacuumed","count":7}"#);
422    }
423
424    #[test]
425    fn bulk_action_round_trip() {
426        for action in [
427            BulkAction::Retry,
428            BulkAction::Reschedule,
429            BulkAction::Resume,
430            BulkAction::Update,
431        ] {
432            let json = serde_json::to_string(&action).expect("BulkAction serializes");
433            let back: BulkAction = serde_json::from_str(&json).expect("BulkAction deserializes");
434            assert_eq!(back, action);
435        }
436    }
437
438    #[test]
439    fn bulk_request_round_trip() {
440        let request = BulkRequest {
441            task_ids: vec!["a".to_owned(), "b".to_owned()],
442            action: BulkAction::Reschedule,
443            wait_secs: Some(30),
444        };
445        let json = serde_json::to_string(&request).expect("BulkRequest serializes");
446        let back: BulkRequest = serde_json::from_str(&json).expect("BulkRequest deserializes");
447        assert_eq!(back, request);
448    }
449
450    #[test]
451    fn bulk_outcome_round_trip() {
452        let outcome = BulkOutcome {
453            succeeded: vec!["a".to_owned()],
454            failed: vec![BulkFailure {
455                id: "b".to_owned(),
456                error: "not found".to_owned(),
457            }],
458        };
459        let json = serde_json::to_string(&outcome).expect("BulkOutcome serializes");
460        let back: BulkOutcome = serde_json::from_str(&json).expect("BulkOutcome deserializes");
461        assert_eq!(back, outcome);
462    }
463
464    #[test]
465    fn task_status_event_round_trip() {
466        let event = TaskStatusEvent {
467            task_id: "01K7".to_owned(),
468            queue: "Emails".to_owned(),
469            status: "Failed".to_owned(),
470            attempt: 3,
471            done_in_ms: Some(3200),
472            result: Some("timed out".to_owned()),
473        };
474        let json = serde_json::to_string(&event).expect("TaskStatusEvent serializes");
475        let back: TaskStatusEvent =
476            serde_json::from_str(&json).expect("TaskStatusEvent deserializes");
477        assert_eq!(back, event);
478    }
479
480    #[test]
481    fn activity_bucket_round_trip() {
482        let bucket = ActivityBucket {
483            minute_epoch: 1_700_000_040,
484            start: 3,
485            done: 2,
486            failed: 1,
487        };
488        let json = serde_json::to_string(&bucket).expect("ActivityBucket serializes");
489        let back: ActivityBucket =
490            serde_json::from_str(&json).expect("ActivityBucket deserializes");
491        assert_eq!(back, bucket);
492    }
493
494    #[test]
495    fn reschedule_request_round_trip() {
496        let request = RescheduleRequest { wait_secs: 30 };
497        let json = serde_json::to_string(&request).expect("RescheduleRequest serializes");
498        let back: RescheduleRequest =
499            serde_json::from_str(&json).expect("RescheduleRequest deserializes");
500        assert_eq!(back, request);
501    }
502
503    #[test]
504    fn update_request_round_trip() {
505        let request = UpdateRequest {
506            priority: Some(5),
507            meta: Some(serde_json::json!({"note": "hi"})),
508        };
509        let json = serde_json::to_string(&request).expect("UpdateRequest serializes");
510        let back: UpdateRequest = serde_json::from_str(&json).expect("UpdateRequest deserializes");
511        assert_eq!(back, request);
512    }
513
514    #[test]
515    fn reexports_are_the_same_type_as_apalis_board_types() {
516        let entry: LogEntry = LogEntry::default();
517        let upstream: apalis_board_types::LogEntry = entry;
518        let _ = upstream;
519    }
520}