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)]
266#[serde(crate = "printobserver_types::serde")]
267pub struct LookParams {
268 #[serde(default)]
270 pub wait_s: Option<u32>,
271}
272
273#[derive(Debug, Clone, Deserialize)]
275#[serde(crate = "printobserver_types::serde")]
276pub struct SpoolsParams {
277 #[serde(default)]
279 pub include_retired: Option<bool>,
280}
281
282#[derive(Debug, Clone, Deserialize)]
284#[serde(crate = "printobserver_types::serde")]
285pub struct PreflightParams {
286 #[serde(default)]
288 pub file_name: Option<String>,
289 #[serde(default)]
293 pub sheet: Option<String>,
294}
295
296pub const SPOOL_RECENT_EVENTS: u32 = 20;
298
299pub fn router(state: ApiState) -> Router {
307 let mut api = Router::new();
308 for operation in OPERATIONS {
309 api = api.route(operation.path, route_for(&operation));
310 }
311 let api = api
314 .fallback(nothing_here)
315 .layer(from_fn_with_state(
316 Admission {
317 operator: Arc::clone(&state.operator),
318 turns: state.turns.clone(),
319 },
320 authenticate,
321 ))
322 .layer(DefaultBodyLimit::max(BODY_BOUND))
323 .with_state(state);
324 Router::new().nest(VERSION_PREFIX, api)
325}
326
327const BEARER: &[u8] = b"Bearer ";
329
330pub const BODY_BOUND: usize = 2 * 1024 * 1024;
337
338pub const DRAIN_BOUND: Duration = Duration::from_secs(2);
344
345pub async fn authenticate(
363 State(admission): State<Admission>,
364 mut request: Request,
365 next: Next,
366) -> Response {
367 let mut presented = request.headers().get_all(header::AUTHORIZATION).iter();
368 let admitted = match (presented.next(), presented.next()) {
369 (Some(only), None) => only
370 .as_bytes()
371 .strip_prefix(BEARER)
372 .and_then(|offered| admission.caller(offered)),
373 _ => None,
374 };
375 if let Some(caller) = admitted {
376 request.extensions_mut().insert(caller);
377 return next.run(request).await;
378 }
379 {
380 let said = if matches!(*admission.operator, OperatorCredential::Unconfigured) {
381 format!(
382 "this server's API requires a credential, presented as `Authorization: Bearer \
383 <credential>`, and this server has no operator credential yet: run \
384 `{CREDENTIAL_ISSUE}` as the operator, put the `api.credential_verifier` line it \
385 prints into the server's configuration, and restart the service"
386 )
387 } else {
388 format!(
389 "this server's API requires the credential it is configured with, presented as \
390 `Authorization: Bearer <credential>`. An operator without one runs \
391 `{CREDENTIAL_ISSUE}`"
392 )
393 };
394 let mut refused = refusal(StatusCode::UNAUTHORIZED, said);
395 refused.headers_mut().insert(
396 header::WWW_AUTHENTICATE,
397 header::HeaderValue::from_static("Bearer"),
398 );
399 let _ = tokio::time::timeout(
403 DRAIN_BOUND,
404 axum::body::to_bytes(request.into_body(), BODY_BOUND),
405 )
406 .await;
407 refused
408 }
409}
410
411async fn nothing_here() -> Response {
413 refusal(
414 StatusCode::NOT_FOUND,
415 "no operation of this server is served at that path",
416 )
417}
418
419fn route_for(operation: &Operation) -> MethodRouter<ApiState> {
421 if let Effect::Command(spool_command) = operation.effect {
422 let kind = spool_command.action_kind();
423 if operation.path.contains("{spool_id}") {
424 return post(
425 move |state: State<ApiState>,
426 caller: Extension<Caller>,
427 Path(spool_id): Path<SpoolId>,
428 body: Result<Json<Value>, JsonRejection>| async move {
429 command(kind, state, caller, Some(spool_id), body).await
430 },
431 );
432 }
433 return post(
434 move |state: State<ApiState>,
435 caller: Extension<Caller>,
436 body: Result<Json<Value>, JsonRejection>| async move {
437 command(kind, state, caller, None, body).await
438 },
439 );
440 }
441 if let Effect::Recovery(kind) = operation.effect {
442 return post(
443 move |state: State<ApiState>,
444 caller: Extension<Caller>,
445 body: Result<Json<Value>, JsonRejection>| async move {
446 recover(kind, state, caller, body).await
447 },
448 );
449 }
450 if let Effect::Mutating(kind) = operation.effect {
451 return post(
452 move |state: State<ApiState>,
453 caller: Extension<Caller>,
454 print_id: Path<PrintId>,
455 body: Result<Json<ActionBody>, JsonRejection>| async move {
456 act(kind, state, caller, print_id, body).await
457 },
458 );
459 }
460 match (operation.name, operation.method) {
461 ("prints", Method::Get) => get(list_and_adopt_prints),
462 ("status", Method::Get) => get(status),
463 ("context", Method::Get) => get(context),
464 ("image", Method::Get) => get(image),
465 ("history", Method::Get) => get(history),
466 ("events", Method::Get) => get(crate::events::events),
467 ("look", Method::Get) => get(look),
468 (crate::operations::PRINTER_LOOK, Method::Get) => get(printer_look),
469 ("manifest_get", Method::Get) => get(manifest_get),
470 ("manifest_set", Method::Put) => put(manifest_set),
471 ("spools", Method::Get) => get(spools),
472 ("spool", Method::Get) => get(spool),
473 ("printer_history", Method::Get) => get(printer_history),
474 ("preflight", Method::Get) => get(preflight),
475 (crate::operations::RECOVERY_STATUS, Method::Get) => get(recover_status),
476 (name, method) => panic!(
477 "the operation `{name}` is declared as {method} and this router serves no such route"
478 ),
479 }
480}
481
482pub(crate) fn answer<T: printobserver_types::serde::Serialize>(
484 status: StatusCode,
485 body: &T,
486) -> Response {
487 let rendered = match printobserver_types::serde_json::to_vec(body) {
488 Ok(bytes) => bytes,
489 Err(error) => {
490 return (
491 StatusCode::INTERNAL_SERVER_ERROR,
492 [(header::CONTENT_TYPE, crate::operations::MEDIA_TYPE)],
493 format!("{{\"error\":\"{error}\"}}"),
494 )
495 .into_response();
496 }
497 };
498 (
499 status,
500 [(header::CONTENT_TYPE, crate::operations::MEDIA_TYPE)],
501 rendered,
502 )
503 .into_response()
504}
505
506pub(crate) fn refusal(status: StatusCode, detail: impl core::fmt::Display) -> Response {
508 answer(status, &ErrorAnswer::saying(detail))
509}
510
511pub(crate) fn store_status(error: &StoreError) -> StatusCode {
513 match error {
514 StoreError::NotFound { .. } => StatusCode::NOT_FOUND,
515 StoreError::LimitRefused { .. } | StoreError::ConstraintRefused { .. } => {
516 StatusCode::BAD_REQUEST
517 }
518 StoreError::Database { .. } | StoreError::Io { .. } => StatusCode::INTERNAL_SERVER_ERROR,
519 }
520}
521
522fn core_status(error: &CoreError) -> StatusCode {
524 match error {
525 CoreError::NoSuchPrint { .. } => StatusCode::NOT_FOUND,
526 CoreError::Store(store) => store_status(store),
527 _ => StatusCode::INTERNAL_SERVER_ERROR,
528 }
529}
530
531async fn act(
539 kind: ActionKind,
540 State(state): State<ApiState>,
541 Extension(caller): Extension<Caller>,
542 Path(print_id): Path<PrintId>,
543 body: Result<Json<ActionBody>, JsonRejection>,
544) -> Response {
545 if kind == ActionKind::StartPrint
546 && let Some(refused) =
547 operator_refused(&caller, &crate::operations::command_for("start_print"))
548 {
549 return refused;
550 }
551 if let Some(refused) = scope_refused(&caller, print_id) {
552 return refused;
553 }
554 let body = match body {
555 Ok(Json(body)) => body,
556 Err(rejected) => return rejected.into_response(),
557 };
558 if let Some(refused) = claim_refused(&caller, &body.actor) {
559 return refused;
560 }
561 let action = match body.into_action(kind) {
562 Ok(action) => action,
563 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
564 };
565 let outcome = match state.supervisor.request_action(print_id, action).await {
566 Ok(outcome) => outcome,
567 Err(error) => return refusal(core_status(&error), error),
568 };
569 let printer_refusal = match &outcome.record.outcome {
570 Some(ExecutionOutcome::Failed { reason }) => Some(reason.clone()),
571 _ => None,
572 };
573 let status = match outcome.record.decision {
574 PolicyDecision::Accepted if printer_refusal.is_none() => StatusCode::OK,
575 PolicyDecision::Accepted => StatusCode::BAD_GATEWAY,
579 PolicyDecision::Rejected(_) => StatusCode::CONFLICT,
582 };
583 answer(
584 status,
585 &ActionAnswer {
586 record: outcome.record,
587 intervention: outcome.intervention,
588 printer_refusal,
589 },
590 )
591}
592
593async fn command(
602 kind: ActionKind,
603 State(state): State<ApiState>,
604 Extension(caller): Extension<Caller>,
605 spool_id: Option<SpoolId>,
606 body: Result<Json<Value>, JsonRejection>,
607) -> Response {
608 let body = match body {
609 Ok(Json(body)) => body,
610 Err(rejected) => return rejected.into_response(),
611 };
612 let Some(fields) = body.as_object() else {
613 return refusal(
614 StatusCode::BAD_REQUEST,
615 "a spool command's body is a document of its fields",
616 );
617 };
618 let actor = match claimed_actor(fields) {
619 Ok(actor) => actor,
620 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
621 };
622 if let Some(refused) = claim_refused(&caller, &actor) {
623 return refused;
624 }
625 let asked = match spool_command_of(kind, spool_id, body) {
626 Ok(asked) => asked,
627 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
628 };
629 let outcome = match state.supervisor.request_spool_command(asked).await {
630 Ok(outcome) => outcome,
631 Err(error) => return refusal(core_status(&error), error),
632 };
633 let status = match outcome.decision {
634 PolicyDecision::Accepted => StatusCode::OK,
635 PolicyDecision::Rejected(_) => StatusCode::CONFLICT,
637 };
638 answer(
639 status,
640 &SpoolCommandAnswer {
641 decision: outcome.decision,
642 spool: outcome.spool,
643 events: outcome.events,
644 },
645 )
646}
647
648async fn recover(
656 kind: RecoveryActionKind,
657 State(state): State<ApiState>,
658 Extension(caller): Extension<Caller>,
659 body: Result<Json<Value>, JsonRejection>,
660) -> Response {
661 let body = match body {
662 Ok(Json(body)) => body,
663 Err(rejected) => return rejected.into_response(),
664 };
665 if let Some(fields) = body.as_object() {
666 let actor = match claimed_actor(fields) {
667 Ok(actor) => actor,
668 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
669 };
670 if let Some(refused) = claim_refused(&caller, &actor) {
671 return refused;
672 }
673 }
674 let (action, actor, reason) = match recovery_of(kind, body) {
675 Ok(asked) => asked,
676 Err(rejected) => return refusal(StatusCode::BAD_REQUEST, rejected),
677 };
678 let issued = match state
679 .supervisor
680 .request_recovery(action.clone(), actor, reason)
681 .await
682 {
683 Ok(issued) => issued,
684 Err(error) => return refusal(core_status(&error), error),
685 };
686 let config = state.supervisor.config().recovery;
687 let status = match &issued.decision {
688 RecoveryDecision::Executed(ExecutionOutcome::Succeeded) => StatusCode::OK,
689 RecoveryDecision::Executed(ExecutionOutcome::Failed { .. }) => StatusCode::BAD_GATEWAY,
692 RecoveryDecision::Rejected(_) => StatusCode::CONFLICT,
694 };
695 answer(
696 status,
697 &RecoveryAnswer {
698 detail: recovery_detail(&action, &issued.decision, config.as_ref()),
699 action,
700 decision: issued.decision,
701 events: vec![issued.requested, issued.settled],
702 },
703 )
704}
705
706async fn recover_status(
709 State(state): State<ApiState>,
710 Extension(caller): Extension<Caller>,
711) -> Response {
712 let class = match caller {
713 Caller::Operator => ActorClass::Operator,
714 Caller::Turn(_) => ActorClass::Agent,
715 };
716 match state.supervisor.recovery_status(class).await {
717 Ok(status) => answer(StatusCode::OK, &status),
718 Err(error) => refusal(core_status(&error), error),
719 }
720}
721
722async fn spools(State(state): State<ApiState>, Query(params): Query<SpoolsParams>) -> Response {
724 let listed = match state
725 .supervisor
726 .spools(params.include_retired.unwrap_or(false))
727 .await
728 {
729 Ok(listed) => listed,
730 Err(error) => return refusal(core_status(&error), error),
731 };
732 match state.supervisor.pending_charges(None).await {
733 Ok(pending) => answer(StatusCode::OK, &SpoolsAnswer::of(listed, pending)),
734 Err(error) => refusal(core_status(&error), error),
735 }
736}
737
738async fn spool(State(state): State<ApiState>, Path(spool_id): Path<SpoolId>) -> Response {
740 let found = match state.supervisor.spool(spool_id).await {
741 Ok(Some(found)) => found,
742 Ok(None) => {
743 return refusal(
744 StatusCode::NOT_FOUND,
745 format!("there is no spool {spool_id}"),
746 );
747 }
748 Err(error) => return refusal(core_status(&error), error),
749 };
750 let query = TimelineQuery {
751 spool_id: Some(spool_id),
752 limit: Some(SPOOL_RECENT_EVENTS),
753 ..every_timeline_kind()
754 };
755 match state.supervisor.timeline(query).await {
756 Ok(recent) => answer(
757 StatusCode::OK,
758 &SpoolAnswer {
759 spool: found,
760 recent,
761 },
762 ),
763 Err(error) => refusal(core_status(&error), error),
764 }
765}
766
767const fn every_timeline_kind() -> TimelineQuery {
769 TimelineQuery {
770 kinds: Vec::new(),
771 since: None,
772 until: None,
773 spool_id: None,
774 before: None,
775 limit: None,
776 }
777}
778
779fn read_one<T: core::str::FromStr>(name: &str, text: &str) -> Result<T, String>
781where
782 T::Err: core::fmt::Display,
783{
784 text.parse()
785 .map_err(|error: T::Err| format!("`{name}` is `{text}`, which will not do: {error}"))
786}
787
788fn timeline_query(asked: &[(String, String)]) -> Result<TimelineQuery, String> {
795 let mut query = every_timeline_kind();
796 let mut seen: Vec<&str> = Vec::new();
797 for (name, text) in asked {
798 if name != "kinds" {
799 if seen.contains(&name.as_str()) {
800 return Err(format!(
801 "`{name}` was given more than once, and this read takes one"
802 ));
803 }
804 seen.push(name);
805 }
806 match name.as_str() {
807 "kinds" => query.kinds.push(read_one::<EventKind>(name, text)?),
808 "since" => query.since = Some(read_one::<Timestamp>(name, text)?),
809 "until" => query.until = Some(read_one::<Timestamp>(name, text)?),
810 "spool_id" => query.spool_id = Some(read_one::<SpoolId>(name, text)?),
811 "before" => query.before = Some(read_one::<EventId>(name, text)?),
812 "limit" => query.limit = Some(read_one::<u32>(name, text)?),
813 other => return Err(format!("the printer history takes no `{other}`")),
814 }
815 }
816 Ok(query)
817}
818
819async fn printer_history(
825 State(state): State<ApiState>,
826 Query(asked): Query<Vec<(String, String)>>,
827) -> Response {
828 let query = match timeline_query(&asked) {
829 Ok(query) => query,
830 Err(refused) => return refusal(StatusCode::BAD_REQUEST, refused),
831 };
832 let limit = match query.resolved_limit() {
833 Ok(limit) => limit,
834 Err(error) => return refusal(store_status(&error), error),
835 };
836 let events = match state.supervisor.timeline(query.clone()).await {
837 Ok(events) => events,
838 Err(error) => return refusal(core_status(&error), error),
839 };
840 let full = u32::try_from(events.len()).is_ok_and(|read| read == limit);
841 let next = match events.last() {
842 Some(last) if full => {
843 let older = TimelineQuery {
844 before: Some(last.id),
845 limit: Some(1),
846 ..query
847 };
848 match state.supervisor.timeline(older).await {
849 Ok(older) if older.is_empty() => None,
850 Ok(_) => Some(last.id),
851 Err(error) => return refusal(core_status(&error), error),
852 }
853 }
854 _ => None,
855 };
856 answer(StatusCode::OK, &TimelineAnswer { events, next })
857}
858
859async fn preflight(
863 State(state): State<ApiState>,
864 Query(params): Query<PreflightParams>,
865) -> Response {
866 let Some(named) = params.file_name else {
867 return refusal(
868 StatusCode::BAD_REQUEST,
869 "a filament check needs `file_name`, and this request carries none",
870 );
871 };
872 let file_name = match FileName::new(&named) {
873 Ok(file_name) => file_name,
874 Err(error) => return refusal(StatusCode::BAD_REQUEST, error),
875 };
876 let sheet = match params.sheet.map(SheetId::try_from).transpose() {
877 Ok(sheet) => sheet,
878 Err(why) => return refusal(StatusCode::BAD_REQUEST, why),
879 };
880 match state.supervisor.preflight(&file_name, sheet.as_ref()).await {
881 Ok(preflight) => answer(StatusCode::OK, &PreflightAnswer { preflight }),
882 Err(error) => refusal(core_status(&error), error),
883 }
884}
885
886async fn list_and_adopt_prints(State(state): State<ApiState>) -> Response {
893 match state.supervisor.list_and_adopt_prints().await {
894 Ok(listing) => answer(
895 StatusCode::OK,
896 &PrintsAnswer {
897 prints: listing.prints,
898 active: listing.active,
899 },
900 ),
901 Err(error) => refusal(core_status(&error), error),
902 }
903}
904
905async fn status(
911 State(state): State<ApiState>,
912 Extension(caller): Extension<Caller>,
913 Path(print_id): Path<PrintId>,
914) -> Response {
915 if let Some(refused) = scope_refused(&caller, print_id) {
916 return refused;
917 }
918 match state.prints.print(print_id).await {
919 Ok(Some(_)) => {}
920 Ok(None) => {
921 return refusal(
922 StatusCode::NOT_FOUND,
923 format!("there is no print {print_id}"),
924 );
925 }
926 Err(error) => return refusal(store_status(&error), error),
927 }
928 let context = match state.supervisor.context(print_id).await {
929 Ok(context) => context,
930 Err(error) => return refusal(core_status(&error), error),
931 };
932 let session = match state.sessions.session(print_id).await {
933 Ok(session) => session,
934 Err(error) => return refusal(store_status(&error), error),
935 };
936 answer(
937 StatusCode::OK,
938 &StatusAnswer {
939 print: context.print,
940 printer: context.printer,
941 job: context.job,
942 session,
943 interventions: context.interventions,
944 detector: context.detector,
945 },
946 )
947}
948
949async fn context(
957 State(state): State<ApiState>,
958 Extension(caller): Extension<Caller>,
959 Path(print_id): Path<PrintId>,
960) -> Response {
961 if let Some(refused) = scope_refused(&caller, print_id) {
962 return refused;
963 }
964 let context = match state.supervisor.context(print_id).await {
965 Ok(context) => context,
966 Err(error) => return refusal(core_status(&error), error),
967 };
968 let mut image_path = None;
969 if let Some(latest) = context.latest_image.as_ref() {
970 match state.images.image(latest.id).await {
971 Ok(lookup) => image_path = ImageAnswer::from(lookup).path,
972 Err(error) => return refusal(store_status(&error), error),
973 }
974 }
975 answer(
976 StatusCode::OK,
977 &ContextAnswer {
978 context,
979 image_path,
980 },
981 )
982}
983
984async fn look(
992 State(state): State<ApiState>,
993 Extension(caller): Extension<Caller>,
994 Path(print_id): Path<PrintId>,
995 Query(params): Query<LookParams>,
996) -> Response {
997 if let Some(refused) = scope_refused(&caller, print_id) {
998 return refused;
999 }
1000 let wait_s = params.wait_s.unwrap_or(0);
1001 if wait_s > MAX_LOOK_WAIT_S {
1002 return refusal(
1003 StatusCode::BAD_REQUEST,
1004 format!("wait_s may be at most {MAX_LOOK_WAIT_S}; {wait_s} was asked for"),
1005 );
1006 }
1007 match state.prints.print(print_id).await {
1008 Ok(Some(_)) => {}
1009 Ok(None) => {
1010 return refusal(StatusCode::NOT_FOUND, CoreError::NoSuchPrint { print_id });
1011 }
1012 Err(error) => return refusal(store_status(&error), error),
1013 }
1014 let supervisor = Arc::clone(&state.supervisor);
1015 let taken = tokio::task::spawn_blocking(move || {
1016 let started = std::time::Instant::now();
1017 let arrived = supervisor.await_arrivals(print_id, Duration::from_secs(u64::from(wait_s)));
1018 printobserver_core::block_on(supervisor.take_look(print_id, started.elapsed(), arrived))
1019 })
1020 .await;
1021 match taken {
1022 Ok(Ok(look)) => answer(StatusCode::OK, &look),
1023 Ok(Err(error)) => refusal(core_status(&error), error),
1024 Err(error) => refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
1025 }
1026}
1027
1028async fn printer_look(
1035 State(state): State<ApiState>,
1036 Extension(caller): Extension<Caller>,
1037 Query(params): Query<LookParams>,
1038) -> Response {
1039 if let Some(refused) = printless_refused(&caller, "a look at the printer with no print named") {
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 let waited = Duration::from_secs(u64::from(wait_s));
1050 tokio::time::sleep(waited).await;
1051 match state.supervisor.take_printer_look(waited).await {
1052 Ok(look) => answer(StatusCode::OK, &look),
1053 Err(error) => refusal(core_status(&error), error),
1054 }
1055}
1056
1057async fn image(
1063 State(state): State<ApiState>,
1064 Extension(caller): Extension<Caller>,
1065 Path(image_id): Path<ImageId>,
1066) -> Response {
1067 match state.images.image(image_id).await {
1068 Ok(lookup) => {
1069 let belongs_to = match &lookup {
1070 printobserver_core::ImageLookup::Found { record, .. }
1071 | printobserver_core::ImageLookup::FileMissing { record } => record.print_id,
1072 };
1073 let refused = match belongs_to {
1074 Some(print_id) => scope_refused(&caller, print_id),
1075 None => {
1076 printless_refused(&caller, "a frame of the printer that belongs to no print")
1077 }
1078 };
1079 if let Some(refused) = refused {
1080 return refused;
1081 }
1082 answer(StatusCode::OK, &ImageAnswer::from(lookup))
1083 }
1084 Err(error) => refusal(store_status(&error), error),
1085 }
1086}
1087
1088async fn history(
1090 State(state): State<ApiState>,
1091 Extension(caller): Extension<Caller>,
1092 Path(print_id): Path<PrintId>,
1093 Query(params): Query<HistoryParams>,
1094) -> Response {
1095 if let Some(refused) = scope_refused(&caller, print_id) {
1096 return refused;
1097 }
1098 let query = HistoryQuery {
1099 print_id,
1100 kinds: Vec::new(),
1101 since: None,
1102 until: None,
1103 limit: params.limit,
1104 };
1105 match state.events.history(query).await {
1106 Ok(events) => answer(StatusCode::OK, &HistoryAnswer { events }),
1107 Err(error) => refusal(store_status(&error), error),
1108 }
1109}
1110
1111async fn manifest_get(
1113 State(state): State<ApiState>,
1114 Extension(caller): Extension<Caller>,
1115 Path(print_id): Path<PrintId>,
1116) -> Response {
1117 if let Some(refused) = scope_refused(&caller, print_id) {
1118 return refused;
1119 }
1120 let manifest = match state.prints.manifest(print_id).await {
1121 Ok(manifest) => manifest,
1122 Err(error) => return refusal(store_status(&error), error),
1123 };
1124 let narrowings = match state.prints.print(print_id).await {
1125 Ok(print) => print.map(|record| record.narrowings).unwrap_or_default(),
1126 Err(error) => return refusal(store_status(&error), error),
1127 };
1128 answer(
1129 StatusCode::OK,
1130 &ManifestAnswer {
1131 manifest,
1132 narrowings,
1133 },
1134 )
1135}
1136
1137async fn manifest_set(
1146 State(state): State<ApiState>,
1147 Extension(caller): Extension<Caller>,
1148 Path(print_id): Path<PrintId>,
1149 body: Result<Json<ManifestBody>, JsonRejection>,
1150) -> Response {
1151 if let Some(refused) =
1152 operator_refused(&caller, &crate::operations::command_for("manifest_set"))
1153 {
1154 return refused;
1155 }
1156 let body = match body {
1157 Ok(Json(body)) => body,
1158 Err(rejected) => return rejected.into_response(),
1159 };
1160 if let Err(rejected) = body.reason() {
1161 return refusal(StatusCode::BAD_REQUEST, rejected);
1162 }
1163 let narrowed = effective_bounds(&state.supervisor.config().envelope, Some(&body.manifest));
1164 if let Err(error) = state
1165 .prints
1166 .put_manifest(print_id, body.manifest.clone())
1167 .await
1168 {
1169 return refusal(store_status(&error), error);
1170 }
1171 for narrowing in narrowed.narrowings.clone() {
1172 if let Err(error) = state.prints.record_narrowing(print_id, narrowing).await {
1173 return refusal(store_status(&error), error);
1174 }
1175 }
1176 answer(
1177 StatusCode::OK,
1178 &ManifestAnswer {
1179 manifest: Some(body.manifest),
1180 narrowings: narrowed.narrowings,
1181 },
1182 )
1183}
1184
1185#[cfg(test)]
1186mod tests {
1187 use axum::http::StatusCode;
1188 use printobserver_core::CoreError;
1189 use printobserver_core::store::StoreError;
1190
1191 use super::{core_status, store_status};
1192
1193 #[test]
1196 fn every_store_refusal_is_answered_under_a_status_a_caller_can_act_on() {
1197 for (error, expected) in [
1198 (
1199 StoreError::NotFound {
1200 what: "print".to_owned(),
1201 },
1202 StatusCode::NOT_FOUND,
1203 ),
1204 (
1205 StoreError::LimitRefused {
1206 limit: 1_000,
1207 asked_for: 2_000,
1208 },
1209 StatusCode::BAD_REQUEST,
1210 ),
1211 (
1212 StoreError::ConstraintRefused {
1213 constraint: "actions.decision".to_owned(),
1214 },
1215 StatusCode::BAD_REQUEST,
1216 ),
1217 (
1218 StoreError::Database {
1219 detail: "the disk is full".to_owned(),
1220 },
1221 StatusCode::INTERNAL_SERVER_ERROR,
1222 ),
1223 (
1224 StoreError::Io {
1225 detail: "the disk is full".to_owned(),
1226 },
1227 StatusCode::INTERNAL_SERVER_ERROR,
1228 ),
1229 ] {
1230 assert_eq!(store_status(&error), expected, "{error}");
1231 }
1232 }
1233
1234 #[test]
1237 fn a_print_nothing_holds_is_not_found_and_a_port_failure_is_this_servers_own() {
1238 assert_eq!(
1239 core_status(&CoreError::NoSuchPrint {
1240 print_id: printobserver_types::PrintId::new(),
1241 }),
1242 StatusCode::NOT_FOUND
1243 );
1244 assert_eq!(
1245 core_status(&CoreError::Store(StoreError::NotFound {
1246 what: "print".to_owned(),
1247 })),
1248 StatusCode::NOT_FOUND
1249 );
1250 assert_eq!(
1251 core_status(&CoreError::Unrepresentable {
1252 detail: "an instant".to_owned(),
1253 }),
1254 StatusCode::INTERNAL_SERVER_ERROR
1255 );
1256 }
1257}