2022-08-31 23:25:17 +02:00
|
|
|
use axum::{
|
2023-03-29 18:20:51 +02:00
|
|
|
body,
|
|
|
|
extract::State,
|
|
|
|
middleware::Next,
|
2023-04-02 15:27:06 +02:00
|
|
|
response::{Html, IntoResponse, Response},
|
2023-03-29 18:20:51 +02:00
|
|
|
routing::get,
|
|
|
|
Router,
|
2022-08-31 23:25:17 +02:00
|
|
|
};
|
2023-07-29 11:51:04 +02:00
|
|
|
use chrono::{DateTime, FixedOffset};
|
|
|
|
use hyper::{
|
|
|
|
header::{self, CONTENT_TYPE},
|
|
|
|
HeaderMap, Request, StatusCode,
|
|
|
|
};
|
2023-03-25 22:12:49 +01:00
|
|
|
use lazy_static::lazy_static;
|
2023-03-29 18:20:51 +02:00
|
|
|
use prometheus::{opts, Encoder, IntCounterVec, TextEncoder};
|
2023-03-25 22:12:49 +01:00
|
|
|
use std::sync::Arc;
|
2023-04-03 23:33:43 +02:00
|
|
|
use tower_http::services::ServeFile;
|
2023-07-29 12:12:46 +02:00
|
|
|
use tracing::{
|
|
|
|
instrument,
|
|
|
|
log::{error, info},
|
|
|
|
};
|
2022-08-31 23:20:59 +02:00
|
|
|
|
2023-03-29 18:03:54 +02:00
|
|
|
use crate::{AppState, WebsiteError};
|
2022-08-31 23:20:59 +02:00
|
|
|
|
2023-03-25 22:12:49 +01:00
|
|
|
pub mod posts;
|
2023-03-29 21:48:27 +02:00
|
|
|
pub mod tags;
|
2023-03-25 22:12:49 +01:00
|
|
|
|
|
|
|
lazy_static! {
|
2023-03-26 12:01:59 +02:00
|
|
|
pub static ref HIT_COUNTER: IntCounterVec = prometheus::register_int_counter_vec!(
|
2023-03-29 18:20:51 +02:00
|
|
|
opts!(
|
|
|
|
"http_requests_total",
|
|
|
|
"Total amount of http requests received"
|
|
|
|
),
|
2023-03-29 18:03:54 +02:00
|
|
|
&["route", "method", "status"]
|
2023-03-26 12:01:59 +02:00
|
|
|
)
|
|
|
|
.unwrap();
|
2023-03-25 22:12:49 +01:00
|
|
|
}
|
|
|
|
|
2023-03-29 18:19:39 +02:00
|
|
|
pub fn routes(state: &Arc<AppState>) -> Router<Arc<AppState>> {
|
2023-03-29 18:03:54 +02:00
|
|
|
Router::new()
|
|
|
|
.route("/", get(index))
|
2023-04-02 15:26:20 +02:00
|
|
|
.merge(posts::router())
|
|
|
|
.merge(tags::router())
|
2023-03-29 18:19:39 +02:00
|
|
|
.merge(posts::alias_router(state.posts.values()))
|
2023-04-02 15:26:20 +02:00
|
|
|
.layer(axum::middleware::from_fn(metrics_middleware))
|
2023-03-29 18:03:54 +02:00
|
|
|
.route("/healthcheck", get(healthcheck))
|
|
|
|
.route("/metrics", get(metrics))
|
2023-04-02 15:27:06 +02:00
|
|
|
.route_service(
|
|
|
|
"/posts/:slug/*path",
|
2023-04-03 23:33:25 +02:00
|
|
|
tower_http::services::ServeDir::new("./").fallback(ServeFile::new("./404.html")),
|
2023-04-02 15:27:06 +02:00
|
|
|
)
|
2023-04-03 23:33:43 +02:00
|
|
|
.route_service(
|
|
|
|
"/static/*path",
|
|
|
|
tower_http::services::ServeDir::new("./").fallback(ServeFile::new("./404.html")),
|
|
|
|
)
|
2023-04-03 23:33:25 +02:00
|
|
|
.fallback_service(ServeFile::new("./404.html"))
|
2023-03-29 18:03:54 +02:00
|
|
|
}
|
|
|
|
|
2023-03-25 16:14:53 +01:00
|
|
|
#[instrument(skip(state))]
|
2023-03-25 22:12:49 +01:00
|
|
|
pub async fn index(
|
2023-03-29 18:03:54 +02:00
|
|
|
State(state): State<Arc<AppState>>,
|
2023-07-29 11:51:04 +02:00
|
|
|
) -> std::result::Result<Response, WebsiteError> {
|
2022-08-31 23:20:59 +02:00
|
|
|
let ctx = tera::Context::new();
|
2022-08-31 23:25:17 +02:00
|
|
|
let res = state.tera.render("index.html", &ctx).map_err(|e| {
|
|
|
|
error!("Failed rendering index: {}", e);
|
2023-03-25 21:38:16 +01:00
|
|
|
WebsiteError::NotFound
|
2022-08-31 23:25:17 +02:00
|
|
|
})?;
|
2023-07-29 12:12:46 +02:00
|
|
|
Ok((
|
|
|
|
StatusCode::OK,
|
|
|
|
[(header::LAST_MODIFIED, state.startup_time.to_rfc2822())],
|
|
|
|
Html(res),
|
2023-07-29 11:51:04 +02:00
|
|
|
)
|
2023-07-29 12:12:46 +02:00
|
|
|
.into_response())
|
2023-03-29 18:03:54 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
async fn healthcheck() -> &'static str {
|
|
|
|
"OK"
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn metrics() -> impl IntoResponse {
|
|
|
|
let encoder = TextEncoder::new();
|
|
|
|
let metric_families = prometheus::gather();
|
|
|
|
let mut buffer = vec![];
|
|
|
|
encoder.encode(&metric_families, &mut buffer).unwrap();
|
|
|
|
|
|
|
|
Response::builder()
|
|
|
|
.status(200)
|
|
|
|
.header(CONTENT_TYPE, encoder.format_type())
|
|
|
|
.body(body::boxed(body::Full::from(buffer)))
|
|
|
|
.unwrap()
|
2022-08-31 23:20:59 +02:00
|
|
|
}
|
|
|
|
|
2023-03-29 21:48:27 +02:00
|
|
|
pub async fn not_found() -> impl IntoResponse {
|
|
|
|
(StatusCode::NOT_FOUND, ())
|
2023-03-26 12:40:25 +02:00
|
|
|
}
|
|
|
|
|
2023-03-29 18:03:54 +02:00
|
|
|
pub async fn metrics_middleware<B>(request: Request<B>, next: Next<B>) -> Response {
|
|
|
|
let path = request.uri().path().to_string();
|
|
|
|
let method = request.method().to_string();
|
2023-03-29 21:48:27 +02:00
|
|
|
|
2023-03-29 18:03:54 +02:00
|
|
|
let response = next.run(request).await;
|
2023-03-29 21:48:27 +02:00
|
|
|
|
|
|
|
if !response.status().is_client_error() {
|
|
|
|
HIT_COUNTER
|
|
|
|
.with_label_values(&[&path, &method, response.status().as_str()])
|
|
|
|
.inc();
|
2023-04-10 00:46:58 +02:00
|
|
|
} else if response.status() == StatusCode::NOT_FOUND {
|
|
|
|
HIT_COUNTER
|
|
|
|
.with_label_values(&["not found", &method, response.status().as_str()])
|
|
|
|
.inc();
|
2023-03-29 21:48:27 +02:00
|
|
|
}
|
|
|
|
|
2023-03-29 18:03:54 +02:00
|
|
|
response
|
|
|
|
}
|
|
|
|
|
2023-07-29 12:04:37 +02:00
|
|
|
fn should_return_304(headers: &HeaderMap, last_changed: Option<DateTime<FixedOffset>>) -> bool {
|
2023-07-29 11:51:04 +02:00
|
|
|
let Some(date) = last_changed else {
|
|
|
|
info!("no last modified date");
|
|
|
|
return false;
|
|
|
|
};
|
|
|
|
let Some(since) = headers.get(header::IF_MODIFIED_SINCE) else {
|
|
|
|
info!("no IF_MODIFIED_SINCE header");
|
|
|
|
return false;
|
|
|
|
};
|
|
|
|
|
|
|
|
let Ok(parsed) = DateTime::<FixedOffset>::parse_from_rfc2822(since.to_str().unwrap()) else {
|
|
|
|
info!("failed to parse IF_MODIFIED_SINCE header");
|
|
|
|
return false;
|
|
|
|
};
|
|
|
|
|
|
|
|
date > parsed
|
|
|
|
}
|
|
|
|
|
2023-03-25 21:38:16 +01:00
|
|
|
impl IntoResponse for WebsiteError {
|
2022-08-31 23:20:59 +02:00
|
|
|
fn into_response(self) -> Response {
|
|
|
|
match self {
|
2023-03-25 21:38:16 +01:00
|
|
|
WebsiteError::NotFound => {
|
2023-03-25 16:14:53 +01:00
|
|
|
info!("not found");
|
|
|
|
(StatusCode::NOT_FOUND, ()).into_response()
|
|
|
|
}
|
2023-03-25 21:38:16 +01:00
|
|
|
WebsiteError::InternalError(e) => {
|
2023-04-10 00:46:58 +02:00
|
|
|
if let Some(s) = e.source() {
|
|
|
|
error!("internal error: {}: {}", e, s);
|
|
|
|
} else {
|
|
|
|
error!("internal error: {}", e);
|
|
|
|
}
|
2023-03-25 16:14:53 +01:00
|
|
|
(StatusCode::INTERNAL_SERVER_ERROR, ()).into_response()
|
|
|
|
}
|
2022-08-31 23:20:59 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2023-03-26 13:05:39 +02:00
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
2023-03-29 18:31:20 +02:00
|
|
|
use std::sync::Arc;
|
|
|
|
|
|
|
|
use crate::AppState;
|
|
|
|
|
2023-03-26 13:05:39 +02:00
|
|
|
#[test]
|
|
|
|
fn render_index() {
|
|
|
|
let tera = tera::Tera::new("templates/**/*").unwrap();
|
|
|
|
let ctx = tera::Context::new();
|
|
|
|
let _res = tera.render("index.html", &ctx).unwrap();
|
|
|
|
}
|
2023-03-29 18:31:20 +02:00
|
|
|
|
|
|
|
#[tokio::test]
|
|
|
|
async fn setup_routes() {
|
|
|
|
// Load the actual posts, just to make this test fail if
|
|
|
|
// aliases overlap with themselves or other routes
|
2023-03-29 21:48:27 +02:00
|
|
|
let posts = crate::post::load_all().await.unwrap();
|
2023-03-29 18:31:20 +02:00
|
|
|
let state = Arc::new(AppState {
|
2023-07-29 11:51:04 +02:00
|
|
|
startup_time: chrono::offset::Utc::now(),
|
2023-04-03 23:33:25 +02:00
|
|
|
base_url: "http://localhost:8180".into(),
|
2023-03-29 18:31:20 +02:00
|
|
|
tera: tera::Tera::new("templates/**/*").unwrap(),
|
2023-03-29 21:48:27 +02:00
|
|
|
tags: crate::tag::get_tags(posts.values()),
|
|
|
|
posts,
|
2023-03-29 18:31:20 +02:00
|
|
|
});
|
|
|
|
|
2023-04-02 15:26:20 +02:00
|
|
|
super::routes(&state).with_state(state).into_make_service();
|
2023-03-29 18:31:20 +02:00
|
|
|
}
|
2023-03-26 13:05:39 +02:00
|
|
|
}
|