Skip to main content

brep_plm/api/
mod.rs

1//! The HTTP surface: the router, the session cookie, and the helpers every
2//! handler shares.
3//!
4//! Two families of route live here and they answer different callers:
5//!
6//! * `/api/...` — the PLM itself: accounts, part types, the catalog, parts,
7//!   revisions, uses lists, BOMs and where-used, families and templates,
8//!   the bake queue, sourcing and settings.
9//!   The browser page in `web/` is its only client today.
10//! * `/api/store/...` — the DOCUMENT surface, shaped to what the CAD app's
11//!   `StoreBackend` needs from a remote backend (see [`store`]).
12//!
13//! Every handler that changes anything returns the new `seq`, so a client
14//! never has to ask a second question to find out whether its cache is stale.
15
16pub mod accounts;
17pub mod attachments;
18pub mod audit_log;
19pub mod backups;
20pub mod bake_worker;
21pub mod bom;
22mod bom_config;
23mod frontend;
24pub mod cad;
25pub mod catalog;
26pub mod family;
27pub mod parts;
28pub mod preferences;
29pub mod review;
30pub mod scripts;
31pub mod credentials;
32pub mod eco;
33pub mod settings;
34pub mod setup;
35pub mod workflow;
36pub mod thumbnails;
37pub mod sourcing;
38pub mod store;
39pub mod workspace;
40pub mod native_import;
41
42use std::sync::Arc;
43
44use std::net::SocketAddr;
45
46use axum::extract::{ConnectInfo, Request, State};
47use axum::http::{header, HeaderMap, Method, StatusCode};
48use axum::middleware::Next;
49use axum::response::{IntoResponse, Response};
50use axum::routing::{delete, get, patch, post, put};
51use axum::Router;
52
53use crate::db::{self, Db};
54use crate::audit;
55use crate::model::{Actor, TokenScope, User};
56use crate::security::{self, Credential};
57use crate::Error;
58
59/// The cookie the browser session rides in.
60pub const SESSION_COOKIE: &str = "plm_session";
61
62/// The header a browser request that changes anything carries its session's
63/// CSRF token in ([`crate::security`]).
64pub const CSRF_HEADER: &str = "x-csrf-token";
65
66/// Shared handler state.
67pub type Shared = Arc<Db>;
68
69/// Build the whole router.
70pub fn router(db: Shared) -> Router {
71    Router::new()
72        // -- the page ------------------------------------------------------
73        .route("/", get(frontend::index))
74        .route("/*path", get(frontend::file))
75        // -- the hosted CAD app and the server describing itself -----------
76        .route("/cad", get(cad::entry))
77        .route("/cad/", get(cad::entry))
78        .route("/cad/app", get(cad::entry))
79        .route("/cad/app/", get(cad::entry))
80        .route("/cad/app/*path", get(cad::file))
81        .route("/cad/config", get(cad::config))
82        .route("/api/setup/import", post(setup::import))
83        .route("/api/setup/kicad-libraries", get(setup::kicad_libraries))
84        .route("/api/setup/kicad-part-type", post(setup::kicad_part_type))
85        .route("/api/setup/kicad-taxonomy", post(setup::kicad_taxonomy))
86        .route("/api/workflows", get(workflow::definitions).post(workflow::save))
87        .route("/api/workflow-runs", get(workflow::runs).post(workflow::start))
88        .route("/api/workflow-runs/:id", get(workflow::detail))
89        .route("/api/workflow-runs/:id/actions", post(workflow::act))
90        .route("/api/workflow-runs/:id/control", post(workflow::control))
91        // -- accounts ------------------------------------------------------
92        .route("/api/login", post(accounts::login))
93        .route("/api/logout", post(accounts::logout))
94        .route("/api/me", get(accounts::me))
95        .route("/api/me/preferences", get(preferences::list))
96        .route(
97            "/api/me/preferences/:key",
98            get(preferences::read).put(preferences::write).delete(preferences::remove),
99        )
100        .route("/api/users", get(accounts::list_users).post(accounts::create_user))
101        .route("/api/users/:id", patch(accounts::update_user))
102        .route("/api/users/:id/sign-out", post(credentials::sign_out_user))
103        // -- credentials ---------------------------------------------------
104        .route("/api/me/password", post(credentials::change_password))
105        .route("/api/logout-all", post(credentials::logout_all))
106        .route("/api/tokens", get(credentials::list_tokens).post(credentials::create_token))
107        .route("/api/tokens/:id", delete(credentials::revoke_token))
108        .route(
109            "/api/security/lockouts",
110            get(credentials::list_lockouts).delete(credentials::clear_lockouts),
111        )
112        .route(
113            "/api/part-types",
114            get(accounts::list_part_types).post(accounts::create_part_type),
115        )
116        .route("/api/part-types/:id", patch(accounts::update_part_type))
117        .route("/api/part-types/:id/fields", get(bom_config::type_fields).put(bom_config::set_type_fields))
118        .route("/api/bom/configuration", get(bom_config::configuration))
119        .route("/api/bom/occurrence-fields", axum::routing::put(bom_config::set_occurrence_fields))
120        .route("/api/bom/layouts", post(bom_config::save_layout))
121        .route("/api/bom/layouts/:id", delete(bom_config::delete_layout))
122        .route("/api/bom/selection", axum::routing::put(bom_config::select_layout))
123        .route("/api/parts/:id/revisions/:rev/attributes", get(bom_config::revision_attributes).patch(bom_config::patch_revision_attributes))
124        .route("/api/parts/:id/revisions/:rev/occurrences", patch(bom_config::patch_occurrences))
125        // -- parts and revisions -------------------------------------------
126        .route("/api/parts", get(parts::list_parts).post(parts::create_part))
127        .route("/api/parts/:id", get(parts::get_part).patch(parts::update_part))
128        .route("/api/parts/:id/revisions", post(parts::create_revision))
129        .route("/api/parts/:id/revisions/:rev/checkout", post(parts::checkout))
130        .route("/api/parts/:id/revisions/:rev/checkin", post(parts::checkin))
131        .route("/api/parts/:id/revisions/:rev/state", post(parts::set_state))
132        .route("/api/parts/:id/revisions/:rev", delete(parts::delete_revision))
133        // -- review and approval -------------------------------------------
134        .route("/api/parts/:id/revisions/:rev/submit", post(review::submit))
135        .route(
136            "/api/parts/:id/revisions/:rev/review",
137            get(review::get_review).patch(review::change),
138        )
139        .route("/api/parts/:id/revisions/:rev/review/decision", post(review::decide))
140        .route("/api/parts/:id/revisions/:rev/comments", post(review::comment))
141        .route("/api/inbox", get(review::inbox))
142        // -- change orders -------------------------------------------------
143        .route("/api/ecos", get(eco::list).post(eco::create))
144        .route("/api/ecos/numbering", get(eco::numbering).patch(eco::set_numbering))
145        .route("/api/ecos/:id", get(eco::get).patch(eco::update))
146        .route("/api/ecos/:id/items", post(eco::add_item))
147        .route("/api/ecos/:id/items/:rev", delete(eco::remove_item))
148        .route("/api/ecos/:id/submit", post(eco::submit))
149        .route("/api/ecos/:id/withdraw", post(eco::withdraw))
150        .route("/api/ecos/:id/cancel", post(eco::cancel))
151        .route("/api/ecos/:id/release", post(eco::release))
152        .route("/api/ecos/:id/review", patch(eco::change_review))
153        .route("/api/ecos/:id/review/decision", post(eco::decide))
154        .route("/api/ecos/:id/comments", post(eco::comment))
155        // -- assembly structure: uses lists, BOMs and where-used -----------
156        .route(
157            "/api/parts/:id/revisions/:rev/uses",
158            get(bom::get_uses).put(bom::put_uses),
159        )
160        .route("/api/parts/:id/revisions/:rev/bom", get(bom::get_bom))
161        .route("/api/parts/:id/revisions/:rev/import", put(native_import::write))
162        .route("/api/import/validate", post(native_import::validate))
163        .route("/api/parts/:id/bom/diff", get(bom::diff))
164        .route("/api/parts/:id/where-used", get(bom::where_used))
165        .route("/api/parts/:id/replace", post(bom::replace))
166        // -- attachments ------------------------------------------------------
167        .route(
168            "/api/parts/:id/attachments",
169            get(attachments::list).post(attachments::upload_to_part),
170        )
171        .route("/api/parts/:id/revisions/:rev/attachments", post(attachments::upload_to_revision))
172        // -- thumbnails -------------------------------------------------------
173        .route(
174            "/api/parts/:id/revisions/:rev/thumbnail",
175            get(thumbnails::get_revision).put(thumbnails::put),
176        )
177        .route("/api/parts/:id/thumbnail", get(thumbnails::get_part))
178        .route(
179            "/api/attachments/:id",
180            get(attachments::download).put(attachments::replace).delete(attachments::remove),
181        )
182        .route("/api/attachments/:id/info", get(attachments::info))
183        // -- backups and exports (administrators) ---------------------------
184        .route("/api/admin/backups", get(backups::status).post(backups::run))
185        .route("/api/admin/backups/file/:name", get(backups::saved_file))
186        .route("/api/admin/backup", get(backups::download))
187        .route("/api/admin/export", get(backups::export))
188        // -- families, templates and the bake queue ------------------------
189        .route("/api/parts/:id/family", get(family::family))
190        .route("/api/parts/:id/family/import", post(family::import))
191        .route("/api/parts/:id/generate", post(family::generate))
192        .route("/api/parts/:id/template", get(family::template))
193        .route("/api/parts/:id/spin-out", post(family::spin_out))
194        .route("/api/bake/jobs", get(family::jobs))
195        .route("/api/bake/jobs/progress", post(family::progress))
196        .route("/api/bake/worker", get(bake_worker::status))
197        .route("/api/bake/worker/start", post(bake_worker::start))
198        .route("/api/bake/worker/stop", post(bake_worker::stop))
199        .route("/api/bake/resave", post(family::resave))
200        .route("/api/bake/next", post(family::next))
201        .route("/api/bake/jobs/:id/claim", post(family::claim))
202        .route("/api/bake/jobs/:id/renew", post(family::renew))
203        .route("/api/bake/jobs/:id/result", put(family::result))
204        .route("/api/bake/jobs/:id/fail", post(family::fail))
205        .route("/api/bake/jobs/:id/retry", post(family::retry))
206        .route("/api/parts/:id/sourcing", post(sourcing::add_manufacturer_part))
207        .route(
208            "/api/parts/:id/sourcing/:mp",
209            patch(sourcing::update_manufacturer_part).delete(sourcing::delete_manufacturer_part),
210        )
211        .route("/api/parts/:id/sourcing/:mp/offers", post(sourcing::add_offer))
212        .route(
213            "/api/parts/:id/sourcing/:mp/offers/:offer",
214            patch(sourcing::update_offer).delete(sourcing::delete_offer),
215        )
216        // -- sourcing: who makes parts and who sells them -----------------
217        .route(
218            "/api/manufacturers",
219            get(sourcing::list_manufacturers).post(sourcing::create_manufacturer),
220        )
221        .route(
222            "/api/manufacturers/:id",
223            patch(sourcing::update_manufacturer).delete(sourcing::delete_manufacturer),
224        )
225        .route("/api/suppliers", get(sourcing::list_suppliers).post(sourcing::create_supplier))
226        .route(
227            "/api/suppliers/:id",
228            patch(sourcing::update_supplier).delete(sourcing::delete_supplier),
229        )
230        // -- the catalog ---------------------------------------------------
231        .route("/api/categories", get(catalog::list).post(catalog::create))
232        .route(
233            "/api/categories/:id",
234            patch(catalog::update).delete(catalog::remove),
235        )
236        .route("/api/categories/:id/schema", get(catalog::schema))
237        // -- the administrator's settings ----------------------------------
238        .route("/api/settings", get(settings::get).patch(settings::update))
239        // -- the administrator's scripts -----------------------------------
240        .route("/api/scripts", get(scripts::list))
241        .route("/api/scripts/run", post(scripts::run))
242        .route(
243            "/api/scripts/file/*path",
244            get(scripts::read).put(scripts::write).delete(scripts::remove),
245        )
246        // -- the document surface the CAD app will consume -----------------
247        .route("/api/store/index", get(store::index))
248        .route("/api/store/changes", get(store::changes))
249        .route("/api/store/doc/*key", get(store::read_doc))
250        .route("/api/store/doc/*key", put(store::write_doc))
251        .route("/api/store/doc/*key", delete(store::delete_doc))
252        // -- the audit log -------------------------------------------------
253        .route("/api/audit", get(audit_log::query))
254        .route("/api/parts/:id/history", get(audit_log::part_history))
255        // -- workspaces: each user's folders of links and files -------------
256        .route("/api/workspaces", get(workspace::list_workspaces))
257        .route("/api/workspace/entries", get(workspace::list_folder))
258        .route("/api/workspace/folders", post(workspace::create_folder))
259        .route("/api/workspace/links", post(workspace::create_link))
260        .route("/api/workspace/files", post(workspace::create_file))
261        .route(
262            "/api/workspace/entries/:id",
263            get(workspace::get_entry).patch(workspace::update_entry).delete(workspace::delete_entry),
264        )
265        .route(
266            "/api/workspace/entries/:id/content",
267            get(workspace::download).put(workspace::replace_file),
268        )
269        .route("/api/workspace/entries/:id/versions", get(workspace::versions))
270        .route("/api/workspace/entries/:id/versions/:version/restore", post(workspace::restore))
271        .route("/api/workspace/entries/:id/promote", post(workspace::promote))
272        .layer(axum::middleware::from_fn_with_state(Arc::clone(&db), guard))
273        .with_state(db)
274}
275
276// ===========================================================================
277// Sessions
278// ===========================================================================
279
280/// The session token the request carries, if any.
281pub fn session_token(headers: &HeaderMap) -> Option<String> {
282    let raw = headers.get(header::COOKIE)?.to_str().ok()?;
283    raw.split(';').find_map(|pair| {
284        let (name, value) = pair.split_once('=')?;
285        (name.trim() == SESSION_COOKIE).then(|| value.trim().to_string())
286    })
287}
288
289/// Who a request is, once its credential has been checked.
290#[derive(Debug, Clone)]
291pub struct Identity {
292    pub user: User,
293    /// The session token, for a browser.
294    pub session: Option<String>,
295    /// The API token's id and scope, for anything else.
296    pub token: Option<(String, TokenScope)>,
297}
298
299/// The signed-in user, or a 401. A browser session or an API token
300/// ([`crate::security`]) — the handler does not care which.
301pub fn require_user(db: &Db, headers: &HeaderMap) -> Result<User, Error> {
302    identify(db, headers).map(|identity| identity.user)
303}
304
305/// Check the request's credential and say who it is.
306///
307/// A session expires after [`crate::model::Settings::session_idle_minutes`]
308/// without a request, and [`crate::model::Settings::session_max_hours`] after
309/// sign-in however busy it is. Both are checked on every request, so nothing
310/// has to sweep. Touching `last_seen` costs a metadata write, so it is
311/// re-stamped at most once a minute.
312pub fn identify(db: &Db, headers: &HeaderMap) -> Result<Identity, Error> {
313    match security::credential(headers) {
314        None => Err(Error::unauthorized("not signed in")),
315        Some(Credential::Bearer(secret)) => identify_token(db, &secret),
316        Some(Credential::Session(token)) => identify_session(db, &token),
317    }
318}
319
320fn identify_session(db: &Db, token: &str) -> Result<Identity, Error> {
321    let now = db::now();
322    let outcome = db.read(|state| {
323        let session = state.sessions.get(token)?;
324        let user = state.user(&session.user_id)?;
325        Some((session.last_seen, db::session_expired(&state.settings, session, now), user.clone()))
326    });
327    let Some((last_seen, expired, user)) = outcome else {
328        return Err(Error::unauthorized("session has expired"));
329    };
330    if expired {
331        let token = token.to_string();
332        let _ = db.mutate(move |state| {
333            state.sessions.retain(|s| s.token != token);
334            Ok(())
335        });
336        return Err(Error::unauthorized("session has expired"));
337    }
338    if !user.active {
339        return Err(Error::forbidden("this account is disabled"));
340    }
341    if now.saturating_sub(last_seen) > 60 {
342        let token = token.to_string();
343        let _ = db.mutate(move |state| {
344            if let Some(session) = state.sessions.get_mut(&token) {
345                session.last_seen = now;
346            }
347            Ok(())
348        });
349    }
350    Ok(Identity { user, session: Some(token.to_string()), token: None })
351}
352
353fn identify_token(db: &Db, secret: &str) -> Result<Identity, Error> {
354    let hash = security::token_hash(secret);
355    let found = db.read(|state| {
356        let token = state.api_tokens.iter().find(|t| security::same_secret(&t.hash, &hash))?;
357        let user = state.user(&token.user_id)?;
358        Some((token.clone(), user.clone()))
359    });
360    let Some((token, user)) = found else {
361        return Err(Error::unauthorized("that API token is not valid"));
362    };
363    let now = db::now();
364    if token.expires_at.is_some_and(|at| at <= now) {
365        return Err(Error::unauthorized("that API token has expired"));
366    }
367    if !user.active {
368        return Err(Error::forbidden("this account is disabled"));
369    }
370    if token.last_used_at.is_none_or(|at| now.saturating_sub(at) > 60) {
371        let id = token.id.clone();
372        let _ = db.mutate(move |state| {
373            if let Some(t) = state.api_tokens.iter_mut().find(|t| t.id == id) {
374                t.last_used_at = Some(now);
375            }
376            Ok(())
377        });
378    }
379    Ok(Identity { user, session: None, token: Some((token.id, token.scope)) })
380}
381
382/// The `Set-Cookie` value that starts a browser session.
383pub fn session_cookie(db: &Db, headers: &HeaderMap, token: &str) -> String {
384    let settings = db.settings();
385    let max_age = if settings.session_max_hours > 0 {
386        settings.session_max_hours * 3600
387    } else {
388        settings.session_idle_minutes * 60
389    };
390    let secure = if db.security().config.cookie_is_secure(headers) { "; Secure" } else { "" };
391    // HttpOnly so script cannot read it; SameSite=Lax so another site's form
392    // post does not carry it. Secure per `--secure-cookies`.
393    format!("{SESSION_COOKIE}={token}; HttpOnly; SameSite=Lax; Path=/; Max-Age={max_age}{secure}")
394}
395
396/// The `Set-Cookie` value that ends one.
397pub fn clear_cookie(db: &Db, headers: &HeaderMap) -> String {
398    let secure = if db.security().config.cookie_is_secure(headers) { "; Secure" } else { "" };
399    format!("{SESSION_COOKIE}=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0{secure}")
400}
401
402/// Every request passes through here before its handler.
403///
404/// * A request with an API token is refused if the token is not valid, or if
405///   its scope does not allow the request ([`security::scope_refusal`]).
406/// * A request that changes anything and rides a session cookie must carry the
407///   session's CSRF token in `X-CSRF-Token`. `/api/login` is exempt — there is
408///   no session yet, and it only takes a JSON body, which another site's form
409///   cannot send.
410/// * Every response gets the security headers ([`security::security_headers`]).
411///
412/// The request then runs as its [`Actor`], so the audit log can say who made
413/// every change it causes ([`crate::audit`]).
414pub async fn guard(State(db): State<Shared>, request: Request, next: Next) -> Response {
415    let path = request.uri().path().to_string();
416    let api = path.starts_with("/api/");
417    let secure = db.security().config.is_secure_request(request.headers());
418    if api {
419        if let Err(error) = check_request(&db, request.method(), &path, request.headers()) {
420            let mut response = error.into_response();
421            security::security_headers(response.headers_mut(), secure, true);
422            return response;
423        }
424    }
425    let peer = request.extensions().get::<ConnectInfo<SocketAddr>>().map(|ConnectInfo(addr)| addr.ip());
426    let actor = actor_of(&db, request.headers(), peer);
427    let mut response = audit::scope(actor, next.run(request)).await;
428    // The hosted CAD app answers with its own policy ([`crate::cad`]); every
429    // other response gets the PLM's, whatever its handler set.
430    let own_policy = if path.starts_with(crate::cad::PREFIX) {
431        response.headers_mut().remove(header::CONTENT_SECURITY_POLICY)
432    } else {
433        None
434    };
435    let inline_document = response.status().is_success()
436        && (path.starts_with("/api/attachments/") || path.starts_with("/api/workspace/entries/"))
437        && response.headers().get(header::CONTENT_DISPOSITION).and_then(|v| v.to_str().ok()).is_some_and(|v| v.starts_with("inline;"))
438        && response.headers().get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).is_some_and(|mime| mime == "application/pdf");
439    security::security_headers(response.headers_mut(), secure, api);
440    if inline_document {
441        response.headers_mut().insert(header::CONTENT_SECURITY_POLICY, axum::http::HeaderValue::from_static("default-src 'none'; frame-ancestors 'self'; base-uri 'none'"));
442        response.headers_mut().insert("x-frame-options", axum::http::HeaderValue::from_static("SAMEORIGIN"));
443    }
444    if let Some(policy) = own_policy {
445        response.headers_mut().insert(header::CONTENT_SECURITY_POLICY, policy);
446    }
447    response
448}
449
450/// Who a request is, for the audit log: read-only, and without the expiry
451/// checks — the handler still decides whether the credential is good, and a
452/// session that expires during this request is logged as ended by its owner.
453pub fn actor_of(db: &Db, headers: &HeaderMap, peer: Option<std::net::IpAddr>) -> Actor {
454    let ip = db.security().config.client_ip(headers, peer).map(|ip| ip.to_string()).unwrap_or_default();
455    let found = match security::credential(headers) {
456        Some(Credential::Session(token)) => db.read(|state| {
457            let session = state.sessions.iter().find(|s| s.token == token)?;
458            let user = state.user(&session.user_id)?;
459            Some((user.id.clone(), user.username.clone(), "session"))
460        }),
461        Some(Credential::Bearer(secret)) => {
462            let hash = security::token_hash(&secret);
463            db.read(|state| {
464                let token = state.api_tokens.iter().find(|t| security::same_secret(&t.hash, &hash))?;
465                let user = state.user(&token.user_id)?;
466                Some((user.id.clone(), user.username.clone(), "token"))
467            })
468        }
469        None => None,
470    };
471    match found {
472        Some((user_id, username, via)) => Actor { user_id, username, via: via.into(), ip },
473        None => Actor { ip, ..Actor::system() },
474    }
475}
476
477fn check_request(db: &Db, method: &Method, path: &str, headers: &HeaderMap) -> Result<(), Error> {
478    match security::credential(headers) {
479        Some(Credential::Bearer(secret)) => {
480            let identity = identify_token(db, &secret)?;
481            if let Some((_, scope)) = identity.token {
482                if let Some(refusal) = security::scope_refusal(scope, method, path) {
483                    return Err(Error::forbidden(refusal));
484                }
485            }
486            Ok(())
487        }
488        Some(Credential::Session(token)) if security::is_mutating(method) && path != "/api/login" => {
489            let expected = db.read(|state| {
490                state.sessions.iter().find(|s| s.token == token).map(|s| s.csrf.clone())
491            });
492            // No such session: the handler answers 401 as it always has.
493            let Some(expected) = expected else { return Ok(()) };
494            let sent = headers.get(CSRF_HEADER).and_then(|v| v.to_str().ok()).unwrap_or("");
495            if expected.is_empty() || !security::same_secret(&expected, sent) {
496                return Err(Error::forbidden(
497                    "this request is missing its CSRF token — reload the page and try again",
498                ));
499            }
500            Ok(())
501        }
502        _ => Ok(()),
503    }
504}
505
506/// The signed-in user, who must be an administrator.
507pub fn require_admin(db: &Db, headers: &HeaderMap) -> Result<User, Error> {
508    let user = require_user(db, headers)?;
509    if !user.is_admin() {
510        return Err(Error::forbidden("this needs the admin group"));
511    }
512    Ok(user)
513}
514
515/// The signed-in user, who must be able to create and edit work.
516pub fn require_author(db: &Db, headers: &HeaderMap) -> Result<User, Error> {
517    let user = require_user(db, headers)?;
518    if !user.can_author() {
519        return Err(Error::forbidden("this needs the author group"));
520    }
521    Ok(user)
522}
523
524/// Run `work` on the blocking pool. Anything that may call a script goes
525/// through here: a hook can wait on the network or a child process, and that
526/// wait must not stall the async runtime's worker threads.
527///
528/// The request's actor goes with the work, so a change made on the blocking
529/// pool is logged as the caller's.
530pub async fn blocking<R: Send + 'static>(
531    work: impl FnOnce() -> Result<R, Error> + Send + 'static,
532) -> Result<R, Error> {
533    let actor = audit::current_actor();
534    tokio::task::spawn_blocking(move || audit::as_actor(actor, work))
535        .await
536        .map_err(Error::internal)?
537}
538
539/// `{ "ok": true, "seq": n }` — the shape every mutating handler answers with.
540pub fn ok_seq(db: &Db) -> Response {
541    let seq = db.read(|state| state.seq);
542    axum::Json(serde_json::json!({ "ok": true, "seq": seq })).into_response()
543}
544
545/// A tiny health probe, useful before the page exists.
546pub async fn health(State(db): State<Shared>) -> Response {
547    let (users, parts, seq) = db.read(|s| (s.users.len(), s.parts.len(), s.seq));
548    (
549        StatusCode::OK,
550        axum::Json(serde_json::json!({
551            "ok": true, "users": users, "parts": parts, "seq": seq,
552        })),
553    )
554        .into_response()
555}