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
56use std::sync::Arc;
57use std::time::Duration;
58
59use axum::Json;
60use axum::extract::rejection::JsonRejection;
61use axum::extract::{DefaultBodyLimit, Extension, Path, Query, Request, State};
62use axum::http::{StatusCode, header};
63use axum::middleware::{Next, from_fn_with_state};
64use axum::response::{IntoResponse, Response};
65use axum::routing::{get, post, put};
66use axum::{Router, routing::MethodRouter};
67use printobserver_core::store::TimelineQuery;
68use printobserver_core::store::{
69    EventStore, HistoryQuery, ImageStore, PrintStore, SessionStore, StoreError,
70};
71use printobserver_core::{ActionKind, Actor, ExecutionOutcome, PolicyDecision, SpoolId};
72use printobserver_core::{CoreError, MAX_LOOK_WAIT_S, Supervisor, effective_bounds};
73use printobserver_types::serde::Deserialize;
74use printobserver_types::serde_json::Value;
75use printobserver_types::{EventId, EventKind, FileName, ImageId, PrintId, Timestamp};
76
77use crate::operations::{Effect, Method, OPERATIONS, Operation, VERSION_PREFIX};
78use crate::server::{CREDENTIAL_ISSUE, OperatorCredential};
79use crate::turns::{TurnBinding, TurnCredentials};
80use crate::wire::{
81    ActionAnswer, ActionBody, ContextAnswer, ErrorAnswer, HistoryAnswer, ImageAnswer,
82    ManifestAnswer, ManifestBody, PreflightAnswer, PrintsAnswer, SpoolAnswer, SpoolCommandAnswer,
83    SpoolsAnswer, StatusAnswer, TimelineAnswer, claimed_actor, spool_command_of,
84};
85
86/// What every handler is given: the supervisor, and the stores the reads
87/// answer out of — the four aggregates a route reads, and not the actions,
88/// which reach the store through the supervisor alone.
89#[derive(Clone)]
90pub struct ApiState {
91    /// The supervision core, which every action passes through.
92    pub supervisor: Arc<Supervisor>,
93    /// The print records, their manifests and their narrowings.
94    pub prints: Arc<dyn PrintStore>,
95    /// The event log.
96    pub events: Arc<dyn EventStore>,
97    /// The images stored beside the events.
98    pub images: Arc<dyn ImageStore>,
99    /// The supervision sessions.
100    pub sessions: Arc<dyn SessionStore>,
101    /// What the operator's credential is checked against before anything
102    /// above is reached.
103    pub operator: Arc<OperatorCredential>,
104    /// The live supervision turns' credentials, checked the same way.
105    pub turns: TurnCredentials,
106    /// The broadcast an events read waits on, raised once an event is stored.
107    pub stored: crate::events::Stored,
108}
109
110/// Who one request authenticated as.
111#[derive(Debug, Clone, PartialEq, Eq)]
112pub enum Caller {
113    /// The operator, by the credential the operator's verifier admits.
114    Operator,
115    /// One supervision turn's run: the agent, in one session, on one print.
116    Turn(TurnBinding),
117}
118
119impl Caller {
120    /// This caller, as a refusal names it.
121    fn named(&self) -> String {
122        match self {
123            Self::Operator => "the operator".to_owned(),
124            Self::Turn(binding) => format!(
125                "the agent in session `{}` on print {}",
126                binding.session_name(),
127                binding.print_id()
128            ),
129        }
130    }
131}
132
133/// One claimed actor, as a refusal names it.
134fn claimed(actor: &Actor) -> String {
135    match actor {
136        Actor::Operator => "the operator".to_owned(),
137        Actor::System => "the system".to_owned(),
138        Actor::Agent { session_name } => format!("the agent in session `{session_name}`"),
139    }
140}
141
142/// Refuse a claimed actor that is not the caller, before anything is decided.
143///
144/// The system is claimed by nobody: its actions are the server's own, and no
145/// credential this server admits is the server.
146fn claim_refused(caller: &Caller, actor: &Actor) -> Option<Response> {
147    let held = match (caller, actor) {
148        (Caller::Operator, Actor::Operator) => true,
149        (Caller::Turn(binding), Actor::Agent { session_name }) => {
150            *session_name == binding.session_name()
151        }
152        _ => false,
153    };
154    if held {
155        return None;
156    }
157    let why = if matches!(actor, Actor::System) {
158        "no credential may claim the system, whose actions are the server's own"
159    } else {
160        "a request acts as the identity its credential authenticated, and no other"
161    };
162    Some(refusal(
163        StatusCode::FORBIDDEN,
164        format!(
165            "this request authenticated as {} and claims to be {}: {why}",
166            caller.named(),
167            claimed(actor)
168        ),
169    ))
170}
171
172/// Refuse a turn's request about any print but its own.
173pub(crate) fn scope_refused(caller: &Caller, print_id: PrintId) -> Option<Response> {
174    match caller {
175        Caller::Turn(binding) if binding.print_id() != print_id => Some(refusal(
176            StatusCode::FORBIDDEN,
177            format!(
178                "this request authenticated as {} and names print {print_id}: a supervision \
179                 turn's credential reaches its own print alone",
180                caller.named()
181            ),
182        )),
183        _ => None,
184    }
185}
186
187/// Refuse a turn's request for a write that is not about its running print:
188/// starting a print, and replacing a manifest, are the operator's alone.
189fn operator_refused(caller: &Caller, command: &str) -> Option<Response> {
190    match caller {
191        Caller::Turn(_) => Some(refusal(
192            StatusCode::FORBIDDEN,
193            format!(
194                "this request authenticated as {} and asks for `{command}`, which is the \
195                 operator's alone: a supervision turn's credential does not reach it",
196                caller.named()
197            ),
198        )),
199        Caller::Operator => None,
200    }
201}
202
203/// What [`authenticate`] checks a presented credential against.
204#[derive(Clone)]
205pub struct Admission {
206    /// The operator's.
207    operator: Arc<OperatorCredential>,
208    /// The live turns'.
209    turns: TurnCredentials,
210}
211
212impl Admission {
213    /// Who a presented credential authenticates as, when it is anybody.
214    fn caller(&self, presented: &[u8]) -> Option<Caller> {
215        if let Some(binding) = self.turns.admit(presented) {
216            return Some(Caller::Turn(binding));
217        }
218        self.operator.admits(presented).then_some(Caller::Operator)
219    }
220}
221
222impl core::fmt::Debug for ApiState {
223    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
224        formatter.debug_struct("ApiState").finish_non_exhaustive()
225    }
226}
227
228/// How many events a history read asks for, when it asks for a number.
229#[derive(Debug, Clone, Deserialize)]
230#[serde(crate = "printobserver_types::serde")]
231pub struct HistoryParams {
232    /// The limit asked for; absent takes the port's own default window.
233    #[serde(default)]
234    pub limit: Option<u32>,
235}
236
237/// How long a look asks to wait for something to arrive, in whole seconds.
238#[derive(Debug, Clone, Deserialize)]
239#[serde(crate = "printobserver_types::serde")]
240pub struct LookParams {
241    /// The wait asked for; absent looks at once.
242    #[serde(default)]
243    pub wait_s: Option<u32>,
244}
245
246/// Whether a spools read asks for the retired ones too.
247#[derive(Debug, Clone, Deserialize)]
248#[serde(crate = "printobserver_types::serde")]
249pub struct SpoolsParams {
250    /// Asked for; absent, the retired spools are left out.
251    #[serde(default)]
252    pub include_retired: Option<bool>,
253}
254
255/// The file a filament check is about.
256#[derive(Debug, Clone, Deserialize)]
257#[serde(crate = "printobserver_types::serde")]
258pub struct PreflightParams {
259    /// The file, as the printer names it.
260    #[serde(default)]
261    pub file_name: Option<String>,
262}
263
264/// How many of a spool's own events its read carries, newest first.
265pub const SPOOL_RECENT_EVENTS: u32 = 20;
266
267/// Every public operation, beneath the one versioned prefix.
268///
269/// # Panics
270///
271/// Panics when [`OPERATIONS`] declares an entry this function has no route for,
272/// which is a declaration and a router that have come apart — the one state
273/// this server must not come up in quietly.
274pub fn router(state: ApiState) -> Router {
275    let mut api = Router::new();
276    for operation in OPERATIONS {
277        api = api.route(operation.path, route_for(&operation));
278    }
279    // The layer is added after every route and the fallback, which is what
280    // puts all of them behind it.
281    let api = api
282        .fallback(nothing_here)
283        .layer(from_fn_with_state(
284            Admission {
285                operator: Arc::clone(&state.operator),
286                turns: state.turns.clone(),
287            },
288            authenticate,
289        ))
290        .layer(DefaultBodyLimit::max(BODY_BOUND))
291        .with_state(state);
292    Router::new().nest(VERSION_PREFIX, api)
293}
294
295/// The scheme the credential is presented under.
296const BEARER: &[u8] = b"Bearer ";
297
298/// How much of a request's body this server reads, admitted or refused.
299///
300/// One bound for both: the router's body limit is set from it, so it is what
301/// every extractor reads an admitted body to, and what [`authenticate`] drains
302/// a refused one to — a body the server would have taken is one it drains,
303/// and a larger one is left where it is either way.
304pub const BODY_BOUND: usize = 2 * 1024 * 1024;
305
306/// How long [`authenticate`] waits for a refused request's body to arrive.
307///
308/// A caller that sent a head and then nothing would otherwise hold its refusal
309/// open for as long as it liked; after this the refusal goes out over whatever
310/// arrived, and the connection ends as it did before there was a drain.
311pub const DRAIN_BOUND: Duration = Duration::from_secs(2);
312
313/// Admit a request that presented the operator's credential or a live turn's,
314/// hand every handler who it authenticated as, and refuse every other request
315/// before anything reads it.
316///
317/// Exactly one `Authorization` header, spelled `Bearer ` and then the
318/// credential. Two headers, another scheme, another spelling of this one, and a
319/// credential that is nobody's are all the same refusal, which says what to
320/// present and nothing about what was presented — and, on a server that has no
321/// operator credential yet, names the command that issues one.
322///
323/// The refusal is decided on the head alone, and the body is then drained, up
324/// to [`BODY_BOUND`], before it is answered. Nothing reads what is
325/// drained: a connection closed with a body still unread on it is closed with
326/// a reset rather than an end, and a caller on Windows — where a reset discards
327/// everything received and not yet read — then reads the abort in place of the
328/// `401` that was already on its way. Linux hands over what was queued first,
329/// which is why the same race is only ever seen there.
330pub async fn authenticate(
331    State(admission): State<Admission>,
332    mut request: Request,
333    next: Next,
334) -> Response {
335    let mut presented = request.headers().get_all(header::AUTHORIZATION).iter();
336    let admitted = match (presented.next(), presented.next()) {
337        (Some(only), None) => only
338            .as_bytes()
339            .strip_prefix(BEARER)
340            .and_then(|offered| admission.caller(offered)),
341        _ => None,
342    };
343    if let Some(caller) = admitted {
344        request.extensions_mut().insert(caller);
345        return next.run(request).await;
346    }
347    {
348        let said = if matches!(*admission.operator, OperatorCredential::Unconfigured) {
349            format!(
350                "this server's API requires a credential, presented as `Authorization: Bearer \
351                 <credential>`, and this server has no operator credential yet: run \
352                 `{CREDENTIAL_ISSUE}` as the operator, put the `api.credential_verifier` line it \
353                 prints into the server's configuration, and restart the service"
354            )
355        } else {
356            format!(
357                "this server's API requires the credential it is configured with, presented as \
358                 `Authorization: Bearer <credential>`. An operator without one runs \
359                 `{CREDENTIAL_ISSUE}`"
360            )
361        };
362        let mut refused = refusal(StatusCode::UNAUTHORIZED, said);
363        refused.headers_mut().insert(
364            header::WWW_AUTHENTICATE,
365            header::HeaderValue::from_static("Bearer"),
366        );
367        // A body past the bound, or one that has not arrived inside
368        // `DRAIN_BOUND`, is left where it is: the refusal is the answer either
369        // way, and what a caller then meets on the connection is its own doing.
370        let _ = tokio::time::timeout(
371            DRAIN_BOUND,
372            axum::body::to_bytes(request.into_body(), BODY_BOUND),
373        )
374        .await;
375        refused
376    }
377}
378
379/// A path beneath the versioned prefix that no operation serves.
380async fn nothing_here() -> Response {
381    refusal(
382        StatusCode::NOT_FOUND,
383        "no operation of this server is served at that path",
384    )
385}
386
387/// The route one declared operation is served by.
388fn route_for(operation: &Operation) -> MethodRouter<ApiState> {
389    if let Effect::Command(spool_command) = operation.effect {
390        let kind = spool_command.action_kind();
391        if operation.path.contains("{spool_id}") {
392            return post(
393                move |state: State<ApiState>,
394                      caller: Extension<Caller>,
395                      Path(spool_id): Path<SpoolId>,
396                      body: Result<Json<Value>, JsonRejection>| async move {
397                    command(kind, state, caller, Some(spool_id), body).await
398                },
399            );
400        }
401        return post(
402            move |state: State<ApiState>,
403                  caller: Extension<Caller>,
404                  body: Result<Json<Value>, JsonRejection>| async move {
405                command(kind, state, caller, None, body).await
406            },
407        );
408    }
409    if let Effect::Mutating(kind) = operation.effect {
410        return post(
411            move |state: State<ApiState>,
412                  caller: Extension<Caller>,
413                  print_id: Path<PrintId>,
414                  body: Result<Json<ActionBody>, JsonRejection>| async move {
415                act(kind, state, caller, print_id, body).await
416            },
417        );
418    }
419    match (operation.name, operation.method) {
420        ("prints", Method::Get) => get(list_and_adopt_prints),
421        ("status", Method::Get) => get(status),
422        ("context", Method::Get) => get(context),
423        ("image", Method::Get) => get(image),
424        ("history", Method::Get) => get(history),
425        ("events", Method::Get) => get(crate::events::events),
426        ("look", Method::Get) => get(look),
427        ("manifest_get", Method::Get) => get(manifest_get),
428        ("manifest_set", Method::Put) => put(manifest_set),
429        ("spools", Method::Get) => get(spools),
430        ("spool", Method::Get) => get(spool),
431        ("printer_history", Method::Get) => get(printer_history),
432        ("preflight", Method::Get) => get(preflight),
433        (name, method) => panic!(
434            "the operation `{name}` is declared as {method} and this router serves no such route"
435        ),
436    }
437}
438
439/// One answer, rendered as JSON under the media type every operation answers in.
440pub(crate) fn answer<T: printobserver_types::serde::Serialize>(
441    status: StatusCode,
442    body: &T,
443) -> Response {
444    let rendered = match printobserver_types::serde_json::to_vec(body) {
445        Ok(bytes) => bytes,
446        Err(error) => {
447            return (
448                StatusCode::INTERNAL_SERVER_ERROR,
449                [(header::CONTENT_TYPE, crate::operations::MEDIA_TYPE)],
450                format!("{{\"error\":\"{error}\"}}"),
451            )
452                .into_response();
453        }
454    };
455    (
456        status,
457        [(header::CONTENT_TYPE, crate::operations::MEDIA_TYPE)],
458        rendered,
459    )
460        .into_response()
461}
462
463/// One refusal, rendered as JSON under the same media type.
464pub(crate) fn refusal(status: StatusCode, detail: impl core::fmt::Display) -> Response {
465    answer(status, &ErrorAnswer::saying(detail))
466}
467
468/// The status a store refusal is answered under.
469pub(crate) fn store_status(error: &StoreError) -> StatusCode {
470    match error {
471        StoreError::NotFound { .. } => StatusCode::NOT_FOUND,
472        StoreError::LimitRefused { .. } | StoreError::ConstraintRefused { .. } => {
473            StatusCode::BAD_REQUEST
474        }
475        StoreError::Database { .. } | StoreError::Io { .. } => StatusCode::INTERNAL_SERVER_ERROR,
476    }
477}
478
479/// The status a core refusal is answered under.
480fn core_status(error: &CoreError) -> StatusCode {
481    match error {
482        CoreError::NoSuchPrint { .. } => StatusCode::NOT_FOUND,
483        CoreError::Store(store) => store_status(store),
484        _ => StatusCode::INTERNAL_SERVER_ERROR,
485    }
486}
487
488/// Ask for one action of the vocabulary against one print.
489///
490/// Who may ask is settled before the policy is: a turn's credential reaches
491/// no start and no print but its own — whatever the body says, so those two
492/// answer `403` ahead of any rejection of the body itself — and the claimed
493/// actor is held to the caller. A
494/// request refused here is decided on by nothing and recorded nowhere.
495async fn act(
496    kind: ActionKind,
497    State(state): State<ApiState>,
498    Extension(caller): Extension<Caller>,
499    Path(print_id): Path<PrintId>,
500    body: Result<Json<ActionBody>, JsonRejection>,
501) -> Response {
502    if kind == ActionKind::StartPrint
503        && let Some(refused) =
504            operator_refused(&caller, &crate::operations::command_for("start_print"))
505    {
506        return refused;
507    }
508    if let Some(refused) = scope_refused(&caller, print_id) {
509        return refused;
510    }
511    let body = match body {
512        Ok(Json(body)) => body,
513        Err(rejected) => return rejected.into_response(),
514    };
515    if let Some(refused) = claim_refused(&caller, &body.actor) {
516        return refused;
517    }
518    let action = match body.into_action(kind) {
519        Ok(action) => action,
520        Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
521    };
522    let outcome = match state.supervisor.request_action(print_id, action).await {
523        Ok(outcome) => outcome,
524        Err(error) => return refusal(core_status(&error), error),
525    };
526    let printer_refusal = match &outcome.record.outcome {
527        Some(ExecutionOutcome::Failed { reason }) => Some(reason.clone()),
528        _ => None,
529    };
530    let status = match outcome.record.decision {
531        PolicyDecision::Accepted if printer_refusal.is_none() => StatusCode::OK,
532        // The policy accepted it and the machine did not. That is a request
533        // that was made and refused rather than one that never happened, so
534        // the record and the printer's own words are the answer.
535        PolicyDecision::Accepted => StatusCode::BAD_GATEWAY,
536        // The rejection itself is the answer: its reason, the value asked for
537        // and the range allowed are what let a caller ask again correctly.
538        PolicyDecision::Rejected(_) => StatusCode::CONFLICT,
539    };
540    answer(
541        status,
542        &ActionAnswer {
543            record: outcome.record,
544            intervention: outcome.intervention,
545            printer_refusal,
546        },
547    )
548}
549
550/// Ask the spool ledger for one command.
551///
552/// The claimed actor is held to the caller before anything else of the body is
553/// read, and a body with no reason is refused before the domain is asked —
554/// so a request refused here is recorded nowhere. Whether the actor may ask at
555/// all is the envelope's grant, which the domain rules on and records like
556/// every refusal: a supervision turn's agent is refused there, under the
557/// default grants, rather than here.
558async fn command(
559    kind: ActionKind,
560    State(state): State<ApiState>,
561    Extension(caller): Extension<Caller>,
562    spool_id: Option<SpoolId>,
563    body: Result<Json<Value>, JsonRejection>,
564) -> Response {
565    let body = match body {
566        Ok(Json(body)) => body,
567        Err(rejected) => return rejected.into_response(),
568    };
569    let Some(fields) = body.as_object() else {
570        return refusal(
571            StatusCode::BAD_REQUEST,
572            "a spool command's body is a document of its fields",
573        );
574    };
575    let actor = match claimed_actor(fields) {
576        Ok(actor) => actor,
577        Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
578    };
579    if let Some(refused) = claim_refused(&caller, &actor) {
580        return refused;
581    }
582    let asked = match spool_command_of(kind, spool_id, body) {
583        Ok(asked) => asked,
584        Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
585    };
586    let outcome = match state.supervisor.request_spool_command(asked).await {
587        Ok(outcome) => outcome,
588        Err(error) => return refusal(core_status(&error), error),
589    };
590    let status = match outcome.decision {
591        PolicyDecision::Accepted => StatusCode::OK,
592        // The refusal is the answer, exactly as a print action's is.
593        PolicyDecision::Rejected(_) => StatusCode::CONFLICT,
594    };
595    answer(
596        status,
597        &SpoolCommandAnswer {
598            decision: outcome.decision,
599            spool: outcome.spool,
600            events: outcome.events,
601        },
602    )
603}
604
605/// Every spool, beside one line each and the charges a tool is holding.
606async fn spools(State(state): State<ApiState>, Query(params): Query<SpoolsParams>) -> Response {
607    let listed = match state
608        .supervisor
609        .spools(params.include_retired.unwrap_or(false))
610        .await
611    {
612        Ok(listed) => listed,
613        Err(error) => return refusal(core_status(&error), error),
614    };
615    match state.supervisor.pending_charges(None).await {
616        Ok(pending) => answer(StatusCode::OK, &SpoolsAnswer::of(listed, pending)),
617        Err(error) => refusal(core_status(&error), error),
618    }
619}
620
621/// One spool, and the newest of the printer's own events that name it.
622async fn spool(State(state): State<ApiState>, Path(spool_id): Path<SpoolId>) -> Response {
623    let found = match state.supervisor.spool(spool_id).await {
624        Ok(Some(found)) => found,
625        Ok(None) => {
626            return refusal(
627                StatusCode::NOT_FOUND,
628                format!("there is no spool {spool_id}"),
629            );
630        }
631        Err(error) => return refusal(core_status(&error), error),
632    };
633    let query = TimelineQuery {
634        spool_id: Some(spool_id),
635        limit: Some(SPOOL_RECENT_EVENTS),
636        ..every_timeline_kind()
637    };
638    match state.supervisor.timeline(query).await {
639        Ok(recent) => answer(
640            StatusCode::OK,
641            &SpoolAnswer {
642                spool: found,
643                recent,
644            },
645        ),
646        Err(error) => refusal(core_status(&error), error),
647    }
648}
649
650/// The printer history unfiltered: every timeline kind, the default window.
651const fn every_timeline_kind() -> TimelineQuery {
652    TimelineQuery {
653        kinds: Vec::new(),
654        since: None,
655        until: None,
656        spool_id: None,
657        before: None,
658        limit: None,
659    }
660}
661
662/// One value of a printer history read, refused naming it when it is not one.
663fn read_one<T: core::str::FromStr>(name: &str, text: &str) -> Result<T, String>
664where
665    T::Err: core::fmt::Display,
666{
667    text.parse()
668        .map_err(|error: T::Err| format!("`{name}` is `{text}`, which will not do: {error}"))
669}
670
671/// The printer history query a request's values make.
672///
673/// `kinds` may be given any number of times, each one kind; every other value
674/// at most once. A value this read does not take is refused naming it rather
675/// than ignored, because a filter that was quietly dropped answers more than
676/// was asked for.
677fn timeline_query(asked: &[(String, String)]) -> Result<TimelineQuery, String> {
678    let mut query = every_timeline_kind();
679    let mut seen: Vec<&str> = Vec::new();
680    for (name, text) in asked {
681        if name != "kinds" {
682            if seen.contains(&name.as_str()) {
683                return Err(format!(
684                    "`{name}` was given more than once, and this read takes one"
685                ));
686            }
687            seen.push(name);
688        }
689        match name.as_str() {
690            "kinds" => query.kinds.push(read_one::<EventKind>(name, text)?),
691            "since" => query.since = Some(read_one::<Timestamp>(name, text)?),
692            "until" => query.until = Some(read_one::<Timestamp>(name, text)?),
693            "spool_id" => query.spool_id = Some(read_one::<SpoolId>(name, text)?),
694            "before" => query.before = Some(read_one::<EventId>(name, text)?),
695            "limit" => query.limit = Some(read_one::<u32>(name, text)?),
696            other => return Err(format!("the printer history takes no `{other}`")),
697        }
698    }
699    Ok(query)
700}
701
702/// One page of the printer's own history, newest first, and the cursor for
703/// the page after it when there is one.
704///
705/// The cursor is answered only when an older event exists, so a caller paging
706/// by it stops at the last page rather than one empty page after it.
707async fn printer_history(
708    State(state): State<ApiState>,
709    Query(asked): Query<Vec<(String, String)>>,
710) -> Response {
711    let query = match timeline_query(&asked) {
712        Ok(query) => query,
713        Err(refused) => return refusal(StatusCode::BAD_REQUEST, refused),
714    };
715    let limit = match query.resolved_limit() {
716        Ok(limit) => limit,
717        Err(error) => return refusal(store_status(&error), error),
718    };
719    let events = match state.supervisor.timeline(query.clone()).await {
720        Ok(events) => events,
721        Err(error) => return refusal(core_status(&error), error),
722    };
723    let full = u32::try_from(events.len()).is_ok_and(|read| read == limit);
724    let next = match events.last() {
725        Some(last) if full => {
726            let older = TimelineQuery {
727                before: Some(last.id),
728                limit: Some(1),
729                ..query
730            };
731            match state.supervisor.timeline(older).await {
732                Ok(older) if older.is_empty() => None,
733                Ok(_) => Some(last.id),
734                Err(error) => return refusal(core_status(&error), error),
735            }
736        }
737        _ => None,
738    };
739    answer(StatusCode::OK, &TimelineAnswer { events, next })
740}
741
742/// Whether the spools loaded hold enough for one file, read now.
743async fn preflight(
744    State(state): State<ApiState>,
745    Query(params): Query<PreflightParams>,
746) -> Response {
747    let Some(named) = params.file_name else {
748        return refusal(
749            StatusCode::BAD_REQUEST,
750            "a filament check needs `file_name`, and this request carries none",
751        );
752    };
753    let file_name = match FileName::new(&named) {
754        Ok(file_name) => file_name,
755        Err(error) => return refusal(StatusCode::BAD_REQUEST, error),
756    };
757    match state.supervisor.preflight(&file_name).await {
758        Ok(preflight) => answer(StatusCode::OK, &PreflightAnswer { preflight }),
759        Err(error) => refusal(core_status(&error), error),
760    }
761}
762
763/// List every print, and name the one the printer's job belongs to.
764///
765/// Reading this adopts that job when no open print carries its file name, which
766/// is how a print started at the printer gets an identifier before anything has
767/// reported on it. A printer that cannot be read still answers the stored
768/// prints, with nothing active.
769async fn list_and_adopt_prints(State(state): State<ApiState>) -> Response {
770    match state.supervisor.list_and_adopt_prints().await {
771        Ok(listing) => answer(
772            StatusCode::OK,
773            &PrintsAnswer {
774                prints: listing.prints,
775                active: listing.active,
776            },
777        ),
778        Err(error) => refusal(core_status(&error), error),
779    }
780}
781
782/// Read one print's status.
783///
784/// The print answered is the context's, read after the context read settled
785/// the open prints against the printer's job — so a status that finds the job
786/// over answers the print it closed rather than the one it found.
787async fn status(
788    State(state): State<ApiState>,
789    Extension(caller): Extension<Caller>,
790    Path(print_id): Path<PrintId>,
791) -> Response {
792    if let Some(refused) = scope_refused(&caller, print_id) {
793        return refused;
794    }
795    match state.prints.print(print_id).await {
796        Ok(Some(_)) => {}
797        Ok(None) => {
798            return refusal(
799                StatusCode::NOT_FOUND,
800                format!("there is no print {print_id}"),
801            );
802        }
803        Err(error) => return refusal(store_status(&error), error),
804    }
805    let context = match state.supervisor.context(print_id).await {
806        Ok(context) => context,
807        Err(error) => return refusal(core_status(&error), error),
808    };
809    let session = match state.sessions.session(print_id).await {
810        Ok(session) => session,
811        Err(error) => return refusal(store_status(&error), error),
812    };
813    answer(
814        StatusCode::OK,
815        &StatusAnswer {
816            print: context.print,
817            printer: context.printer,
818            job: context.job,
819            session,
820            interventions: context.interventions,
821            detector: context.detector,
822        },
823    )
824}
825
826/// Read everything a supervision turn is given about one print, with the
827/// latest image materialized.
828///
829/// The path is looked up through the same store read the image operation
830/// answers from, so the two operations cannot disagree about where an image
831/// is. An image whose record is intact and whose file is gone answers no path,
832/// which is what the caller's own missing-file failure is about.
833async fn context(
834    State(state): State<ApiState>,
835    Extension(caller): Extension<Caller>,
836    Path(print_id): Path<PrintId>,
837) -> Response {
838    if let Some(refused) = scope_refused(&caller, print_id) {
839        return refused;
840    }
841    let context = match state.supervisor.context(print_id).await {
842        Ok(context) => context,
843        Err(error) => return refusal(core_status(&error), error),
844    };
845    let mut image_path = None;
846    if let Some(latest) = context.latest_image.as_ref() {
847        match state.images.image(latest.id).await {
848            Ok(lookup) => image_path = ImageAnswer::from(lookup).path,
849            Err(error) => return refusal(store_status(&error), error),
850        }
851    }
852    answer(
853        StatusCode::OK,
854        &ContextAnswer {
855            context,
856            image_path,
857        },
858    )
859}
860
861/// Take a fresh look at one print.
862///
863/// A wait longer than the supervisor allows is refused rather than shortened,
864/// and a print nothing is held under is refused before any wait. The wait
865/// itself runs on a blocking thread, exactly as a turn does, so that a minute
866/// and a half of waiting holds no asynchronous worker the agent's own requests
867/// are answered on.
868async fn look(
869    State(state): State<ApiState>,
870    Extension(caller): Extension<Caller>,
871    Path(print_id): Path<PrintId>,
872    Query(params): Query<LookParams>,
873) -> Response {
874    if let Some(refused) = scope_refused(&caller, print_id) {
875        return refused;
876    }
877    let wait_s = params.wait_s.unwrap_or(0);
878    if wait_s > MAX_LOOK_WAIT_S {
879        return refusal(
880            StatusCode::BAD_REQUEST,
881            format!("wait_s may be at most {MAX_LOOK_WAIT_S}; {wait_s} was asked for"),
882        );
883    }
884    match state.prints.print(print_id).await {
885        Ok(Some(_)) => {}
886        Ok(None) => {
887            return refusal(StatusCode::NOT_FOUND, CoreError::NoSuchPrint { print_id });
888        }
889        Err(error) => return refusal(store_status(&error), error),
890    }
891    let supervisor = Arc::clone(&state.supervisor);
892    let taken = tokio::task::spawn_blocking(move || {
893        let started = std::time::Instant::now();
894        let arrived = supervisor.await_arrivals(print_id, Duration::from_secs(u64::from(wait_s)));
895        printobserver_core::block_on(supervisor.take_look(print_id, started.elapsed(), arrived))
896    })
897    .await;
898    match taken {
899        Ok(Ok(look)) => answer(StatusCode::OK, &look),
900        Ok(Err(error)) => refusal(core_status(&error), error),
901        Err(error) => refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
902    }
903}
904
905/// Materialize one image: its record, and the absolute path its bytes are at.
906///
907/// An image belongs to one print, so a turn's credential reaches the images of
908/// its own print alone.
909async fn image(
910    State(state): State<ApiState>,
911    Extension(caller): Extension<Caller>,
912    Path(image_id): Path<ImageId>,
913) -> Response {
914    match state.images.image(image_id).await {
915        Ok(lookup) => {
916            let belongs_to = match &lookup {
917                printobserver_core::ImageLookup::Found { record, .. }
918                | printobserver_core::ImageLookup::FileMissing { record } => record.print_id,
919            };
920            if let Some(refused) = scope_refused(&caller, belongs_to) {
921                return refused;
922            }
923            answer(StatusCode::OK, &ImageAnswer::from(lookup))
924        }
925        Err(error) => refusal(store_status(&error), error),
926    }
927}
928
929/// Read one print's events, newest first.
930async fn history(
931    State(state): State<ApiState>,
932    Extension(caller): Extension<Caller>,
933    Path(print_id): Path<PrintId>,
934    Query(params): Query<HistoryParams>,
935) -> Response {
936    if let Some(refused) = scope_refused(&caller, print_id) {
937        return refused;
938    }
939    let query = HistoryQuery {
940        print_id,
941        kinds: Vec::new(),
942        since: None,
943        until: None,
944        limit: params.limit,
945    };
946    match state.events.history(query).await {
947        Ok(events) => answer(StatusCode::OK, &HistoryAnswer { events }),
948        Err(error) => refusal(store_status(&error), error),
949    }
950}
951
952/// Read one print's manifest.
953async fn manifest_get(
954    State(state): State<ApiState>,
955    Extension(caller): Extension<Caller>,
956    Path(print_id): Path<PrintId>,
957) -> Response {
958    if let Some(refused) = scope_refused(&caller, print_id) {
959        return refused;
960    }
961    let manifest = match state.prints.manifest(print_id).await {
962        Ok(manifest) => manifest,
963        Err(error) => return refusal(store_status(&error), error),
964    };
965    let narrowings = match state.prints.print(print_id).await {
966        Ok(print) => print.map(|record| record.narrowings).unwrap_or_default(),
967        Err(error) => return refusal(store_status(&error), error),
968    };
969    answer(
970        StatusCode::OK,
971        &ManifestAnswer {
972            manifest,
973            narrowings,
974        },
975    )
976}
977
978/// Write one print's manifest.
979///
980/// A manifest narrows what any actor may ask for, so replacing one is a change
981/// to the bounds a print runs under and carries a reason like every other
982/// change. The reason is ruled on **before** anything is written, so a request
983/// without one leaves the stored manifest and the print's narrowings as they
984/// were — and every range it asked wider than the envelope allows is recorded
985/// on the print, exactly as it is when a start attaches one.
986async fn manifest_set(
987    State(state): State<ApiState>,
988    Extension(caller): Extension<Caller>,
989    Path(print_id): Path<PrintId>,
990    body: Result<Json<ManifestBody>, JsonRejection>,
991) -> Response {
992    if let Some(refused) =
993        operator_refused(&caller, &crate::operations::command_for("manifest_set"))
994    {
995        return refused;
996    }
997    let body = match body {
998        Ok(Json(body)) => body,
999        Err(rejected) => return rejected.into_response(),
1000    };
1001    if let Err(rejected) = body.reason() {
1002        return refusal(StatusCode::BAD_REQUEST, rejected);
1003    }
1004    let narrowed = effective_bounds(&state.supervisor.config().envelope, Some(&body.manifest));
1005    if let Err(error) = state
1006        .prints
1007        .put_manifest(print_id, body.manifest.clone())
1008        .await
1009    {
1010        return refusal(store_status(&error), error);
1011    }
1012    for narrowing in narrowed.narrowings.clone() {
1013        if let Err(error) = state.prints.record_narrowing(print_id, narrowing).await {
1014            return refusal(store_status(&error), error);
1015        }
1016    }
1017    answer(
1018        StatusCode::OK,
1019        &ManifestAnswer {
1020            manifest: Some(body.manifest),
1021            narrowings: narrowed.narrowings,
1022        },
1023    )
1024}
1025
1026#[cfg(test)]
1027mod tests {
1028    use axum::http::StatusCode;
1029    use printobserver_core::CoreError;
1030    use printobserver_core::store::StoreError;
1031
1032    use super::{core_status, store_status};
1033
1034    /// Every refusal the store can make is answered under a status a caller can
1035    /// act on: what it asked for, what is not there, and what went wrong here.
1036    #[test]
1037    fn every_store_refusal_is_answered_under_a_status_a_caller_can_act_on() {
1038        for (error, expected) in [
1039            (
1040                StoreError::NotFound {
1041                    what: "print".to_owned(),
1042                },
1043                StatusCode::NOT_FOUND,
1044            ),
1045            (
1046                StoreError::LimitRefused {
1047                    limit: 1_000,
1048                    asked_for: 2_000,
1049                },
1050                StatusCode::BAD_REQUEST,
1051            ),
1052            (
1053                StoreError::ConstraintRefused {
1054                    constraint: "actions.decision".to_owned(),
1055                },
1056                StatusCode::BAD_REQUEST,
1057            ),
1058            (
1059                StoreError::Database {
1060                    detail: "the disk is full".to_owned(),
1061                },
1062                StatusCode::INTERNAL_SERVER_ERROR,
1063            ),
1064            (
1065                StoreError::Io {
1066                    detail: "the disk is full".to_owned(),
1067                },
1068                StatusCode::INTERNAL_SERVER_ERROR,
1069            ),
1070        ] {
1071            assert_eq!(store_status(&error), expected, "{error}");
1072        }
1073    }
1074
1075    /// A print nothing holds is not found; a port that failed is this server's
1076    /// own failure rather than the caller's.
1077    #[test]
1078    fn a_print_nothing_holds_is_not_found_and_a_port_failure_is_this_servers_own() {
1079        assert_eq!(
1080            core_status(&CoreError::NoSuchPrint {
1081                print_id: printobserver_types::PrintId::new(),
1082            }),
1083            StatusCode::NOT_FOUND
1084        );
1085        assert_eq!(
1086            core_status(&CoreError::Store(StoreError::NotFound {
1087                what: "print".to_owned(),
1088            })),
1089            StatusCode::NOT_FOUND
1090        );
1091        assert_eq!(
1092            core_status(&CoreError::Unrepresentable {
1093                detail: "an instant".to_owned(),
1094            }),
1095            StatusCode::INTERNAL_SERVER_ERROR
1096        );
1097    }
1098}