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