1use 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#[derive(Clone)]
43pub struct ApiState {
44 pub supervisor: Arc<Supervisor>,
46 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#[derive(Debug, Clone, Deserialize)]
58#[serde(crate = "printobserver_types::serde")]
59pub struct HistoryParams {
60 #[serde(default)]
62 pub limit: Option<u32>,
63}
64
65pub 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
80fn 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
102fn 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
123fn refusal(status: StatusCode, detail: impl core::fmt::Display) -> Response {
125 answer(status, &ErrorAnswer::saying(detail))
126}
127
128fn 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
139fn 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
148async 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 PolicyDecision::Accepted => StatusCode::BAD_GATEWAY,
173 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
187async 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
219async 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
247async 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
255async 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
274async 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
293async 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 #[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 #[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}