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