From 5bb80700a1662a0d4177f9e06ba0c1f669c155d4 Mon Sep 17 00:00:00 2001 From: eri Date: Mon, 29 Jan 2024 14:33:52 +0100 Subject: [PATCH] =?UTF-8?q?feat:=20intentar=20resolver=20problemas=20servi?= =?UTF-8?q?dor=20=E2=9A=99=EF=B8=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cargo.toml | 2 +- README.md | 2 +- scripts/cinemazarelos.service | 2 ++ src/lib.rs | 30 ++++++++++++++++++++++++++++-- src/main.rs | 16 ++++++++++++---- src/routes.rs | 25 ++++++++++++++++++++++++- src/routes/peliculas.rs | 5 ++--- 7 files changed, 70 insertions(+), 12 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index acdcceb..dfcf316 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,7 +22,7 @@ sqlx = { version = "0.7", features = [ "runtime-tokio", "tls-rustls", "postgres" time = { version = "0.3", features = ["serde", "local-offset"] } tokio = { version = "1.35", features = ["full"] } tower = "0.4" -tower-http = { version = "0.5", features = ["fs"] } +tower-http = { version = "0.5", features = ["fs", "trace", "timeout"] } tower-livereload = "0.9" tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter", "time"] } diff --git a/README.md b/README.md index fd55966..bde4011 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ Unha vez esté todo listo podemos modificar a táboa de películas. 2. Engadir a imaxe á carpeta `assets/posters/[CURSO]` usando o editor web e facer un commit. Se vas a engadir varios é mellor facer un só commit con todos. Verificar que está ben engadida 3. Copiar o nome de arquivo **sen** a extensión (por exemplo `02_irma_vep`) e pegalo na columna _poster_ -**Importante:** Non se verán os cambios ata que a páxina borre a caché. Isto sucede cada 6 horas, para facelo manualmente preme [este enlace](https://cinemazarelos.com/api/clear/cache) cando haxas cambiado todo. +**Importante:** Non se verán os cambios ata que a páxina se actualice. Podes comprobar o estado neste [enlace](https://github.com/eerii/cinemazarelos/actions/workflows/deploy.yaml). Este proceso soe tardar sobre 2 minutos. ### Nivel 2: Crear ou editar unha nova páxina estática diff --git a/scripts/cinemazarelos.service b/scripts/cinemazarelos.service index d666a6d..628d370 100644 --- a/scripts/cinemazarelos.service +++ b/scripts/cinemazarelos.service @@ -6,6 +6,8 @@ After=network.target Type=simple WorkingDirectory=/home/ubuntu/cinemazarelos ExecStart=/home/ubuntu/cinemazarelos/cinemazarelos +Restart=always +RestartSec=10 [Install] WantedBy=default.target diff --git a/src/lib.rs b/src/lib.rs index 6dd59c2..428de69 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2,7 +2,7 @@ use std::{fmt::Display, str::FromStr, sync::Arc}; use db::Conexion; use serde::{de, Deserialize, Deserializer}; -use tokio::sync::RwLock; +use tokio::{signal, sync::RwLock}; use tracing_subscriber::{fmt::time::OffsetTime, layer::SubscriberExt, util::SubscriberInitExt}; mod db; @@ -30,7 +30,7 @@ pub fn init_tracing() { let level = if cfg!(debug_assertions) { "cinemazarelos=debug,tower_http=debug" } else { - "cinemazarelos=info,tower_http=info" + "cinemazarelos=debug,tower_http=info" }; tracing_subscriber::registry() @@ -55,3 +55,29 @@ where Some(s) => FromStr::from_str(s).map_err(de::Error::custom).map(Some), } } + +// Graceful shutdown + +pub async fn shutdown_signal() { + let ctrl_c = async { + signal::ctrl_c() + .await + .expect("failed to install Ctrl+C handler"); + }; + + #[cfg(unix)] + let terminate = async { + signal::unix::signal(signal::unix::SignalKind::terminate()) + .expect("failed to install signal handler") + .recv() + .await; + }; + + #[cfg(not(unix))] + let terminate = std::future::pending::<()>(); + + tokio::select! { + _ = ctrl_c => {}, + _ = terminate => {}, + } +} diff --git a/src/main.rs b/src/main.rs index 408e490..580009d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,4 +1,4 @@ -use cinemazarelos::{init_tracing, routes::router}; +use cinemazarelos::{init_tracing, routes::router, shutdown_signal}; use tokio::net::TcpListener; use tower_http::services::ServeDir; use tracing::info; @@ -21,11 +21,19 @@ async fn main() { }; // Lanzar o servidor - let listener = TcpListener::bind("0.0.0.0:3000").await.unwrap(); + let listener = TcpListener::bind("0.0.0.0:3000") + .await + .expect("Fallo ó crear o servidor"); + info!( "Servidor activo en http://{}", - listener.local_addr().unwrap() + listener + .local_addr() + .expect("Fallo obtendo o enderezo do servidor") ); - axum::serve(listener, app).await.unwrap(); + axum::serve(listener, app) + .with_graceful_shutdown(shutdown_signal()) + .await + .expect("Fallo executando o servidor"); } diff --git a/src/routes.rs b/src/routes.rs index 24715f0..327c89b 100644 --- a/src/routes.rs +++ b/src/routes.rs @@ -1,4 +1,11 @@ -use axum::{extract::State, routing::get, Router}; +use std::time::Duration; + +use axum::{ + extract::{MatchedPath, Request, State}, + routing::get, + Router, +}; +use tower_http::{timeout::TimeoutLayer, trace::TraceLayer}; use crate::{db::RepoPeliculas, SharedState}; @@ -50,6 +57,22 @@ pub fn router() -> Router { get(blog::artigo_blog), ) .nest("/api", api) + .layer(( + TraceLayer::new_for_http() + .make_span_with(|req: &Request| { + let method = req.method(); + let uri = req.uri(); + + let matched_path = req + .extensions() + .get::() + .map(|matched_path| matched_path.as_str()); + + tracing::debug_span!("request", %method, %uri, matched_path) + }) + .on_failure(()), + TimeoutLayer::new(Duration::from_secs(10)), + )) } // ··············· diff --git a/src/routes/peliculas.rs b/src/routes/peliculas.rs index 7f72765..38d8e44 100644 --- a/src/routes/peliculas.rs +++ b/src/routes/peliculas.rs @@ -1,6 +1,6 @@ use askama::Template; use axum::extract::{Query, State}; -use chrono::{Datelike, Days, Local}; +use chrono::{Datelike, Local}; use serde::Deserialize; use time::Date; @@ -140,8 +140,7 @@ pub async fn calendario(State(state): State) -> TemplateCalendarioP peliculas.sort_by(|a, b| a.fecha_ciclo.cmp(&b.fecha_ciclo)); // Eleximos as películas que aínda non foron - // TODO: Eliminar checked_sub_days, é só para probar as pelis pasadas - let hoxe = Local::now().checked_sub_days(Days::new(320)).unwrap(); + let hoxe = Local::now(); let hoxe = Date::from_ordinal_date(hoxe.year(), hoxe.ordinal() as u16).unwrap(); peliculas.retain(|p| p.fecha_ciclo.is_some() && p.fecha_ciclo.unwrap() > hoxe);