Skip to content

Commit

Permalink
feat: intentar resolver problemas servidor ⚙️
Browse files Browse the repository at this point in the history
  • Loading branch information
eerii committed Jan 29, 2024
1 parent 8b5a086 commit 5bb8070
Show file tree
Hide file tree
Showing 7 changed files with 70 additions and 12 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"] }
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 2 additions & 0 deletions scripts/cinemazarelos.service
Original file line number Diff line number Diff line change
Expand Up @@ -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
30 changes: 28 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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()
Expand All @@ -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 => {},
}
}
16 changes: 12 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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");
}
25 changes: 24 additions & 1 deletion src/routes.rs
Original file line number Diff line number Diff line change
@@ -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};

Expand Down Expand Up @@ -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::<MatchedPath>()
.map(|matched_path| matched_path.as_str());

tracing::debug_span!("request", %method, %uri, matched_path)
})
.on_failure(()),
TimeoutLayer::new(Duration::from_secs(10)),
))
}

// ···············
Expand Down
5 changes: 2 additions & 3 deletions src/routes/peliculas.rs
Original file line number Diff line number Diff line change
@@ -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;

Expand Down Expand Up @@ -140,8 +140,7 @@ pub async fn calendario(State(state): State<SharedState>) -> 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);

Expand Down

0 comments on commit 5bb8070

Please sign in to comment.