1use std::sync::Arc;
62use std::time::Duration;
63
64use axum::Json;
65use axum::extract::rejection::JsonRejection;
66use axum::extract::{DefaultBodyLimit, Extension, Path, Query, Request, State};
67use axum::http::{StatusCode, header};
68use axum::middleware::{Next, from_fn_with_state};
69use axum::response::{IntoResponse, Response};
70use axum::routing::{get, post, put};
71use axum::{Router, routing::MethodRouter};
72use printobserver_core::recovery::recovery_detail;
73use printobserver_core::store::TimelineQuery;
74use printobserver_core::store::{
75 EventStore, HistoryQuery, ImageStore, PrintStore, SessionStore, StoreError,
76};
77use printobserver_core::{
78 ActionKind, Actor, ActorClass, ExecutionOutcome, PolicyDecision, RecoveryActionKind,
79 RecoveryDecision, SpoolId,
80};
81use printobserver_core::{CoreError, MAX_LOOK_WAIT_S, Supervisor, effective_bounds};
82use printobserver_types::serde::Deserialize;
83use printobserver_types::serde_json::Value;
84use printobserver_types::{EventId, EventKind, FileName, ImageId, PrintId, Timestamp};
85
86use crate::operations::{Effect, Method, OPERATIONS, Operation, VERSION_PREFIX};
87use crate::server::{CREDENTIAL_ISSUE, OperatorCredential};
88use crate::turns::{TurnBinding, TurnCredentials};
89use crate::wire::{
90 ActionAnswer, ActionBody, ContextAnswer, ErrorAnswer, HistoryAnswer, ImageAnswer,
91 ManifestAnswer, ManifestBody, PreflightAnswer, PrintsAnswer, RecoveryAnswer, SpoolAnswer,
92 SpoolCommandAnswer, SpoolsAnswer, StatusAnswer, TimelineAnswer, claimed_actor, recovery_of,
93 spool_command_of,
94};
95
96#[derive(Clone)]
100pub struct ApiState {
101 pub supervisor: Arc<Supervisor>,
103 pub prints: Arc<dyn PrintStore>,
105 pub events: Arc<dyn EventStore>,
107 pub images: Arc<dyn ImageStore>,
109 pub sessions: Arc<dyn SessionStore>,
111 pub operator: Arc<OperatorCredential>,
114 pub turns: TurnCredentials,
116 pub stored: crate::events::Stored,
118}
119
120#[derive(Debug, Clone, PartialEq, Eq)]
122pub enum Caller {
123 Operator,
125 Turn(TurnBinding),
127}
128
129impl Caller {
130 fn named(&self) -> String {
132 match self {
133 Self::Operator => "the operator".to_owned(),
134 Self::Turn(binding) => format!(
135 "the agent in session `{}` on print {}",
136 binding.session_name(),
137 binding.print_id()
138 ),
139 }
140 }
141}
142
143fn claimed(actor: &Actor) -> String {
145 match actor {
146 Actor::Operator => "the operator".to_owned(),
147 Actor::System => "the system".to_owned(),
148 Actor::Agent { session_name } => format!("the agent in session `{session_name}`"),
149 }
150}
151
152fn claim_refused(caller: &Caller, actor: &Actor) -> Option<Response> {
157 let held = match (caller, actor) {
158 (Caller::Operator, Actor::Operator) => true,
159 (Caller::Turn(binding), Actor::Agent { session_name }) => {
160 *session_name == binding.session_name()
161 }
162 _ => false,
163 };
164 if held {
165 return None;
166 }
167 let why = if matches!(actor, Actor::System) {
168 "no credential may claim the system, whose actions are the server's own"
169 } else {
170 "a request acts as the identity its credential authenticated, and no other"
171 };
172 Some(refusal(
173 StatusCode::FORBIDDEN,
174 format!(
175 "this request authenticated as {} and claims to be {}: {why}",
176 caller.named(),
177 claimed(actor)
178 ),
179 ))
180}
181
182pub(crate) fn scope_refused(caller: &Caller, print_id: PrintId) -> Option<Response> {
184 match caller {
185 Caller::Turn(binding) if binding.print_id() != print_id => Some(refusal(
186 StatusCode::FORBIDDEN,
187 format!(
188 "this request authenticated as {} and names print {print_id}: a supervision \
189 turn's credential reaches its own print alone",
190 caller.named()
191 ),
192 )),
193 _ => None,
194 }
195}
196
197fn operator_refused(caller: &Caller, command: &str) -> Option<Response> {
200 match caller {
201 Caller::Turn(_) => Some(refusal(
202 StatusCode::FORBIDDEN,
203 format!(
204 "this request authenticated as {} and asks for `{command}`, which is the \
205 operator's alone: a supervision turn's credential does not reach it",
206 caller.named()
207 ),
208 )),
209 Caller::Operator => None,
210 }
211}
212
213#[derive(Clone)]
215pub struct Admission {
216 operator: Arc<OperatorCredential>,
218 turns: TurnCredentials,
220}
221
222impl Admission {
223 fn caller(&self, presented: &[u8]) -> Option<Caller> {
225 if let Some(binding) = self.turns.admit(presented) {
226 return Some(Caller::Turn(binding));
227 }
228 self.operator.admits(presented).then_some(Caller::Operator)
229 }
230}
231
232impl core::fmt::Debug for ApiState {
233 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
234 formatter.debug_struct("ApiState").finish_non_exhaustive()
235 }
236}
237
238#[derive(Debug, Clone, Deserialize)]
240#[serde(crate = "printobserver_types::serde")]
241pub struct HistoryParams {
242 #[serde(default)]
244 pub limit: Option<u32>,
245}
246
247#[derive(Debug, Clone, Deserialize)]
249#[serde(crate = "printobserver_types::serde")]
250pub struct LookParams {
251 #[serde(default)]
253 pub wait_s: Option<u32>,
254}
255
256#[derive(Debug, Clone, Deserialize)]
258#[serde(crate = "printobserver_types::serde")]
259pub struct SpoolsParams {
260 #[serde(default)]
262 pub include_retired: Option<bool>,
263}
264
265#[derive(Debug, Clone, Deserialize)]
267#[serde(crate = "printobserver_types::serde")]
268pub struct PreflightParams {
269 #[serde(default)]
271 pub file_name: Option<String>,
272}
273
274pub const SPOOL_RECENT_EVENTS: u32 = 20;
276
277pub fn router(state: ApiState) -> Router {
285 let mut api = Router::new();
286 for operation in OPERATIONS {
287 api = api.route(operation.path, route_for(&operation));
288 }
289 let api = api
292 .fallback(nothing_here)
293 .layer(from_fn_with_state(
294 Admission {
295 operator: Arc::clone(&state.operator),
296 turns: state.turns.clone(),
297 },
298 authenticate,
299 ))
300 .layer(DefaultBodyLimit::max(BODY_BOUND))
301 .with_state(state);
302 Router::new().nest(VERSION_PREFIX, api)
303}
304
305const BEARER: &[u8] = b"Bearer ";
307
308pub const BODY_BOUND: usize = 2 * 1024 * 1024;
315
316pub const DRAIN_BOUND: Duration = Duration::from_secs(2);
322
323pub async fn authenticate(
341 State(admission): State<Admission>,
342 mut request: Request,
343 next: Next,
344) -> Response {
345 let mut presented = request.headers().get_all(header::AUTHORIZATION).iter();
346 let admitted = match (presented.next(), presented.next()) {
347 (Some(only), None) => only
348 .as_bytes()
349 .strip_prefix(BEARER)
350 .and_then(|offered| admission.caller(offered)),
351 _ => None,
352 };
353 if let Some(caller) = admitted {
354 request.extensions_mut().insert(caller);
355 return next.run(request).await;
356 }
357 {
358 let said = if matches!(*admission.operator, OperatorCredential::Unconfigured) {
359 format!(
360 "this server's API requires a credential, presented as `Authorization: Bearer \
361 <credential>`, and this server has no operator credential yet: run \
362 `{CREDENTIAL_ISSUE}` as the operator, put the `api.credential_verifier` line it \
363 prints into the server's configuration, and restart the service"
364 )
365 } else {
366 format!(
367 "this server's API requires the credential it is configured with, presented as \
368 `Authorization: Bearer <credential>`. An operator without one runs \
369 `{CREDENTIAL_ISSUE}`"
370 )
371 };
372 let mut refused = refusal(StatusCode::UNAUTHORIZED, said);
373 refused.headers_mut().insert(
374 header::WWW_AUTHENTICATE,
375 header::HeaderValue::from_static("Bearer"),
376 );
377 let _ = tokio::time::timeout(
381 DRAIN_BOUND,
382 axum::body::to_bytes(request.into_body(), BODY_BOUND),
383 )
384 .await;
385 refused
386 }
387}
388
389async fn nothing_here() -> Response {
391 refusal(
392 StatusCode::NOT_FOUND,
393 "no operation of this server is served at that path",
394 )
395}
396
397fn route_for(operation: &Operation) -> MethodRouter<ApiState> {
399 if let Effect::Command(spool_command) = operation.effect {
400 let kind = spool_command.action_kind();
401 if operation.path.contains("{spool_id}") {
402 return post(
403 move |state: State<ApiState>,
404 caller: Extension<Caller>,
405 Path(spool_id): Path<SpoolId>,
406 body: Result<Json<Value>, JsonRejection>| async move {
407 command(kind, state, caller, Some(spool_id), body).await
408 },
409 );
410 }
411 return post(
412 move |state: State<ApiState>,
413 caller: Extension<Caller>,
414 body: Result<Json<Value>, JsonRejection>| async move {
415 command(kind, state, caller, None, body).await
416 },
417 );
418 }
419 if let Effect::Recovery(kind) = operation.effect {
420 return post(
421 move |state: State<ApiState>,
422 caller: Extension<Caller>,
423 body: Result<Json<Value>, JsonRejection>| async move {
424 recover(kind, state, caller, body).await
425 },
426 );
427 }
428 if let Effect::Mutating(kind) = operation.effect {
429 return post(
430 move |state: State<ApiState>,
431 caller: Extension<Caller>,
432 print_id: Path<PrintId>,
433 body: Result<Json<ActionBody>, JsonRejection>| async move {
434 act(kind, state, caller, print_id, body).await
435 },
436 );
437 }
438 match (operation.name, operation.method) {
439 ("prints", Method::Get) => get(list_and_adopt_prints),
440 ("status", Method::Get) => get(status),
441 ("context", Method::Get) => get(context),
442 ("image", Method::Get) => get(image),
443 ("history", Method::Get) => get(history),
444 ("events", Method::Get) => get(crate::events::events),
445 ("look", Method::Get) => get(look),
446 ("manifest_get", Method::Get) => get(manifest_get),
447 ("manifest_set", Method::Put) => put(manifest_set),
448 ("spools", Method::Get) => get(spools),
449 ("spool", Method::Get) => get(spool),
450 ("printer_history", Method::Get) => get(printer_history),
451 ("preflight", Method::Get) => get(preflight),
452 (crate::operations::RECOVERY_STATUS, Method::Get) => get(recover_status),
453 (name, method) => panic!(
454 "the operation `{name}` is declared as {method} and this router serves no such route"
455 ),
456 }
457}
458
459pub(crate) fn answer<T: printobserver_types::serde::Serialize>(
461 status: StatusCode,
462 body: &T,
463) -> Response {
464 let rendered = match printobserver_types::serde_json::to_vec(body) {
465 Ok(bytes) => bytes,
466 Err(error) => {
467 return (
468 StatusCode::INTERNAL_SERVER_ERROR,
469 [(header::CONTENT_TYPE, crate::operations::MEDIA_TYPE)],
470 format!("{{\"error\":\"{error}\"}}"),
471 )
472 .into_response();
473 }
474 };
475 (
476 status,
477 [(header::CONTENT_TYPE, crate::operations::MEDIA_TYPE)],
478 rendered,
479 )
480 .into_response()
481}
482
483pub(crate) fn refusal(status: StatusCode, detail: impl core::fmt::Display) -> Response {
485 answer(status, &ErrorAnswer::saying(detail))
486}
487
488pub(crate) fn store_status(error: &StoreError) -> StatusCode {
490 match error {
491 StoreError::NotFound { .. } => StatusCode::NOT_FOUND,
492 StoreError::LimitRefused { .. } | StoreError::ConstraintRefused { .. } => {
493 StatusCode::BAD_REQUEST
494 }
495 StoreError::Database { .. } | StoreError::Io { .. } => StatusCode::INTERNAL_SERVER_ERROR,
496 }
497}
498
499fn core_status(error: &CoreError) -> StatusCode {
501 match error {
502 CoreError::NoSuchPrint { .. } => StatusCode::NOT_FOUND,
503 CoreError::Store(store) => store_status(store),
504 _ => StatusCode::INTERNAL_SERVER_ERROR,
505 }
506}
507
508async fn act(
516 kind: ActionKind,
517 State(state): State<ApiState>,
518 Extension(caller): Extension<Caller>,
519 Path(print_id): Path<PrintId>,
520 body: Result<Json<ActionBody>, JsonRejection>,
521) -> Response {
522 if kind == ActionKind::StartPrint
523 && let Some(refused) =
524 operator_refused(&caller, &crate::operations::command_for("start_print"))
525 {
526 return refused;
527 }
528 if let Some(refused) = scope_refused(&caller, print_id) {
529 return refused;
530 }
531 let body = match body {
532 Ok(Json(body)) => body,
533 Err(rejected) => return rejected.into_response(),
534 };
535 if let Some(refused) = claim_refused(&caller, &body.actor) {
536 return refused;
537 }
538 let action = match body.into_action(kind) {
539 Ok(action) => action,
540 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
541 };
542 let outcome = match state.supervisor.request_action(print_id, action).await {
543 Ok(outcome) => outcome,
544 Err(error) => return refusal(core_status(&error), error),
545 };
546 let printer_refusal = match &outcome.record.outcome {
547 Some(ExecutionOutcome::Failed { reason }) => Some(reason.clone()),
548 _ => None,
549 };
550 let status = match outcome.record.decision {
551 PolicyDecision::Accepted if printer_refusal.is_none() => StatusCode::OK,
552 PolicyDecision::Accepted => StatusCode::BAD_GATEWAY,
556 PolicyDecision::Rejected(_) => StatusCode::CONFLICT,
559 };
560 answer(
561 status,
562 &ActionAnswer {
563 record: outcome.record,
564 intervention: outcome.intervention,
565 printer_refusal,
566 },
567 )
568}
569
570async fn command(
579 kind: ActionKind,
580 State(state): State<ApiState>,
581 Extension(caller): Extension<Caller>,
582 spool_id: Option<SpoolId>,
583 body: Result<Json<Value>, JsonRejection>,
584) -> Response {
585 let body = match body {
586 Ok(Json(body)) => body,
587 Err(rejected) => return rejected.into_response(),
588 };
589 let Some(fields) = body.as_object() else {
590 return refusal(
591 StatusCode::BAD_REQUEST,
592 "a spool command's body is a document of its fields",
593 );
594 };
595 let actor = match claimed_actor(fields) {
596 Ok(actor) => actor,
597 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
598 };
599 if let Some(refused) = claim_refused(&caller, &actor) {
600 return refused;
601 }
602 let asked = match spool_command_of(kind, spool_id, body) {
603 Ok(asked) => asked,
604 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
605 };
606 let outcome = match state.supervisor.request_spool_command(asked).await {
607 Ok(outcome) => outcome,
608 Err(error) => return refusal(core_status(&error), error),
609 };
610 let status = match outcome.decision {
611 PolicyDecision::Accepted => StatusCode::OK,
612 PolicyDecision::Rejected(_) => StatusCode::CONFLICT,
614 };
615 answer(
616 status,
617 &SpoolCommandAnswer {
618 decision: outcome.decision,
619 spool: outcome.spool,
620 events: outcome.events,
621 },
622 )
623}
624
625async fn recover(
633 kind: RecoveryActionKind,
634 State(state): State<ApiState>,
635 Extension(caller): Extension<Caller>,
636 body: Result<Json<Value>, JsonRejection>,
637) -> Response {
638 let body = match body {
639 Ok(Json(body)) => body,
640 Err(rejected) => return rejected.into_response(),
641 };
642 if let Some(fields) = body.as_object() {
643 let actor = match claimed_actor(fields) {
644 Ok(actor) => actor,
645 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
646 };
647 if let Some(refused) = claim_refused(&caller, &actor) {
648 return refused;
649 }
650 }
651 let (action, actor, reason) = match recovery_of(kind, body) {
652 Ok(asked) => asked,
653 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
654 };
655 let issued = match state
656 .supervisor
657 .request_recovery(action.clone(), actor, reason)
658 .await
659 {
660 Ok(issued) => issued,
661 Err(error) => return refusal(core_status(&error), error),
662 };
663 let config = state.supervisor.config().recovery;
664 let status = match &issued.decision {
665 RecoveryDecision::Executed(ExecutionOutcome::Succeeded) => StatusCode::OK,
666 RecoveryDecision::Executed(ExecutionOutcome::Failed { .. }) => StatusCode::BAD_GATEWAY,
669 RecoveryDecision::Rejected(_) => StatusCode::CONFLICT,
671 };
672 answer(
673 status,
674 &RecoveryAnswer {
675 detail: recovery_detail(&action, &issued.decision, config.as_ref()),
676 action,
677 decision: issued.decision,
678 events: vec![issued.requested, issued.settled],
679 },
680 )
681}
682
683async fn recover_status(
686 State(state): State<ApiState>,
687 Extension(caller): Extension<Caller>,
688) -> Response {
689 let class = match caller {
690 Caller::Operator => ActorClass::Operator,
691 Caller::Turn(_) => ActorClass::Agent,
692 };
693 match state.supervisor.recovery_status(class).await {
694 Ok(status) => answer(StatusCode::OK, &status),
695 Err(error) => refusal(core_status(&error), error),
696 }
697}
698
699async fn spools(State(state): State<ApiState>, Query(params): Query<SpoolsParams>) -> Response {
701 let listed = match state
702 .supervisor
703 .spools(params.include_retired.unwrap_or(false))
704 .await
705 {
706 Ok(listed) => listed,
707 Err(error) => return refusal(core_status(&error), error),
708 };
709 match state.supervisor.pending_charges(None).await {
710 Ok(pending) => answer(StatusCode::OK, &SpoolsAnswer::of(listed, pending)),
711 Err(error) => refusal(core_status(&error), error),
712 }
713}
714
715async fn spool(State(state): State<ApiState>, Path(spool_id): Path<SpoolId>) -> Response {
717 let found = match state.supervisor.spool(spool_id).await {
718 Ok(Some(found)) => found,
719 Ok(None) => {
720 return refusal(
721 StatusCode::NOT_FOUND,
722 format!("there is no spool {spool_id}"),
723 );
724 }
725 Err(error) => return refusal(core_status(&error), error),
726 };
727 let query = TimelineQuery {
728 spool_id: Some(spool_id),
729 limit: Some(SPOOL_RECENT_EVENTS),
730 ..every_timeline_kind()
731 };
732 match state.supervisor.timeline(query).await {
733 Ok(recent) => answer(
734 StatusCode::OK,
735 &SpoolAnswer {
736 spool: found,
737 recent,
738 },
739 ),
740 Err(error) => refusal(core_status(&error), error),
741 }
742}
743
744const fn every_timeline_kind() -> TimelineQuery {
746 TimelineQuery {
747 kinds: Vec::new(),
748 since: None,
749 until: None,
750 spool_id: None,
751 before: None,
752 limit: None,
753 }
754}
755
756fn read_one<T: core::str::FromStr>(name: &str, text: &str) -> Result<T, String>
758where
759 T::Err: core::fmt::Display,
760{
761 text.parse()
762 .map_err(|error: T::Err| format!("`{name}` is `{text}`, which will not do: {error}"))
763}
764
765fn timeline_query(asked: &[(String, String)]) -> Result<TimelineQuery, String> {
772 let mut query = every_timeline_kind();
773 let mut seen: Vec<&str> = Vec::new();
774 for (name, text) in asked {
775 if name != "kinds" {
776 if seen.contains(&name.as_str()) {
777 return Err(format!(
778 "`{name}` was given more than once, and this read takes one"
779 ));
780 }
781 seen.push(name);
782 }
783 match name.as_str() {
784 "kinds" => query.kinds.push(read_one::<EventKind>(name, text)?),
785 "since" => query.since = Some(read_one::<Timestamp>(name, text)?),
786 "until" => query.until = Some(read_one::<Timestamp>(name, text)?),
787 "spool_id" => query.spool_id = Some(read_one::<SpoolId>(name, text)?),
788 "before" => query.before = Some(read_one::<EventId>(name, text)?),
789 "limit" => query.limit = Some(read_one::<u32>(name, text)?),
790 other => return Err(format!("the printer history takes no `{other}`")),
791 }
792 }
793 Ok(query)
794}
795
796async fn printer_history(
802 State(state): State<ApiState>,
803 Query(asked): Query<Vec<(String, String)>>,
804) -> Response {
805 let query = match timeline_query(&asked) {
806 Ok(query) => query,
807 Err(refused) => return refusal(StatusCode::BAD_REQUEST, refused),
808 };
809 let limit = match query.resolved_limit() {
810 Ok(limit) => limit,
811 Err(error) => return refusal(store_status(&error), error),
812 };
813 let events = match state.supervisor.timeline(query.clone()).await {
814 Ok(events) => events,
815 Err(error) => return refusal(core_status(&error), error),
816 };
817 let full = u32::try_from(events.len()).is_ok_and(|read| read == limit);
818 let next = match events.last() {
819 Some(last) if full => {
820 let older = TimelineQuery {
821 before: Some(last.id),
822 limit: Some(1),
823 ..query
824 };
825 match state.supervisor.timeline(older).await {
826 Ok(older) if older.is_empty() => None,
827 Ok(_) => Some(last.id),
828 Err(error) => return refusal(core_status(&error), error),
829 }
830 }
831 _ => None,
832 };
833 answer(StatusCode::OK, &TimelineAnswer { events, next })
834}
835
836async fn preflight(
838 State(state): State<ApiState>,
839 Query(params): Query<PreflightParams>,
840) -> Response {
841 let Some(named) = params.file_name else {
842 return refusal(
843 StatusCode::BAD_REQUEST,
844 "a filament check needs `file_name`, and this request carries none",
845 );
846 };
847 let file_name = match FileName::new(&named) {
848 Ok(file_name) => file_name,
849 Err(error) => return refusal(StatusCode::BAD_REQUEST, error),
850 };
851 match state.supervisor.preflight(&file_name).await {
852 Ok(preflight) => answer(StatusCode::OK, &PreflightAnswer { preflight }),
853 Err(error) => refusal(core_status(&error), error),
854 }
855}
856
857async fn list_and_adopt_prints(State(state): State<ApiState>) -> Response {
864 match state.supervisor.list_and_adopt_prints().await {
865 Ok(listing) => answer(
866 StatusCode::OK,
867 &PrintsAnswer {
868 prints: listing.prints,
869 active: listing.active,
870 },
871 ),
872 Err(error) => refusal(core_status(&error), error),
873 }
874}
875
876async fn status(
882 State(state): State<ApiState>,
883 Extension(caller): Extension<Caller>,
884 Path(print_id): Path<PrintId>,
885) -> Response {
886 if let Some(refused) = scope_refused(&caller, print_id) {
887 return refused;
888 }
889 match state.prints.print(print_id).await {
890 Ok(Some(_)) => {}
891 Ok(None) => {
892 return refusal(
893 StatusCode::NOT_FOUND,
894 format!("there is no print {print_id}"),
895 );
896 }
897 Err(error) => return refusal(store_status(&error), error),
898 }
899 let context = match state.supervisor.context(print_id).await {
900 Ok(context) => context,
901 Err(error) => return refusal(core_status(&error), error),
902 };
903 let session = match state.sessions.session(print_id).await {
904 Ok(session) => session,
905 Err(error) => return refusal(store_status(&error), error),
906 };
907 answer(
908 StatusCode::OK,
909 &StatusAnswer {
910 print: context.print,
911 printer: context.printer,
912 job: context.job,
913 session,
914 interventions: context.interventions,
915 detector: context.detector,
916 },
917 )
918}
919
920async fn context(
928 State(state): State<ApiState>,
929 Extension(caller): Extension<Caller>,
930 Path(print_id): Path<PrintId>,
931) -> Response {
932 if let Some(refused) = scope_refused(&caller, print_id) {
933 return refused;
934 }
935 let context = match state.supervisor.context(print_id).await {
936 Ok(context) => context,
937 Err(error) => return refusal(core_status(&error), error),
938 };
939 let mut image_path = None;
940 if let Some(latest) = context.latest_image.as_ref() {
941 match state.images.image(latest.id).await {
942 Ok(lookup) => image_path = ImageAnswer::from(lookup).path,
943 Err(error) => return refusal(store_status(&error), error),
944 }
945 }
946 answer(
947 StatusCode::OK,
948 &ContextAnswer {
949 context,
950 image_path,
951 },
952 )
953}
954
955async fn look(
963 State(state): State<ApiState>,
964 Extension(caller): Extension<Caller>,
965 Path(print_id): Path<PrintId>,
966 Query(params): Query<LookParams>,
967) -> Response {
968 if let Some(refused) = scope_refused(&caller, print_id) {
969 return refused;
970 }
971 let wait_s = params.wait_s.unwrap_or(0);
972 if wait_s > MAX_LOOK_WAIT_S {
973 return refusal(
974 StatusCode::BAD_REQUEST,
975 format!("wait_s may be at most {MAX_LOOK_WAIT_S}; {wait_s} was asked for"),
976 );
977 }
978 match state.prints.print(print_id).await {
979 Ok(Some(_)) => {}
980 Ok(None) => {
981 return refusal(StatusCode::NOT_FOUND, CoreError::NoSuchPrint { print_id });
982 }
983 Err(error) => return refusal(store_status(&error), error),
984 }
985 let supervisor = Arc::clone(&state.supervisor);
986 let taken = tokio::task::spawn_blocking(move || {
987 let started = std::time::Instant::now();
988 let arrived = supervisor.await_arrivals(print_id, Duration::from_secs(u64::from(wait_s)));
989 printobserver_core::block_on(supervisor.take_look(print_id, started.elapsed(), arrived))
990 })
991 .await;
992 match taken {
993 Ok(Ok(look)) => answer(StatusCode::OK, &look),
994 Ok(Err(error)) => refusal(core_status(&error), error),
995 Err(error) => refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
996 }
997}
998
999async fn image(
1004 State(state): State<ApiState>,
1005 Extension(caller): Extension<Caller>,
1006 Path(image_id): Path<ImageId>,
1007) -> Response {
1008 match state.images.image(image_id).await {
1009 Ok(lookup) => {
1010 let belongs_to = match &lookup {
1011 printobserver_core::ImageLookup::Found { record, .. }
1012 | printobserver_core::ImageLookup::FileMissing { record } => record.print_id,
1013 };
1014 if let Some(refused) = scope_refused(&caller, belongs_to) {
1015 return refused;
1016 }
1017 answer(StatusCode::OK, &ImageAnswer::from(lookup))
1018 }
1019 Err(error) => refusal(store_status(&error), error),
1020 }
1021}
1022
1023async fn history(
1025 State(state): State<ApiState>,
1026 Extension(caller): Extension<Caller>,
1027 Path(print_id): Path<PrintId>,
1028 Query(params): Query<HistoryParams>,
1029) -> Response {
1030 if let Some(refused) = scope_refused(&caller, print_id) {
1031 return refused;
1032 }
1033 let query = HistoryQuery {
1034 print_id,
1035 kinds: Vec::new(),
1036 since: None,
1037 until: None,
1038 limit: params.limit,
1039 };
1040 match state.events.history(query).await {
1041 Ok(events) => answer(StatusCode::OK, &HistoryAnswer { events }),
1042 Err(error) => refusal(store_status(&error), error),
1043 }
1044}
1045
1046async fn manifest_get(
1048 State(state): State<ApiState>,
1049 Extension(caller): Extension<Caller>,
1050 Path(print_id): Path<PrintId>,
1051) -> Response {
1052 if let Some(refused) = scope_refused(&caller, print_id) {
1053 return refused;
1054 }
1055 let manifest = match state.prints.manifest(print_id).await {
1056 Ok(manifest) => manifest,
1057 Err(error) => return refusal(store_status(&error), error),
1058 };
1059 let narrowings = match state.prints.print(print_id).await {
1060 Ok(print) => print.map(|record| record.narrowings).unwrap_or_default(),
1061 Err(error) => return refusal(store_status(&error), error),
1062 };
1063 answer(
1064 StatusCode::OK,
1065 &ManifestAnswer {
1066 manifest,
1067 narrowings,
1068 },
1069 )
1070}
1071
1072async fn manifest_set(
1081 State(state): State<ApiState>,
1082 Extension(caller): Extension<Caller>,
1083 Path(print_id): Path<PrintId>,
1084 body: Result<Json<ManifestBody>, JsonRejection>,
1085) -> Response {
1086 if let Some(refused) =
1087 operator_refused(&caller, &crate::operations::command_for("manifest_set"))
1088 {
1089 return refused;
1090 }
1091 let body = match body {
1092 Ok(Json(body)) => body,
1093 Err(rejected) => return rejected.into_response(),
1094 };
1095 if let Err(rejected) = body.reason() {
1096 return refusal(StatusCode::BAD_REQUEST, rejected);
1097 }
1098 let narrowed = effective_bounds(&state.supervisor.config().envelope, Some(&body.manifest));
1099 if let Err(error) = state
1100 .prints
1101 .put_manifest(print_id, body.manifest.clone())
1102 .await
1103 {
1104 return refusal(store_status(&error), error);
1105 }
1106 for narrowing in narrowed.narrowings.clone() {
1107 if let Err(error) = state.prints.record_narrowing(print_id, narrowing).await {
1108 return refusal(store_status(&error), error);
1109 }
1110 }
1111 answer(
1112 StatusCode::OK,
1113 &ManifestAnswer {
1114 manifest: Some(body.manifest),
1115 narrowings: narrowed.narrowings,
1116 },
1117 )
1118}
1119
1120#[cfg(test)]
1121mod tests {
1122 use axum::http::StatusCode;
1123 use printobserver_core::CoreError;
1124 use printobserver_core::store::StoreError;
1125
1126 use super::{core_status, store_status};
1127
1128 #[test]
1131 fn every_store_refusal_is_answered_under_a_status_a_caller_can_act_on() {
1132 for (error, expected) in [
1133 (
1134 StoreError::NotFound {
1135 what: "print".to_owned(),
1136 },
1137 StatusCode::NOT_FOUND,
1138 ),
1139 (
1140 StoreError::LimitRefused {
1141 limit: 1_000,
1142 asked_for: 2_000,
1143 },
1144 StatusCode::BAD_REQUEST,
1145 ),
1146 (
1147 StoreError::ConstraintRefused {
1148 constraint: "actions.decision".to_owned(),
1149 },
1150 StatusCode::BAD_REQUEST,
1151 ),
1152 (
1153 StoreError::Database {
1154 detail: "the disk is full".to_owned(),
1155 },
1156 StatusCode::INTERNAL_SERVER_ERROR,
1157 ),
1158 (
1159 StoreError::Io {
1160 detail: "the disk is full".to_owned(),
1161 },
1162 StatusCode::INTERNAL_SERVER_ERROR,
1163 ),
1164 ] {
1165 assert_eq!(store_status(&error), expected, "{error}");
1166 }
1167 }
1168
1169 #[test]
1172 fn a_print_nothing_holds_is_not_found_and_a_port_failure_is_this_servers_own() {
1173 assert_eq!(
1174 core_status(&CoreError::NoSuchPrint {
1175 print_id: printobserver_types::PrintId::new(),
1176 }),
1177 StatusCode::NOT_FOUND
1178 );
1179 assert_eq!(
1180 core_status(&CoreError::Store(StoreError::NotFound {
1181 what: "print".to_owned(),
1182 })),
1183 StatusCode::NOT_FOUND
1184 );
1185 assert_eq!(
1186 core_status(&CoreError::Unrepresentable {
1187 detail: "an instant".to_owned(),
1188 }),
1189 StatusCode::INTERNAL_SERVER_ERROR
1190 );
1191 }
1192}