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//!
12//! # Every action takes the same one path
13//!
14//! An action asked for here goes to
15//! [`Supervisor::request_action`](printobserver_core::Supervisor::request_action),
16//! which is the same call an operator's action makes and an agent's action
17//! makes. The policy is not re-implemented here and is not bypassed here: a
18//! rejected request answers the rejection the policy made, carrying its reason,
19//! the value asked for and the range allowed, and reaches no action method of
20//! the printer port at all.
21
22use std::sync::Arc;
23
24use axum::Json;
25use axum::extract::{Path, Query, State};
26use axum::http::{StatusCode, header};
27use axum::response::{IntoResponse, Response};
28use axum::routing::{get, post, put};
29use axum::{Router, routing::MethodRouter};
30use printobserver_core::{CoreError, Supervisor, effective_bounds};
31use printobserver_store_api::{HistoryQuery, StoreError, StorePort};
32use printobserver_types::serde::Deserialize;
33use printobserver_types::{ActionKind, ExecutionOutcome, ImageId, PolicyDecision, PrintId};
34
35use crate::operations::{Effect, Method, OPERATIONS, Operation, VERSION_PREFIX};
36use crate::wire::{
37    ActionAnswer, ActionBody, ContextAnswer, ErrorAnswer, HistoryAnswer, ImageAnswer,
38    ManifestAnswer, ManifestBody, StatusAnswer,
39};
40
41/// What every handler is given: the supervisor, and the store beside it.
42#[derive(Clone)]
43pub struct ApiState {
44    /// The supervision core, which every action passes through.
45    pub supervisor: Arc<Supervisor>,
46    /// Durable state, which the reads answer out of.
47    pub store: Arc<dyn StorePort>,
48}
49
50impl core::fmt::Debug for ApiState {
51    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
52        formatter.debug_struct("ApiState").finish_non_exhaustive()
53    }
54}
55
56/// How many events a history read asks for, when it asks for a number.
57#[derive(Debug, Clone, Deserialize)]
58#[serde(crate = "printobserver_types::serde")]
59pub struct HistoryParams {
60    /// The limit asked for; absent takes the port's own default window.
61    #[serde(default)]
62    pub limit: Option<u32>,
63}
64
65/// Every public operation, beneath the one versioned prefix.
66///
67/// # Panics
68///
69/// Panics when [`OPERATIONS`] declares an entry this function has no route for,
70/// which is a declaration and a router that have come apart — the one state
71/// this server must not come up in quietly.
72pub fn router(state: ApiState) -> Router {
73    let mut api = Router::new();
74    for operation in OPERATIONS {
75        api = api.route(operation.path, route_for(&operation));
76    }
77    Router::new().nest(VERSION_PREFIX, api.with_state(state))
78}
79
80/// The route one declared operation is served by.
81fn route_for(operation: &Operation) -> MethodRouter<ApiState> {
82    if let Effect::Mutating(kind) = operation.effect {
83        return post(
84            move |state: State<ApiState>, print_id: Path<PrintId>, body: Json<ActionBody>| async move {
85                act(kind, state, print_id, body).await
86            },
87        );
88    }
89    match (operation.name, operation.method) {
90        ("status", Method::Get) => get(status),
91        ("context", Method::Get) => get(context),
92        ("image", Method::Get) => get(image),
93        ("history", Method::Get) => get(history),
94        ("manifest_get", Method::Get) => get(manifest_get),
95        ("manifest_set", Method::Put) => put(manifest_set),
96        (name, method) => panic!(
97            "the operation `{name}` is declared as {method} and this router serves no such route"
98        ),
99    }
100}
101
102/// One answer, rendered as JSON under the media type every operation answers in.
103fn answer<T: printobserver_types::serde::Serialize>(status: StatusCode, body: &T) -> Response {
104    let rendered = match printobserver_types::serde_json::to_vec(body) {
105        Ok(bytes) => bytes,
106        Err(error) => {
107            return (
108                StatusCode::INTERNAL_SERVER_ERROR,
109                [(header::CONTENT_TYPE, crate::operations::MEDIA_TYPE)],
110                format!("{{\"error\":\"{error}\"}}"),
111            )
112                .into_response();
113        }
114    };
115    (
116        status,
117        [(header::CONTENT_TYPE, crate::operations::MEDIA_TYPE)],
118        rendered,
119    )
120        .into_response()
121}
122
123/// One refusal, rendered as JSON under the same media type.
124fn refusal(status: StatusCode, detail: impl core::fmt::Display) -> Response {
125    answer(status, &ErrorAnswer::saying(detail))
126}
127
128/// The status a store refusal is answered under.
129fn store_status(error: &StoreError) -> StatusCode {
130    match error {
131        StoreError::NotFound { .. } => StatusCode::NOT_FOUND,
132        StoreError::LimitRefused { .. } | StoreError::ConstraintRefused { .. } => {
133            StatusCode::BAD_REQUEST
134        }
135        StoreError::Database { .. } | StoreError::Io { .. } => StatusCode::INTERNAL_SERVER_ERROR,
136    }
137}
138
139/// The status a core refusal is answered under.
140fn core_status(error: &CoreError) -> StatusCode {
141    match error {
142        CoreError::NoSuchPrint { .. } => StatusCode::NOT_FOUND,
143        CoreError::Store(store) => store_status(store),
144        _ => StatusCode::INTERNAL_SERVER_ERROR,
145    }
146}
147
148/// Ask for one action of the vocabulary against one print.
149async fn act(
150    kind: ActionKind,
151    State(state): State<ApiState>,
152    Path(print_id): Path<PrintId>,
153    Json(body): Json<ActionBody>,
154) -> Response {
155    let action = match body.into_action(kind) {
156        Ok(action) => action,
157        Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
158    };
159    let outcome = match state.supervisor.request_action(print_id, action).await {
160        Ok(outcome) => outcome,
161        Err(error) => return refusal(core_status(&error), error),
162    };
163    let printer_refusal = match &outcome.record.outcome {
164        Some(ExecutionOutcome::Failed { reason }) => Some(reason.clone()),
165        _ => None,
166    };
167    let status = match outcome.record.decision {
168        PolicyDecision::Accepted if printer_refusal.is_none() => StatusCode::OK,
169        // The policy accepted it and the machine did not. That is a request
170        // that was made and refused rather than one that never happened, so
171        // the record and the printer's own words are the answer.
172        PolicyDecision::Accepted => StatusCode::BAD_GATEWAY,
173        // The rejection itself is the answer: its reason, the value asked for
174        // and the range allowed are what let a caller ask again correctly.
175        PolicyDecision::Rejected(_) => StatusCode::CONFLICT,
176    };
177    answer(
178        status,
179        &ActionAnswer {
180            record: outcome.record,
181            intervention: outcome.intervention,
182            printer_refusal,
183        },
184    )
185}
186
187/// Read one print's status.
188async fn status(State(state): State<ApiState>, Path(print_id): Path<PrintId>) -> Response {
189    let print = match state.store.print(print_id).await {
190        Ok(Some(print)) => print,
191        Ok(None) => {
192            return refusal(
193                StatusCode::NOT_FOUND,
194                format!("there is no print {print_id}"),
195            );
196        }
197        Err(error) => return refusal(store_status(&error), error),
198    };
199    let context = match state.supervisor.context(print_id).await {
200        Ok(context) => context,
201        Err(error) => return refusal(core_status(&error), error),
202    };
203    let session = match state.store.session(print_id).await {
204        Ok(session) => session,
205        Err(error) => return refusal(store_status(&error), error),
206    };
207    answer(
208        StatusCode::OK,
209        &StatusAnswer {
210            print,
211            printer: context.printer,
212            job: context.job,
213            session,
214            interventions: context.interventions,
215        },
216    )
217}
218
219/// Read everything a supervision turn is given about one print, with the
220/// latest image materialized.
221///
222/// The path is looked up through the same store read the image operation
223/// answers from, so the two operations cannot disagree about where an image
224/// is. An image whose record is intact and whose file is gone answers no path,
225/// which is what the caller's own missing-file failure is about.
226async fn context(State(state): State<ApiState>, Path(print_id): Path<PrintId>) -> Response {
227    let context = match state.supervisor.context(print_id).await {
228        Ok(context) => context,
229        Err(error) => return refusal(core_status(&error), error),
230    };
231    let mut image_path = None;
232    if let Some(latest) = context.latest_image.as_ref() {
233        match state.store.image(latest.id).await {
234            Ok(lookup) => image_path = ImageAnswer::from(lookup).path,
235            Err(error) => return refusal(store_status(&error), error),
236        }
237    }
238    answer(
239        StatusCode::OK,
240        &ContextAnswer {
241            context,
242            image_path,
243        },
244    )
245}
246
247/// Materialize one image: its record, and the absolute path its bytes are at.
248async fn image(State(state): State<ApiState>, Path(image_id): Path<ImageId>) -> Response {
249    match state.store.image(image_id).await {
250        Ok(lookup) => answer(StatusCode::OK, &ImageAnswer::from(lookup)),
251        Err(error) => refusal(store_status(&error), error),
252    }
253}
254
255/// Read one print's events, newest first.
256async fn history(
257    State(state): State<ApiState>,
258    Path(print_id): Path<PrintId>,
259    Query(params): Query<HistoryParams>,
260) -> Response {
261    let query = HistoryQuery {
262        print_id,
263        kinds: Vec::new(),
264        since: None,
265        until: None,
266        limit: params.limit,
267    };
268    match state.store.history(query).await {
269        Ok(events) => answer(StatusCode::OK, &HistoryAnswer { events }),
270        Err(error) => refusal(store_status(&error), error),
271    }
272}
273
274/// Read one print's manifest.
275async fn manifest_get(State(state): State<ApiState>, Path(print_id): Path<PrintId>) -> Response {
276    let manifest = match state.store.manifest(print_id).await {
277        Ok(manifest) => manifest,
278        Err(error) => return refusal(store_status(&error), error),
279    };
280    let narrowings = match state.store.print(print_id).await {
281        Ok(print) => print.map(|record| record.narrowings).unwrap_or_default(),
282        Err(error) => return refusal(store_status(&error), error),
283    };
284    answer(
285        StatusCode::OK,
286        &ManifestAnswer {
287            manifest,
288            narrowings,
289        },
290    )
291}
292
293/// Write one print's manifest.
294///
295/// A manifest narrows what any actor may ask for, so replacing one is a change
296/// to the bounds a print runs under and carries a reason like every other
297/// change. The reason is ruled on **before** anything is written, so a request
298/// without one leaves the stored manifest and the print's narrowings as they
299/// were — and every range it asked wider than the envelope allows is recorded
300/// on the print, exactly as it is when a start attaches one.
301async fn manifest_set(
302    State(state): State<ApiState>,
303    Path(print_id): Path<PrintId>,
304    Json(body): Json<ManifestBody>,
305) -> Response {
306    if let Err(rejected) = body.reason() {
307        return refusal(StatusCode::BAD_REQUEST, rejected);
308    }
309    let narrowed = effective_bounds(&state.supervisor.config().envelope, Some(&body.manifest));
310    if let Err(error) = state
311        .store
312        .put_manifest(print_id, body.manifest.clone())
313        .await
314    {
315        return refusal(store_status(&error), error);
316    }
317    for narrowing in narrowed.narrowings.clone() {
318        if let Err(error) = state.store.record_narrowing(print_id, narrowing).await {
319            return refusal(store_status(&error), error);
320        }
321    }
322    answer(
323        StatusCode::OK,
324        &ManifestAnswer {
325            manifest: Some(body.manifest),
326            narrowings: narrowed.narrowings,
327        },
328    )
329}
330
331#[cfg(test)]
332mod tests {
333    use axum::http::StatusCode;
334    use printobserver_core::CoreError;
335    use printobserver_store_api::StoreError;
336
337    use super::{core_status, store_status};
338
339    /// Every refusal the store can make is answered under a status a caller can
340    /// act on: what it asked for, what is not there, and what went wrong here.
341    #[test]
342    fn every_store_refusal_is_answered_under_a_status_a_caller_can_act_on() {
343        for (error, expected) in [
344            (
345                StoreError::NotFound {
346                    what: "print".to_owned(),
347                },
348                StatusCode::NOT_FOUND,
349            ),
350            (
351                StoreError::LimitRefused {
352                    limit: 1_000,
353                    asked_for: 2_000,
354                },
355                StatusCode::BAD_REQUEST,
356            ),
357            (
358                StoreError::ConstraintRefused {
359                    constraint: "actions.decision".to_owned(),
360                },
361                StatusCode::BAD_REQUEST,
362            ),
363            (
364                StoreError::Database {
365                    detail: "the disk is full".to_owned(),
366                },
367                StatusCode::INTERNAL_SERVER_ERROR,
368            ),
369            (
370                StoreError::Io {
371                    detail: "the disk is full".to_owned(),
372                },
373                StatusCode::INTERNAL_SERVER_ERROR,
374            ),
375        ] {
376            assert_eq!(store_status(&error), expected, "{error}");
377        }
378    }
379
380    /// A print nothing holds is not found; a port that failed is this server's
381    /// own failure rather than the caller's.
382    #[test]
383    fn a_print_nothing_holds_is_not_found_and_a_port_failure_is_this_servers_own() {
384        assert_eq!(
385            core_status(&CoreError::NoSuchPrint {
386                print_id: printobserver_types::PrintId::new(),
387            }),
388            StatusCode::NOT_FOUND
389        );
390        assert_eq!(
391            core_status(&CoreError::Store(StoreError::NotFound {
392                what: "print".to_owned(),
393            })),
394            StatusCode::NOT_FOUND
395        );
396        assert_eq!(
397            core_status(&CoreError::Unrepresentable {
398                detail: "an instant".to_owned(),
399            }),
400            StatusCode::INTERNAL_SERVER_ERROR
401        );
402    }
403}