Skip to content

Commit

Permalink
refactor(backend): impl telemetry in announcement resource(and it's r…
Browse files Browse the repository at this point in the history
…elated endpoints)
  • Loading branch information
Eason0729 committed Jul 20, 2024
1 parent 80bcef0 commit 5eba7ea
Show file tree
Hide file tree
Showing 10 changed files with 109 additions and 39 deletions.
11 changes: 11 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions backend/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ governor = "0.6.0"
http = "^0.2"
lazy_static = "1.5.0"
prost-wkt-types = { workspace = true }
tracing-futures = "0.2.5"

[dependencies.grpc]
path = "../grpc"
Expand Down
5 changes: 0 additions & 5 deletions backend/src/controller/crypto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ pub struct CryptoController {
}

impl CryptoController {
#[tracing::instrument(parent=span,name="crypto_construct",level = "info",skip_all)]
pub fn new(span: &Span) -> Self {
let salt = CONFIG.database.salt.as_bytes().to_vec();
Self {
Expand All @@ -41,7 +40,6 @@ impl CryptoController {
}
}
/// hash `src` and compare hash value with `hashed`
#[tracing::instrument(name = "crypto_hasheq_controller", level = "debug", skip_all)]
pub fn hash_eq(&self, src: &str, hashed: &[u8]) -> bool {
let src_hashed: Vec<u8> = self.hash(src);
let mut result = true;
Expand All @@ -53,7 +51,6 @@ impl CryptoController {
result
}
/// get BLAKE2b-512 hashed bytes with salt
#[tracing::instrument(name = "crypto_hash_controller", level = "debug", skip_all)]
pub fn hash(&self, src: &str) -> Vec<u8> {
let mut hasher = Blake2b512::new();
hasher.update([src.as_bytes(), self.salt.as_slice()].concat());
Expand All @@ -64,7 +61,6 @@ impl CryptoController {
/// Serialize and calculate checksum and return
///
/// Note that it shouldn't be an security measurement
#[tracing::instrument(level = "debug", skip_all, name = "encode")]
pub fn encode<M: Serialize>(&self, obj: M) -> Result<String> {
let mut raw = postcard::to_allocvec(&obj)?;

Expand All @@ -80,7 +76,6 @@ impl CryptoController {
/// check signature and return the object
///
/// Error if signature invaild
#[tracing::instrument(level = "debug", skip_all, name = "decode")]
pub fn decode<M: DeserializeOwned>(&self, raw: String) -> Result<M> {
let mut raw = URL_SAFE_NO_PAD.decode(raw)?;

Expand Down
119 changes: 87 additions & 32 deletions backend/src/endpoint/announcement.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use super::tools::*;
use opentelemetry::trace::FutureExt;

use grpc::backend::announcement_server::*;

Expand Down Expand Up @@ -51,7 +52,12 @@ impl From<PartialModel> for AnnouncementInfo {

#[async_trait]
impl Announcement for ArcServer {
#[instrument(skip_all, level = "debug")]
#[instrument(
skip_all,
level = "info",
name = "Announcement.list",
err(level = "debug", Display)
)]
async fn list(
&self,
req: Request<ListAnnouncementRequest>,
Expand Down Expand Up @@ -92,7 +98,12 @@ impl Announcement for ArcServer {
remain,
}))
}
#[instrument(skip_all, level = "debug")]
#[instrument(
skip_all,
level = "info",
name = "Announcement.full_info",
err(level = "debug", Display)
)]
async fn full_info(&self, req: Request<Id>) -> Result<Response<AnnouncementFullInfo>, Status> {
let (auth, req) = self.rate_limit(req).in_current_span().await?;

Expand All @@ -108,7 +119,40 @@ impl Announcement for ArcServer {

Ok(Response::new(model.with_auth(&auth).into()))
}
#[instrument(skip_all, level = "debug")]
#[instrument(
skip_all,
level = "info",
name = "Announcement.full_info_by_contest",
err(level = "debug", Display)
)]
async fn full_info_by_contest(
&self,
req: Request<AddAnnouncementToContestRequest>,
) -> Result<Response<AnnouncementFullInfo>, Status> {
let (auth, req) = self.rate_limit(req).in_current_span().await?;

let parent: contest::IdModel =
contest::Entity::related_read_by_id(&auth, Into::<i32>::into(req.contest_id), &self.db)
.in_current_span()
.await?;
let model = parent
.upgrade()
.find_related(Entity)
.filter(Column::Id.eq(Into::<i32>::into(req.announcement_id)))
.one(self.db.deref())
.instrument(info_span!("fetch").or_current())
.await
.map_err(Into::<Error>::into)?
.ok_or(Error::NotInDB)?;

Ok(Response::new(model.with_auth(&auth).into()))
}
#[instrument(
skip_all,
level = "info",
name = "Announcement.create",
err(level = "debug", Display)
)]
async fn create(
&self,
req: Request<CreateAnnouncementRequest>,
Expand Down Expand Up @@ -143,9 +187,16 @@ impl Announcement for ArcServer {
self.dup.store(user_id, uuid, id.clone());
tracing::debug!(id = id.id, "announcement_created");

tracing::info!(count.announcement = 1);

Ok(Response::new(id))
}
#[instrument(skip_all, level = "debug")]
#[instrument(
skip_all,
level = "info",
name = "Announcement.update",
err(level = "debug", Display)
)]
async fn update(
&self,
req: Request<UpdateAnnouncementRequest>,
Expand Down Expand Up @@ -182,7 +233,12 @@ impl Announcement for ArcServer {

Ok(Response::new(()))
}
#[instrument(skip_all, level = "debug")]
#[instrument(
skip_all,
level = "info",
name = "Announcement.remove",
err(level = "debug", Display)
)]
async fn remove(&self, req: Request<Id>) -> Result<Response<()>, Status> {
let (auth, req) = self.rate_limit(req).in_current_span().await?;

Expand All @@ -198,9 +254,16 @@ impl Announcement for ArcServer {

tracing::debug!(id = req.id);

tracing::info!(counter.announcement = -1);

Ok(Response::new(()))
}
#[instrument(skip_all, level = "debug")]
#[instrument(
skip_all,
level = "info",
name = "Announcement.add_to_contest",
err(level = "debug", Display)
)]
async fn add_to_contest(
&self,
req: Request<AddAnnouncementToContestRequest>,
Expand Down Expand Up @@ -244,7 +307,12 @@ impl Announcement for ArcServer {

Ok(Response::new(()))
}
#[instrument(skip_all, level = "debug")]
#[instrument(
skip_all,
level = "info",
name = "Announcement.remove_from_contest",
err(level = "debug", Display)
)]
async fn remove_from_contest(
&self,
req: Request<AddAnnouncementToContestRequest>,
Expand All @@ -269,7 +337,12 @@ impl Announcement for ArcServer {

Ok(Response::new(()))
}
#[instrument(skip_all, level = "debug")]
#[instrument(
skip_all,
level = "info",
name = "Announcement.publish",
err(level = "debug", Display)
)]
async fn publish(&self, req: Request<Id>) -> Result<Response<()>, Status> {
let (auth, req) = self.rate_limit(req).in_current_span().await?;
let perm = auth.user_perm();
Expand Down Expand Up @@ -299,7 +372,12 @@ impl Announcement for ArcServer {

Ok(Response::new(()))
}
#[instrument(skip_all, level = "debug")]
#[instrument(
skip_all,
level = "info",
name = "Announcement.unpublish",
err(level = "debug", Display)
)]
async fn unpublish(&self, req: Request<Id>) -> Result<Response<()>, Status> {
let (auth, req) = self.rate_limit(req).in_current_span().await?;
let perm = auth.user_perm();
Expand Down Expand Up @@ -329,27 +407,4 @@ impl Announcement for ArcServer {

Ok(Response::new(()))
}
#[instrument(skip_all, level = "debug")]
async fn full_info_by_contest(
&self,
req: Request<AddAnnouncementToContestRequest>,
) -> Result<Response<AnnouncementFullInfo>, Status> {
let (auth, req) = self.rate_limit(req).in_current_span().await?;

let parent: contest::IdModel =
contest::Entity::related_read_by_id(&auth, Into::<i32>::into(req.contest_id), &self.db)
.in_current_span()
.await?;
let model = parent
.upgrade()
.find_related(Entity)
.filter(Column::Id.eq(Into::<i32>::into(req.announcement_id)))
.one(self.db.deref())
.instrument(info_span!("fetch").or_current())
.await
.map_err(Into::<Error>::into)?
.ok_or(Error::NotInDB)?;

Ok(Response::new(model.with_auth(&auth).into()))
}
}
1 change: 1 addition & 0 deletions backend/src/endpoint/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ mod tools {
time::*,
};
pub use crate::{fill_active_model, fill_exist_active_model, server::ArcServer, TonicStream};
pub use tracing::{Instrument, Level};
}

