Skip to main content

navree_queue/
ui.rs

1//! A Navree UI part for an operation (the `ui` feature): [`OperationProgress`], a region that
2//! follows a queued operation and ends as a link to its result.
3//!
4//! An export or an import page starts an operation, then has nothing to show but "working".
5//! The region polls the operation's page fragment (and, with the live hub, hears it change),
6//! draws a progress bar and the operation's note, and when the operation finishes stops polling
7//! and shows the result: a link when the result holds a `url`, the error when it failed.
8//!
9//! ```ignore
10//! let op = operations.start(&uow, Operation::new("deals.export").owner(user)).await?;
11//! operations.dispatch(&uow, &op, ExportDeals { operation: op.id }).await?;
12//! // On the page:
13//! OperationProgress::new(op.id).live()
14//! // In the job, when it is done:
15//! operations.complete(op.id, json!({ "url": "/exports/deals.csv" })).await?;
16//! ```
17//!
18//! `QueueModule` mounts the fragment at `GET /operations/{id}/progress` (the same sign-in and
19//! visibility rules as the JSON route: the owner and holders of `operations.view`, a 404 for
20//! everyone else) when the app has `DatabaseModule` and an authenticator. It draws the
21//! English words; to draw other words, mount a route of your own that answers with
22//! `OperationProgress::new(id).labels(words).record(record)`.
23
24use std::sync::Arc;
25use std::time::Duration;
26
27use http::Method;
28use navree_contracts::BoxFuture;
29use navree_http::{ApiMeta, AppError, Authenticator, Controller, CurrentPrincipal, Path, RouteDef};
30use navree_kernel::{Injectable, KernelError, ProviderKey, Resolver};
31use navree_ui::html::{Href, LocalHref};
32use navree_ui::{Alert, AlertTone, Button, LiveStream, Node, Progress, Region, View, el};
33use serde_json::Value;
34use uuid::Uuid;
35
36use crate::operations::{OperationRecord, OperationStatus, operation_topic, visible};
37use crate::{Operations, QueueOptions};
38
39/// Where `QueueModule` serves the fragment of an operation, with the id in place of `{id}`.
40pub const PROGRESS_PATH: &str = "/operations/{id}/progress";
41
42/// How often the region asks again while it has no live stream to hear.
43const POLL: Duration = Duration::from_secs(2);
44
45/// The words of an [`OperationProgress`]. English by default. `{done}` and `{total}` are
46/// filled in.
47#[derive(Clone, Debug, PartialEq, Eq)]
48pub struct OperationLabels {
49    /// An operation that has not begun.
50    pub waiting: String,
51    /// An operation at work, when it has no note of its own.
52    pub working: String,
53    /// How far an operation got: `{done} of {total}`.
54    pub of: String,
55    /// An operation that succeeded.
56    pub done: String,
57    /// The link to the result of an operation that succeeded.
58    pub download: String,
59    /// An operation that failed, when it has no message.
60    pub failed: String,
61    /// An operation that was cancelled.
62    pub cancelled: String,
63}
64
65impl Default for OperationLabels {
66    fn default() -> Self {
67        Self {
68            waiting: "Waiting to start".to_owned(),
69            working: "Working".to_owned(),
70            of: "{done} of {total}".to_owned(),
71            done: "Done".to_owned(),
72            download: "Download".to_owned(),
73            failed: "This did not finish".to_owned(),
74            cancelled: "Cancelled".to_owned(),
75        }
76    }
77}
78
79/// A region that follows an operation. See the [module](self) for how a page uses it.
80///
81/// ```
82/// use navree_queue::ui::OperationProgress;
83/// use navree_ui::render;
84/// use uuid::Uuid;
85///
86/// let id = Uuid::now_v7();
87/// let html = render(&OperationProgress::new(id).into());
88/// assert!(html.contains(&format!(r#"data-ui-src="/operations/{id}/progress""#)));
89/// assert!(html.contains("data-ui-poll"));
90/// assert!(html.contains("Waiting to start"));
91/// ```
92#[derive(Clone, Debug)]
93#[must_use]
94pub struct OperationProgress {
95    id: Uuid,
96    src: Href,
97    poll: Duration,
98    stream: Option<LiveStream>,
99    labels: OperationLabels,
100    result_key: String,
101    record: Option<OperationRecord>,
102}
103
104impl OperationProgress {
105    /// The progress of operation `id`, fetched from the fragment `QueueModule` serves.
106    pub fn new(id: Uuid) -> Self {
107        Self {
108            id,
109            src: Href::from(PROGRESS_PATH.replace("{id}", &id.to_string())),
110            poll: POLL,
111            stream: None,
112            labels: OperationLabels::default(),
113            result_key: "url".to_owned(),
114            record: None,
115        }
116    }
117
118    /// Fetches the fragment from `src` instead (a route of your own).
119    pub fn src(mut self, src: impl Into<Href>) -> Self {
120        self.src = src.into();
121        self
122    }
123
124    /// Asks again this often while the operation is unfinished (2 seconds by default).
125    pub fn poll(mut self, every: Duration) -> Self {
126        self.poll = every;
127        self
128    }
129
130    /// Also hears the operation change on the app's live hub, so the region fetches as
131    /// soon as something happened rather than at the next poll. It needs `RealtimeModule`;
132    /// without it the region only polls.
133    pub fn live(self) -> Self {
134        let topic = operation_topic(self.id);
135        self.live_on(LiveStream::topics([topic]))
136    }
137
138    /// [`live`](Self::live) on a stream of your own, which must carry the topic
139    /// [`operation_topic`].
140    pub fn live_on(mut self, stream: LiveStream) -> Self {
141        self.stream = Some(stream);
142        self
143    }
144
145    /// Sets the words.
146    pub fn labels(mut self, labels: OperationLabels) -> Self {
147        self.labels = labels;
148        self
149    }
150
151    /// Reads the link to the result from this key of the operation's `result` (`url` by
152    /// default). Only an address on this site becomes a link.
153    pub fn result_key(mut self, key: impl Into<String>) -> Self {
154        self.result_key = key.into();
155        self
156    }
157
158    /// Draws the operation as it is now, the way the fragment answers.
159    pub fn record(mut self, record: OperationRecord) -> Self {
160        self.record = Some(record);
161        self
162    }
163
164    fn status(&self) -> OperationStatus {
165        self.record
166            .as_ref()
167            .map_or(OperationStatus::Pending, |record| record.status)
168    }
169
170    fn body(&self) -> Node {
171        let words = &self.labels;
172        let status = self.status();
173        let state = el("div")
174            .slot("operation-progress")
175            .attr("data-state", status.as_str())
176            .attr("role", "status");
177        let Some(record) = &self.record else {
178            return state
179                .children((
180                    Progress::indeterminate(words.waiting.clone()),
181                    el("p").child(words.waiting.clone()),
182                ))
183                .into();
184        };
185        match status {
186            OperationStatus::Pending => state
187                .children((
188                    Progress::indeterminate(words.waiting.clone()),
189                    el("p").child(words.waiting.clone()),
190                ))
191                .into(),
192            OperationStatus::Running => {
193                let progress = &record.progress;
194                let label = if record.progress.note.is_empty() {
195                    words.working.clone()
196                } else {
197                    record.progress.note.clone()
198                };
199                let bar = if progress.total == 0 {
200                    Progress::indeterminate(label.clone())
201                } else {
202                    Progress::new(u32::from(progress.percent), 100, label.clone())
203                };
204                let count = (progress.total > 0).then(|| {
205                    el("p").slot("operation-count").child(
206                        words
207                            .of
208                            .replace("{done}", &progress.done.to_string())
209                            .replace("{total}", &progress.total.to_string()),
210                    )
211                });
212                state.children((bar, el("p").child(label), count)).into()
213            }
214            OperationStatus::Succeeded => {
215                let link = self
216                    .result_link(record)
217                    .map(|href| Button::outline(words.download.clone()).href(href));
218                state
219                    .children((el("p").child(words.done.clone()), link))
220                    .into()
221            }
222            OperationStatus::Failed => {
223                let text = record
224                    .error
225                    .clone()
226                    .filter(|error| !error.is_empty())
227                    .unwrap_or_else(|| words.failed.clone());
228                state
229                    .children(Alert::new(AlertTone::Danger).title(text))
230                    .into()
231            }
232            OperationStatus::Cancelled => state
233                .children(el("p").child(words.cancelled.clone()))
234                .into(),
235        }
236    }
237
238    /// The address on this site the operation's result names, if it names one.
239    fn result_link(&self, record: &OperationRecord) -> Option<Href> {
240        let text = record
241            .result
242            .as_ref()?
243            .get(&self.result_key)
244            .and_then(Value::as_str)?;
245        let local = LocalHref::parse(text).ok()?;
246        Some(Href::from(local.as_str()))
247    }
248}
249
250impl From<OperationProgress> for Node {
251    fn from(progress: OperationProgress) -> Self {
252        let finished = progress
253            .record
254            .as_ref()
255            .is_some_and(OperationRecord::is_finished);
256        let mut region =
257            Region::new(format!("operation-{}", progress.id)).src(progress.src.clone());
258        // A finished operation never changes: nothing left to ask.
259        if !finished {
260            region = region.poll(progress.poll);
261            if let Some(stream) = &progress.stream {
262                region = region.live_on(stream.on(operation_topic(progress.id)));
263            }
264        }
265        region.children(progress.body()).into()
266    }
267}
268
269/// The fragment of an operation: `GET /operations/{id}/progress`, mounted by `QueueModule`.
270pub struct OperationProgressController {
271    operations: Option<Arc<Operations>>,
272}
273
274impl Injectable for OperationProgressController {
275    fn dependencies() -> Vec<ProviderKey> {
276        vec![ProviderKey::of::<QueueOptions>()]
277    }
278
279    fn construct(r: Resolver) -> BoxFuture<'static, Result<Self, KernelError>> {
280        Box::pin(async move {
281            let options = r.get::<QueueOptions>().await?;
282            let app = r.app();
283            let mounted = options.operations.routes
284                && app.try_get::<dyn Authenticator>().await.is_some()
285                && app.try_get::<navree_db::Db>().await.is_some();
286            let operations = if mounted {
287                app.try_get::<Operations>().await
288            } else {
289                None
290            };
291            Ok(Self { operations })
292        })
293    }
294}
295
296impl Controller for OperationProgressController {
297    fn prefix(&self) -> &'static str {
298        ""
299    }
300
301    fn routes(self: Arc<Self>) -> Vec<RouteDef> {
302        let Some(operations) = self.operations.clone() else {
303            return Vec::new();
304        };
305        let show = move |CurrentPrincipal(principal): CurrentPrincipal, Path(id): Path<String>| {
306            let operations = operations.clone();
307            async move {
308                let record = visible(&operations, &principal, &id).await?;
309                let id = record.id;
310                Ok::<_, AppError>(
311                    View::new("Operation").body(OperationProgress::new(id).record(record)),
312                )
313            }
314        };
315        vec![
316            RouteDef::on(Method::GET, format!("!{PROGRESS_PATH}"), show)
317                .authenticated()
318                .name("operations.progress")
319                .api(ApiMeta {
320                    summary: Some("An operation's progress, drawn for a page".to_owned()),
321                    description: Some(
322                        "The `OperationProgress` region as HTML: a page asks for it again while \
323                         the operation runs."
324                            .to_owned(),
325                    ),
326                    tags: vec!["Operations".to_owned()],
327                    responses: vec![401, 404],
328                    ..ApiMeta::default()
329                }),
330        ]
331    }
332}
333
334#[cfg(test)]
335mod tests {
336    use serde_json::json;
337
338    use super::*;
339
340    fn record(
341        status: OperationStatus,
342        done: u64,
343        total: u64,
344        note: &str,
345        result: Option<Value>,
346    ) -> OperationRecord {
347        let percent = (done * 100)
348            .checked_div(total)
349            .map_or(0, |share| u8::try_from(share.min(100)).unwrap_or(100));
350        OperationRecord {
351            id: Uuid::nil(),
352            kind: "export".to_owned(),
353            status,
354            progress: crate::operations::OperationProgress {
355                done,
356                total,
357                percent,
358                note: note.to_owned(),
359            },
360            result,
361            error: (status == OperationStatus::Failed)
362                .then(|| "The file could not be made.".to_owned()),
363            owner_id: None,
364            workspace_id: None,
365            batch_id: None,
366            created_at: chrono::Utc::now(),
367            started_at: None,
368            heartbeat_at: None,
369            finished_at: None,
370            updated_at: chrono::Utc::now(),
371            version: 0,
372            job: None,
373            idempotent: false,
374            redispatches: 0,
375        }
376    }
377
378    fn html(progress: OperationProgress) -> String {
379        navree_ui::render(&progress.into())
380    }
381
382    #[test]
383    fn an_unfinished_operation_polls_and_shows_how_far_it_got() {
384        let at = |done, total| {
385            html(OperationProgress::new(Uuid::nil()).record(record(
386                OperationStatus::Running,
387                done,
388                total,
389                "Writing rows",
390                None,
391            )))
392        };
393        let page = at(40, 100);
394        assert!(page.contains("data-ui-poll"), "{page}");
395        assert!(page.contains(r#"data-state="running""#), "{page}");
396        assert!(page.contains("Writing rows"), "{page}");
397        assert!(page.contains("40 of 100"), "{page}");
398        assert!(page.contains(r#"value="40""#), "{page}");
399    }
400
401    #[test]
402    fn a_finished_operation_stops_polling_and_links_to_its_result() {
403        let done = html(OperationProgress::new(Uuid::nil()).record(record(
404            OperationStatus::Succeeded,
405            100,
406            100,
407            "",
408            Some(json!({ "url": "/exports/deals.csv" })),
409        )));
410        assert!(!done.contains("data-ui-poll"), "{done}");
411        assert!(done.contains(r#"href="/exports/deals.csv""#), "{done}");
412        assert!(done.contains("Done"), "{done}");
413
414        // An address off this site is not a link.
415        let off = html(OperationProgress::new(Uuid::nil()).record(record(
416            OperationStatus::Succeeded,
417            1,
418            1,
419            "",
420            Some(json!({ "url": "https://evil.example/x" })),
421        )));
422        assert!(!off.contains("evil.example"), "{off}");
423        let script = html(OperationProgress::new(Uuid::nil()).record(record(
424            OperationStatus::Succeeded,
425            1,
426            1,
427            "",
428            Some(json!({ "url": "javascript:alert(1)" })),
429        )));
430        assert!(!script.contains("javascript"), "{script}");
431    }
432
433    #[test]
434    fn a_failed_operation_says_why_and_a_cancelled_one_says_so() {
435        let failed = html(OperationProgress::new(Uuid::nil()).record(record(
436            OperationStatus::Failed,
437            3,
438            10,
439            "",
440            None,
441        )));
442        assert!(failed.contains("The file could not be made."), "{failed}");
443        assert!(!failed.contains("data-ui-poll"), "{failed}");
444        let cancelled = html(OperationProgress::new(Uuid::nil()).record(record(
445            OperationStatus::Cancelled,
446            3,
447            10,
448            "",
449            None,
450        )));
451        assert!(cancelled.contains("Cancelled"), "{cancelled}");
452    }
453
454    #[test]
455    fn the_live_hub_is_heard_for_the_operation_until_it_finishes() {
456        let id = Uuid::now_v7();
457        let page = html(OperationProgress::new(id).live());
458        assert!(page.contains("data-ui-live-src"), "{page}");
459        assert!(page.contains(&operation_topic(id)), "{page}");
460        let done = html(OperationProgress::new(id).live().record(record(
461            OperationStatus::Succeeded,
462            1,
463            1,
464            "",
465            None,
466        )));
467        assert!(!done.contains("data-ui-live-src"), "{done}");
468    }
469
470    #[test]
471    fn the_words_are_the_pages_own() {
472        let words = OperationLabels {
473            waiting: "शुरू होने की प्रतीक्षा".to_owned(),
474            ..OperationLabels::default()
475        };
476        let page = html(OperationProgress::new(Uuid::nil()).labels(words));
477        assert!(page.contains("शुरू होने की प्रतीक्षा"), "{page}");
478    }
479}