1use 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#[derive(Clone)]
90pub struct ApiState {
91 pub supervisor: Arc<Supervisor>,
93 pub prints: Arc<dyn PrintStore>,
95 pub events: Arc<dyn EventStore>,
97 pub images: Arc<dyn ImageStore>,
99 pub sessions: Arc<dyn SessionStore>,
101 pub operator: Arc<OperatorCredential>,
104 pub turns: TurnCredentials,
106 pub stored: crate::events::Stored,
108}
109
110#[derive(Debug, Clone, PartialEq, Eq)]
112pub enum Caller {
113 Operator,
115 Turn(TurnBinding),
117}
118
119impl Caller {
120 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
133fn 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
142fn 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
172pub(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
187fn 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#[derive(Clone)]
205pub struct Admission {
206 operator: Arc<OperatorCredential>,
208 turns: TurnCredentials,
210}
211
212impl Admission {
213 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#[derive(Debug, Clone, Deserialize)]
230#[serde(crate = "printobserver_types::serde")]
231pub struct HistoryParams {
232 #[serde(default)]
234 pub limit: Option<u32>,
235}
236
237#[derive(Debug, Clone, Deserialize)]
239#[serde(crate = "printobserver_types::serde")]
240pub struct LookParams {
241 #[serde(default)]
243 pub wait_s: Option<u32>,
244}
245
246#[derive(Debug, Clone, Deserialize)]
248#[serde(crate = "printobserver_types::serde")]
249pub struct SpoolsParams {
250 #[serde(default)]
252 pub include_retired: Option<bool>,
253}
254
255#[derive(Debug, Clone, Deserialize)]
257#[serde(crate = "printobserver_types::serde")]
258pub struct PreflightParams {
259 #[serde(default)]
261 pub file_name: Option<String>,
262}
263
264pub const SPOOL_RECENT_EVENTS: u32 = 20;
266
267pub 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 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
295const BEARER: &[u8] = b"Bearer ";
297
298pub const BODY_BOUND: usize = 2 * 1024 * 1024;
305
306pub const DRAIN_BOUND: Duration = Duration::from_secs(2);
312
313pub 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 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
379async fn nothing_here() -> Response {
381 refusal(
382 StatusCode::NOT_FOUND,
383 "no operation of this server is served at that path",
384 )
385}
386
387fn 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
439pub(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
463pub(crate) fn refusal(status: StatusCode, detail: impl core::fmt::Display) -> Response {
465 answer(status, &ErrorAnswer::saying(detail))
466}
467
468pub(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
479fn 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
488async 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 PolicyDecision::Accepted => StatusCode::BAD_GATEWAY,
536 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
550async 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 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
605async 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
621async 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
650const 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
662fn 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
671fn 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
702async 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
742async 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
763async 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
782async 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
826async 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
861async 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
905async 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
929async 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
952async 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
978async 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 #[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 #[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}