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, SheetId, 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 printless_refused(caller: &Caller, what: &str) -> Option<Response> {
201 match caller {
202 Caller::Turn(_) => Some(refusal(
203 StatusCode::FORBIDDEN,
204 format!(
205 "this request authenticated as {} and asks for {what}: a supervision turn's \
206 credential reaches its own print alone",
207 caller.named()
208 ),
209 )),
210 Caller::Operator => None,
211 }
212}
213
214fn operator_refused(caller: &Caller, command: &str) -> Option<Response> {
217 match caller {
218 Caller::Turn(_) => Some(refusal(
219 StatusCode::FORBIDDEN,
220 format!(
221 "this request authenticated as {} and asks for `{command}`, which is the \
222 operator's alone: a supervision turn's credential does not reach it",
223 caller.named()
224 ),
225 )),
226 Caller::Operator => None,
227 }
228}
229
230#[derive(Clone)]
232pub struct Admission {
233 operator: Arc<OperatorCredential>,
235 turns: TurnCredentials,
237}
238
239impl Admission {
240 fn caller(&self, presented: &[u8]) -> Option<Caller> {
242 if let Some(binding) = self.turns.admit(presented) {
243 return Some(Caller::Turn(binding));
244 }
245 self.operator.admits(presented).then_some(Caller::Operator)
246 }
247}
248
249impl core::fmt::Debug for ApiState {
250 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
251 formatter.debug_struct("ApiState").finish_non_exhaustive()
252 }
253}
254
255#[derive(Debug, Clone, Deserialize)]
257#[serde(crate = "printobserver_types::serde")]
258pub struct HistoryParams {
259 #[serde(default)]
261 pub limit: Option<u32>,
262}
263
264#[derive(Debug, Clone, Deserialize)]
267#[serde(crate = "printobserver_types::serde")]
268pub struct ContextParams {
269 #[serde(default)]
271 pub since: Option<printobserver_types::EventId>,
272}
273
274#[derive(Debug, Clone, Deserialize)]
276#[serde(crate = "printobserver_types::serde")]
277pub struct LookParams {
278 #[serde(default)]
280 pub wait_s: Option<u32>,
281}
282
283#[derive(Debug, Clone, Deserialize)]
285#[serde(crate = "printobserver_types::serde")]
286pub struct SpoolsParams {
287 #[serde(default)]
289 pub include_retired: Option<bool>,
290}
291
292#[derive(Debug, Clone, Deserialize)]
294#[serde(crate = "printobserver_types::serde")]
295pub struct PreflightParams {
296 #[serde(default)]
298 pub file_name: Option<String>,
299 #[serde(default)]
303 pub sheet: Option<String>,
304}
305
306pub const SPOOL_RECENT_EVENTS: u32 = 20;
308
309pub fn router(state: ApiState) -> Router {
317 let mut api = Router::new();
318 for operation in OPERATIONS {
319 api = api.route(operation.path, route_for(&operation));
320 }
321 let api = api
324 .fallback(nothing_here)
325 .layer(from_fn_with_state(
326 Admission {
327 operator: Arc::clone(&state.operator),
328 turns: state.turns.clone(),
329 },
330 authenticate,
331 ))
332 .layer(DefaultBodyLimit::max(BODY_BOUND))
333 .with_state(state);
334 Router::new().nest(VERSION_PREFIX, api)
335}
336
337const BEARER: &[u8] = b"Bearer ";
339
340pub const BODY_BOUND: usize = 2 * 1024 * 1024;
347
348pub const DRAIN_BOUND: Duration = Duration::from_secs(2);
354
355pub async fn authenticate(
373 State(admission): State<Admission>,
374 mut request: Request,
375 next: Next,
376) -> Response {
377 let mut presented = request.headers().get_all(header::AUTHORIZATION).iter();
378 let admitted = match (presented.next(), presented.next()) {
379 (Some(only), None) => only
380 .as_bytes()
381 .strip_prefix(BEARER)
382 .and_then(|offered| admission.caller(offered)),
383 _ => None,
384 };
385 if let Some(caller) = admitted {
386 request.extensions_mut().insert(caller);
387 return next.run(request).await;
388 }
389 {
390 let said = if matches!(*admission.operator, OperatorCredential::Unconfigured) {
391 format!(
392 "this server's API requires a credential, presented as `Authorization: Bearer \
393 <credential>`, and this server has no operator credential yet: run \
394 `{CREDENTIAL_ISSUE}` as the operator, put the `api.credential_verifier` line it \
395 prints into the server's configuration, and restart the service"
396 )
397 } else {
398 format!(
399 "this server's API requires the credential it is configured with, presented as \
400 `Authorization: Bearer <credential>`. An operator without one runs \
401 `{CREDENTIAL_ISSUE}`"
402 )
403 };
404 let mut refused = refusal(StatusCode::UNAUTHORIZED, said);
405 refused.headers_mut().insert(
406 header::WWW_AUTHENTICATE,
407 header::HeaderValue::from_static("Bearer"),
408 );
409 let _ = tokio::time::timeout(
413 DRAIN_BOUND,
414 axum::body::to_bytes(request.into_body(), BODY_BOUND),
415 )
416 .await;
417 refused
418 }
419}
420
421async fn nothing_here() -> Response {
423 refusal(
424 StatusCode::NOT_FOUND,
425 "no operation of this server is served at that path",
426 )
427}
428
429fn route_for(operation: &Operation) -> MethodRouter<ApiState> {
431 if let Effect::Command(spool_command) = operation.effect {
432 let kind = spool_command.action_kind();
433 if operation.path.contains("{spool_id}") {
434 return post(
435 move |state: State<ApiState>,
436 caller: Extension<Caller>,
437 Path(spool_id): Path<SpoolId>,
438 body: Result<Json<Value>, JsonRejection>| async move {
439 command(kind, state, caller, Some(spool_id), body).await
440 },
441 );
442 }
443 return post(
444 move |state: State<ApiState>,
445 caller: Extension<Caller>,
446 body: Result<Json<Value>, JsonRejection>| async move {
447 command(kind, state, caller, None, body).await
448 },
449 );
450 }
451 if let Effect::Recovery(kind) = operation.effect {
452 return post(
453 move |state: State<ApiState>,
454 caller: Extension<Caller>,
455 body: Result<Json<Value>, JsonRejection>| async move {
456 recover(kind, state, caller, body).await
457 },
458 );
459 }
460 if let Effect::Mutating(kind) = operation.effect {
461 return post(
462 move |state: State<ApiState>,
463 caller: Extension<Caller>,
464 print_id: Path<PrintId>,
465 body: Result<Json<ActionBody>, JsonRejection>| async move {
466 act(kind, state, caller, print_id, body).await
467 },
468 );
469 }
470 match (operation.name, operation.method) {
471 ("prints", Method::Get) => get(list_and_adopt_prints),
472 ("status", Method::Get) => get(status),
473 ("context", Method::Get) => get(context),
474 ("image", Method::Get) => get(image),
475 ("history", Method::Get) => get(history),
476 ("events", Method::Get) => get(crate::events::events),
477 ("look", Method::Get) => get(look),
478 (crate::operations::PRINTER_LOOK, Method::Get) => get(printer_look),
479 ("manifest_get", Method::Get) => get(manifest_get),
480 ("manifest_set", Method::Put) => put(manifest_set),
481 ("spools", Method::Get) => get(spools),
482 ("spool", Method::Get) => get(spool),
483 ("printer_history", Method::Get) => get(printer_history),
484 ("preflight", Method::Get) => get(preflight),
485 (crate::operations::RECOVERY_STATUS, Method::Get) => get(recover_status),
486 (name, method) => panic!(
487 "the operation `{name}` is declared as {method} and this router serves no such route"
488 ),
489 }
490}
491
492pub(crate) fn answer<T: printobserver_types::serde::Serialize>(
494 status: StatusCode,
495 body: &T,
496) -> Response {
497 let rendered = match printobserver_types::serde_json::to_vec(body) {
498 Ok(bytes) => bytes,
499 Err(error) => {
500 return (
501 StatusCode::INTERNAL_SERVER_ERROR,
502 [(header::CONTENT_TYPE, crate::operations::MEDIA_TYPE)],
503 format!("{{\"error\":\"{error}\"}}"),
504 )
505 .into_response();
506 }
507 };
508 (
509 status,
510 [(header::CONTENT_TYPE, crate::operations::MEDIA_TYPE)],
511 rendered,
512 )
513 .into_response()
514}
515
516pub(crate) fn refusal(status: StatusCode, detail: impl core::fmt::Display) -> Response {
518 answer(status, &ErrorAnswer::saying(detail))
519}
520
521pub(crate) fn store_status(error: &StoreError) -> StatusCode {
523 match error {
524 StoreError::NotFound { .. } => StatusCode::NOT_FOUND,
525 StoreError::LimitRefused { .. } | StoreError::ConstraintRefused { .. } => {
526 StatusCode::BAD_REQUEST
527 }
528 StoreError::Database { .. } | StoreError::Io { .. } => StatusCode::INTERNAL_SERVER_ERROR,
529 }
530}
531
532fn core_status(error: &CoreError) -> StatusCode {
534 match error {
535 CoreError::NoSuchPrint { .. } => StatusCode::NOT_FOUND,
536 CoreError::Store(store) => store_status(store),
537 _ => StatusCode::INTERNAL_SERVER_ERROR,
538 }
539}
540
541async fn act(
549 kind: ActionKind,
550 State(state): State<ApiState>,
551 Extension(caller): Extension<Caller>,
552 Path(print_id): Path<PrintId>,
553 body: Result<Json<ActionBody>, JsonRejection>,
554) -> Response {
555 if kind == ActionKind::StartPrint
556 && let Some(refused) =
557 operator_refused(&caller, &crate::operations::command_for("start_print"))
558 {
559 return refused;
560 }
561 if let Some(refused) = scope_refused(&caller, print_id) {
562 return refused;
563 }
564 let body = match body {
565 Ok(Json(body)) => body,
566 Err(rejected) => return rejected.into_response(),
567 };
568 if let Some(refused) = claim_refused(&caller, &body.actor) {
569 return refused;
570 }
571 let action = match body.into_action(kind) {
572 Ok(action) => action,
573 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
574 };
575 let outcome = match state.supervisor.request_action(print_id, action).await {
576 Ok(outcome) => outcome,
577 Err(error) => return refusal(core_status(&error), error),
578 };
579 let printer_refusal = match &outcome.record.outcome {
580 Some(ExecutionOutcome::Failed { reason }) => Some(reason.clone()),
581 _ => None,
582 };
583 let status = match outcome.record.decision {
584 PolicyDecision::Accepted if printer_refusal.is_none() => StatusCode::OK,
585 PolicyDecision::Accepted => StatusCode::BAD_GATEWAY,
589 PolicyDecision::Rejected(_) => StatusCode::CONFLICT,
592 };
593 answer(
594 status,
595 &ActionAnswer {
596 record: outcome.record,
597 intervention: outcome.intervention,
598 printer_refusal,
599 },
600 )
601}
602
603async fn command(
612 kind: ActionKind,
613 State(state): State<ApiState>,
614 Extension(caller): Extension<Caller>,
615 spool_id: Option<SpoolId>,
616 body: Result<Json<Value>, JsonRejection>,
617) -> Response {
618 let body = match body {
619 Ok(Json(body)) => body,
620 Err(rejected) => return rejected.into_response(),
621 };
622 let Some(fields) = body.as_object() else {
623 return refusal(
624 StatusCode::BAD_REQUEST,
625 "a spool command's body is a document of its fields",
626 );
627 };
628 let actor = match claimed_actor(fields) {
629 Ok(actor) => actor,
630 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
631 };
632 if let Some(refused) = claim_refused(&caller, &actor) {
633 return refused;
634 }
635 let asked = match spool_command_of(kind, spool_id, body) {
636 Ok(asked) => asked,
637 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
638 };
639 let outcome = match state.supervisor.request_spool_command(asked).await {
640 Ok(outcome) => outcome,
641 Err(error) => return refusal(core_status(&error), error),
642 };
643 let status = match outcome.decision {
644 PolicyDecision::Accepted => StatusCode::OK,
645 PolicyDecision::Rejected(_) => StatusCode::CONFLICT,
647 };
648 answer(
649 status,
650 &SpoolCommandAnswer {
651 decision: outcome.decision,
652 spool: outcome.spool,
653 events: outcome.events,
654 },
655 )
656}
657
658async fn recover(
666 kind: RecoveryActionKind,
667 State(state): State<ApiState>,
668 Extension(caller): Extension<Caller>,
669 body: Result<Json<Value>, JsonRejection>,
670) -> Response {
671 let body = match body {
672 Ok(Json(body)) => body,
673 Err(rejected) => return rejected.into_response(),
674 };
675 if let Some(fields) = body.as_object() {
676 let actor = match claimed_actor(fields) {
677 Ok(actor) => actor,
678 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
679 };
680 if let Some(refused) = claim_refused(&caller, &actor) {
681 return refused;
682 }
683 }
684 let (action, actor, reason) = match recovery_of(kind, body) {
685 Ok(asked) => asked,
686 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
687 };
688 let issued = match state
689 .supervisor
690 .request_recovery(action.clone(), actor, reason)
691 .await
692 {
693 Ok(issued) => issued,
694 Err(error) => return refusal(core_status(&error), error),
695 };
696 let config = state.supervisor.config().recovery;
697 let status = match &issued.decision {
698 RecoveryDecision::Executed(ExecutionOutcome::Succeeded) => StatusCode::OK,
699 RecoveryDecision::Executed(ExecutionOutcome::Failed { .. }) => StatusCode::BAD_GATEWAY,
702 RecoveryDecision::Rejected(_) => StatusCode::CONFLICT,
704 };
705 answer(
706 status,
707 &RecoveryAnswer {
708 detail: recovery_detail(&action, &issued.decision, config.as_ref()),
709 action,
710 decision: issued.decision,
711 events: vec![issued.requested, issued.settled],
712 },
713 )
714}
715
716async fn recover_status(
719 State(state): State<ApiState>,
720 Extension(caller): Extension<Caller>,
721) -> Response {
722 let class = match caller {
723 Caller::Operator => ActorClass::Operator,
724 Caller::Turn(_) => ActorClass::Agent,
725 };
726 match state.supervisor.recovery_status(class).await {
727 Ok(status) => answer(StatusCode::OK, &status),
728 Err(error) => refusal(core_status(&error), error),
729 }
730}
731
732async fn spools(State(state): State<ApiState>, Query(params): Query<SpoolsParams>) -> Response {
734 let listed = match state
735 .supervisor
736 .spools(params.include_retired.unwrap_or(false))
737 .await
738 {
739 Ok(listed) => listed,
740 Err(error) => return refusal(core_status(&error), error),
741 };
742 match state.supervisor.pending_charges(None).await {
743 Ok(pending) => answer(StatusCode::OK, &SpoolsAnswer::of(listed, pending)),
744 Err(error) => refusal(core_status(&error), error),
745 }
746}
747
748async fn spool(State(state): State<ApiState>, Path(spool_id): Path<SpoolId>) -> Response {
750 let found = match state.supervisor.spool(spool_id).await {
751 Ok(Some(found)) => found,
752 Ok(None) => {
753 return refusal(
754 StatusCode::NOT_FOUND,
755 format!("there is no spool {spool_id}"),
756 );
757 }
758 Err(error) => return refusal(core_status(&error), error),
759 };
760 let query = TimelineQuery {
761 spool_id: Some(spool_id),
762 limit: Some(SPOOL_RECENT_EVENTS),
763 ..every_timeline_kind()
764 };
765 match state.supervisor.timeline(query).await {
766 Ok(recent) => answer(
767 StatusCode::OK,
768 &SpoolAnswer {
769 spool: found,
770 recent,
771 },
772 ),
773 Err(error) => refusal(core_status(&error), error),
774 }
775}
776
777const fn every_timeline_kind() -> TimelineQuery {
779 TimelineQuery {
780 kinds: Vec::new(),
781 since: None,
782 until: None,
783 spool_id: None,
784 before: None,
785 limit: None,
786 }
787}
788
789fn read_one<T: core::str::FromStr>(name: &str, text: &str) -> Result<T, String>
791where
792 T::Err: core::fmt::Display,
793{
794 text.parse()
795 .map_err(|error: T::Err| format!("`{name}` is `{text}`, which will not do: {error}"))
796}
797
798fn timeline_query(asked: &[(String, String)]) -> Result<TimelineQuery, String> {
805 let mut query = every_timeline_kind();
806 let mut seen: Vec<&str> = Vec::new();
807 for (name, text) in asked {
808 if name != "kinds" {
809 if seen.contains(&name.as_str()) {
810 return Err(format!(
811 "`{name}` was given more than once, and this read takes one"
812 ));
813 }
814 seen.push(name);
815 }
816 match name.as_str() {
817 "kinds" => query.kinds.push(read_one::<EventKind>(name, text)?),
818 "since" => query.since = Some(read_one::<Timestamp>(name, text)?),
819 "until" => query.until = Some(read_one::<Timestamp>(name, text)?),
820 "spool_id" => query.spool_id = Some(read_one::<SpoolId>(name, text)?),
821 "before" => query.before = Some(read_one::<EventId>(name, text)?),
822 "limit" => query.limit = Some(read_one::<u32>(name, text)?),
823 other => return Err(format!("the printer history takes no `{other}`")),
824 }
825 }
826 Ok(query)
827}
828
829async fn printer_history(
835 State(state): State<ApiState>,
836 Query(asked): Query<Vec<(String, String)>>,
837) -> Response {
838 let query = match timeline_query(&asked) {
839 Ok(query) => query,
840 Err(refused) => return refusal(StatusCode::BAD_REQUEST, refused),
841 };
842 let limit = match query.resolved_limit() {
843 Ok(limit) => limit,
844 Err(error) => return refusal(store_status(&error), error),
845 };
846 let events = match state.supervisor.timeline(query.clone()).await {
847 Ok(events) => events,
848 Err(error) => return refusal(core_status(&error), error),
849 };
850 let full = u32::try_from(events.len()).is_ok_and(|read| read == limit);
851 let next = match events.last() {
852 Some(last) if full => {
853 let older = TimelineQuery {
854 before: Some(last.id),
855 limit: Some(1),
856 ..query
857 };
858 match state.supervisor.timeline(older).await {
859 Ok(older) if older.is_empty() => None,
860 Ok(_) => Some(last.id),
861 Err(error) => return refusal(core_status(&error), error),
862 }
863 }
864 _ => None,
865 };
866 answer(StatusCode::OK, &TimelineAnswer { events, next })
867}
868
869async fn preflight(
873 State(state): State<ApiState>,
874 Query(params): Query<PreflightParams>,
875) -> Response {
876 let Some(named) = params.file_name else {
877 return refusal(
878 StatusCode::BAD_REQUEST,
879 "a filament check needs `file_name`, and this request carries none",
880 );
881 };
882 let file_name = match FileName::new(&named) {
883 Ok(file_name) => file_name,
884 Err(error) => return refusal(StatusCode::BAD_REQUEST, error),
885 };
886 let sheet = match params.sheet.map(SheetId::try_from).transpose() {
887 Ok(sheet) => sheet,
888 Err(why) => return refusal(StatusCode::BAD_REQUEST, why),
889 };
890 match state.supervisor.preflight(&file_name, sheet.as_ref()).await {
891 Ok(preflight) => answer(StatusCode::OK, &PreflightAnswer { preflight }),
892 Err(error) => refusal(core_status(&error), error),
893 }
894}
895
896async fn list_and_adopt_prints(State(state): State<ApiState>) -> Response {
903 match state.supervisor.list_and_adopt_prints().await {
904 Ok(listing) => answer(
905 StatusCode::OK,
906 &PrintsAnswer {
907 prints: listing.prints,
908 active: listing.active,
909 },
910 ),
911 Err(error) => refusal(core_status(&error), error),
912 }
913}
914
915async fn status(
921 State(state): State<ApiState>,
922 Extension(caller): Extension<Caller>,
923 Path(print_id): Path<PrintId>,
924) -> Response {
925 if let Some(refused) = scope_refused(&caller, print_id) {
926 return refused;
927 }
928 match state.prints.print(print_id).await {
929 Ok(Some(_)) => {}
930 Ok(None) => {
931 return refusal(
932 StatusCode::NOT_FOUND,
933 format!("there is no print {print_id}"),
934 );
935 }
936 Err(error) => return refusal(store_status(&error), error),
937 }
938 let context = match context_of(&state, print_id).await {
939 Ok(context) => context,
940 Err(refused) => return refused,
941 };
942 let session = match state.sessions.session(print_id).await {
943 Ok(session) => session,
944 Err(error) => return refusal(store_status(&error), error),
945 };
946 answer(
947 StatusCode::OK,
948 &StatusAnswer {
949 print: context.print,
950 printer: context.printer,
951 job: context.job,
952 session,
953 interventions: context.interventions,
954 detector: context.detector,
955 },
956 )
957}
958
959async fn context_of(
967 state: &ApiState,
968 print_id: PrintId,
969) -> Result<printobserver_core::PrintContext, Response> {
970 let supervisor = Arc::clone(&state.supervisor);
971 let read = tokio::task::spawn_blocking(move || {
972 printobserver_core::block_on(supervisor.context(print_id))
973 })
974 .await;
975 match read {
976 Ok(Ok(context)) => Ok(context),
977 Ok(Err(error)) => Err(refusal(core_status(&error), error)),
978 Err(error) => Err(refusal(StatusCode::INTERNAL_SERVER_ERROR, error)),
979 }
980}
981
982async fn context(
990 State(state): State<ApiState>,
991 Extension(caller): Extension<Caller>,
992 Path(print_id): Path<PrintId>,
993 Query(params): Query<ContextParams>,
994) -> Response {
995 if let Some(refused) = scope_refused(&caller, print_id) {
996 return refused;
997 }
998 let supervisor = Arc::clone(&state.supervisor);
1000 let since = params.since;
1001 let read = tokio::task::spawn_blocking(move || {
1002 printobserver_core::block_on(supervisor.agent_context(print_id, since))
1003 })
1004 .await;
1005 let context = match read {
1006 Ok(Ok(read)) => read,
1007 Ok(Err(error)) => return refusal(core_status(&error), error),
1008 Err(error) => return refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
1009 };
1010 let mut image_path = None;
1011 if let Some(latest) = context.latest_image.as_ref() {
1012 match state.images.image(latest.id).await {
1013 Ok(lookup) => image_path = ImageAnswer::from(lookup).path,
1014 Err(error) => return refusal(store_status(&error), error),
1015 }
1016 }
1017 answer(
1018 StatusCode::OK,
1019 &ContextAnswer {
1020 context,
1021 image_path,
1022 },
1023 )
1024}
1025
1026async fn look(
1034 State(state): State<ApiState>,
1035 Extension(caller): Extension<Caller>,
1036 Path(print_id): Path<PrintId>,
1037 Query(params): Query<LookParams>,
1038) -> Response {
1039 if let Some(refused) = scope_refused(&caller, print_id) {
1040 return refused;
1041 }
1042 let wait_s = params.wait_s.unwrap_or(0);
1043 if wait_s > MAX_LOOK_WAIT_S {
1044 return refusal(
1045 StatusCode::BAD_REQUEST,
1046 format!("wait_s may be at most {MAX_LOOK_WAIT_S}; {wait_s} was asked for"),
1047 );
1048 }
1049 match state.prints.print(print_id).await {
1050 Ok(Some(_)) => {}
1051 Ok(None) => {
1052 return refusal(StatusCode::NOT_FOUND, CoreError::NoSuchPrint { print_id });
1053 }
1054 Err(error) => return refusal(store_status(&error), error),
1055 }
1056 let supervisor = Arc::clone(&state.supervisor);
1057 let taken = tokio::task::spawn_blocking(move || {
1058 let (arrived, waited) =
1059 supervisor.await_look_arrivals(print_id, Duration::from_secs(u64::from(wait_s)));
1060 printobserver_core::block_on(supervisor.take_look(print_id, waited, arrived))
1061 })
1062 .await;
1063 match taken {
1064 Ok(Ok(look)) => answer(StatusCode::OK, &look),
1065 Ok(Err(error)) => refusal(core_status(&error), error),
1066 Err(error) => refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
1067 }
1068}
1069
1070async fn printer_look(
1077 State(state): State<ApiState>,
1078 Extension(caller): Extension<Caller>,
1079 Query(params): Query<LookParams>,
1080) -> Response {
1081 if let Some(refused) = printless_refused(&caller, "a look at the printer with no print named") {
1082 return refused;
1083 }
1084 let wait_s = params.wait_s.unwrap_or(0);
1085 if wait_s > MAX_LOOK_WAIT_S {
1086 return refusal(
1087 StatusCode::BAD_REQUEST,
1088 format!("wait_s may be at most {MAX_LOOK_WAIT_S}; {wait_s} was asked for"),
1089 );
1090 }
1091 let waited = Duration::from_secs(u64::from(wait_s));
1092 tokio::time::sleep(waited).await;
1093 match state.supervisor.take_printer_look(waited).await {
1094 Ok(look) => answer(StatusCode::OK, &look),
1095 Err(error) => refusal(core_status(&error), error),
1096 }
1097}
1098
1099async fn image(
1105 State(state): State<ApiState>,
1106 Extension(caller): Extension<Caller>,
1107 Path(image_id): Path<ImageId>,
1108) -> Response {
1109 match state.images.image(image_id).await {
1110 Ok(lookup) => {
1111 let belongs_to = match &lookup {
1112 printobserver_core::ImageLookup::Found { record, .. }
1113 | printobserver_core::ImageLookup::FileMissing { record } => record.print_id,
1114 };
1115 let refused = match belongs_to {
1116 Some(print_id) => scope_refused(&caller, print_id),
1117 None => {
1118 printless_refused(&caller, "a frame of the printer that belongs to no print")
1119 }
1120 };
1121 if let Some(refused) = refused {
1122 return refused;
1123 }
1124 answer(StatusCode::OK, &ImageAnswer::from(lookup))
1125 }
1126 Err(error) => refusal(store_status(&error), error),
1127 }
1128}
1129
1130async fn history(
1132 State(state): State<ApiState>,
1133 Extension(caller): Extension<Caller>,
1134 Path(print_id): Path<PrintId>,
1135 Query(params): Query<HistoryParams>,
1136) -> Response {
1137 if let Some(refused) = scope_refused(&caller, print_id) {
1138 return refused;
1139 }
1140 let query = HistoryQuery {
1141 print_id,
1142 kinds: Vec::new(),
1143 since: None,
1144 until: None,
1145 limit: params.limit,
1146 };
1147 match state.events.history(query).await {
1148 Ok(events) => answer(StatusCode::OK, &HistoryAnswer { events }),
1149 Err(error) => refusal(store_status(&error), error),
1150 }
1151}
1152
1153async fn manifest_get(
1155 State(state): State<ApiState>,
1156 Extension(caller): Extension<Caller>,
1157 Path(print_id): Path<PrintId>,
1158) -> Response {
1159 if let Some(refused) = scope_refused(&caller, print_id) {
1160 return refused;
1161 }
1162 let manifest = match state.prints.manifest(print_id).await {
1163 Ok(manifest) => manifest,
1164 Err(error) => return refusal(store_status(&error), error),
1165 };
1166 let narrowings = match state.prints.print(print_id).await {
1167 Ok(print) => print.map(|record| record.narrowings).unwrap_or_default(),
1168 Err(error) => return refusal(store_status(&error), error),
1169 };
1170 answer(
1171 StatusCode::OK,
1172 &ManifestAnswer {
1173 manifest,
1174 narrowings,
1175 },
1176 )
1177}
1178
1179async fn manifest_set(
1188 State(state): State<ApiState>,
1189 Extension(caller): Extension<Caller>,
1190 Path(print_id): Path<PrintId>,
1191 body: Result<Json<ManifestBody>, JsonRejection>,
1192) -> Response {
1193 if let Some(refused) =
1194 operator_refused(&caller, &crate::operations::command_for("manifest_set"))
1195 {
1196 return refused;
1197 }
1198 let body = match body {
1199 Ok(Json(body)) => body,
1200 Err(rejected) => return rejected.into_response(),
1201 };
1202 if let Err(rejected) = body.reason() {
1203 return refusal(StatusCode::BAD_REQUEST, rejected);
1204 }
1205 let narrowed = effective_bounds(&state.supervisor.config().envelope, Some(&body.manifest));
1206 if let Err(error) = state
1207 .prints
1208 .put_manifest(print_id, body.manifest.clone())
1209 .await
1210 {
1211 return refusal(store_status(&error), error);
1212 }
1213 for narrowing in narrowed.narrowings.clone() {
1214 if let Err(error) = state.prints.record_narrowing(print_id, narrowing).await {
1215 return refusal(store_status(&error), error);
1216 }
1217 }
1218 answer(
1219 StatusCode::OK,
1220 &ManifestAnswer {
1221 manifest: Some(body.manifest),
1222 narrowings: narrowed.narrowings,
1223 },
1224 )
1225}
1226
1227#[cfg(test)]
1228mod tests {
1229 use axum::http::StatusCode;
1230 use printobserver_core::CoreError;
1231 use printobserver_core::store::StoreError;
1232
1233 use super::{core_status, store_status};
1234
1235 #[test]
1238 fn every_store_refusal_is_answered_under_a_status_a_caller_can_act_on() {
1239 for (error, expected) in [
1240 (
1241 StoreError::NotFound {
1242 what: "print".to_owned(),
1243 },
1244 StatusCode::NOT_FOUND,
1245 ),
1246 (
1247 StoreError::LimitRefused {
1248 limit: 1_000,
1249 asked_for: 2_000,
1250 },
1251 StatusCode::BAD_REQUEST,
1252 ),
1253 (
1254 StoreError::ConstraintRefused {
1255 constraint: "actions.decision".to_owned(),
1256 },
1257 StatusCode::BAD_REQUEST,
1258 ),
1259 (
1260 StoreError::Database {
1261 detail: "the disk is full".to_owned(),
1262 },
1263 StatusCode::INTERNAL_SERVER_ERROR,
1264 ),
1265 (
1266 StoreError::Io {
1267 detail: "the disk is full".to_owned(),
1268 },
1269 StatusCode::INTERNAL_SERVER_ERROR,
1270 ),
1271 ] {
1272 assert_eq!(store_status(&error), expected, "{error}");
1273 }
1274 }
1275
1276 #[test]
1279 fn a_print_nothing_holds_is_not_found_and_a_port_failure_is_this_servers_own() {
1280 assert_eq!(
1281 core_status(&CoreError::NoSuchPrint {
1282 print_id: printobserver_types::PrintId::new(),
1283 }),
1284 StatusCode::NOT_FOUND
1285 );
1286 assert_eq!(
1287 core_status(&CoreError::Store(StoreError::NotFound {
1288 what: "print".to_owned(),
1289 })),
1290 StatusCode::NOT_FOUND
1291 );
1292 assert_eq!(
1293 core_status(&CoreError::Unrepresentable {
1294 detail: "an instant".to_owned(),
1295 }),
1296 StatusCode::INTERNAL_SERVER_ERROR
1297 );
1298 }
1299}