Skip to main content

brep_plm/
audit.rs

1//! The audit log: who changed what, and when, for every change to the store.
2//!
3//! # How every change is caught
4//!
5//! Nothing calls "log this" at each of the store's many write paths — one
6//! forgotten call would be a silent hole. Instead [`crate::db::Db::mutate`],
7//! which every change already goes through, compares the state before and
8//! after and turns the difference into events ([`diff`]). A write path added
9//! later is logged without anyone remembering to. The few events that are not
10//! a change to the store — a failed sign-in, a script file edited in the
11//! browser, a test run — are recorded explicitly ([`crate::db::Db::record`]).
12//!
13//! An event is written in the SAME SQLite transaction as its change
14//! ([`crate::sql::Sql::write`]): a change is never on disk without its events,
15//! and a change that is refused or rolled back leaves none.
16//!
17//! # Who
18//!
19//! The request guard knows who a request is; the store does not, and most of
20//! its methods are not told. So the guard runs each request inside a
21//! task-local [`Actor`] scope ([`scope`]), the blocking pool carries it across
22//! ([`crate::api::blocking`]), and `mutate` reads it ([`current_actor`]).
23//! Anything outside a request — start-up, a test driving the store directly —
24//! is the `system` actor unless it says otherwise ([`as_actor`]).
25//!
26//! # Where
27//!
28//! Behind [`AuditSink`], so the storage can change without the rest noticing.
29//! The store's sink is the `audit` table of `plm.sqlite` ([`crate::sql::Sql`]),
30//! with an index for each filter the API offers. Nothing is ever deleted from
31//! it. [`JsonlSink`] is the file store's sink (`audit.jsonl`), kept so an old
32//! log can still be read; [`crate::db::migrate_files`] imports one.
33//!
34//! # Actions
35//!
36//! `create`, `update`, `delete` for anything; and more specific ones where a
37//! field says what happened:
38//! * revisions: `release`, `submit` (to in review), `supersede`, `obsolete`,
39//!   `return-to-draft`, `checkout`, `checkin`, `break-lock`, `document`,
40//!   `uses`, `bake`;
41//! * parts: `sourcing`;
42//! * users: `password`, `groups`, `enable`, `disable`;
43//! * tokens: `revoke` (a deleted token);
44//! * sign-ins: `sign-in`, `session-ended`, `sign-in-failed`;
45//! * scripts: `script-write`, `script-delete`, `script-run`.
46//! * preferences (kind `preference`, entity `<user id>/<key>`): `update`,
47//!   `delete` — written by [`crate::sql::Sql::set_preference`] in the write's
48//!   own transaction, since preferences do not go through `mutate`; the
49//!   `@recovery` mirror is not logged ([`crate::api::preferences`]).
50
51use std::collections::{BTreeMap, BTreeSet};
52use std::fs::{File, OpenOptions};
53use std::io::{self, BufRead, BufReader, Write};
54use std::path::PathBuf;
55use std::sync::Mutex;
56
57use serde::Deserialize;
58use serde_json::{Map, Value};
59
60use crate::model::{Actor, AuditEvent, EntityRef, FieldChange, Timestamp};
61
62// ===========================================================================
63// Who is acting
64// ===========================================================================
65
66tokio::task_local! {
67    static ACTOR: Actor;
68}
69
70/// Who the current request is, or the `system` actor outside one.
71pub fn current_actor() -> Actor {
72    ACTOR.try_with(Clone::clone).unwrap_or_else(|_| Actor::system())
73}
74
75/// Run `work` as `actor`, synchronously — the blocking pool, a test.
76pub fn as_actor<R>(actor: Actor, work: impl FnOnce() -> R) -> R {
77    ACTOR.sync_scope(actor, work)
78}
79
80/// Run a future as `actor` — the request guard.
81pub async fn scope<F: std::future::Future>(actor: Actor, future: F) -> F::Output {
82    ACTOR.scope(actor, future).await
83}
84
85// ===========================================================================
86// Where events go
87// ===========================================================================
88
89/// What an event store must do. Appends assign the ids; nothing edits or
90/// deletes an event.
91pub trait AuditSink: Send + Sync {
92    /// Append `events` in order, numbering each. Returns them numbered.
93    fn append(&self, events: Vec<AuditEvent>) -> io::Result<Vec<AuditEvent>>;
94    /// The events matching `filter`, newest first.
95    fn query(&self, filter: &AuditFilter) -> io::Result<Vec<AuditEvent>>;
96}
97
98/// Narrowing a query. Every field is optional; empty means no constraint.
99#[derive(Debug, Clone, Default, Deserialize)]
100pub struct AuditFilter {
101    /// The entity's kind (`part`, `revision`, `user`, …).
102    #[serde(default)]
103    pub kind: String,
104    /// The entity's id.
105    #[serde(default)]
106    pub entity: String,
107    /// A part's id: the part's own events AND its revisions'.
108    #[serde(default)]
109    pub part: String,
110    /// A user id or username (the username ignoring ASCII case).
111    #[serde(default)]
112    pub user: String,
113    #[serde(default)]
114    pub action: String,
115    /// Unix seconds, inclusive.
116    #[serde(default)]
117    pub since: Option<Timestamp>,
118    #[serde(default)]
119    pub until: Option<Timestamp>,
120    /// Only events older than this id — the next page.
121    #[serde(default)]
122    pub before: Option<u64>,
123    /// At most this many; the API caps it.
124    #[serde(default)]
125    pub limit: Option<usize>,
126    /// Only these kinds (the API narrows a non-administrator to parts and
127    /// revisions). Empty: any.
128    #[serde(skip)]
129    pub kinds: Vec<String>,
130}
131
132impl AuditFilter {
133    pub fn matches(&self, event: &AuditEvent) -> bool {
134        (self.kind.is_empty() || event.entity.kind == self.kind)
135            && (self.kinds.is_empty() || self.kinds.iter().any(|k| *k == event.entity.kind))
136            && (self.entity.is_empty() || event.entity.id == self.entity)
137            && (self.part.is_empty()
138                || event.entity.part_id == self.part
139                || (event.entity.kind == "part" && event.entity.id == self.part))
140            && (self.user.is_empty()
141                || event.actor.user_id == self.user
142                || event.actor.username.eq_ignore_ascii_case(&self.user))
143            && (self.action.is_empty() || event.action == self.action)
144            && self.since.is_none_or(|t| event.at >= t)
145            && self.until.is_none_or(|t| event.at <= t)
146            && self.before.is_none_or(|id| event.id < id)
147    }
148}
149
150/// `audit.jsonl`: one event per line, appended, never rewritten.
151///
152/// A query reads the whole file. A line that does not parse (a torn write from
153/// a crash) is skipped, not fatal. No longer the store's sink: see
154/// [`crate::sql::Sql`].
155pub struct JsonlSink {
156    path: PathBuf,
157    /// The next id, and the lock that keeps two appends from interleaving.
158    next: Mutex<u64>,
159}
160
161impl JsonlSink {
162    pub fn open(path: impl Into<PathBuf>) -> io::Result<Self> {
163        let path = path.into();
164        let mut last = 0;
165        if path.exists() {
166            for line in BufReader::new(File::open(&path)?).lines() {
167                if let Ok(event) = serde_json::from_str::<AuditEvent>(&line?) {
168                    last = last.max(event.id);
169                }
170            }
171        }
172        Ok(JsonlSink { path, next: Mutex::new(last + 1) })
173    }
174}
175
176impl AuditSink for JsonlSink {
177    fn append(&self, mut events: Vec<AuditEvent>) -> io::Result<Vec<AuditEvent>> {
178        if events.is_empty() {
179            return Ok(events);
180        }
181        let mut next = self.next.lock().unwrap_or_else(|e| e.into_inner());
182        let mut text = String::new();
183        let mut id = *next;
184        for event in &mut events {
185            event.id = id;
186            id += 1;
187            text.push_str(&serde_json::to_string(event).map_err(io::Error::other)?);
188            text.push('\n');
189        }
190        // One write per batch, in append mode, so a batch lands whole or a
191        // reader sees a torn last line it skips.
192        let mut file = OpenOptions::new().create(true).append(true).open(&self.path)?;
193        file.write_all(text.as_bytes())?;
194        file.flush()?;
195        *next = id;
196        Ok(events)
197    }
198
199    fn query(&self, filter: &AuditFilter) -> io::Result<Vec<AuditEvent>> {
200        // Hold the append lock so a query never sees half a batch.
201        let _next = self.next.lock().unwrap_or_else(|e| e.into_inner());
202        if !self.path.exists() {
203            return Ok(Vec::new());
204        }
205        let mut found = Vec::new();
206        for line in BufReader::new(File::open(&self.path)?).lines() {
207            let Ok(event) = serde_json::from_str::<AuditEvent>(&line?) else { continue };
208            if filter.matches(&event) {
209                found.push(event);
210            }
211        }
212        found.reverse();
213        if let Some(limit) = filter.limit {
214            found.truncate(limit);
215        }
216        Ok(found)
217    }
218}
219
220// ===========================================================================
221// Turning a change into events
222// ===========================================================================
223
224/// Fields whose change alone is not worth an event: bookkeeping that moves
225/// with every real change, or on every request.
226const QUIET_FIELDS: [&str; 4] = ["modified_at", "last_seen", "last_used_at", "next"];
227
228/// Fields whose values are secrets: the event says they changed, never what to.
229const SECRET_FIELDS: [&str; 3] = ["password", "hash", "csrf"];
230
231/// Store keys that are the store's own bookkeeping, not anyone's record.
232const BOOKKEEPING: [&str; 3] = ["seq", "changes", "changes_from"];
233
234/// Collections of records keyed by `id`: the store key, the entity kind, and
235/// the field a person calls one by.
236const COLLECTIONS: [(&str, &str, &str); 8] = [
237    ("workspace", "workspace", "name"),
238    ("change_orders", "eco", "number"),
239    ("users", "user", "username"),
240    ("api_tokens", "token", "name"),
241    ("part_types", "part-type", "name"),
242    ("categories", "category", "name"),
243    ("manufacturers", "manufacturer", "name"),
244    ("suppliers", "supplier", "name"),
245];
246
247/// Every event that turns the store from `before` into `after`, by `actor`
248/// at `at`, stamped with the new `seq`. Ids are left 0 for the sink.
249pub fn diff(before: &Value, after: &Value, actor: &Actor, at: Timestamp, seq: u64) -> Vec<AuditEvent> {
250    let mut out = Vec::new();
251    let mut push = |action: &str, entity: EntityRef, changes: BTreeMap<String, FieldChange>| {
252        out.push(AuditEvent {
253            id: 0,
254            at,
255            actor: actor.clone(),
256            action: action.to_string(),
257            entity,
258            changes,
259            detail: String::new(),
260            seq,
261        });
262    };
263    let empty = Map::new();
264    let before_map = before.as_object().unwrap_or(&empty);
265    let after_map = after.as_object().unwrap_or(&empty);
266    let keys: BTreeSet<&String> = before_map.keys().chain(after_map.keys()).collect();
267
268    for key in keys {
269        let old = before_map.get(key).unwrap_or(&Value::Null);
270        let new = after_map.get(key).unwrap_or(&Value::Null);
271        if old == new || BOOKKEEPING.contains(&key.as_str()) {
272            continue;
273        }
274        match key.as_str() {
275            "parts" => diff_parts(old, new, &mut push),
276            "sessions" => diff_sessions(old, new, before_map, after_map, &mut push),
277            "settings" => {
278                let changes = field_changes(old, new, &[]);
279                if !changes.is_empty() {
280                    push("update", entity("settings", "settings", "Settings", ""), changes);
281                }
282            }
283            name => {
284                if let Some((_, kind, label)) = COLLECTIONS.iter().find(|(store, _, _)| *store == name) {
285                    diff_collection(old, new, kind, label, &mut push);
286                } else if keyed(old) && keyed(new) {
287                    // A collection a later slice adds: logged by its store
288                    // name, rather than silently not at all.
289                    diff_collection(old, new, name, "name", &mut push);
290                } else {
291                    let mut changes = BTreeMap::new();
292                    changes.insert(name.to_string(), FieldChange { before: old.clone(), after: new.clone() });
293                    push("update", entity(name, name, name, ""), changes);
294                }
295            }
296        }
297    }
298    out
299}
300
301fn entity(kind: &str, id: &str, label: &str, part_id: &str) -> EntityRef {
302    EntityRef { kind: kind.into(), id: id.into(), label: label.into(), part_id: part_id.into() }
303}
304
305/// Whether `value` is a list of records with ids (or empty).
306fn keyed(value: &Value) -> bool {
307    match value {
308        Value::Array(items) => items.iter().all(|item| item.get("id").and_then(Value::as_str).is_some()),
309        Value::Null => true,
310        _ => false,
311    }
312}
313
314fn by_id(value: &Value) -> BTreeMap<String, &Value> {
315    value
316        .as_array()
317        .map(|items| {
318            items
319                .iter()
320                .filter_map(|item| Some((item.get("id")?.as_str()?.to_string(), item)))
321                .collect()
322        })
323        .unwrap_or_default()
324}
325
326fn text<'a>(value: &'a Value, field: &str) -> &'a str {
327    value.get(field).and_then(Value::as_str).unwrap_or("")
328}
329
330/// The fields that differ between two records, minus `skip` and the quiet
331/// ones, with secrets redacted. A missing record is `null`: every field of
332/// the other side appears.
333fn field_changes(before: &Value, after: &Value, skip: &[&str]) -> BTreeMap<String, FieldChange> {
334    let empty = Map::new();
335    let old = before.as_object().unwrap_or(&empty);
336    let new = after.as_object().unwrap_or(&empty);
337    let mut changes = BTreeMap::new();
338    for key in old.keys().chain(new.keys()).collect::<BTreeSet<_>>() {
339        if skip.contains(&key.as_str()) || QUIET_FIELDS.contains(&key.as_str()) {
340            continue;
341        }
342        let a = old.get(key).cloned().unwrap_or(Value::Null);
343        let b = new.get(key).cloned().unwrap_or(Value::Null);
344        if a == b {
345            continue;
346        }
347        let change = if SECRET_FIELDS.contains(&key.as_str()) {
348            let mark = |v: &Value| if v.is_null() { Value::Null } else { Value::from("(secret)") };
349            FieldChange { before: mark(&a), after: mark(&b) }
350        } else {
351            FieldChange { before: a, after: b }
352        };
353        changes.insert(key.clone(), change);
354    }
355    changes
356}
357
358fn diff_collection(
359    old: &Value,
360    new: &Value,
361    kind: &str,
362    label_field: &str,
363    push: &mut impl FnMut(&str, EntityRef, BTreeMap<String, FieldChange>),
364) {
365    let before = by_id(old);
366    let after = by_id(new);
367    for id in before.keys().chain(after.keys()).collect::<BTreeSet<_>>() {
368        let (a, b) = (before.get(id).copied(), after.get(id).copied());
369        let record = b.or(a).unwrap_or(&Value::Null);
370        let who = entity(kind, id, text(record, label_field), "");
371        let changes = field_changes(a.unwrap_or(&Value::Null), b.unwrap_or(&Value::Null), &[]);
372        match (a, b) {
373            (None, Some(_)) => push("create", who, changes),
374            (Some(_), None) => push(if kind == "token" { "revoke" } else { "delete" }, who, changes),
375            _ if changes.is_empty() => {}
376            _ => {
377                let action = match kind {
378                    "user" => user_action(&changes),
379                    "eco" => eco_action(&changes),
380                    "workspace" => workspace_action(&changes),
381                    _ => "update",
382                };
383                push(action, who, changes);
384            }
385        }
386    }
387}
388
389/// A workspace entry's change, named by what moved: a new file version
390/// (a replace or a restore), a move to another folder, a rename, or a link
391/// pinned or set to follow.
392fn workspace_action(changes: &BTreeMap<String, FieldChange>) -> &'static str {
393    let moved: Vec<&str> = changes.keys().map(String::as_str).filter(|k| !QUIET_FIELDS.contains(k)).collect();
394    match moved.as_slice() {
395        ["versions"] => "version",
396        ["parent"] | ["name", "parent"] => "move",
397        ["name"] => "rename",
398        ["link"] => "pin",
399        _ => "update",
400    }
401}
402
403fn user_action(changes: &BTreeMap<String, FieldChange>) -> &'static str {
404    let only = |field: &str| changes.len() == 1 && changes.contains_key(field);
405    if only("password") {
406        "password"
407    } else if only("groups") {
408        "groups"
409    } else if only("active") {
410        if changes["active"].after == Value::Bool(true) { "enable" } else { "disable" }
411    } else {
412        "update"
413    }
414}
415
416fn diff_parts(old: &Value, new: &Value, push: &mut impl FnMut(&str, EntityRef, BTreeMap<String, FieldChange>)) {
417    let before = by_id(old);
418    let after = by_id(new);
419    for id in before.keys().chain(after.keys()).collect::<BTreeSet<_>>() {
420        let (a, b) = (before.get(id).copied(), after.get(id).copied());
421        let part = b.or(a).unwrap_or(&Value::Null);
422        let number = text(part, "number").to_string();
423        let changes = field_changes(a.unwrap_or(&Value::Null), b.unwrap_or(&Value::Null), &["revisions"]);
424        let who = entity("part", id, &number, "");
425        match (a, b) {
426            (None, Some(_)) => push("create", who, changes),
427            (Some(_), None) => push("delete", who, changes),
428            _ if changes.is_empty() => {}
429            _ => {
430                let action = if changes.len() == 1 && changes.contains_key("sourcing") { "sourcing" } else { "update" };
431                push(action, who, changes);
432            }
433        }
434        let revs_before = by_id(a.and_then(|p| p.get("revisions")).unwrap_or(&Value::Null));
435        let revs_after = by_id(b.and_then(|p| p.get("revisions")).unwrap_or(&Value::Null));
436        for rev in revs_before.keys().chain(revs_after.keys()).collect::<BTreeSet<_>>() {
437            let (x, y) = (revs_before.get(rev).copied(), revs_after.get(rev).copied());
438            let record = y.or(x).unwrap_or(&Value::Null);
439            let label = format!("{number} rev {}", text(record, "label"));
440            let who = entity("revision", rev, &label, id);
441            let changes = field_changes(x.unwrap_or(&Value::Null), y.unwrap_or(&Value::Null), &[]);
442            match (x, y) {
443                (None, Some(_)) => push("create", who, changes),
444                (Some(_), None) => push("delete", who, changes),
445                _ if changes.is_empty() => {}
446                _ => {
447                    let action = revision_action(&changes);
448                    push(action, who, changes);
449                }
450            }
451        }
452    }
453}
454
455/// The one word that best says what happened to a revision. Several fields
456/// can change at once (a release also stamps who and when); the most
457/// significant one names the event, and every field is still in `changes`.
458fn revision_action(changes: &BTreeMap<String, FieldChange>) -> &'static str {
459    // A reviewer's decision names the event even when it also moved the
460    // lifecycle (a rejection sends the revision back to Draft).
461    if let Some(change) = changes.get("reviews") {
462        if let Some(verdict) = new_decision(&change.before, &change.after) {
463            return verdict;
464        }
465        if let Some(status) = last_review_status(&change.after) {
466            if status == "withdrawn" && last_review_status(&change.before) != Some("withdrawn") {
467                return "withdraw";
468            }
469        }
470    }
471    if let Some(change) = changes.get("lifecycle") {
472        return match change.after.as_str().unwrap_or("") {
473            "released" => "release",
474            "inreview" => "submit",
475            "superseded" => "supersede",
476            "obsolete" => "obsolete",
477            "draft" => "return-to-draft",
478            _ => "update",
479        };
480    }
481    if let Some(change) = changes.get("lock") {
482        return match (change.before.is_null(), change.after.is_null()) {
483            (true, false) => "checkout",
484            (false, true) => {
485                // The holder checking in, or someone else breaking the lock:
486                // the diff cannot tell who acted, so the caller's name is in
487                // the actor and the holder's in `before`.
488                "checkin"
489            }
490            _ => "checkout",
491        };
492    }
493    if changes.contains_key("content_hash") {
494        return "document";
495    }
496    if changes.contains_key("uses") {
497        return "uses";
498    }
499    if changes.contains_key("bake") {
500        return "bake";
501    }
502    if changes.contains_key("reviews") {
503        return "review-update";
504    }
505    if changes.contains_key("comments") {
506        return "comment";
507    }
508    "update"
509}
510
511/// The one word that best says what happened to a change order: a decision,
512/// then its state, then its items, its round, its discussion.
513fn eco_action(changes: &BTreeMap<String, FieldChange>) -> &'static str {
514    if let Some(change) = changes.get("reviews") {
515        if let Some(verdict) = new_decision(&change.before, &change.after) {
516            return verdict;
517        }
518    }
519    if let Some(change) = changes.get("state") {
520        let was = change.before.as_str().unwrap_or("");
521        return match change.after.as_str().unwrap_or("") {
522            "inreview" | "approved" if was == "draft" => "submit",
523            "approved" => "approve",
524            "released" => "release",
525            "cancelled" => "cancel",
526            "draft" => "withdraw",
527            _ => "update",
528        };
529    }
530    if changes.contains_key("items") {
531        return "items";
532    }
533    if changes.contains_key("reviews") {
534        return "review-update";
535    }
536    if changes.contains_key("comments") {
537        return "comment";
538    }
539    "update"
540}
541
542/// The verdict of a decision `after` has that `before` did not, in the last
543/// review round of a `reviews` list.
544pub(crate) fn new_decision(before: &Value, after: &Value) -> Option<&'static str> {
545    let decisions = |v: &Value| -> usize {
546        v.as_array()
547            .and_then(|rounds| rounds.last())
548            .and_then(|r| r.get("decisions"))
549            .and_then(Value::as_array)
550            .map(Vec::len)
551            .unwrap_or(0)
552    };
553    let same_round = |v: &Value| v.as_array().and_then(|r| r.last()).and_then(|r| r.get("id")).cloned();
554    let grew = decisions(after) > decisions(before) || (same_round(before) != same_round(after) && decisions(after) > 0);
555    if !grew {
556        return None;
557    }
558    let verdict = after
559        .as_array()?
560        .last()?
561        .get("decisions")?
562        .as_array()?
563        .last()?
564        .get("verdict")?
565        .as_str()?;
566    Some(if verdict == "reject" { "reject" } else { "approve" })
567}
568
569/// The status of the last round in a `reviews` list.
570pub(crate) fn last_review_status(value: &Value) -> Option<&str> {
571    value.as_array()?.last()?.get("status")?.as_str()
572}
573
574fn diff_sessions(
575    old: &Value,
576    new: &Value,
577    before: &Map<String, Value>,
578    after: &Map<String, Value>,
579    push: &mut impl FnMut(&str, EntityRef, BTreeMap<String, FieldChange>),
580) {
581    // Keyed by token, which never leaves this function: the event names the
582    // user, not the session.
583    let tokens = |value: &Value| -> BTreeMap<String, String> {
584        value
585            .as_array()
586            .map(|items| {
587                items
588                    .iter()
589                    .filter_map(|s| Some((s.get("token")?.as_str()?.to_string(), s.get("user_id")?.as_str()?.to_string())))
590                    .collect()
591            })
592            .unwrap_or_default()
593    };
594    let username = |user_id: &str| -> String {
595        for map in [after, before] {
596            if let Some(users) = map.get("users").and_then(Value::as_array) {
597                if let Some(user) = users.iter().find(|u| text(u, "id") == user_id) {
598                    return text(user, "username").to_string();
599                }
600            }
601        }
602        String::new()
603    };
604    let (a, b) = (tokens(old), tokens(new));
605    for (token, user_id) in &b {
606        if !a.contains_key(token) {
607            push("sign-in", entity("user", user_id, &username(user_id), ""), BTreeMap::new());
608        }
609    }
610    // Several sessions of one user ending at once (sign out everywhere) are
611    // one event, with the count.
612    let mut ended: BTreeMap<&str, u64> = BTreeMap::new();
613    for (token, user_id) in &a {
614        if !b.contains_key(token) {
615            *ended.entry(user_id).or_default() += 1;
616        }
617    }
618    for (user_id, count) in ended {
619        let mut changes = BTreeMap::new();
620        changes.insert("sessions".to_string(), FieldChange { before: Value::from(count), after: Value::from(0) });
621        push("session-ended", entity("user", user_id, &username(user_id), ""), changes);
622    }
623}
624
625/// The lock change of a `checkin` event names whose lock it was; when that
626/// is not the actor, the event is really a broken lock.
627pub fn refine(mut events: Vec<AuditEvent>) -> Vec<AuditEvent> {
628    for event in &mut events {
629        if event.action == "checkin" {
630            let holder = event
631                .changes
632                .get("lock")
633                .and_then(|c| c.before.get("user_id"))
634                .and_then(Value::as_str)
635                .unwrap_or("");
636            if !holder.is_empty() && holder != event.actor.user_id {
637                event.action = "break-lock".into();
638            }
639        }
640    }
641    events
642}
643
644/// CSV of events, for the admin's export.
645pub fn to_csv(events: &[AuditEvent]) -> String {
646    let quote = |text: &str| {
647        if text.contains([',', '"', '\n', '\r']) {
648            format!("\"{}\"", text.replace('"', "\"\""))
649        } else {
650            text.to_string()
651        }
652    };
653    let mut out = String::from("id,at,user,via,ip,action,kind,entity,label,part,changes,detail,seq\n");
654    for e in events {
655        let changes = if e.changes.is_empty() {
656            String::new()
657        } else {
658            serde_json::to_string(&e.changes).unwrap_or_default()
659        };
660        let row = [
661            e.id.to_string(),
662            e.at.to_string(),
663            e.actor.username.clone(),
664            e.actor.via.clone(),
665            e.actor.ip.clone(),
666            e.action.clone(),
667            e.entity.kind.clone(),
668            e.entity.id.clone(),
669            e.entity.label.clone(),
670            e.entity.part_id.clone(),
671            changes,
672            e.detail.clone(),
673            e.seq.to_string(),
674        ];
675        out.push_str(&row.iter().map(|f| quote(f)).collect::<Vec<_>>().join(","));
676        out.push('\n');
677    }
678    out
679}
680