brep_plm/api/preferences.rs
1//! The per-user preferences store (plm-cad-integration-todo D1, P5): where the
2//! CAD app keeps its reserved keys when the PLM is its store, so a user's
3//! settings, dock layout, pins and libraries follow them to any machine, and
4//! the mirror of their unsaved work (`@recovery`) can be resumed on another.
5//!
6//! | Route | Answers |
7//! | --- | --- |
8//! | `GET /api/me/preferences[?since=v]` | `{ version, keys: [{ key, version, size, modified, deleted }] }` |
9//! | `GET /api/me/preferences/:key` | the value's bytes, `X-Preference-Version: v`; `204` (no body) when unset |
10//! | `PUT /api/me/preferences/:key` | `{ ok, key, version, size }` |
11//! | `DELETE /api/me/preferences/:key` | `{ ok, key, version }` |
12//!
13//! # Whose
14//!
15//! The caller's, always: there is no user in the path, so no request can name
16//! another account's set — an administrator's included. A browser session or
17//! an API token of the same account reads and writes the same set; a `read`
18//! token may only read, and the scope rules apply as to any route.
19//!
20//! # Which keys
21//!
22//! Exactly [`KEYS`], the CAD app's reserved keys. Any other key is a `400`:
23//! documents go to the store routes, and directory rows are not used in PLM
24//! mode (D1). A value is opaque JSON — it must parse, and is kept byte for
25//! byte.
26//!
27//! # How a second client notices
28//!
29//! Each user's set has one VERSION, bumped by every write and every delete of
30//! a live key, and each row carries the version it was last written at. A
31//! client polls `GET /api/me/preferences?since=<the version it holds>` and
32//! gets back only the keys that moved, a deleted one with `deleted: true`;
33//! `since` absent or 0 lists the live keys. That is the store feed's shape
34//! (`/api/store/changes?since=`) without its `stale`: a deleted key is kept as
35//! a row, so the answer is always complete. The last write wins; there is no
36//! precondition.
37//!
38//! This version is NOT the store's `seq`: a preference is not a document, and
39//! a dock layout saved must not move every other client's document feed.
40//!
41//! # Where
42//!
43//! The `preferences` table of `plm.sqlite`, read and written directly — not
44//! the in-memory state every other record lives in, because every change
45//! re-serializes that state's small fields and a `@recovery` value is whole
46//! unsaved models. Being in `plm.sqlite`, it is in every backup, and a restore
47//! brings it back.
48//!
49//! # The audit log
50//!
51//! A write or delete of any key but `@recovery` is logged as kind `preference`,
52//! entity `<user id>/<key>`, action `update` or `delete`, with the value's size
53//! and never the value, in the SAME transaction as the write. `@recovery` is
54//! not logged: the app rewrites it seconds after every edit while a document
55//! is unsaved and removes it the moment one is saved, so its events would
56//! bury everything else a user did, and they would record nothing a reviewer
57//! can act on — the document saves they lead to are logged.
58//!
59//! # Size
60//!
61//! A settings key holds at most [`PREFERENCE_LIMIT`]; `@recovery` holds unsaved
62//! documents, so it takes the document limit (`--max-document-mb`). Over
63//! either is a `413` with a sentence.
64
65use axum::body::Body;
66use axum::extract::{Path, Query, State};
67use axum::http::{header, HeaderMap, StatusCode};
68use axum::response::{IntoResponse, Response};
69use axum::Json;
70use serde::Deserialize;
71use serde_json::json;
72
73use super::store::{megabytes, read_bounded};
74use super::{blocking, require_user, Shared};
75use crate::model::{AuditEvent, EntityRef, User};
76use crate::Error;
77
78/// The largest value a settings key may hold, in bytes.
79pub const PREFERENCE_LIMIT: u64 = 256 * 1024;
80
81/// The mirror of the app's autosave blob.
82pub const RECOVERY: &str = "@recovery";
83
84/// The keys a user may keep: the CAD app's reserved keys (`BREP_app`'s
85/// `store.rs`), and nothing else.
86pub const KEYS: &[&str] = &[
87 "@settings",
88 "@dock_layout",
89 "@pinned",
90 "@feature_palette_display",
91 "@kicad_library",
92 "@recent_documents",
93 RECOVERY,
94];
95
96/// The header a value's version rides on.
97pub const VERSION_HEADER: &str = "x-preference-version";
98
99fn reserved(key: &str) -> Result<&'static str, Error> {
100 KEYS.iter().copied().find(|k| *k == key).ok_or_else(|| {
101 Error::bad_request(format!("'{key}' is not a preference — the keys are {}", KEYS.join(", ")))
102 })
103}
104
105#[derive(Debug, Deserialize)]
106pub struct Since {
107 #[serde(default)]
108 pub since: u64,
109}
110
111/// The caller's keys, as metadata.
112pub async fn list(
113 State(db): State<Shared>,
114 headers: HeaderMap,
115 Query(query): Query<Since>,
116) -> Result<Response, Error> {
117 let user = require_user(&db, &headers)?;
118 let (version, keys) = db.sql().preferences(&user.id, query.since).map_err(Error::internal)?;
119 Ok(Json(json!({ "version": version, "keys": keys })).into_response())
120}
121
122/// One of the caller's values, byte for byte.
123pub async fn read(
124 State(db): State<Shared>,
125 headers: HeaderMap,
126 Path(key): Path<String>,
127) -> Result<Response, Error> {
128 let user = require_user(&db, &headers)?;
129 let key = reserved(&key)?;
130 let found = blocking(move || db.sql().preference(&user.id, key).map_err(Error::internal)).await?;
131 // Unset is an answer, not an error — as a revision with no document answers `204` on
132 // the store routes. A `404` here made a browser log an error for every key a new
133 // user had never set, on every first visit.
134 let Some((value, version)) = found else {
135 return Ok(StatusCode::NO_CONTENT.into_response());
136 };
137 Ok((
138 StatusCode::OK,
139 [(header::CONTENT_TYPE, "application/json; charset=utf-8".to_string()), (header::HeaderName::from_static(VERSION_HEADER), version.to_string())],
140 value,
141 )
142 .into_response())
143}
144
145/// Set one of the caller's values.
146pub async fn write(
147 State(db): State<Shared>,
148 headers: HeaderMap,
149 Path(key): Path<String>,
150 body: Body,
151) -> Result<Response, Error> {
152 let user = require_user(&db, &headers)?;
153 let key = reserved(&key)?;
154 let limit = if key == RECOVERY { db.security().config.document_limit() } else { PREFERENCE_LIMIT };
155 let what = if key == RECOVERY { "document" } else { "preference" };
156 let value = read_bounded(&headers, body, limit, || {
157 format!("the {key} value is over the {} {what} limit", megabytes(limit))
158 })
159 .await?;
160 if serde_json::from_str::<serde_json::Value>(&value).is_err() {
161 return Err(Error::bad_request(format!("a preference must be JSON, and the {key} value is not")));
162 }
163 let size = value.len();
164 let version = blocking(move || {
165 let event = audited(&user, key, "update", format!("{size} bytes"));
166 db.sql().set_preference(&user.id, key, Some(&value), crate::db::now(), event).map_err(Error::internal)
167 })
168 .await?;
169 Ok(Json(json!({ "ok": true, "key": key, "version": version, "size": size })).into_response())
170}
171
172/// Remove one of the caller's values. Removing one that is not set is not an
173/// error and changes nothing.
174pub async fn remove(
175 State(db): State<Shared>,
176 headers: HeaderMap,
177 Path(key): Path<String>,
178) -> Result<Response, Error> {
179 let user = require_user(&db, &headers)?;
180 let key = reserved(&key)?;
181 let version = blocking(move || {
182 let event = audited(&user, key, "delete", String::new());
183 db.sql().set_preference(&user.id, key, None, crate::db::now(), event).map_err(Error::internal)
184 })
185 .await?;
186 Ok(Json(json!({ "ok": true, "key": key, "version": version })).into_response())
187}
188
189/// The event a change to `key` is logged as, or none for `@recovery`.
190fn audited(user: &User, key: &str, action: &str, detail: String) -> Option<AuditEvent> {
191 (key != RECOVERY).then(|| AuditEvent {
192 id: 0,
193 at: crate::db::now(),
194 actor: crate::audit::current_actor(),
195 action: action.into(),
196 entity: EntityRef {
197 kind: "preference".into(),
198 id: format!("{}/{key}", user.id),
199 label: format!("{} {key}", user.username),
200 part_id: String::new(),
201 },
202 changes: Default::default(),
203 detail,
204 seq: 0,
205 })
206}