Skip to main content

printobserver_server/
api.rs

1//! The HTTP surface, built by folding over the declared operations.
2//!
3//! # The router is the declaration
4//!
5//! Nothing here writes a route out. [`router`] walks
6//! [`OPERATIONS`](crate::operations::OPERATIONS) and registers one route per
7//! entry beneath the one versioned prefix, so the set served and the set
8//! declared cannot come apart — and the ten mutating operations share one
9//! handler which is given the [`ActionKind`] its own entry declares, so a
10//! request cannot reach an action the operation it was sent to does not name.
11//! The five spool commands share one handler of their own on the same terms.
12//!
13//! # Every action takes the same one path
14//!
15//! An action asked for here goes to
16//! [`Supervisor::request_action`](printobserver_core::Supervisor::request_action),
17//! which is the same call an operator's action makes and an agent's action
18//! makes. The policy is not re-implemented here and is not bypassed here: a
19//! rejected request answers the rejection the policy made, carrying its reason,
20//! the value asked for and the range allowed, and reaches no action method of
21//! the printer port at all.
22//!
23//! # Nothing is served to a caller that did not present a credential
24//!
25//! Every route beneath the versioned prefix — and the prefix's own fallback, so
26//! that a path nothing serves is refused the same way — sits behind
27//! [`authenticate`], which runs before any extractor reads a path, a query or a
28//! body. A request whose `Authorization` header is not exactly
29//! `Bearer <credential>`, for the operator's credential or a live supervision
30//! turn's, is answered `401` there, so it reaches no handler, no store, no
31//! printer port and no record. There is no route that skips it and no
32//! configuration that turns it off: [`ApiState`] cannot be built without what
33//! a credential is checked against.
34//!
35//! # Every request is the identity its credential authenticated
36//!
37//! What [`authenticate`] admitted is a [`Caller`]: the operator, or one turn —
38//! the agent, in one session, on one print. Every handler is given it, and the
39//! body's `actor` is a claim held to it **before** the policy is asked
40//! anything: a claim that is not the caller — an operator credential claiming
41//! to be the agent, a turn claiming to be the operator or another session, and
42//! anybody claiming to be the system, whose actions are the server's own — is
43//! refused `403` naming both, and nothing is decided or recorded. A turn's
44//! credential reaches its own print alone, the listing of prints beside it,
45//! and neither of the two writes that are not about a running print: starting
46//! one and replacing a manifest. So the class the policy rules on, and the
47//! agent's minimum interval with it, is the one the credential authenticated
48//! rather than the one the request claimed.
49//!
50//! The spool ledger is the printer's rather than one print's, so its four
51//! reads are open to every caller — a turn included, which is how the agent
52//! reads what is loaded and what a file needs — and its commands are held to
53//! the same claim and then to the envelope's own grants, which the domain rules
54//! on and records.
55//!
56//! The recovery operations are the printer's too: their read is open to every
57//! caller, answering what each action would meet for that caller, and each
58//! action is held to the same claim and then to the recovery grants and the
59//! machine's own state, which the domain rules on and records.
60
61use std::sync::Arc;
62use std::time::Duration;
63
64use axum::Json;
65use axum::extract::rejection::JsonRejection;
66use axum::extract::{DefaultBodyLimit, Extension, Path, Query, Request, State};
67use axum::http::{StatusCode, header};
68use axum::middleware::{Next, from_fn_with_state};
69use axum::response::{IntoResponse, Response};
70use axum::routing::{get, post, put};
71use axum::{Router, routing::MethodRouter};
72use printobserver_core::recovery::recovery_detail;
73use printobserver_core::store::TimelineQuery;
74use printobserver_core::store::{
75    EventStore, HistoryQuery, ImageStore, PrintStore, SessionStore, StoreError,
76};
77use printobserver_core::{
78    ActionKind, Actor, ActorClass, ExecutionOutcome, PolicyDecision, RecoveryActionKind,
79    RecoveryDecision, SheetId, SpoolId,
80};
81use printobserver_core::{CoreError, MAX_LOOK_WAIT_S, Supervisor, effective_bounds};
82use printobserver_types::serde::Deserialize;
83use printobserver_types::serde_json::Value;
84use printobserver_types::{EventId, EventKind, FileName, ImageId, PrintId, Timestamp};
85
86use crate::operations::{Effect, Method, OPERATIONS, Operation, VERSION_PREFIX};
87use crate::server::{CREDENTIAL_ISSUE, OperatorCredential};
88use crate::turns::{TurnBinding, TurnCredentials};
89use crate::wire::{
90    ActionAnswer, ActionBody, BedClearAnswer, BedClearBody, ContextAnswer, ErrorAnswer,
91    HistoryAnswer, ImageAnswer, ManifestAnswer, ManifestBody, PreflightAnswer, PrintsAnswer,
92    RecoveryAnswer, SpoolAnswer, SpoolCommandAnswer, SpoolsAnswer, StatusAnswer, TimelineAnswer,
93    claimed_actor, reason_of, recovery_of, spool_command_of,
94};
95
96/// What every handler is given: the supervisor, and the stores the reads
97/// answer out of — the four aggregates a route reads, and not the actions,
98/// which reach the store through the supervisor alone.
99#[derive(Clone)]
100pub struct ApiState {
101    /// The supervision core, which every action passes through.
102    pub supervisor: Arc<Supervisor>,
103    /// The print records, their manifests and their narrowings.
104    pub prints: Arc<dyn PrintStore>,
105    /// The event log.
106    pub events: Arc<dyn EventStore>,
107    /// The images stored beside the events.
108    pub images: Arc<dyn ImageStore>,
109    /// The supervision sessions.
110    pub sessions: Arc<dyn SessionStore>,
111    /// What the operator's credential is checked against before anything
112    /// above is reached.
113    pub operator: Arc<OperatorCredential>,
114    /// The live supervision turns' credentials, checked the same way.
115    pub turns: TurnCredentials,
116    /// The broadcast an events read waits on, raised once an event is stored.
117    pub stored: crate::events::Stored,
118}
119
120/// Who one request authenticated as.
121#[derive(Debug, Clone, PartialEq, Eq)]
122pub enum Caller {
123    /// The operator, by the credential the operator's verifier admits.
124    Operator,
125    /// One supervision turn's run: the agent, in one session, on one print.
126    Turn(TurnBinding),
127}
128
129impl Caller {
130    /// This caller, as a refusal names it.
131    fn named(&self) -> String {
132        match self {
133            Self::Operator => "the operator".to_owned(),
134            Self::Turn(binding) => format!(
135                "the agent in session `{}` on print {}",
136                binding.session_name(),
137                binding.print_id()
138            ),
139        }
140    }
141}
142
143/// One claimed actor, as a refusal names it.
144fn claimed(actor: &Actor) -> String {
145    match actor {
146        Actor::Operator => "the operator".to_owned(),
147        Actor::System => "the system".to_owned(),
148        Actor::Agent { session_name } => format!("the agent in session `{session_name}`"),
149    }
150}
151
152/// Refuse a claimed actor that is not the caller, before anything is decided.
153///
154/// The system is claimed by nobody: its actions are the server's own, and no
155/// credential this server admits is the server.
156fn claim_refused(caller: &Caller, actor: &Actor) -> Option<Response> {
157    let held = match (caller, actor) {
158        (Caller::Operator, Actor::Operator) => true,
159        (Caller::Turn(binding), Actor::Agent { session_name }) => {
160            *session_name == binding.session_name()
161        }
162        _ => false,
163    };
164    if held {
165        return None;
166    }
167    let why = if matches!(actor, Actor::System) {
168        "no credential may claim the system, whose actions are the server's own"
169    } else {
170        "a request acts as the identity its credential authenticated, and no other"
171    };
172    Some(refusal(
173        StatusCode::FORBIDDEN,
174        format!(
175            "this request authenticated as {} and claims to be {}: {why}",
176            caller.named(),
177            claimed(actor)
178        ),
179    ))
180}
181
182/// Refuse a turn's request about any print but its own.
183pub(crate) fn scope_refused(caller: &Caller, print_id: PrintId) -> Option<Response> {
184    match caller {
185        Caller::Turn(binding) if binding.print_id() != print_id => Some(refusal(
186            StatusCode::FORBIDDEN,
187            format!(
188                "this request authenticated as {} and names print {print_id}: a supervision \
189                 turn's credential reaches its own print alone",
190                caller.named()
191            ),
192        )),
193        _ => None,
194    }
195}
196
197/// Refuse a turn's request for something that belongs to no print: a turn's
198/// credential reaches its own print alone, and what belongs to none is the
199/// operator's.
200fn printless_refused(caller: &Caller, what: &str) -> Option<Response> {
201    match caller {
202        Caller::Turn(_) => Some(refusal(
203            StatusCode::FORBIDDEN,
204            format!(
205                "this request authenticated as {} and asks for {what}: a supervision turn's \
206                 credential reaches its own print alone",
207                caller.named()
208            ),
209        )),
210        Caller::Operator => None,
211    }
212}
213
214/// Refuse a turn's request for a write that is not about its running print:
215/// starting a print, and replacing a manifest, are the operator's alone.
216fn operator_refused(caller: &Caller, command: &str) -> Option<Response> {
217    match caller {
218        Caller::Turn(_) => Some(refusal(
219            StatusCode::FORBIDDEN,
220            format!(
221                "this request authenticated as {} and asks for `{command}`, which is the \
222                 operator's alone: a supervision turn's credential does not reach it",
223                caller.named()
224            ),
225        )),
226        Caller::Operator => None,
227    }
228}
229
230/// Refuse a turn's acknowledgement before the turn has taken a look.
231///
232/// The frames a turn's context names are already old when it reads them, so
233/// what a turn writes down of its event is judged from a look it took — or
234/// from the image it was handed, which counts as its look, because a turn
235/// handed one is allowed no other; the operator, who is not a turn, is held to
236/// nothing here.
237fn unlooked_refused(
238    turns: &TurnCredentials,
239    caller: &Caller,
240    print_id: PrintId,
241) -> Option<Response> {
242    match caller {
243        Caller::Turn(binding) if !turns.has_looked(binding) => Some(refusal(
244            StatusCode::FORBIDDEN,
245            format!(
246                "this request authenticated as {} and acknowledges an event before the turn \
247                 has taken a look: run `printobserver look --print-id {print_id}`, open the \
248                 frames it names, and acknowledge what they show",
249                caller.named()
250            ),
251        )),
252        _ => None,
253    }
254}
255
256/// What [`authenticate`] checks a presented credential against.
257#[derive(Clone)]
258pub struct Admission {
259    /// The operator's.
260    operator: Arc<OperatorCredential>,
261    /// The live turns'.
262    turns: TurnCredentials,
263}
264
265impl Admission {
266    /// Who a presented credential authenticates as, when it is anybody.
267    fn caller(&self, presented: &[u8]) -> Option<Caller> {
268        if let Some(binding) = self.turns.admit(presented) {
269            return Some(Caller::Turn(binding));
270        }
271        self.operator.admits(presented).then_some(Caller::Operator)
272    }
273}
274
275impl core::fmt::Debug for ApiState {
276    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
277        formatter.debug_struct("ApiState").finish_non_exhaustive()
278    }
279}
280
281/// How many events a history read asks for, when it asks for a number.
282#[derive(Debug, Clone, Deserialize)]
283#[serde(crate = "printobserver_types::serde")]
284pub struct HistoryParams {
285    /// The limit asked for; absent takes the port's own default window.
286    #[serde(default)]
287    pub limit: Option<u32>,
288}
289
290/// The event a context read is asked `since`: only the events newer than it
291/// are answered, because the caller has read the rest.
292#[derive(Debug, Clone, Deserialize)]
293#[serde(crate = "printobserver_types::serde")]
294pub struct ContextParams {
295    /// The newest event the caller has read; absent answers the recent window.
296    #[serde(default)]
297    pub since: Option<printobserver_types::EventId>,
298}
299
300/// How long a look asks to wait for something to arrive, in whole seconds.
301#[derive(Debug, Clone, Deserialize)]
302#[serde(crate = "printobserver_types::serde")]
303pub struct LookParams {
304    /// The wait asked for; absent looks at once.
305    #[serde(default)]
306    pub wait_s: Option<u32>,
307}
308
309/// Whether a spools read asks for the retired ones too.
310#[derive(Debug, Clone, Deserialize)]
311#[serde(crate = "printobserver_types::serde")]
312pub struct SpoolsParams {
313    /// Asked for; absent, the retired spools are left out.
314    #[serde(default)]
315    pub include_retired: Option<bool>,
316}
317
318/// The file a filament check is about, and the sheet it would go down on.
319#[derive(Debug, Clone, Deserialize)]
320#[serde(crate = "printobserver_types::serde")]
321pub struct PreflightParams {
322    /// The file, as the printer names it.
323    #[serde(default)]
324    pub file_name: Option<String>,
325    /// The build sheet the sheet check is read against; absent, the check
326    /// reports no sheet result, and a blank one is refused.
327    // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
328    #[serde(default)]
329    pub sheet: Option<String>,
330}
331
332/// How many of a spool's own events its read carries, newest first.
333pub const SPOOL_RECENT_EVENTS: u32 = 20;
334
335/// Every public operation, beneath the one versioned prefix.
336///
337/// # Panics
338///
339/// Panics when [`OPERATIONS`] declares an entry this function has no route for,
340/// which is a declaration and a router that have come apart — the one state
341/// this server must not come up in quietly.
342pub fn router(state: ApiState) -> Router {
343    let mut api = Router::new();
344    for operation in OPERATIONS {
345        api = api.route(operation.path, route_for(&operation));
346    }
347    // The layer is added after every route and the fallback, which is what
348    // puts all of them behind it.
349    let api = api
350        .fallback(nothing_here)
351        .layer(from_fn_with_state(
352            Admission {
353                operator: Arc::clone(&state.operator),
354                turns: state.turns.clone(),
355            },
356            authenticate,
357        ))
358        .layer(DefaultBodyLimit::max(BODY_BOUND))
359        .with_state(state);
360    Router::new().nest(VERSION_PREFIX, api)
361}
362
363/// The scheme the credential is presented under.
364const BEARER: &[u8] = b"Bearer ";
365
366/// How much of a request's body this server reads, admitted or refused.
367///
368/// One bound for both: the router's body limit is set from it, so it is what
369/// every extractor reads an admitted body to, and what [`authenticate`] drains
370/// a refused one to — a body the server would have taken is one it drains,
371/// and a larger one is left where it is either way.
372pub const BODY_BOUND: usize = 2 * 1024 * 1024;
373
374/// How long [`authenticate`] waits for a refused request's body to arrive.
375///
376/// A caller that sent a head and then nothing would otherwise hold its refusal
377/// open for as long as it liked; after this the refusal goes out over whatever
378/// arrived, and the connection ends as it did before there was a drain.
379pub const DRAIN_BOUND: Duration = Duration::from_secs(2);
380
381/// Admit a request that presented the operator's credential or a live turn's,
382/// hand every handler who it authenticated as, and refuse every other request
383/// before anything reads it.
384///
385/// Exactly one `Authorization` header, spelled `Bearer ` and then the
386/// credential. Two headers, another scheme, another spelling of this one, and a
387/// credential that is nobody's are all the same refusal, which says what to
388/// present and nothing about what was presented — and, on a server that has no
389/// operator credential yet, names the command that issues one.
390///
391/// The refusal is decided on the head alone, and the body is then drained, up
392/// to [`BODY_BOUND`], before it is answered. Nothing reads what is
393/// drained: a connection closed with a body still unread on it is closed with
394/// a reset rather than an end, and a caller on Windows — where a reset discards
395/// everything received and not yet read — then reads the abort in place of the
396/// `401` that was already on its way. Linux hands over what was queued first,
397/// which is why the same race is only ever seen there.
398pub async fn authenticate(
399    State(admission): State<Admission>,
400    mut request: Request,
401    next: Next,
402) -> Response {
403    let mut presented = request.headers().get_all(header::AUTHORIZATION).iter();
404    let admitted = match (presented.next(), presented.next()) {
405        (Some(only), None) => only
406            .as_bytes()
407            .strip_prefix(BEARER)
408            .and_then(|offered| admission.caller(offered)),
409        _ => None,
410    };
411    if let Some(caller) = admitted {
412        request.extensions_mut().insert(caller);
413        return next.run(request).await;
414    }
415    {
416        let said = if matches!(*admission.operator, OperatorCredential::Unconfigured) {
417            format!(
418                "this server's API requires a credential, presented as `Authorization: Bearer \
419                 <credential>`, and this server has no operator credential yet: run \
420                 `{CREDENTIAL_ISSUE}` as the operator, put the `api.credential_verifier` line it \
421                 prints into the server's configuration, and restart the service"
422            )
423        } else {
424            format!(
425                "this server's API requires the credential it is configured with, presented as \
426                 `Authorization: Bearer <credential>`. An operator without one runs \
427                 `{CREDENTIAL_ISSUE}`"
428            )
429        };
430        let mut refused = refusal(StatusCode::UNAUTHORIZED, said);
431        refused.headers_mut().insert(
432            header::WWW_AUTHENTICATE,
433            header::HeaderValue::from_static("Bearer"),
434        );
435        // A body past the bound, or one that has not arrived inside
436        // `DRAIN_BOUND`, is left where it is: the refusal is the answer either
437        // way, and what a caller then meets on the connection is its own doing.
438        let _ = tokio::time::timeout(
439            DRAIN_BOUND,
440            axum::body::to_bytes(request.into_body(), BODY_BOUND),
441        )
442        .await;
443        refused
444    }
445}
446
447/// A path beneath the versioned prefix that no operation serves.
448async fn nothing_here() -> Response {
449    refusal(
450        StatusCode::NOT_FOUND,
451        "no operation of this server is served at that path",
452    )
453}
454
455/// The route one declared operation is served by.
456fn route_for(operation: &Operation) -> MethodRouter<ApiState> {
457    if let Effect::Command(spool_command) = operation.effect {
458        let kind = spool_command.action_kind();
459        if operation.path.contains("{spool_id}") {
460            return post(
461                move |state: State<ApiState>,
462                      caller: Extension<Caller>,
463                      Path(spool_id): Path<SpoolId>,
464                      body: Result<Json<Value>, JsonRejection>| async move {
465                    command(kind, state, caller, Some(spool_id), body).await
466                },
467            );
468        }
469        return post(
470            move |state: State<ApiState>,
471                  caller: Extension<Caller>,
472                  body: Result<Json<Value>, JsonRejection>| async move {
473                command(kind, state, caller, None, body).await
474            },
475        );
476    }
477    if let Effect::Recovery(kind) = operation.effect {
478        return post(
479            move |state: State<ApiState>,
480                  caller: Extension<Caller>,
481                  body: Result<Json<Value>, JsonRejection>| async move {
482                recover(kind, state, caller, body).await
483            },
484        );
485    }
486    if let Effect::Mutating(kind) = operation.effect {
487        return post(
488            move |state: State<ApiState>,
489                  caller: Extension<Caller>,
490                  print_id: PrintPath,
491                  body: Result<Json<ActionBody>, JsonRejection>| async move {
492                act(kind, state, caller, print_id, body).await
493            },
494        );
495    }
496    match (operation.name, operation.method) {
497        ("prints", Method::Get) => get(list_and_adopt_prints),
498        ("status", Method::Get) => get(status),
499        ("context", Method::Get) => get(context),
500        ("image", Method::Get) => get(image),
501        ("history", Method::Get) => get(history),
502        ("events", Method::Get) => get(crate::events::events),
503        ("look", Method::Get) => get(look),
504        (crate::operations::PRINTER_LOOK, Method::Get) => get(printer_look),
505        ("manifest_get", Method::Get) => get(manifest_get),
506        ("manifest_set", Method::Put) => put(manifest_set),
507        ("spools", Method::Get) => get(spools),
508        ("spool", Method::Get) => get(spool),
509        ("printer_history", Method::Get) => get(printer_history),
510        ("preflight", Method::Get) => get(preflight),
511        (crate::operations::RECOVERY_STATUS, Method::Get) => get(recover_status),
512        (crate::operations::BED_CLEAR, Method::Post) => post(bed_clear),
513        (name, method) => panic!(
514            "the operation `{name}` is declared as {method} and this router serves no such route"
515        ),
516    }
517}
518
519/// One answer, rendered as JSON under the media type every operation answers in.
520pub(crate) fn answer<T: printobserver_types::serde::Serialize>(
521    status: StatusCode,
522    body: &T,
523) -> Response {
524    let rendered = match printobserver_types::serde_json::to_vec(body) {
525        Ok(bytes) => bytes,
526        Err(error) => {
527            return (
528                StatusCode::INTERNAL_SERVER_ERROR,
529                [(header::CONTENT_TYPE, crate::operations::MEDIA_TYPE)],
530                format!("{{\"error\":\"{error}\"}}"),
531            )
532                .into_response();
533        }
534    };
535    (
536        status,
537        [(header::CONTENT_TYPE, crate::operations::MEDIA_TYPE)],
538        rendered,
539    )
540        .into_response()
541}
542
543/// One refusal, rendered as JSON under the same media type.
544pub(crate) fn refusal(status: StatusCode, detail: impl core::fmt::Display) -> Response {
545    answer(status, &ErrorAnswer::saying(detail))
546}
547
548/// What a print id that names no print is refused with, after what was wrong
549/// with it: what to pass instead.
550pub(crate) const PRINT_ID_REFUSED: &str = "a print is named by its id, a UUID, as `printobserver prints` \
551lists it; a start with no print open may name none, and is made under one minted for it";
552
553/// The print a route's path names, refused in this server's own error shape,
554/// saying what to pass, when the path names no print at all.
555pub(crate) struct PrintPath(pub(crate) PrintId);
556
557impl<S: Send + Sync> axum::extract::FromRequestParts<S> for PrintPath {
558    type Rejection = Response;
559
560    async fn from_request_parts(
561        parts: &mut axum::http::request::Parts,
562        state: &S,
563    ) -> Result<Self, Self::Rejection> {
564        match Path::<PrintId>::from_request_parts(parts, state).await {
565            Ok(Path(print_id)) => Ok(Self(print_id)),
566            Err(rejected) => Err(refusal(
567                StatusCode::BAD_REQUEST,
568                format!("{}: {PRINT_ID_REFUSED}", rejected.body_text()),
569            )),
570        }
571    }
572}
573
574/// The status a store refusal is answered under.
575pub(crate) fn store_status(error: &StoreError) -> StatusCode {
576    match error {
577        StoreError::NotFound { .. } => StatusCode::NOT_FOUND,
578        StoreError::LimitRefused { .. } | StoreError::ConstraintRefused { .. } => {
579            StatusCode::BAD_REQUEST
580        }
581        StoreError::Database { .. } | StoreError::Io { .. } => StatusCode::INTERNAL_SERVER_ERROR,
582    }
583}
584
585/// The status a core refusal is answered under.
586fn core_status(error: &CoreError) -> StatusCode {
587    match error {
588        CoreError::NoSuchPrint { .. } => StatusCode::NOT_FOUND,
589        CoreError::Store(store) => store_status(store),
590        _ => StatusCode::INTERNAL_SERVER_ERROR,
591    }
592}
593
594/// Ask for one action of the vocabulary against one print.
595///
596/// Who may ask is settled before the policy is: a turn's credential reaches
597/// no start and no print but its own — whatever the body says, so those two
598/// answer `403` ahead of any rejection of the body itself — and the claimed
599/// actor is held to the caller. A
600/// request refused here is decided on by nothing and recorded nowhere.
601async fn act(
602    kind: ActionKind,
603    State(state): State<ApiState>,
604    Extension(caller): Extension<Caller>,
605    PrintPath(print_id): PrintPath,
606    body: Result<Json<ActionBody>, JsonRejection>,
607) -> Response {
608    if kind == ActionKind::StartPrint
609        && let Some(refused) =
610            operator_refused(&caller, &crate::operations::command_for("start_print"))
611    {
612        return refused;
613    }
614    if let Some(refused) = scope_refused(&caller, print_id) {
615        return refused;
616    }
617    let body = match body {
618        Ok(Json(body)) => body,
619        Err(rejected) => return rejected.into_response(),
620    };
621    if let Some(refused) = claim_refused(&caller, &body.actor) {
622        return refused;
623    }
624    if kind == ActionKind::AcknowledgeFailure
625        && let Some(refused) = unlooked_refused(&state.turns, &caller, print_id)
626    {
627        return refused;
628    }
629    let action = match body.into_action(kind) {
630        Ok(action) => action,
631        Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
632    };
633    let outcome = match state.supervisor.request_action(print_id, action).await {
634        Ok(outcome) => outcome,
635        Err(error) => return refusal(core_status(&error), error),
636    };
637    let printer_refusal = match &outcome.record.outcome {
638        Some(ExecutionOutcome::Failed { reason }) => Some(reason.clone()),
639        _ => None,
640    };
641    let status = match outcome.record.decision {
642        PolicyDecision::Accepted if printer_refusal.is_none() => StatusCode::OK,
643        // The policy accepted it and the machine did not. That is a request
644        // that was made and refused rather than one that never happened, so
645        // the record and the printer's own words are the answer.
646        PolicyDecision::Accepted => StatusCode::BAD_GATEWAY,
647        // The rejection itself is the answer: its reason, the value asked for
648        // and the range allowed are what let a caller ask again correctly.
649        PolicyDecision::Rejected(_) => StatusCode::CONFLICT,
650    };
651    answer(
652        status,
653        &ActionAnswer {
654            record: outcome.record,
655            intervention: outcome.intervention,
656            printer_refusal,
657        },
658    )
659}
660
661/// Ask the spool ledger for one command.
662///
663/// The claimed actor is held to the caller before anything else of the body is
664/// read, and a body with no reason is refused before the domain is asked —
665/// so a request refused here is recorded nowhere. Whether the actor may ask at
666/// all is the envelope's grant, which the domain rules on and records like
667/// every refusal: a supervision turn's agent is refused there, under the
668/// default grants, rather than here.
669async fn command(
670    kind: ActionKind,
671    State(state): State<ApiState>,
672    Extension(caller): Extension<Caller>,
673    spool_id: Option<SpoolId>,
674    body: Result<Json<Value>, JsonRejection>,
675) -> Response {
676    let body = match body {
677        Ok(Json(body)) => body,
678        Err(rejected) => return rejected.into_response(),
679    };
680    let Some(fields) = body.as_object() else {
681        return refusal(
682            StatusCode::BAD_REQUEST,
683            "a spool command's body is a document of its fields",
684        );
685    };
686    let actor = match claimed_actor(fields) {
687        Ok(actor) => actor,
688        Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
689    };
690    if let Some(refused) = claim_refused(&caller, &actor) {
691        return refused;
692    }
693    let asked = match spool_command_of(kind, spool_id, body) {
694        Ok(asked) => asked,
695        Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
696    };
697    let outcome = match state.supervisor.request_spool_command(asked).await {
698        Ok(outcome) => outcome,
699        Err(error) => return refusal(core_status(&error), error),
700    };
701    let status = match outcome.decision {
702        PolicyDecision::Accepted => StatusCode::OK,
703        // The refusal is the answer, exactly as a print action's is.
704        PolicyDecision::Rejected(_) => StatusCode::CONFLICT,
705    };
706    answer(
707        status,
708        &SpoolCommandAnswer {
709            decision: outcome.decision,
710            spool: outcome.spool,
711            events: outcome.events,
712        },
713    )
714}
715
716/// Ask the printer for one recovery action.
717///
718/// The body is held to the action's own fields, a reason and an actor before
719/// anything is decided, and the claimed actor to the caller — so a request
720/// refused here is recorded nowhere and reaches no printer. Whether the actor
721/// may ask, and whether the printer is in a state the action is safe from, is
722/// the supervision core's to rule on and record.
723async fn recover(
724    kind: RecoveryActionKind,
725    State(state): State<ApiState>,
726    Extension(caller): Extension<Caller>,
727    body: Result<Json<Value>, JsonRejection>,
728) -> Response {
729    let body = match body {
730        Ok(Json(body)) => body,
731        Err(rejected) => return rejected.into_response(),
732    };
733    if let Some(fields) = body.as_object() {
734        let actor = match claimed_actor(fields) {
735            Ok(actor) => actor,
736            Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
737        };
738        if let Some(refused) = claim_refused(&caller, &actor) {
739            return refused;
740        }
741    }
742    let (action, actor, reason) = match recovery_of(kind, body) {
743        Ok(asked) => asked,
744        Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
745    };
746    let issued = match state
747        .supervisor
748        .request_recovery(action.clone(), actor, reason)
749        .await
750    {
751        Ok(issued) => issued,
752        Err(error) => return refusal(core_status(&error), error),
753    };
754    let config = state.supervisor.config().recovery;
755    let status = match &issued.decision {
756        RecoveryDecision::Executed(ExecutionOutcome::Succeeded) => StatusCode::OK,
757        // The printer was asked and refused: a request that was made rather
758        // than one that never happened, answered with the printer's words.
759        RecoveryDecision::Executed(ExecutionOutcome::Failed { .. }) => StatusCode::BAD_GATEWAY,
760        // The refusal is the answer, as a print action's is.
761        RecoveryDecision::Rejected(_) => StatusCode::CONFLICT,
762    };
763    answer(
764        status,
765        &RecoveryAnswer {
766            detail: recovery_detail(&action, &issued.decision, config.as_ref()),
767            action,
768            decision: issued.decision,
769            events: vec![issued.requested, issued.settled],
770        },
771    )
772}
773
774/// What a recorded bed-clear means from now on, in a sentence for a person.
775pub const BED_CLEAR_DETAIL: &str = "recorded: until the next print starts, a Z home is decided \
776    as though it asserted the bed clear, and a heat, a park and an XY home as though they \
777    asserted the nozzle clear of the part, wherever the operator's word counts";
778
779/// Record the operator's word that the bed is clear.
780///
781/// The claimed actor is held to the caller before anything is written, and
782/// the one actor admitted is the operator: a turn claiming the operator, any
783/// claim to the system, and the agent's own word are each refused `403` and
784/// recorded nowhere. A reason that is absent or blank is refused before
785/// anything is written.
786async fn bed_clear(
787    State(state): State<ApiState>,
788    Extension(caller): Extension<Caller>,
789    body: Result<Json<Value>, JsonRejection>,
790) -> Response {
791    let body = match body {
792        Ok(Json(body)) => body,
793        Err(rejected) => return rejected.into_response(),
794    };
795    let Some(fields) = body.as_object() else {
796        return refusal(
797            StatusCode::BAD_REQUEST,
798            "the body is not a document carrying an `actor` and a `reason`",
799        );
800    };
801    let actor = match claimed_actor(fields) {
802        Ok(actor) => actor,
803        Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
804    };
805    if let Some(refused) = claim_refused(&caller, &actor) {
806        return refused;
807    }
808    if actor != Actor::Operator {
809        return refusal(
810            StatusCode::FORBIDDEN,
811            format!(
812                "{} may not say the bed is clear: an assertion is a person's word for what \
813                 they can see, and only the operator's is recorded",
814                claimed(&actor)
815            ),
816        );
817    }
818    let body: BedClearBody = match printobserver_types::serde_json::from_value(body) {
819        Ok(body) => body,
820        Err(error) => {
821            return refusal(
822                StatusCode::BAD_REQUEST,
823                format!("the body is not an `actor` and a `reason`: {error}"),
824            );
825        }
826    };
827    let reason = match reason_of(body.reason.as_deref()) {
828        Ok(reason) => reason,
829        Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
830    };
831    match state.supervisor.assert_bed_clear(reason).await {
832        Ok(event) => answer(
833            StatusCode::OK,
834            &BedClearAnswer {
835                event,
836                detail: BED_CLEAR_DETAIL.to_owned(),
837            },
838        ),
839        Err(error) => refusal(core_status(&error), error),
840    }
841}
842
843/// Everything a recovery is checked against now, and what each action would
844/// meet for the caller.
845async fn recover_status(
846    State(state): State<ApiState>,
847    Extension(caller): Extension<Caller>,
848) -> Response {
849    let class = match caller {
850        Caller::Operator => ActorClass::Operator,
851        Caller::Turn(_) => ActorClass::Agent,
852    };
853    match state.supervisor.recovery_status(class).await {
854        Ok(status) => answer(StatusCode::OK, &status),
855        Err(error) => refusal(core_status(&error), error),
856    }
857}
858
859/// Every spool, beside one line each and the charges a tool is holding.
860async fn spools(State(state): State<ApiState>, Query(params): Query<SpoolsParams>) -> Response {
861    let listed = match state
862        .supervisor
863        .spools(params.include_retired.unwrap_or(false))
864        .await
865    {
866        Ok(listed) => listed,
867        Err(error) => return refusal(core_status(&error), error),
868    };
869    match state.supervisor.pending_charges(None).await {
870        Ok(pending) => answer(StatusCode::OK, &SpoolsAnswer::of(listed, pending)),
871        Err(error) => refusal(core_status(&error), error),
872    }
873}
874
875/// One spool, and the newest of the printer's own events that name it.
876async fn spool(State(state): State<ApiState>, Path(spool_id): Path<SpoolId>) -> Response {
877    let found = match state.supervisor.spool(spool_id).await {
878        Ok(Some(found)) => found,
879        Ok(None) => {
880            return refusal(
881                StatusCode::NOT_FOUND,
882                format!("there is no spool {spool_id}"),
883            );
884        }
885        Err(error) => return refusal(core_status(&error), error),
886    };
887    let query = TimelineQuery {
888        spool_id: Some(spool_id),
889        limit: Some(SPOOL_RECENT_EVENTS),
890        ..every_timeline_kind()
891    };
892    match state.supervisor.timeline(query).await {
893        Ok(recent) => answer(
894            StatusCode::OK,
895            &SpoolAnswer {
896                spool: found,
897                recent,
898            },
899        ),
900        Err(error) => refusal(core_status(&error), error),
901    }
902}
903
904/// The printer history unfiltered: every timeline kind, the default window.
905const fn every_timeline_kind() -> TimelineQuery {
906    TimelineQuery {
907        kinds: Vec::new(),
908        since: None,
909        until: None,
910        spool_id: None,
911        before: None,
912        limit: None,
913    }
914}
915
916/// One value of a printer history read, refused naming it when it is not one.
917fn read_one<T: core::str::FromStr>(name: &str, text: &str) -> Result<T, String>
918where
919    T::Err: core::fmt::Display,
920{
921    text.parse()
922        .map_err(|error: T::Err| format!("`{name}` is `{text}`, which will not do: {error}"))
923}
924
925/// The printer history query a request's values make.
926///
927/// `kinds` may be given any number of times, each one kind; every other value
928/// at most once. A value this read does not take is refused naming it rather
929/// than ignored, because a filter that was quietly dropped answers more than
930/// was asked for.
931fn timeline_query(asked: &[(String, String)]) -> Result<TimelineQuery, String> {
932    let mut query = every_timeline_kind();
933    let mut seen: Vec<&str> = Vec::new();
934    for (name, text) in asked {
935        if name != "kinds" {
936            if seen.contains(&name.as_str()) {
937                return Err(format!(
938                    "`{name}` was given more than once, and this read takes one"
939                ));
940            }
941            seen.push(name);
942        }
943        match name.as_str() {
944            "kinds" => query.kinds.push(read_one::<EventKind>(name, text)?),
945            "since" => query.since = Some(read_one::<Timestamp>(name, text)?),
946            "until" => query.until = Some(read_one::<Timestamp>(name, text)?),
947            "spool_id" => query.spool_id = Some(read_one::<SpoolId>(name, text)?),
948            "before" => query.before = Some(read_one::<EventId>(name, text)?),
949            "limit" => query.limit = Some(read_one::<u32>(name, text)?),
950            other => return Err(format!("the printer history takes no `{other}`")),
951        }
952    }
953    Ok(query)
954}
955
956/// One page of the printer's own history, newest first, and the cursor for
957/// the page after it when there is one.
958///
959/// The cursor is answered only when an older event exists, so a caller paging
960/// by it stops at the last page rather than one empty page after it.
961async fn printer_history(
962    State(state): State<ApiState>,
963    Query(asked): Query<Vec<(String, String)>>,
964) -> Response {
965    let query = match timeline_query(&asked) {
966        Ok(query) => query,
967        Err(refused) => return refusal(StatusCode::BAD_REQUEST, refused),
968    };
969    let limit = match query.resolved_limit() {
970        Ok(limit) => limit,
971        Err(error) => return refusal(store_status(&error), error),
972    };
973    let events = match state.supervisor.timeline(query.clone()).await {
974        Ok(events) => events,
975        Err(error) => return refusal(core_status(&error), error),
976    };
977    let full = u32::try_from(events.len()).is_ok_and(|read| read == limit);
978    let next = match events.last() {
979        Some(last) if full => {
980            let older = TimelineQuery {
981                before: Some(last.id),
982                limit: Some(1),
983                ..query
984            };
985            match state.supervisor.timeline(older).await {
986                Ok(older) if older.is_empty() => None,
987                Ok(_) => Some(last.id),
988                Err(error) => return refusal(core_status(&error), error),
989            }
990        }
991        _ => None,
992    };
993    answer(StatusCode::OK, &TimelineAnswer { events, next })
994}
995
996/// Whether the spools loaded hold enough for one file, the file was sliced
997/// for their material and, when a sheet is given, that sheet suits it — read
998/// now.
999async fn preflight(
1000    State(state): State<ApiState>,
1001    Query(params): Query<PreflightParams>,
1002) -> Response {
1003    let Some(named) = params.file_name else {
1004        return refusal(
1005            StatusCode::BAD_REQUEST,
1006            "a filament check needs `file_name`, and this request carries none",
1007        );
1008    };
1009    let file_name = match FileName::new(&named) {
1010        Ok(file_name) => file_name,
1011        Err(error) => return refusal(StatusCode::BAD_REQUEST, error),
1012    };
1013    let sheet = match params.sheet.map(SheetId::try_from).transpose() {
1014        Ok(sheet) => sheet,
1015        Err(why) => return refusal(StatusCode::BAD_REQUEST, why),
1016    };
1017    match state.supervisor.preflight(&file_name, sheet.as_ref()).await {
1018        Ok(preflight) => answer(StatusCode::OK, &PreflightAnswer { preflight }),
1019        Err(error) => refusal(core_status(&error), error),
1020    }
1021}
1022
1023/// List every print, and name the one the printer's job belongs to.
1024///
1025/// Reading this adopts that job when no open print carries its file name, which
1026/// is how a print started at the printer gets an identifier before anything has
1027/// reported on it. A printer that cannot be read still answers the stored
1028/// prints, with nothing active.
1029async fn list_and_adopt_prints(State(state): State<ApiState>) -> Response {
1030    match state.supervisor.list_and_adopt_prints().await {
1031        Ok(listing) => answer(
1032            StatusCode::OK,
1033            &PrintsAnswer {
1034                prints: listing.prints,
1035                active: listing.active,
1036            },
1037        ),
1038        Err(error) => refusal(core_status(&error), error),
1039    }
1040}
1041
1042/// Read one print's status.
1043///
1044/// The print answered is the context's, read after the context read settled
1045/// the open prints against the printer's job — so a status that finds the job
1046/// over answers the print it closed rather than the one it found.
1047async fn status(
1048    State(state): State<ApiState>,
1049    Extension(caller): Extension<Caller>,
1050    PrintPath(print_id): PrintPath,
1051) -> Response {
1052    if let Some(refused) = scope_refused(&caller, print_id) {
1053        return refused;
1054    }
1055    match state.prints.print(print_id).await {
1056        Ok(Some(_)) => {}
1057        Ok(None) => {
1058            return refusal(
1059                StatusCode::NOT_FOUND,
1060                format!("there is no print {print_id}"),
1061            );
1062        }
1063        Err(error) => return refusal(store_status(&error), error),
1064    }
1065    let context = match context_of(&state, print_id).await {
1066        Ok(context) => context,
1067        Err(refused) => return refused,
1068    };
1069    let session = match state.sessions.session(print_id).await {
1070        Ok(session) => session,
1071        Err(error) => return refusal(store_status(&error), error),
1072    };
1073    answer(
1074        StatusCode::OK,
1075        &StatusAnswer {
1076            print: context.print,
1077            printer: context.printer,
1078            job: context.job,
1079            session,
1080            interventions: context.interventions,
1081            detector: context.detector,
1082        },
1083    )
1084}
1085
1086/// One print's context, read off the request's own thread.
1087///
1088/// The first read of a print's context after it starts reads the print's
1089/// whole G-code to index it, through a printer port that blocks while it
1090/// reads, so it is taken on a blocking thread, as a look is: a request that
1091/// held an asynchronous worker for the length of a download would hold every
1092/// task queued behind it there too.
1093async fn context_of(
1094    state: &ApiState,
1095    print_id: PrintId,
1096) -> Result<printobserver_core::PrintContext, Response> {
1097    let supervisor = Arc::clone(&state.supervisor);
1098    let read = tokio::task::spawn_blocking(move || {
1099        printobserver_core::block_on(supervisor.context(print_id))
1100    })
1101    .await;
1102    match read {
1103        Ok(Ok(context)) => Ok(context),
1104        Ok(Err(error)) => Err(refusal(core_status(&error), error)),
1105        Err(error) => Err(refusal(StatusCode::INTERNAL_SERVER_ERROR, error)),
1106    }
1107}
1108
1109/// Read everything a supervision turn is given about one print, with the
1110/// latest image materialized.
1111///
1112/// The path is looked up through the same store read the image operation
1113/// answers from, so the two operations cannot disagree about where an image
1114/// is. An image whose record is intact and whose file is gone answers no path,
1115/// which is what the caller's own missing-file failure is about.
1116async fn context(
1117    State(state): State<ApiState>,
1118    Extension(caller): Extension<Caller>,
1119    PrintPath(print_id): PrintPath,
1120    Query(params): Query<ContextParams>,
1121) -> Response {
1122    if let Some(refused) = scope_refused(&caller, print_id) {
1123        return refused;
1124    }
1125    // Off the request's own thread, for the reason `context_of` gives.
1126    let supervisor = Arc::clone(&state.supervisor);
1127    let since = params.since;
1128    let read = tokio::task::spawn_blocking(move || {
1129        printobserver_core::block_on(supervisor.agent_context(print_id, since))
1130    })
1131    .await;
1132    let context = match read {
1133        Ok(Ok(read)) => read,
1134        Ok(Err(error)) => return refusal(core_status(&error), error),
1135        Err(error) => return refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
1136    };
1137    let mut image_path = None;
1138    if let Some(latest) = context.latest_image.as_ref() {
1139        match state.images.image(latest.id).await {
1140            Ok(lookup) => image_path = ImageAnswer::from(lookup).path,
1141            Err(error) => return refusal(store_status(&error), error),
1142        }
1143    }
1144    answer(
1145        StatusCode::OK,
1146        &ContextAnswer {
1147            context,
1148            image_path,
1149        },
1150    )
1151}
1152
1153/// Take a fresh look at one print.
1154///
1155/// A wait longer than the supervisor allows is refused rather than shortened,
1156/// and a print nothing is held under is refused before any wait. The wait
1157/// itself runs on a blocking thread, exactly as a turn does, so that a minute
1158/// and a half of waiting holds no asynchronous worker the agent's own requests
1159/// are answered on.
1160async fn look(
1161    State(state): State<ApiState>,
1162    Extension(caller): Extension<Caller>,
1163    PrintPath(print_id): PrintPath,
1164    Query(params): Query<LookParams>,
1165) -> Response {
1166    if let Some(refused) = scope_refused(&caller, print_id) {
1167        return refused;
1168    }
1169    let wait_s = params.wait_s.unwrap_or(0);
1170    if wait_s > MAX_LOOK_WAIT_S {
1171        return refusal(
1172            StatusCode::BAD_REQUEST,
1173            format!("wait_s may be at most {MAX_LOOK_WAIT_S}; {wait_s} was asked for"),
1174        );
1175    }
1176    match state.prints.print(print_id).await {
1177        Ok(Some(_)) => {}
1178        Ok(None) => {
1179            return refusal(StatusCode::NOT_FOUND, CoreError::NoSuchPrint { print_id });
1180        }
1181        Err(error) => return refusal(store_status(&error), error),
1182    }
1183    // A look that was asked for counts whatever the camera then gives it: a
1184    // turn whose camera is down has still looked, and can say so.
1185    if let Caller::Turn(binding) = &caller {
1186        state.turns.note_look(binding);
1187    }
1188    let supervisor = Arc::clone(&state.supervisor);
1189    let taken = tokio::task::spawn_blocking(move || {
1190        let (arrived, waited) =
1191            supervisor.await_look_arrivals(print_id, Duration::from_secs(u64::from(wait_s)));
1192        printobserver_core::block_on(supervisor.take_look(print_id, waited, arrived))
1193    })
1194    .await;
1195    match taken {
1196        Ok(Ok(look)) => answer(StatusCode::OK, &look),
1197        Ok(Err(error)) => refusal(core_status(&error), error),
1198        Err(error) => refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
1199    }
1200}
1201
1202/// Take a fresh look at the printer, with no print named.
1203///
1204/// The look and its frame belong to no print, and the wait is a plain wait:
1205/// nothing any print's agent is owed can end it or be taken by it. A turn's
1206/// credential reaches its own print alone, so this is the operator's; a wait
1207/// longer than the supervisor allows is refused rather than shortened.
1208async fn printer_look(
1209    State(state): State<ApiState>,
1210    Extension(caller): Extension<Caller>,
1211    Query(params): Query<LookParams>,
1212) -> Response {
1213    if let Some(refused) = printless_refused(&caller, "a look at the printer with no print named") {
1214        return refused;
1215    }
1216    let wait_s = params.wait_s.unwrap_or(0);
1217    if wait_s > MAX_LOOK_WAIT_S {
1218        return refusal(
1219            StatusCode::BAD_REQUEST,
1220            format!("wait_s may be at most {MAX_LOOK_WAIT_S}; {wait_s} was asked for"),
1221        );
1222    }
1223    let waited = Duration::from_secs(u64::from(wait_s));
1224    tokio::time::sleep(waited).await;
1225    match state.supervisor.take_printer_look(waited).await {
1226        Ok(look) => answer(StatusCode::OK, &look),
1227        Err(error) => refusal(core_status(&error), error),
1228    }
1229}
1230
1231/// Materialize one image: its record, and the absolute path its bytes are at.
1232///
1233/// An image belongs to one print, or to none when it is a frame taken of the
1234/// printer with no print named. A turn's credential reaches the images of its
1235/// own print alone, so a frame of no print is the operator's.
1236async fn image(
1237    State(state): State<ApiState>,
1238    Extension(caller): Extension<Caller>,
1239    Path(image_id): Path<ImageId>,
1240) -> Response {
1241    match state.images.image(image_id).await {
1242        Ok(lookup) => {
1243            let belongs_to = match &lookup {
1244                printobserver_core::ImageLookup::Found { record, .. }
1245                | printobserver_core::ImageLookup::FileMissing { record } => record.print_id,
1246            };
1247            let refused = match belongs_to {
1248                Some(print_id) => scope_refused(&caller, print_id),
1249                None => {
1250                    printless_refused(&caller, "a frame of the printer that belongs to no print")
1251                }
1252            };
1253            if let Some(refused) = refused {
1254                return refused;
1255            }
1256            answer(StatusCode::OK, &ImageAnswer::from(lookup))
1257        }
1258        Err(error) => refusal(store_status(&error), error),
1259    }
1260}
1261
1262/// Read one print's events, newest first.
1263async fn history(
1264    State(state): State<ApiState>,
1265    Extension(caller): Extension<Caller>,
1266    PrintPath(print_id): PrintPath,
1267    Query(params): Query<HistoryParams>,
1268) -> Response {
1269    if let Some(refused) = scope_refused(&caller, print_id) {
1270        return refused;
1271    }
1272    let query = HistoryQuery {
1273        print_id,
1274        kinds: Vec::new(),
1275        since: None,
1276        until: None,
1277        limit: params.limit,
1278    };
1279    match state.events.history(query).await {
1280        Ok(events) => answer(StatusCode::OK, &HistoryAnswer { events }),
1281        Err(error) => refusal(store_status(&error), error),
1282    }
1283}
1284
1285/// Read one print's manifest.
1286async fn manifest_get(
1287    State(state): State<ApiState>,
1288    Extension(caller): Extension<Caller>,
1289    PrintPath(print_id): PrintPath,
1290) -> Response {
1291    if let Some(refused) = scope_refused(&caller, print_id) {
1292        return refused;
1293    }
1294    let manifest = match state.prints.manifest(print_id).await {
1295        Ok(manifest) => manifest,
1296        Err(error) => return refusal(store_status(&error), error),
1297    };
1298    let narrowings = match state.prints.print(print_id).await {
1299        Ok(print) => print.map(|record| record.narrowings).unwrap_or_default(),
1300        Err(error) => return refusal(store_status(&error), error),
1301    };
1302    answer(
1303        StatusCode::OK,
1304        &ManifestAnswer {
1305            manifest,
1306            narrowings,
1307        },
1308    )
1309}
1310
1311/// Write one print's manifest.
1312///
1313/// A manifest narrows what any actor may ask for, so replacing one is a change
1314/// to the bounds a print runs under and carries a reason like every other
1315/// change. The reason is ruled on **before** anything is written, so a request
1316/// without one leaves the stored manifest and the print's narrowings as they
1317/// were — and every range it asked wider than the envelope allows is recorded
1318/// on the print, exactly as it is when a start attaches one.
1319async fn manifest_set(
1320    State(state): State<ApiState>,
1321    Extension(caller): Extension<Caller>,
1322    PrintPath(print_id): PrintPath,
1323    body: Result<Json<ManifestBody>, JsonRejection>,
1324) -> Response {
1325    if let Some(refused) =
1326        operator_refused(&caller, &crate::operations::command_for("manifest_set"))
1327    {
1328        return refused;
1329    }
1330    let body = match body {
1331        Ok(Json(body)) => body,
1332        Err(rejected) => return rejected.into_response(),
1333    };
1334    if let Err(rejected) = body.reason() {
1335        return refusal(StatusCode::BAD_REQUEST, rejected);
1336    }
1337    let narrowed = effective_bounds(&state.supervisor.config().envelope, Some(&body.manifest));
1338    if let Err(error) = state
1339        .prints
1340        .put_manifest(print_id, body.manifest.clone())
1341        .await
1342    {
1343        return refusal(store_status(&error), error);
1344    }
1345    for narrowing in narrowed.narrowings.clone() {
1346        if let Err(error) = state.prints.record_narrowing(print_id, narrowing).await {
1347            return refusal(store_status(&error), error);
1348        }
1349    }
1350    answer(
1351        StatusCode::OK,
1352        &ManifestAnswer {
1353            manifest: Some(body.manifest),
1354            narrowings: narrowed.narrowings,
1355        },
1356    )
1357}
1358
1359#[cfg(test)]
1360mod tests {
1361    use axum::http::StatusCode;
1362    use printobserver_core::CoreError;
1363    use printobserver_core::store::StoreError;
1364
1365    use super::{core_status, store_status};
1366
1367    /// Every refusal the store can make is answered under a status a caller can
1368    /// act on: what it asked for, what is not there, and what went wrong here.
1369    #[test]
1370    fn every_store_refusal_is_answered_under_a_status_a_caller_can_act_on() {
1371        for (error, expected) in [
1372            (
1373                StoreError::NotFound {
1374                    what: "print".to_owned(),
1375                },
1376                StatusCode::NOT_FOUND,
1377            ),
1378            (
1379                StoreError::LimitRefused {
1380                    limit: 1_000,
1381                    asked_for: 2_000,
1382                },
1383                StatusCode::BAD_REQUEST,
1384            ),
1385            (
1386                StoreError::ConstraintRefused {
1387                    constraint: "actions.decision".to_owned(),
1388                },
1389                StatusCode::BAD_REQUEST,
1390            ),
1391            (
1392                StoreError::Database {
1393                    detail: "the disk is full".to_owned(),
1394                },
1395                StatusCode::INTERNAL_SERVER_ERROR,
1396            ),
1397            (
1398                StoreError::Io {
1399                    detail: "the disk is full".to_owned(),
1400                },
1401                StatusCode::INTERNAL_SERVER_ERROR,
1402            ),
1403        ] {
1404            assert_eq!(store_status(&error), expected, "{error}");
1405        }
1406    }
1407
1408    /// A print nothing holds is not found; a port that failed is this server's
1409    /// own failure rather than the caller's.
1410    #[test]
1411    fn a_print_nothing_holds_is_not_found_and_a_port_failure_is_this_servers_own() {
1412        assert_eq!(
1413            core_status(&CoreError::NoSuchPrint {
1414                print_id: printobserver_types::PrintId::new(),
1415            }),
1416            StatusCode::NOT_FOUND
1417        );
1418        assert_eq!(
1419            core_status(&CoreError::Store(StoreError::NotFound {
1420                what: "print".to_owned(),
1421            })),
1422            StatusCode::NOT_FOUND
1423        );
1424        assert_eq!(
1425            core_status(&CoreError::Unrepresentable {
1426                detail: "an instant".to_owned(),
1427            }),
1428            StatusCode::INTERNAL_SERVER_ERROR
1429        );
1430    }
1431}