rustango_cms/lock.rs
1//! `PageLock` — best-effort editor lock on a `cms_page` row.
2//!
3//! Two editors opening the same page in a page-tree CMS expect a
4//! "Page X is being edited by Y" banner instead of a silent
5//! last-write-wins clobber. This module is the foundational lock
6//! primitive; multi-step workflows, inline comments, and
7//! editing-session tracking (B11) all sit on top of it.
8//!
9//! ## Semantics
10//!
11//! - One lock row per page (UNIQUE on `page_id`).
12//! - Lock is *advisory*: acquired on edit-form open, refreshed by the
13//! editor's heartbeat ping, released on a successful POST. A stale
14//! lock (no heartbeat past `expires_at`) is treated as released —
15//! the next editor reuses the row in place.
16//! - Force-unlock is allowed for anyone with the page's Edit
17//! permission; it deletes the row and is audit-logged.
18//!
19//! Why best-effort + TTL instead of a hard SQL lock: editors close
20//! browser tabs all the time; we can't tell the difference between
21//! "closed the tab" and "still editing." A 30-minute sliding TTL gives
22//! the owner room to be away from keyboard without permanently jamming
23//! the page for everyone else.
24//!
25//! ## Lock kinds
26//!
27//! This is the basic editor lock. Workflow-driven locks
28//! (`WorkflowLock`, `ScheduledForPublishLock`) ship with workflows.
29//!
30//! See `src/admin/handlers.rs::page_edit_form` for the acquire site
31//! and `src/admin/handlers.rs::page_edit_submit` for the release site.
32
33use chrono::{DateTime, Duration, Utc};
34use rustango::sql::Auto;
35use rustango::Model;
36use serde::{Deserialize, Serialize};
37
38/// How long a lock survives without a heartbeat refresh. Tune via
39/// `RUSTANGO_CMS_LOCK_TTL_SECS` if shorter sessions are needed.
40pub const DEFAULT_TTL_SECS: i64 = 30 * 60;
41
42/// Heartbeat cadence the editor JS uses to refresh the lock. Set
43/// well under `DEFAULT_TTL_SECS / 2` so a missed ping doesn't drop
44/// the lock mid-session.
45pub const HEARTBEAT_INTERVAL_SECS: i64 = 60;
46
47#[derive(Model, Debug, Clone, Serialize, Deserialize)]
48#[rustango(
49 table = "cms_page_lock",
50 app = "cms",
51 display = "page_id",
52 admin(
53 list_display = "page_id, user_id, acquired_at, expires_at",
54 ordering = "-acquired_at",
55 list_filter = "user_id",
56 )
57)]
58pub struct PageLock {
59 #[rustango(primary_key)]
60 pub id: Auto<i64>,
61
62 /// FK to `cms_page.id`. Application-enforced UNIQUE: only one
63 /// live lock row per page (we delete + insert on takeover rather
64 /// than rely on an SQL constraint to avoid CI gymnastics on
65 /// sqlite/MySQL/PG schema drift).
66 #[rustango(fk = "cms_page", on = "id", index)]
67 pub page_id: i64,
68
69 /// FK to `rustango_users.id` — the editor holding the lock.
70 #[rustango(fk = "rustango_users", on = "id", index)]
71 pub user_id: i64,
72
73 /// When the lock was first acquired (not refreshed). Surfaces in
74 /// the banner as "User X started editing 5 minutes ago."
75 #[rustango(auto_now_add)]
76 pub acquired_at: Auto<DateTime<Utc>>,
77
78 /// Sliding TTL — bumped by every heartbeat ping. After this
79 /// instant the lock is treated as released.
80 pub expires_at: DateTime<Utc>,
81}
82
83impl PageLock {
84 /// True when this lock has aged past its TTL and should be
85 /// treated as released by callers.
86 #[must_use]
87 pub fn is_stale(&self, now: DateTime<Utc>) -> bool {
88 self.expires_at <= now
89 }
90
91 /// True when `user_id` owns this lock (and it isn't stale).
92 #[must_use]
93 pub fn is_owned_by(&self, user_id: i64, now: DateTime<Utc>) -> bool {
94 !self.is_stale(now) && self.user_id == user_id
95 }
96}
97
98/// Outcome of an acquire attempt. `Acquired` means we now hold the
99/// lock (new row, or refreshed our own row). `Held` means someone
100/// else holds an unexpired lock; the caller should render the
101/// read-only banner. `Stolen` is the result when `force=true` —
102/// previous holder's row was deleted and we own the new one.
103#[derive(Debug, Clone)]
104pub enum AcquireOutcome {
105 /// We hold the lock. Payload is the live row.
106 Acquired(PageLock),
107 /// Someone else holds the lock. Payload is their row (used to
108 /// render the banner — username + when acquired).
109 Held(PageLock),
110}
111
112/// Best-effort acquire: returns `Acquired` if the page is free or
113/// already owned by `user_id`, else `Held` with the other user's
114/// row. Refreshes `expires_at` on every call when we own the lock.
115///
116/// `force=true` (admin force-unlock) deletes any existing row and
117/// inserts a fresh one owned by `user_id`. Callers are responsible
118/// for the audit-log entry.
119///
120/// # Errors
121/// Driver / query failures.
122pub async fn acquire(
123 pool: &rustango::sql::Pool,
124 page_id: i64,
125 user_id: i64,
126 force: bool,
127) -> Result<AcquireOutcome, rustango::sql::ExecError> {
128 use rustango::core::Column as _;
129 use rustango::sql::FetcherPool as _;
130
131 let now = Utc::now();
132 let ttl = Duration::seconds(DEFAULT_TTL_SECS);
133 let new_expires = now + ttl;
134
135 let existing: Vec<PageLock> = PageLock::objects()
136 .where_(PageLock::page_id.eq(page_id))
137 .fetch(pool)
138 .await?;
139
140 if let Some(mut row) = existing.into_iter().next() {
141 let stale = row.is_stale(now);
142 let mine = row.user_id == user_id;
143 if mine || stale || force {
144 // Take over: refresh / claim the row in place.
145 row.user_id = user_id;
146 row.expires_at = new_expires;
147 row.save(pool).await?;
148 Ok(AcquireOutcome::Acquired(row))
149 } else {
150 Ok(AcquireOutcome::Held(row))
151 }
152 } else {
153 let mut row = PageLock {
154 id: Auto::Unset,
155 page_id,
156 user_id,
157 acquired_at: Auto::Unset,
158 expires_at: new_expires,
159 };
160 row.insert(pool).await?;
161 Ok(AcquireOutcome::Acquired(row))
162 }
163}
164
165/// Release a lock owned by `user_id`. No-op if the row is missing,
166/// stale, or owned by someone else (the caller's session ended; we
167/// shouldn't silently unlock another user's edit).
168///
169/// # Errors
170/// Driver / query failures.
171pub async fn release(
172 pool: &rustango::sql::Pool,
173 page_id: i64,
174 user_id: i64,
175) -> Result<bool, rustango::sql::ExecError> {
176 use rustango::core::Column as _;
177 use rustango::sql::FetcherPool as _;
178
179 let existing: Vec<PageLock> = PageLock::objects()
180 .where_(PageLock::page_id.eq(page_id))
181 .fetch(pool)
182 .await?;
183 let Some(row) = existing.into_iter().next() else {
184 return Ok(false);
185 };
186 let now = Utc::now();
187 if row.user_id == user_id || row.is_stale(now) {
188 row.delete(pool).await?;
189 Ok(true)
190 } else {
191 Ok(false)
192 }
193}
194
195/// Look up the current lock on a page without mutating it. Returns
196/// `None` if no row exists OR the row is stale. The admin
197/// `page_edit_form` calls this before deciding whether to render the
198/// banner.
199///
200/// # Errors
201/// Driver / query failures.
202pub async fn current(
203 pool: &rustango::sql::Pool,
204 page_id: i64,
205) -> Result<Option<PageLock>, rustango::sql::ExecError> {
206 use rustango::core::Column as _;
207 use rustango::sql::FetcherPool as _;
208
209 let existing: Vec<PageLock> = PageLock::objects()
210 .where_(PageLock::page_id.eq(page_id))
211 .fetch(pool)
212 .await?;
213 let now = Utc::now();
214 Ok(existing.into_iter().find(|r| !r.is_stale(now)))
215}
216
217/// Force-release a lock regardless of ownership. Used by the
218/// `POST /cms-admin/pages/{id}/unlock` admin handler. Returns the
219/// row that was deleted (so the caller can audit-log who held it),
220/// or `None` if the row was already gone.
221///
222/// # Errors
223/// Driver / query failures.
224pub async fn force_release(
225 pool: &rustango::sql::Pool,
226 page_id: i64,
227) -> Result<Option<PageLock>, rustango::sql::ExecError> {
228 use rustango::core::Column as _;
229 use rustango::sql::FetcherPool as _;
230
231 let existing: Vec<PageLock> = PageLock::objects()
232 .where_(PageLock::page_id.eq(page_id))
233 .fetch(pool)
234 .await?;
235 let Some(row) = existing.into_iter().next() else {
236 return Ok(None);
237 };
238 let snapshot = row.clone();
239 row.delete(pool).await?;
240 Ok(Some(snapshot))
241}