improve logging and code organisation

This commit is contained in:
glyph 2022-08-11 13:52:31 +01:00
parent ec90040612
commit 56fc641515
1 changed files with 43 additions and 32 deletions

View File

@ -1,7 +1,7 @@
//! Web server route handlers. //! Web server route handlers.
use async_std::channel::Sender; use async_std::channel::Sender;
use log::{debug, warn}; use log::{info, warn};
use rocket::{form::Form, get, post, response::Redirect, uri, FromForm, State}; use rocket::{form::Form, get, post, response::Redirect, uri, FromForm, State};
use rocket_dyn_templates::{tera::Context, Template}; use rocket_dyn_templates::{tera::Context, Template};
@ -20,15 +20,13 @@ pub struct PeerForm {
#[get("/")] #[get("/")]
pub async fn home(db: &State<Database>) -> Template { pub async fn home(db: &State<Database>) -> Template {
let peers = db.get_peers(); let peers = db.get_peers();
let mut context = Context::new();
let mut peers_unread = Vec::new(); let mut peers_unread = Vec::new();
for peer in peers { for peer in peers {
let unread_count = db.get_unread_post_count(&peer.public_key); let unread_count = db.get_unread_post_count(&peer.public_key);
peers_unread.push((peer, unread_count.to_string())); peers_unread.push((peer, unread_count.to_string()));
} }
let mut context = Context::new();
context.insert("peers", &peers_unread); context.insert("peers", &peers_unread);
Template::render("base", &context.into_json()) Template::render("base", &context.into_json())
@ -38,7 +36,16 @@ pub async fn home(db: &State<Database>) -> Template {
pub async fn delete_post(db: &State<Database>, public_key: &str, msg_id: &str) -> Redirect { pub async fn delete_post(db: &State<Database>, public_key: &str, msg_id: &str) -> Redirect {
// Delete the post from the database. This method cannot panic, so we're // Delete the post from the database. This method cannot panic, so we're
// safe to unwrap the result. // safe to unwrap the result.
db.remove_post(public_key, msg_id).unwrap(); match db.remove_post(public_key, msg_id) {
Ok(_) => info!(
"Removed post {} by {} from 'posts' database tree",
msg_id, public_key
),
Err(e) => warn!(
"Failed to remove post {} by {} from 'posts' database tree: {}",
msg_id, public_key, e
),
}
Redirect::to(uri!(posts(public_key))) Redirect::to(uri!(posts(public_key)))
} }
@ -46,20 +53,17 @@ pub async fn delete_post(db: &State<Database>, public_key: &str, msg_id: &str) -
#[get("/posts/<public_key>")] #[get("/posts/<public_key>")]
pub async fn posts(db: &State<Database>, public_key: &str) -> Template { pub async fn posts(db: &State<Database>, public_key: &str) -> Template {
let peers = db.get_peers(); let peers = db.get_peers();
let mut context = Context::new();
let mut peers_unread = Vec::new(); let mut peers_unread = Vec::new();
for peer in peers { for peer in peers {
let unread_count = db.get_unread_post_count(&peer.public_key); let unread_count = db.get_unread_post_count(&peer.public_key);
peers_unread.push((peer, unread_count.to_string())); peers_unread.push((peer, unread_count.to_string()));
} }
context.insert("peers", &peers_unread);
let posts = db.get_posts(public_key).unwrap(); let posts = db.get_posts(public_key).unwrap();
let mut context = Context::new();
context.insert("selected_peer", &public_key); context.insert("selected_peer", &public_key);
context.insert("peers", &peers_unread);
context.insert("posts", &posts); context.insert("posts", &posts);
Template::render("base", &context.into_json()) Template::render("base", &context.into_json())
@ -68,20 +72,17 @@ pub async fn posts(db: &State<Database>, public_key: &str) -> Template {
#[get("/posts/<public_key>/<msg_id>")] #[get("/posts/<public_key>/<msg_id>")]
pub async fn post(db: &State<Database>, public_key: &str, msg_id: &str) -> Template { pub async fn post(db: &State<Database>, public_key: &str, msg_id: &str) -> Template {
let peers = db.get_peers(); let peers = db.get_peers();
let mut context = Context::new();
let mut peers_unread = Vec::new(); let mut peers_unread = Vec::new();
for peer in peers { for peer in peers {
let unread_count = db.get_unread_post_count(&peer.public_key); let unread_count = db.get_unread_post_count(&peer.public_key);
peers_unread.push((peer, unread_count.to_string())); peers_unread.push((peer, unread_count.to_string()));
} }
context.insert("peers", &peers_unread);
let posts = db.get_posts(public_key).unwrap(); let posts = db.get_posts(public_key).unwrap();
let post = db.get_post(public_key, msg_id).unwrap(); let post = db.get_post(public_key, msg_id).unwrap();
let mut context = Context::new();
context.insert("peers", &peers_unread);
context.insert("selected_peer", &public_key); context.insert("selected_peer", &public_key);
context.insert( context.insert(
"selected_peer_encoded", "selected_peer_encoded",
@ -107,7 +108,7 @@ pub async fn mark_post_read(db: &State<Database>, public_key: &str, msg_id: &str
db.add_post(public_key, post).unwrap(); db.add_post(public_key, post).unwrap();
} else { } else {
warn!( warn!(
"failed to find post {} authored by {} in database", "Failed to find post {} authored by {} in 'posts' database tree",
msg_id, public_key msg_id, public_key
) )
} }
@ -123,7 +124,7 @@ pub async fn mark_post_unread(db: &State<Database>, public_key: &str, msg_id: &s
db.add_post(public_key, post).unwrap(); db.add_post(public_key, post).unwrap();
} else { } else {
warn!( warn!(
"failed to find post {} authored by {} in database", "Failed to find post {} authored by {} in 'posts' database tree",
msg_id, public_key msg_id, public_key
) )
} }
@ -140,13 +141,13 @@ pub async fn download_latest_posts(db: &State<Database>, tx: &State<Sender<Task>
.send(Task::FetchLatestPosts(peer.public_key.clone())) .send(Task::FetchLatestPosts(peer.public_key.clone()))
.await .await
{ {
warn!("task loop error: {}", e) warn!("Task loop error: {}", e)
} }
// Fetch the latest name for each peer we're subscribed to and update // Fetch the latest name for each peer we're subscribed to and update
// the database. // the database.
if let Err(e) = tx.send(Task::FetchLatestName(peer.public_key)).await { if let Err(e) = tx.send(Task::FetchLatestName(peer.public_key)).await {
warn!("task loop error: {}", e) warn!("Task loop error: {}", e)
} }
} }
@ -160,14 +161,16 @@ pub async fn subscribe_form(
tx: &State<Sender<Task>>, tx: &State<Sender<Task>>,
peer: Form<PeerForm>, peer: Form<PeerForm>,
) -> Redirect { ) -> Redirect {
info!("Subscribing to peer {}", &peer.public_key);
if utils::validate_public_key(&peer.public_key).is_ok() { if utils::validate_public_key(&peer.public_key).is_ok() {
debug!("public key {} is valid", &peer.public_key); info!("Public key {} is valid", &peer.public_key);
// Retrieve the name of the peer to which we are subscribing. // Retrieve the name of the peer to which we are subscribing.
let peer_name = match sbot::get_name(&peer.public_key).await { let peer_name = match sbot::get_name(&peer.public_key).await {
Ok(name) => name, Ok(name) => name,
Err(e) => { Err(e) => {
warn!("failed to fetch name for {}: {}", &peer.public_key, e); warn!("Failed to fetch name for peer {}: {}", &peer.public_key, e);
String::from("") String::from("")
} }
}; };
@ -176,16 +179,19 @@ pub async fn subscribe_form(
// Add the peer to the database and then check the follow state. // Add the peer to the database and then check the follow state.
// Follow the peer if our local instance is not already following. // Follow the peer if our local instance is not already following.
if db.add_peer(peer_info).is_ok() { if db.add_peer(peer_info).is_ok() {
debug!("added {} to peer tree in database", &peer.public_key); info!("Added {} to 'peers' database tree", &peer.public_key);
match sbot::is_following(&whoami.0, &peer.public_key).await { match sbot::is_following(&whoami.0, &peer.public_key).await {
Ok(status) if status.as_str() == "false" => { Ok(status) if status.as_str() == "false" => {
match sbot::follow_peer(&peer.public_key).await { match sbot::follow_peer(&peer.public_key).await {
Ok(_) => debug!("followed {}", &peer.public_key), Ok(_) => info!("Followed peer {}", &peer.public_key),
Err(e) => warn!("failed to follow {}: {}", &peer.public_key, e), Err(e) => warn!("Failed to follow peer {}: {}", &peer.public_key, e),
} }
} }
Ok(status) if status.as_str() == "true" => { Ok(status) if status.as_str() == "true" => {
debug!("we already follow {}", &peer.public_key) info!(
"Already following peer {}. No further action taken",
&peer.public_key
)
} }
_ => (), _ => (),
} }
@ -194,16 +200,16 @@ pub async fn subscribe_form(
// Fetch all root posts authored by the peer we're subscribing // Fetch all root posts authored by the peer we're subscribing
// to. Posts will be added to the key-value database. // to. Posts will be added to the key-value database.
if let Err(e) = tx.send(Task::FetchAllPosts(peer_id)).await { if let Err(e) = tx.send(Task::FetchAllPosts(peer_id)).await {
warn!("task loop error: {}", e) warn!("Task loop error: {}", e)
} }
} else { } else {
warn!( warn!(
"failed to add {} to peer tree in database", "Failed to add peer {} to 'peers' database tree",
&peer.public_key &peer.public_key
) )
} }
} else { } else {
warn!("{} is invalid", &peer.public_key); warn!("Public key {} is invalid", &peer.public_key);
} }
Redirect::to(uri!(home)) Redirect::to(uri!(home))
@ -211,14 +217,19 @@ pub async fn subscribe_form(
#[post("/unsubscribe", data = "<peer>")] #[post("/unsubscribe", data = "<peer>")]
pub fn unsubscribe_form(db: &State<Database>, peer: Form<PeerForm>) -> Redirect { pub fn unsubscribe_form(db: &State<Database>, peer: Form<PeerForm>) -> Redirect {
info!("Unsubscribing from peer {}", &peer.public_key);
if let Err(e) = utils::validate_public_key(&peer.public_key) { if let Err(e) = utils::validate_public_key(&peer.public_key) {
warn!("{} is invalid: {}", &peer.public_key, e) warn!("Public key {} is invalid: {}", &peer.public_key, e)
} else { } else {
debug!("public key {} is valid", &peer.public_key); info!("Public key {} is valid", &peer.public_key);
match db.remove_peer(&peer.public_key) { match db.remove_peer(&peer.public_key) {
Ok(_) => debug!("removed {} from peer tree in database", &peer.public_key), Ok(_) => info!(
"Removed peer {} from 'peers' database tree",
&peer.public_key
),
Err(_e) => warn!( Err(_e) => warn!(
"failed to remove {} from peer tree in database", "Failed to remove peer {} from 'peers' database tree",
&peer.public_key &peer.public_key
), ),
} }