Skip to main content

brep_plm/api/
store.rs

1//! The DOCUMENT surface — the contract the CAD app's `StoreBackend` will
2//! consume, shaped to the five obligations a remote backend carries.
3//!
4//! | Obligation | Route |
5//! | --- | --- |
6//! | Metadata-only hydration (never pull the corpus) | `GET /api/store/index` |
7//! | Read one key, seeing other clients' writes | `GET /api/store/doc/*key` |
8//! | Write one key | `PUT /api/store/doc/*key` |
9//! | Delete one key | `DELETE /api/store/doc/*key` |
10//! | A monotonic change sequence + what moved | `GET /api/store/changes?since=` |
11//!
12//! `seq` rides every response so a client's cache-invalidation key never needs
13//! a second request, and `stale` tells a client that has been away too long to
14//! re-read the index rather than trust a short answer.
15//!
16//! # Why a write can be refused
17//!
18//! A `PUT` needs the revision to be EDITABLE and the caller to hold its lock.
19//! Both refusals are `409` with a sentence explaining which, because the CAD
20//! app's write-behind lane surfaces the message to the user after its own
21//! `write()` has already returned — a bare status would leave them with "it
22//! did not save" and nothing else.
23
24use axum::body::Body;
25use axum::extract::{Path, Query, State};
26use axum::http::{header, HeaderMap, StatusCode};
27use axum::response::{IntoResponse, Response};
28use axum::Json;
29use serde::{Deserialize, Serialize};
30
31use super::{require_user, Shared};
32use crate::Error;
33
34/// One row of the index: everything a client needs to list, sort and decide
35/// staleness — and no document bytes.
36#[derive(Debug, Serialize)]
37pub struct IndexEntry {
38    pub key: String,
39    pub part_id: String,
40    pub part_number: String,
41    pub part_name: String,
42    /// What the document is — `normal`, `family` or `template` — fixed when
43    /// the part was made (plm-cad-integration-todo D4).
44    pub document_class: crate::model::DocumentClass,
45    pub revision_id: String,
46    pub revision_label: String,
47    pub lifecycle: &'static str,
48    pub editable: bool,
49    pub content_hash: String,
50    pub size: u64,
51    pub modified: u64,
52    pub locked_by: Option<String>,
53    pub locked_by_me: bool,
54}
55
56#[derive(Debug, Serialize)]
57pub struct Index {
58    pub seq: u64,
59    pub entries: Vec<IndexEntry>,
60}
61
62#[derive(Debug, Default, Deserialize)]
63pub struct IndexQuery {
64    /// Comma-separated document keys: only their rows (a key that names no
65    /// revision is left out). Absent: the whole index.
66    #[serde(default)]
67    pub keys: Option<String>,
68}
69
70/// The whole key space as METADATA. This is `load_index`.
71///
72/// `?keys=part/a/rev/b,part/c/rev/d` answers only those rows, looked up by
73/// part: what a client re-reads after the change feed named them, at a cost
74/// of the keys asked and not of the catalog.
75pub async fn index(
76    State(db): State<Shared>,
77    headers: HeaderMap,
78    query: Option<Query<IndexQuery>>,
79) -> Result<Json<Index>, Error> {
80    let user = require_user(&db, &headers)?;
81    let wanted: Option<Vec<(String, String)>> = query.and_then(|Query(q)| q.keys).map(|keys| {
82        keys.split(',').filter_map(|key| split_key(key.trim()).ok()).collect()
83    });
84    Ok(Json(db.read(|state| {
85        let row = |part: &crate::model::Part, revision: &crate::model::Revision| IndexEntry {
86            key: revision.document_key(&part.id),
87            part_id: part.id.clone(),
88            part_number: part.number.clone(),
89            part_name: part.name.clone(),
90            document_class: part.document_class,
91            revision_id: revision.id.clone(),
92            revision_label: revision.label.clone(),
93            lifecycle: revision.lifecycle.as_str(),
94            editable: revision.lifecycle.is_editable(),
95            content_hash: revision.content_hash.clone(),
96            size: revision.size,
97            modified: revision.modified_at,
98            locked_by: revision.lock.as_ref().and_then(|l| state.user(&l.user_id).map(|u| u.username.clone())),
99            locked_by_me: revision.lock.as_ref().is_some_and(|l| l.user_id == user.id),
100        };
101        let mut entries = Vec::new();
102        match &wanted {
103            Some(keys) => {
104                for (part_id, revision_id) in keys {
105                    if let Some(part) = state.part(part_id) {
106                        if let Some(revision) = part.revision(revision_id) {
107                            entries.push(row(part, revision));
108                        }
109                    }
110                }
111            }
112            None => {
113                for part in &state.parts {
114                    for revision in &part.revisions {
115                        entries.push(row(part, revision));
116                    }
117                }
118            }
119        }
120        Index { seq: state.seq, entries }
121    })))
122}
123
124#[derive(Debug, Deserialize)]
125pub struct Since {
126    #[serde(default)]
127    pub since: u64,
128}
129
130#[derive(Debug, Serialize)]
131pub struct Changes {
132    pub seq: u64,
133    /// The client asked from further back than the log reaches. Its correct
134    /// response is to re-read the index, NOT to treat `keys` as complete.
135    pub stale: bool,
136    pub keys: Vec<String>,
137}
138
139pub async fn changes(
140    State(db): State<Shared>,
141    headers: HeaderMap,
142    Query(query): Query<Since>,
143) -> Result<Json<Changes>, Error> {
144    require_user(&db, &headers)?;
145    let (seq, stale, keys) = db.changes_since(query.since);
146    Ok(Json(Changes { seq, stale, keys }))
147}
148
149/// `part/<part id>/rev/<revision id>` split back into its halves.
150fn split_key(key: &str) -> Result<(String, String), Error> {
151    crate::identity::split_key(key).ok_or_else(|| Error::bad_request(format!(
152        "'{key}' is not a document key — expected part/<part>/rev/<revision>"
153    )))
154}
155
156/// Read one document. This is the LIVE read: it goes to the file every time,
157/// so a client re-reading a key after someone else wrote it sees the new
158/// bytes, which is the whole reason the backend trait requires a `get`.
159pub async fn read_doc(
160    State(db): State<Shared>,
161    headers: HeaderMap,
162    Path(key): Path<String>,
163) -> Result<Response, Error> {
164    require_user(&db, &headers)?;
165    let (part_id, revision_id) = split_key(&key)?;
166    let exists = db.read(|state| {
167        state
168            .part(&part_id)
169            .and_then(|p| p.revision(&revision_id))
170            .is_some()
171    });
172    if !exists {
173        return Err(Error::not_found("revision"));
174    }
175    match db.read_document(&key)? {
176        Some(body) => Ok((
177            StatusCode::OK,
178            [(header::CONTENT_TYPE, "application/json; charset=utf-8")],
179            body,
180        )
181            .into_response()),
182        // A revision with no document yet is a real state, not an error — an
183        // imported part with no 3D model will be exactly this. 204 says "the
184        // revision is there and empty"; 404 would say "no such revision".
185        None => Ok(StatusCode::NO_CONTENT.into_response()),
186    }
187}
188
189/// Write one document.
190///
191/// Refused unless the revision is editable AND the caller holds its lock.
192/// Together those two checks are the immutability rule: there is no path by
193/// which a released revision's bytes change.
194pub async fn write_doc(
195    State(db): State<Shared>,
196    headers: HeaderMap,
197    Path(key): Path<String>,
198    body: Body,
199) -> Result<Response, Error> {
200    let user = require_user(&db, &headers)?;
201    let (part_id, revision_id) = split_key(&key)?;
202    guard_writable(&db, &user, &part_id, &revision_id)?;
203    let limit = db.security().config.document_limit();
204    let body = read_bounded(&headers, body, limit, || {
205        format!("the document is over the {} document limit", megabytes(limit))
206    })
207    .await?;
208
209    // The CAD app writes history JSON. Refusing a body that is not JSON keeps
210    // a truncated upload from becoming a revision's content.
211    if serde_json::from_str::<serde_json::Value>(&body).is_err() {
212        return Err(Error::bad_request("a document must be JSON"));
213    }
214
215    // `If-Match: <content hash>`: write only over that document (a client
216    // retrying a save that failed, based on what it last read).
217    let if_match = headers
218        .get(axum::http::header::IF_MATCH)
219        .and_then(|v| v.to_str().ok())
220        .map(|v| v.trim().trim_matches('"').to_string())
221        .filter(|v| !v.is_empty());
222    // The uses list is derived from the document in the same write
223    // (`derived-uses`); why it was not, when it was not, rides the answer.
224    let (seq, uses_refused) = db.write_document_deriving(&part_id, &revision_id, &body, if_match.as_deref())?;
225    Ok(Json(serde_json::json!({
226        "ok": true,
227        "seq": seq,
228        "uses_refused": uses_refused,
229        "content_hash": db.read(|state|state.part(&part_id).and_then(|p|p.revision(&revision_id)).map(|r|r.content_hash.clone()).unwrap_or_default()),
230        "size": body.len(),
231    }))
232    .into_response())
233}
234
235pub async fn delete_doc(
236    State(db): State<Shared>,
237    headers: HeaderMap,
238    Path(key): Path<String>,
239) -> Result<Response, Error> {
240    let user = require_user(&db, &headers)?;
241    let (part_id, revision_id) = split_key(&key)?;
242    guard_writable(&db, &user, &part_id, &revision_id)?;
243    db.remove_document(&key)?;
244    db.mutate(|state| {
245        if let Some(revision) = state.parts.get_mut(&part_id)
246            .and_then(|p| p.revision_mut(&revision_id))
247        {
248            revision.content_hash.clear();
249            revision.size = 0;
250            revision.modified_at = crate::db::now();
251        }
252        crate::review::document_changed(state, &part_id, &revision_id);
253        Ok(())
254    })?;
255    Ok(super::ok_seq(&db))
256}
257
258/// The two conditions a document write rests on, checked together so the
259/// message can say which one failed ([`crate::db::check_writable`], which the
260/// uses list is written under too).
261fn guard_writable(
262    db: &crate::db::Db,
263    user: &crate::model::User,
264    part_id: &str,
265    revision_id: &str,
266) -> Result<(), Error> {
267    db.read(|state| crate::db::check_writable(state, user, part_id, revision_id))
268}
269
270/// A request body as text, refused with a `413` and `refusal()`'s sentence
271/// past `limit` bytes — read here rather than through axum's `String`
272/// extractor, whose 2 MB default answers a real model document with its own
273/// plain-text 413. A declared `Content-Length` over the limit is refused
274/// before anything is read. A body that is not UTF-8 cannot be JSON.
275pub(crate) async fn read_bounded(
276    headers: &HeaderMap,
277    body: Body,
278    limit: u64,
279    refusal: impl Fn() -> String,
280) -> Result<String, Error> {
281    let too_large = || Error { status: StatusCode::PAYLOAD_TOO_LARGE, message: refusal() };
282    let declared = headers
283        .get(header::CONTENT_LENGTH)
284        .and_then(|v| v.to_str().ok())
285        .and_then(|v| v.parse::<u64>().ok());
286    if declared.is_some_and(|length| length > limit) {
287        return Err(too_large());
288    }
289    let mut bytes = Vec::with_capacity(declared.unwrap_or(0) as usize);
290    let mut body = body;
291    while let Some(chunk) = super::body_io::next_chunk(&mut body).await {
292        let chunk = chunk.map_err(|e| Error::bad_request(format!("the request body broke off: {e}")))?;
293        if bytes.len() as u64 + chunk.len() as u64 > limit {
294            return Err(too_large());
295        }
296        bytes.extend_from_slice(&chunk);
297    }
298    String::from_utf8(bytes).map_err(|_| Error::bad_request("the body must be JSON, and it is not UTF-8 text"))
299}
300
301/// `limit` as a person reads it: whole megabytes, else kilobytes.
302pub(crate) fn megabytes(limit: u64) -> String {
303    const MB: u64 = 1024 * 1024;
304    if limit >= MB && limit % MB == 0 { format!("{} MB", limit / MB) } else { format!("{} KB", limit.div_ceil(1024)) }
305}