Skip to main content

planetary_server/
lib.rs

1//! Implements a common server for Planetary microservices.
2
3use std::any::Any;
4use std::future::Future;
5
6use anyhow::Context as _;
7use axum::Router;
8use axum::body::Body;
9use axum::extract::FromRequest;
10use axum::extract::FromRequestParts;
11use axum::extract::rejection::JsonRejection;
12use axum::extract::rejection::PathRejection;
13use axum::http;
14use axum::http::HeaderName;
15use axum::http::StatusCode;
16use axum::http::header;
17use axum::response::IntoResponse;
18use axum::response::Response;
19use axum::routing::get;
20use bon::Builder;
21use serde::Serialize;
22use serde::Serializer;
23use tokio::net::TcpListener;
24use tower::ServiceBuilder;
25use tower_http::LatencyUnit;
26use tower_http::compression::CompressionLayer;
27use tower_http::sensitive_headers::SetSensitiveRequestHeadersLayer;
28use tower_http::sensitive_headers::SetSensitiveResponseHeadersLayer;
29use tower_http::trace::DefaultMakeSpan;
30use tower_http::trace::DefaultOnResponse;
31use tower_http::trace::TraceLayer;
32use tracing::Span;
33use tracing::debug;
34use tracing::error;
35use tracing::info;
36
37#[cfg(feature = "templating")]
38pub mod templating;
39
40/// The default address to bind the server to.
41pub const DEFAULT_ADDRESS: &str = "0.0.0.0";
42
43/// The default port to bind the server to.
44pub const DEFAULT_PORT: u16 = 8080;
45
46/// Header values to be blocked from logging.
47const SENSITIVE_HEADERS: [HeaderName; 2] = [header::AUTHORIZATION, header::COOKIE];
48
49/// A panic handler for returning 500.
50fn handle_panic(err: Box<dyn Any + Send + 'static>) -> Response {
51    if let Some(s) = err.downcast_ref::<String>() {
52        error!("server panicked: {s}");
53    } else if let Some(s) = err.downcast_ref::<&str>() {
54        error!("server panicked: {s}");
55    } else {
56        error!("server panicked: unknown panic message");
57    };
58
59    Error::internal().into_response()
60}
61
62/// An extractor that wraps the JSON extractor of Axum.
63///
64/// This extractor returns an error object on rejection.
65#[derive(FromRequest)]
66#[from_request(via(axum::Json), rejection(Error))]
67pub struct Json<T>(pub T);
68
69impl<T> IntoResponse for Json<T>
70where
71    T: Serialize,
72{
73    fn into_response(self) -> Response {
74        axum::Json(self.0).into_response()
75    }
76}
77
78/// Helper for serializing a HTTP status code.
79fn serialize_status<S>(status: &StatusCode, serializer: S) -> Result<S::Ok, S::Error>
80where
81    S: Serializer,
82{
83    serializer.serialize_u16(status.as_u16())
84}
85
86/// Represents a generic error from the server.
87#[derive(Serialize, Debug)]
88pub struct Error {
89    /// The status code being returned in the response.
90    #[serde(serialize_with = "serialize_status")]
91    pub status: StatusCode,
92    /// The error message.
93    pub message: String,
94}
95
96impl Error {
97    /// Returns a "not found" JSON error response.
98    pub fn not_found() -> Self {
99        Self {
100            status: StatusCode::NOT_FOUND,
101            message: "the requested resource was not found".to_string(),
102        }
103    }
104
105    /// Returns a "bad request" JSON error response.
106    pub fn bad_request(message: impl Into<String>) -> Self {
107        Self {
108            status: StatusCode::BAD_REQUEST,
109            message: message.into(),
110        }
111    }
112
113    /// Returns a "forbidden" JSON error response.
114    pub fn forbidden() -> Self {
115        Self {
116            status: StatusCode::FORBIDDEN,
117            message: StatusCode::FORBIDDEN.to_string(),
118        }
119    }
120
121    /// Returns an "internal server error" JSON error response.
122    pub fn internal() -> Self {
123        Self {
124            status: StatusCode::INTERNAL_SERVER_ERROR,
125            message: StatusCode::INTERNAL_SERVER_ERROR.to_string(),
126        }
127    }
128
129    /// Returns a "task is not cancelable" error.
130    pub fn not_cancelable() -> Self {
131        Self {
132            status: StatusCode::BAD_REQUEST,
133            message: "task is not in a cancelable state".into(),
134        }
135    }
136}
137
138impl From<anyhow::Error> for Error {
139    fn from(e: anyhow::Error) -> Self {
140        tracing::error!("{e:#}");
141        Self::internal()
142    }
143}
144
145impl From<reqwest::Error> for Error {
146    fn from(e: reqwest::Error) -> Self {
147        tracing::error!("{e:#}");
148        Self::internal()
149    }
150}
151
152#[cfg(feature = "postgres")]
153impl From<planetary_db::postgres::Error> for Error {
154    fn from(e: planetary_db::postgres::Error) -> Self {
155        use planetary_db::postgres::Error::*;
156
157        let (status, message) = match &e {
158            TaskNotFound(_) => (StatusCode::NOT_FOUND, e.to_string()),
159            Pool(e) => {
160                // Log the error but do not return it to the client
161                tracing::error!("database connection error: {e:#}");
162                return Self::internal();
163            }
164            Diesel(e) => {
165                // Log the error but do not return it to the client
166                tracing::error!("database error: {e:#}");
167                return Self::internal();
168            }
169        };
170
171        Self { status, message }
172    }
173}
174
175impl From<planetary_db::Error> for Error {
176    fn from(e: planetary_db::Error) -> Self {
177        let (status, message) = match e {
178            planetary_db::Error::InvalidPageToken(_) => (StatusCode::BAD_REQUEST, e.to_string()),
179            #[cfg(feature = "postgres")]
180            planetary_db::Error::Postgres(e) => return e.into(),
181            planetary_db::Error::Other(e) => return e.into(),
182        };
183
184        Self { status, message }
185    }
186}
187
188impl From<JsonRejection> for Error {
189    fn from(rejection: JsonRejection) -> Self {
190        Self {
191            status: rejection.status(),
192            message: rejection.body_text(),
193        }
194    }
195}
196
197impl IntoResponse for Error {
198    fn into_response(self) -> Response {
199        (self.status, axum::Json(self)).into_response()
200    }
201}
202
203/// Represents the response type for most endpoints.
204pub type ServerResponse<T> = Result<T, Error>;
205
206/// An extractor that wraps the path extractor of Axum.
207///
208/// This extractor returns an error on rejection.
209#[derive(FromRequestParts)]
210#[from_request(via(axum::extract::Path), rejection(Error))]
211pub struct Path<T>(pub T);
212
213impl From<PathRejection> for Error {
214    fn from(rejection: PathRejection) -> Self {
215        Self {
216            status: rejection.status(),
217            message: rejection.body_text(),
218        }
219    }
220}
221
222/// An extractor that wraps the query extractor of Axum (extra).
223///
224/// This extractor returns an error on rejection.
225#[derive(FromRequestParts)]
226#[from_request(via(axum_extra::extract::Query), rejection(Error))]
227pub struct Query<T>(pub T);
228
229impl From<axum_extra::extract::QueryRejection> for Error {
230    fn from(rejection: axum_extra::extract::QueryRejection) -> Self {
231        Self {
232            status: rejection.status(),
233            message: rejection.body_text(),
234        }
235    }
236}
237
238/// The state for a task execution service (TES) server.
239#[derive(Clone, Builder)]
240pub struct Server<S> {
241    /// The address to bind the server to.
242    #[builder(into, default = DEFAULT_ADDRESS)]
243    address: String,
244
245    /// The port to bind the server to.
246    #[builder(into, default = DEFAULT_PORT)]
247    port: u16,
248
249    /// The routers for the server.
250    #[builder(into, default)]
251    routers: Vec<Router<S>>,
252}
253
254impl<S> Server<S>
255where
256    S: Clone + Send + Sync + 'static,
257{
258    /// Runs the server with the given state and shutdown function.
259    pub async fn run<F>(self, state: S, shutdown: F) -> anyhow::Result<()>
260    where
261        F: Future<Output = ()> + Send + 'static,
262    {
263        // Hook up the axum middleware
264        let middleware = ServiceBuilder::new()
265            .layer(SetSensitiveRequestHeadersLayer::new(SENSITIVE_HEADERS))
266            .layer(
267                TraceLayer::new_for_http()
268                    .make_span_with(DefaultMakeSpan::new().include_headers(true))
269                    .on_request(|request: &http::Request<Body>, _span: &Span| {
270                        debug!(
271                            "{method} {path}",
272                            method = request.method(),
273                            path = request.uri().path()
274                        )
275                    })
276                    .on_response(
277                        DefaultOnResponse::new()
278                            .level(tracing::Level::DEBUG)
279                            .latency_unit(LatencyUnit::Micros),
280                    ),
281            )
282            .layer(CompressionLayer::new())
283            .layer(SetSensitiveResponseHeadersLayer::new(SENSITIVE_HEADERS));
284
285        // Construct the axum app
286        let mut router = Router::new().route("/ping", get(|| async {}));
287
288        for merge in self.routers {
289            router = router.merge(merge);
290        }
291
292        // Run the server
293        let addr = format!("{address}:{port}", address = self.address, port = self.port);
294        let listener = TcpListener::bind(&addr)
295            .await
296            .context("binding to the provided address")?;
297
298        info!("listening at {addr}");
299
300        axum::serve(
301            listener,
302            router
303                .fallback(async || Error::not_found())
304                .layer(middleware)
305                .layer(tower_http::catch_panic::CatchPanicLayer::custom(
306                    handle_panic,
307                ))
308                .with_state(state),
309        )
310        .with_graceful_shutdown(shutdown)
311        .await
312        .context("failed to run server")?;
313
314        Ok(())
315    }
316}