// FIXME: currently we report transaction error as internal error,
Expand Down
4 changes: 2 additions & 2 deletions backend/src/entity/announcement.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use super::*;
use grpc::backend::list_announcement_request::Sort;
use tracing::instrument;

pub static NAME: &str = "announcement";

Expand Down Expand Up @@ -252,7 +251,6 @@ impl WithAuthTrait for Paginator {}

impl Paginator {
pub fn new_text(text: String, start_from_end: bool) -> Self {
// FIXME: check dup text
Self::Text(TextPaginator::new(text, start_from_end))
}
pub fn new_sort(sort: Sort, start_from_end: bool) -> Self {
Expand All @@ -273,6 +271,7 @@ impl Paginator {
}

impl<'a, 'b> WithDB<'a, WithAuth<'b, Paginator>> {
#[instrument(skip_all, err(level = "debug", Display))]
pub async fn fetch(&mut self, size: u64, offset: i64) -> Result<Vec<PartialModel>, Error> {
let db = self.0;
let auth = self.1 .0;
Expand All @@ -283,6 +282,7 @@ impl<'a, 'b> WithDB<'a, WithAuth<'b, Paginator>> {
Paginator::Default(ref mut x) => x.fetch(size, offset, auth, db).await,
}
}
#[instrument(skip_all, err(level = "debug", Display))]
pub async fn remain(&self) -> Result<u64, Error> {
let db = self.0;
let auth = self.1 .0;
Expand Down
1 change: 1 addition & 0 deletions backend/src/entity/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ pub mod util;
use sea_orm::{
entity::prelude::*, EntityTrait, FromQueryResult, PrimaryKeyTrait, QueryFilter, Select,
};
use tracing::{instrument, Level};

use crate::util::{auth::Auth, error::Error};
use tonic::async_trait;
Expand Down
2 changes: 2 additions & 0 deletions backend/src/entity/util/with.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use crate::util::auth::Auth;
use sea_orm::DatabaseConnection;

#[derive(Debug)]
pub struct WithAuth<'a, T>(pub &'a Auth, pub T);
#[derive(Debug)]
pub struct WithDB<'a, T>(pub &'a DatabaseConnection, pub T);

pub trait WithAuthTrait
Expand Down
3 changes: 3 additions & 0 deletions backend/src/util/bound.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
use super::error::Error;
use grpc::backend::*;
use tracing::instrument;

pub trait BoundCheck {
/// return true if fail
fn check(&self) -> bool;
#[instrument(skip_all, level = "info")]
fn bound_check(&self) -> Result<(), tonic::Status> {
if self.check() {
tracing::warn!(msg = "bound check fail");
Err(Error::NumberTooLarge.into())
} else {
Ok(())
Expand Down
1 change: 1 addition & 0 deletions backend/src/util/rate_limit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ impl Server {

Ok((auth, req))
}
#[instrument(skip_all, level = "info")]
pub async fn rate_limit<T: RateLimit>(
&self,
req: tonic::Request<T>,
Expand Down

0 comments on commit 5eba7ea

Please sign in to comment.