Skip to main content

rustango_cms/
editing_session.rs

1//! Concurrent-editor tracking.
2//!
3//! Pairs with the editor lock: the lock prevents conflicting
4//! writes; the editing-session model surfaces a banner so people
5//! *see* each other before they collide. Every time the editor JS
6//! pings the lock heartbeat (`POST /cms-admin/pages/{id}/lock-heartbeat`),
7//! we also touch a row in `cms_editing_session` so a separate JSON
8//! endpoint can list the other active viewers/editors.
9//!
10//! ## Liveness
11//!
12//! A session is "active" when `last_seen_at` is within the last
13//! [`ACTIVE_WINDOW_SECS`] seconds. Older rows are garbage-collected
14//! lazily on heartbeat. The GC threshold is 1 hour — long enough to survive transient network blips, short
15//! enough that a closed-tab session falls off in reasonable time.
16//!
17//! ## "Viewing" vs "Editing"
18//!
19//! The `is_editing` boolean is a hint, not a hard guarantee. The
20//! editor JS sets it `true` once the form is touched (any `input`
21//! event) and resets it on every page load. Useful UX signal —
22//! "alice is editing" reads more urgent than "alice is viewing".
23
24use chrono::{DateTime, Utc};
25use rustango::sql::Auto;
26use rustango::Model;
27use serde::{Deserialize, Serialize};
28
29/// How long a session row counts as "active". Stale rows past this
30/// window are filtered out of the JSON response and reaped on the
31/// next heartbeat.
32pub const ACTIVE_WINDOW_SECS: i64 = 90;
33
34/// Rows older than this are garbage-collected on heartbeat — long
35/// past the active window so transient outages don't lose sessions
36/// the editor would otherwise rejoin.
37pub const GC_THRESHOLD_SECS: i64 = 60 * 60;
38
39#[derive(Model, Debug, Clone, Serialize, Deserialize)]
40#[rustango(
41    table = "cms_editing_session",
42    app = "cms",
43    display = "user_id",
44    admin(
45        list_display = "page_id, user_id, is_editing, last_seen_at",
46        ordering = "-last_seen_at",
47        list_filter = "page_id, is_editing",
48    )
49)]
50pub struct EditingSession {
51    #[rustango(primary_key)]
52    pub id: Auto<i64>,
53
54    #[rustango(fk = "cms_page", on = "id", index)]
55    pub page_id: i64,
56
57    #[rustango(fk = "rustango_users", on = "id", index)]
58    pub user_id: i64,
59
60    /// Bumped by each heartbeat. The active-vs-stale gate compares
61    /// this against `now() - ACTIVE_WINDOW_SECS`.
62    pub last_seen_at: DateTime<Utc>,
63
64    /// `true` once the editor JS has detected a form touch on this
65    /// page. Set by the heartbeat ping body (`?is_editing=1`) and
66    /// reset to `false` on a fresh page load.
67    pub is_editing: bool,
68}
69
70/// UPSERT the heartbeat row for `(page_id, user_id)` and bump
71/// `last_seen_at` to now. Application-enforced uniqueness — we
72/// don't have a SQL UNIQUE constraint because not every dialect
73/// agrees on composite uniqueness syntax. The race window is small
74/// enough that the worst-case duplicate row is fine; the GC drops
75/// them.
76///
77/// # Errors
78/// Driver / query failures.
79pub async fn touch(
80    pool: &rustango::sql::Pool,
81    page_id: i64,
82    user_id: i64,
83    is_editing: bool,
84) -> Result<(), rustango::sql::ExecError> {
85    use rustango::core::Column as _;
86    use rustango::sql::FetcherPool as _;
87
88    let existing: Vec<EditingSession> = EditingSession::objects()
89        .where_(EditingSession::page_id.eq(page_id))
90        .where_(EditingSession::user_id.eq(user_id))
91        .fetch(pool)
92        .await?;
93
94    if let Some(mut row) = existing.into_iter().next() {
95        row.last_seen_at = Utc::now();
96        // `is_editing` is sticky-true within a session: once any
97        // ping reports editing, the row stays editing until a fresh
98        // page-load resets it. Reduces UI flicker between viewing
99        // and editing banners.
100        if is_editing {
101            row.is_editing = true;
102        }
103        row.save_pool(pool).await?;
104    } else {
105        let mut row = EditingSession {
106            id: Auto::Unset,
107            page_id,
108            user_id,
109            last_seen_at: Utc::now(),
110            is_editing,
111        };
112        row.insert_pool(pool).await?;
113    }
114    Ok(())
115}
116
117/// Other active sessions on this page (viewer's own session filtered
118/// out). Returns `(user_id, last_seen_at, is_editing)` tuples sorted
119/// by `last_seen_at` desc.
120///
121/// # Errors
122/// Driver / query failures.
123pub async fn others_on_page(
124    pool: &rustango::sql::Pool,
125    page_id: i64,
126    viewer_id: i64,
127) -> Result<Vec<EditingSession>, rustango::sql::ExecError> {
128    use rustango::core::Column as _;
129    use rustango::sql::FetcherPool as _;
130    let cutoff = Utc::now() - chrono::Duration::seconds(ACTIVE_WINDOW_SECS);
131    let rows: Vec<EditingSession> = EditingSession::objects()
132        .where_(EditingSession::page_id.eq(page_id))
133        .where_(EditingSession::user_id.ne(viewer_id))
134        .order_by(&[("last_seen_at", true)]) // desc
135        .fetch(pool)
136        .await?;
137    Ok(rows
138        .into_iter()
139        .filter(|r| r.last_seen_at >= cutoff)
140        .collect())
141}
142
143/// Garbage-collect rows older than [`GC_THRESHOLD_SECS`]. Called
144/// from the heartbeat handler so the table doesn't grow unbounded
145/// — we don't need a cron.
146///
147/// # Errors
148/// Driver / query failures.
149pub async fn gc_stale(pool: &rustango::sql::Pool) -> Result<usize, rustango::sql::ExecError> {
150    use rustango::core::Column as _;
151    use rustango::sql::FetcherPool as _;
152    let cutoff = Utc::now() - chrono::Duration::seconds(GC_THRESHOLD_SECS);
153    let stale: Vec<EditingSession> = EditingSession::objects()
154        .where_(EditingSession::last_seen_at.lt(cutoff))
155        .fetch(pool)
156        .await?;
157    let count = stale.len();
158    for row in stale {
159        row.delete_pool(pool).await?;
160    }
161    Ok(count)
162}