add healthcheck endpoint and startup check

This commit is contained in:
Niccolo Borgioli 2023-06-23 10:17:13 +02:00
parent e02224216a
commit e2711cc887
No known key found for this signature in database
GPG Key ID: D93C615F75EE4F0B
5 changed files with 39 additions and 2 deletions

View File

@ -1,5 +1,6 @@
use actix_web::web; use actix_web::web;
use crate::health;
use crate::note; use crate::note;
use crate::status; use crate::status;
@ -7,6 +8,7 @@ pub fn init(cfg: &mut web::ServiceConfig) {
cfg.service( cfg.service(
web::scope("/api") web::scope("/api")
.service(note::init()) .service(note::init())
.service(status::init()), .service(status::init())
.service(health::init()),
); );
} }

View File

@ -0,0 +1,3 @@
mod routes;
pub use routes::*;

View File

@ -0,0 +1,16 @@
use actix_web::{get, web, HttpResponse, Responder, Scope};
use crate::store;
#[get("/")]
async fn get_live() -> impl Responder {
if store::can_reach_redis() {
return HttpResponse::Ok();
} else {
return HttpResponse::ServiceUnavailable();
}
}
pub fn init() -> Scope {
web::scope("/live").service(get_live)
}

View File

@ -1,8 +1,10 @@
use actix_web::{ use actix_web::{
middleware::{self, Logger}, middleware::{self, Logger},
web, App, HttpServer, web::{self},
App, HttpServer,
}; };
use dotenv::dotenv; use dotenv::dotenv;
use log::error;
#[macro_use] #[macro_use]
extern crate lazy_static; extern crate lazy_static;
@ -10,6 +12,7 @@ extern crate lazy_static;
mod api; mod api;
mod client; mod client;
mod config; mod config;
mod health;
mod note; mod note;
mod size; mod size;
mod status; mod status;
@ -20,6 +23,11 @@ async fn main() -> std::io::Result<()> {
dotenv().ok(); dotenv().ok();
env_logger::init_from_env(env_logger::Env::new().default_filter_or(config::VERBOSITY.as_str())); env_logger::init_from_env(env_logger::Env::new().default_filter_or(config::VERBOSITY.as_str()));
if !store::can_reach_redis() {
error!("cannot reach redis");
panic!("canont reach redis");
}
return HttpServer::new(|| { return HttpServer::new(|| {
App::new() App::new()
.wrap(Logger::new("\"%r\" %s %b %T")) .wrap(Logger::new("\"%r\" %s %b %T"))

View File

@ -19,6 +19,14 @@ fn get_connection() -> Result<redis::Connection, &'static str> {
.map_err(|_| "Unable to connect to redis") .map_err(|_| "Unable to connect to redis")
} }
pub fn can_reach_redis() -> bool {
let conn = get_connection();
return match conn {
Ok(_) => true,
Err(_) => false,
};
}
pub fn set(id: &String, note: &Note) -> Result<(), &'static str> { pub fn set(id: &String, note: &Note) -> Result<(), &'static str> {
let serialized = serde_json::to_string(&note.clone()).unwrap(); let serialized = serde_json::to_string(&note.clone()).unwrap();
let mut conn = get_connection()?; let mut conn = get_connection()?;