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 },
822 )
823}
824
825async fn context(
833 State(state): State<ApiState>,
834 Extension(caller): Extension<Caller>,
835 Path(print_id): Path<PrintId>,
836) -> Response {
837 if let Some(refused) = scope_refused(&caller, print_id) {
838 return refused;
839 }
840 let context = match state.supervisor.context(print_id).await {
841 Ok(context) => context,
842 Err(error) => return refusal(core_status(&error), error),
843 };
844 let mut image_path = None;
845 if let Some(latest) = context.latest_image.as_ref() {
846 match state.images.image(latest.id).await {
847 Ok(lookup) => image_path = ImageAnswer::from(lookup).path,
848 Err(error) => return refusal(store_status(&error), error),
849 }
850 }
851 answer(
852 StatusCode::OK,
853 &ContextAnswer {
854 context,
855 image_path,
856 },
857 )
858}
859
860async fn look(
868 State(state): State<ApiState>,
869 Extension(caller): Extension<Caller>,
870 Path(print_id): Path<PrintId>,
871 Query(params): Query<LookParams>,
872) -> Response {
873 if let Some(refused) = scope_refused(&caller, print_id) {
874 return refused;
875 }
876 let wait_s = params.wait_s.unwrap_or(0);
877 if wait_s > MAX_LOOK_WAIT_S {
878 return refusal(
879 StatusCode::BAD_REQUEST,
880 format!("wait_s may be at most {MAX_LOOK_WAIT_S}; {wait_s} was asked for"),
881 );
882 }
883 match state.prints.print(print_id).await {
884 Ok(Some(_)) => {}
885 Ok(None) => {
886 return refusal(StatusCode::NOT_FOUND, CoreError::NoSuchPrint { print_id });
887 }
888 Err(error) => return refusal(store_status(&error), error),
889 }
890 let supervisor = Arc::clone(&state.supervisor);
891 let taken = tokio::task::spawn_blocking(move || {
892 let started = std::time::Instant::now();
893 let arrived = supervisor.await_arrivals(print_id, Duration::from_secs(u64::from(wait_s)));
894 printobserver_core::block_on(supervisor.take_look(print_id, started.elapsed(), arrived))
895 })
896 .await;
897 match taken {
898 Ok(Ok(look)) => answer(StatusCode::OK, &look),
899 Ok(Err(error)) => refusal(core_status(&error), error),
900 Err(error) => refusal(StatusCode::INTERNAL_SERVER_ERROR, error),
901 }
902}
903
904async fn image(
909 State(state): State<ApiState>,
910 Extension(caller): Extension<Caller>,
911 Path(image_id): Path<ImageId>,
912) -> Response {
913 match state.images.image(image_id).await {
914 Ok(lookup) => {
915 let belongs_to = match &lookup {
916 printobserver_core::ImageLookup::Found { record, .. }
917 | printobserver_core::ImageLookup::FileMissing { record } => record.print_id,
918 };
919 if let Some(refused) = scope_refused(&caller, belongs_to) {
920 return refused;
921 }
922 answer(StatusCode::OK, &ImageAnswer::from(lookup))
923 }
924 Err(error) => refusal(store_status(&error), error),
925 }
926}
927
928async fn history(
930 State(state): State<ApiState>,
931 Extension(caller): Extension<Caller>,
932 Path(print_id): Path<PrintId>,
933 Query(params): Query<HistoryParams>,
934) -> Response {
935 if let Some(refused) = scope_refused(&caller, print_id) {
936 return refused;
937 }
938 let query = HistoryQuery {
939 print_id,
940 kinds: Vec::new(),
941 since: None,
942 until: None,
943 limit: params.limit,
944 };
945 match state.events.history(query).await {
946 Ok(events) => answer(StatusCode::OK, &HistoryAnswer { events }),
947 Err(error) => refusal(store_status(&error), error),
948 }
949}
950
951async fn manifest_get(
953 State(state): State<ApiState>,
954 Extension(caller): Extension<Caller>,
955 Path(print_id): Path<PrintId>,
956) -> Response {
957 if let Some(refused) = scope_refused(&caller, print_id) {
958 return refused;
959 }
960 let manifest = match state.prints.manifest(print_id).await {
961 Ok(manifest) => manifest,
962 Err(error) => return refusal(store_status(&error), error),
963 };
964 let narrowings = match state.prints.print(print_id).await {
965 Ok(print) => print.map(|record| record.narrowings).unwrap_or_default(),
966 Err(error) => return refusal(store_status(&error), error),
967 };
968 answer(
969 StatusCode::OK,
970 &ManifestAnswer {
971 manifest,
972 narrowings,
973 },
974 )
975}
976
977async fn manifest_set(
986 State(state): State<ApiState>,
987 Extension(caller): Extension<Caller>,
988 Path(print_id): Path<PrintId>,
989 body: Result<Json<ManifestBody>, JsonRejection>,
990) -> Response {
991 if let Some(refused) =
992 operator_refused(&caller, &crate::operations::command_for("manifest_set"))
993 {
994 return refused;
995 }
996 let body = match body {
997 Ok(Json(body)) => body,
998 Err(rejected) => return rejected.into_response(),
999 };
1000 if let Err(rejected) = body.reason() {
1001 return refusal(StatusCode::BAD_REQUEST, rejected);
1002 }
1003 let narrowed = effective_bounds(&state.supervisor.config().envelope, Some(&body.manifest));
1004 if let Err(error) = state
1005 .prints
1006 .put_manifest(print_id, body.manifest.clone())
1007 .await
1008 {
1009 return refusal(store_status(&error), error);
1010 }
1011 for narrowing in narrowed.narrowings.clone() {
1012 if let Err(error) = state.prints.record_narrowing(print_id, narrowing).await {
1013 return refusal(store_status(&error), error);
1014 }
1015 }
1016 answer(
1017 StatusCode::OK,
1018 &ManifestAnswer {
1019 manifest: Some(body.manifest),
1020 narrowings: narrowed.narrowings,
1021 },
1022 )
1023}
1024
1025#[cfg(test)]
1026mod tests {
1027 use axum::http::StatusCode;
1028 use printobserver_core::CoreError;
1029 use printobserver_core::store::StoreError;
1030
1031 use super::{core_status, store_status};
1032
1033 #[test]
1036 fn every_store_refusal_is_answered_under_a_status_a_caller_can_act_on() {
1037 for (error, expected) in [
1038 (
1039 StoreError::NotFound {
1040 what: "print".to_owned(),
1041 },
1042 StatusCode::NOT_FOUND,
1043 ),
1044 (
1045 StoreError::LimitRefused {
1046 limit: 1_000,
1047 asked_for: 2_000,
1048 },
1049 StatusCode::BAD_REQUEST,
1050 ),
1051 (
1052 StoreError::ConstraintRefused {
1053 constraint: "actions.decision".to_owned(),
1054 },
1055 StatusCode::BAD_REQUEST,
1056 ),
1057 (
1058 StoreError::Database {
1059 detail: "the disk is full".to_owned(),
1060 },
1061 StatusCode::INTERNAL_SERVER_ERROR,
1062 ),
1063 (
1064 StoreError::Io {
1065 detail: "the disk is full".to_owned(),
1066 },
1067 StatusCode::INTERNAL_SERVER_ERROR,
1068 ),
1069 ] {
1070 assert_eq!(store_status(&error), expected, "{error}");
1071 }
1072 }
1073
1074 #[test]
1077 fn a_print_nothing_holds_is_not_found_and_a_port_failure_is_this_servers_own() {
1078 assert_eq!(
1079 core_status(&CoreError::NoSuchPrint {
1080 print_id: printobserver_types::PrintId::new(),
1081 }),
1082 StatusCode::NOT_FOUND
1083 );
1084 assert_eq!(
1085 core_status(&CoreError::Store(StoreError::NotFound {
1086 what: "print".to_owned(),
1087 })),
1088 StatusCode::NOT_FOUND
1089 );
1090 assert_eq!(
1091 core_status(&CoreError::Unrepresentable {
1092 detail: "an instant".to_owned(),
1093 }),
1094 StatusCode::INTERNAL_SERVER_ERROR
1095 );
1096 }
1097}