Skip to main content

rustango_cms/
page_log.rs

1//! Per-page audit log.
2//!
3//! Every meaningful action on a
4//! page (publish, edit, move, copy, alias create, restore, lock,
5//! unlock, force-unlock, workflow submit / approve / reject / cancel,
6//! comment new / resolved / reopened) lands a row. Revisions answer
7//! "what changed"; log entries answer "who did what, when".
8//!
9//! Best-effort: a log-write failure is logged + swallowed; the
10//! underlying action commits regardless. Compliance > availability
11//! ordering — but in our case the action is the source of truth and
12//! the log is observability.
13
14use chrono::{DateTime, Utc};
15use rustango::sql::Auto;
16use rustango::Model;
17use serde::{Deserialize, Serialize};
18
19// Action constants. Strings (not enum) so plugins can extend the
20// taxonomy without an upstream change.
21pub const ACTION_EDIT: &str = "edit";
22pub const ACTION_PUBLISH: &str = "publish";
23pub const ACTION_UNPUBLISH: &str = "unpublish";
24pub const ACTION_MOVE: &str = "move";
25pub const ACTION_COPY: &str = "copy";
26pub const ACTION_ALIAS_CREATE: &str = "alias_create";
27pub const ACTION_RESTORE: &str = "restore";
28pub const ACTION_LOCK: &str = "lock";
29pub const ACTION_UNLOCK: &str = "unlock";
30pub const ACTION_FORCE_UNLOCK: &str = "force_unlock";
31pub const ACTION_WORKFLOW_SUBMIT: &str = "workflow_submit";
32pub const ACTION_WORKFLOW_APPROVE: &str = "workflow_approve";
33pub const ACTION_WORKFLOW_REJECT: &str = "workflow_reject";
34pub const ACTION_WORKFLOW_CANCEL: &str = "workflow_cancel";
35pub const ACTION_COMMENT_NEW: &str = "comment_new";
36pub const ACTION_COMMENT_RESOLVE: &str = "comment_resolve";
37pub const ACTION_COMMENT_REOPEN: &str = "comment_reopen";
38pub const ACTION_DELETE: &str = "delete";
39
40#[derive(Model, Debug, Clone, Serialize, Deserialize)]
41#[rustango(
42    table = "cms_page_log_entry",
43    app = "cms",
44    display = "action",
45    admin(
46        list_display = "page_id, action, actor_id, created_at",
47        ordering = "-created_at",
48        list_filter = "action",
49    )
50)]
51pub struct PageLogEntry {
52    #[rustango(primary_key)]
53    pub id: Auto<i64>,
54
55    #[rustango(fk = "cms_page", on = "id", index)]
56    pub page_id: i64,
57
58    /// Symbolic action name; values from the `ACTION_*` constants.
59    #[rustango(max_length = 64, index)]
60    pub action: String,
61
62    /// Who did it. None means a system / scheduled action — schedule
63    /// publisher, automated workflow advance, sweep job.
64    #[rustango(fk = "rustango_users", on = "id")]
65    pub actor_id: Option<i64>,
66
67    /// Short human-readable summary ("Published", "Moved to /blog/",
68    /// "Forced unlock of bob's edit session"). Render verbatim in
69    /// the timeline.
70    #[rustango(max_length = 500, default = "''")]
71    pub message: String,
72
73    /// JSON blob — structured metadata for future filtering (e.g.
74    /// `{"workflow_id": 3, "task_id": 7}` on a workflow_submit row).
75    /// Stored as TEXT to stay ORM-portable across dialects.
76    #[rustango(default = "'{}'")]
77    pub data_json: String,
78
79    #[rustango(auto_now_add)]
80    pub created_at: Auto<DateTime<Utc>>,
81}
82
83/// Insert a log entry. Best-effort; on failure logs + returns Ok so
84/// the call-site doesn't have to special-case audit-write errors.
85///
86/// `data` is serialised into the `data_json` column. Pass `None` for
87/// "no extra metadata"; pass any `serde_json::Value` otherwise.
88///
89/// # Errors
90/// Driver / query failures bubble up — callers typically `let _ =`
91/// the result so audit failures don't abort the underlying action.
92pub async fn record(
93    pool: &rustango::sql::Pool,
94    page_id: i64,
95    action: &str,
96    actor_id: Option<i64>,
97    message: impl Into<String>,
98    data: Option<serde_json::Value>,
99) -> Result<(), rustango::sql::ExecError> {
100    let data_json = data
101        .as_ref()
102        .map(|v| serde_json::to_string(v).unwrap_or_else(|_| "{}".to_owned()))
103        .unwrap_or_else(|| "{}".to_owned());
104    let mut row = PageLogEntry {
105        id: Auto::Unset,
106        page_id,
107        action: action.to_owned(),
108        actor_id,
109        message: message.into(),
110        data_json,
111        created_at: Auto::Unset,
112    };
113    row.insert(pool).await?;
114    Ok(())
115}
116
117/// Every log entry for a page, newest first. Bounded by `limit` so
118/// the history tab doesn't render thousands of rows; pass `None` to
119/// return everything (CSV export uses that).
120///
121/// # Errors
122/// Driver / query failures.
123pub async fn for_page(
124    pool: &rustango::sql::Pool,
125    page_id: i64,
126    limit: Option<usize>,
127) -> Result<Vec<PageLogEntry>, rustango::sql::ExecError> {
128    use rustango::core::Column as _;
129    use rustango::sql::FetcherPool as _;
130    let mut rows: Vec<PageLogEntry> = PageLogEntry::objects()
131        .where_(PageLogEntry::page_id.eq(page_id))
132        .order_by(&[("created_at", true)])
133        .fetch(pool)
134        .await?;
135    if let Some(cap) = limit {
136        rows.truncate(cap);
137    }
138    Ok(rows)
139}
140
141/// One-shot fire-and-forget convenience: records a log entry and
142/// swallows + logs any error. Use this at fire-sites where audit
143/// failure should never block the underlying action.
144pub async fn record_or_warn(
145    pool: &rustango::sql::Pool,
146    page_id: i64,
147    action: &str,
148    actor_id: Option<i64>,
149    message: impl Into<String>,
150    data: Option<serde_json::Value>,
151) {
152    let msg = message.into();
153    if let Err(e) = record(pool, page_id, action, actor_id, msg.clone(), data).await {
154        tracing::warn!(
155            target: "rustango_cms::page_log",
156            page_id, action, error = %e,
157            "audit log write failed (continuing)"
158        );
159    }
160}