Skip to main content

tablo_core/
flash.rs

1//! The toast a write flashes for the next request: one [`Notification`] in a JSON cookie with
2//! hardened attributes, which Topcoat flushes on error responses too (topcoat#408).
3
4use topcoat::{
5    context::{Cx, try_context},
6    cookie::{CookieJar, CookieJarCell, Cookies, cookie_store, cookies},
7};
8
9use crate::outcome::Notification;
10
11pub(crate) const COOKIE_NAME: &str = "__Host-tablo_notification";
12
13/// Applies the hardened cookie attributes the flash cookie relies on to writes
14/// and removals alike.
15fn hardened(jar: &CookieJar) -> impl Cookies + '_ {
16    jar.default_path("/")
17        .default_http_only(true)
18        .default_secure(true)
19        .default_same_site(topcoat::cookie::SameSite::Lax)
20}
21
22/// Store a notification for the next request (flash).
23pub fn set_notification(cx: &Cx, notification: Notification) {
24    if try_context::<CookieJarCell>(cx).is_none() {
25        return;
26    }
27    if let Err(error) = cookie_store::<Notification, _>(hardened(cookies(cx)), COOKIE_NAME)
28        .set(notification)
29        .commit()
30    {
31        tracing::error!(error = %error, "flash notification commit failed");
32    }
33}
34
35/// Flashes the failure of a write that passed validation but did not land, titled by the message
36/// `failure`, which names the operation, never the driver's text; the toast appears on the next
37/// panel page.
38pub(crate) fn notify_write_failure(cx: &Cx, failure: &'static str) {
39    set_notification(
40        cx,
41        Notification::error(crate::t!(cx, failure))
42            .description(crate::t!(cx, "tablo-failed-description")),
43    );
44}
45
46/// Take the notification from the request (if present) and clear it.
47pub fn take_notification(cx: &Cx) -> Option<Notification> {
48    try_context::<CookieJarCell>(cx)?;
49    let unparsed = cookie_store::<Notification, _>(hardened(cookies(cx)), COOKIE_NAME);
50    match unparsed.parse() {
51        Ok(Some(store)) => {
52            let notification = store.get();
53            store.remove();
54            Some(notification)
55        }
56        // Unreadable value: expire it with no toast.
57        Err(_) => {
58            cookie_store::<Notification, _>(hardened(cookies(cx)), COOKIE_NAME).remove();
59            None
60        }
61        Ok(None) => None,
62    }
63}
64
65#[cfg(test)]
66mod tests;