Skip to content

Commit

Permalink
chore: add linting and dependencies caching to github action
Browse files Browse the repository at this point in the history
  • Loading branch information
fabioDMFerreira committed Sep 22, 2023
1 parent f39b905 commit 8326f49
Show file tree
Hide file tree
Showing 19 changed files with 93 additions and 75 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,23 @@ jobs:
with:
toolchain: nightly
override: true
components: rustfmt, clippy
- name: Set up cargo cache
uses: actions/cache@v3
continue-on-error: false
with:
path: |
~/.cargo/bin/
~/.cargo/registry/index/
~/.cargo/registry/cache/
~/.cargo/git/db/
target/
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
restore-keys: ${{ runner.os }}-cargo-
- name: Lint
run: |
cargo fmt --all -- --check
cargo clippy -- -D warnings
- uses: actions-rs/cargo@v1
with:
command: test
Expand Down
4 changes: 4 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ cover:
grcov . -s . --binary-path ./target/debug/ -t html --branch --ignore-not-existing -o ./coverage
rm default_*

lint:
cargo fmt
cargo clippy

test:
docker-compose -f docker-compose.tests.yaml up --build

Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# rust-events-oriented-arch

[![Coverage Status](https://coveralls.io/repos/github/fabioDMFerreira/rust-events-oriented-arch/badge.svg?branch=main)](https://coveralls.io/github/fabioDMFerreira/rust-events-oriented-arch?branch=main)

Basic application to learn Rust and events oriented architecture.

## Features
Expand Down
24 changes: 11 additions & 13 deletions news/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,19 +43,17 @@ impl App {
for news in news {
let db_news = self
.news_repo
.find_by_fields(Some(news.title.clone()), Some(news.feed_id.clone()));

if let Ok(db_news) = db_news {
if let None = db_news {
let result = self.news_repo.create(&news);
if let Err(err) = result {
error!("failed creating new {:?}: {}", news, err);
} else {
info!(
"News with title {} of feed {} inserted!",
news.title, news.feed_id
);
}
.find_by_fields(Some(news.title.clone()), Some(news.feed_id));

if let Ok(None) = db_news {
let result = self.news_repo.create(&news);
if let Err(err) = result {
error!("failed creating new {:?}: {}", news, err);
} else {
info!(
"News with title {} of feed {} inserted!",
news.title, news.feed_id
);
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions news/src/handlers/feeds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ async fn get_feeds(feed_repo: web::Data<FeedRepository>) -> HttpResponse {
match result {
Err(err) => {
error!("failed getting feeds: {}", err);
return HttpResponse::InternalServerError().finish();
HttpResponse::InternalServerError().finish()
}
Ok(feeds) => return HttpResponse::Ok().json(feeds),
};
Ok(feeds) => HttpResponse::Ok().json(feeds),
}
}
6 changes: 3 additions & 3 deletions news/src/handlers/news.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ async fn get_news(news_repo: web::Data<NewsRepository>) -> HttpResponse {
match result {
Err(err) => {
error!("failed getting news: {}", err);
return HttpResponse::InternalServerError().finish();
HttpResponse::InternalServerError().finish()
}
Ok(news) => return HttpResponse::Ok().json(news),
};
Ok(news) => HttpResponse::Ok().json(news),
}
}
6 changes: 3 additions & 3 deletions news/src/scrapper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ pub struct Scrapper {

impl Scrapper {
pub fn new(feeds: Vec<RssFeed>) -> Scrapper {
Scrapper { feeds: feeds }
Scrapper { feeds }
}

pub async fn scrap_all(&mut self, tx: Sender<Vec<News>>) -> Result<(), String> {
Expand Down Expand Up @@ -50,7 +50,7 @@ impl Scrapper {
let mut title = "".to_string();
let mut publish_date = chrono::Utc::now().naive_local().date();

if feed_news.authors.len() > 0 {
if !feed_news.authors.is_empty() {
author = feed_news.authors[0].name.clone();
}

Expand Down Expand Up @@ -141,5 +141,5 @@ async fn http_request(url: String) -> Result<Bytes, String> {
return Ok(body);
}

return Err(format!("Request was not successful: {}", response.status()));
Err(format!("Request was not successful: {}", response.status()))
}
10 changes: 8 additions & 2 deletions users/src/actors/ws_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,12 @@ pub struct WebsocketServer {
rng: ThreadRng,
}

impl Default for WebsocketServer {
fn default() -> Self {
Self::new()
}
}

impl WebsocketServer {
pub fn new() -> WebsocketServer {
WebsocketServer {
Expand Down Expand Up @@ -78,8 +84,8 @@ impl Handler<SessionMessage> for WebsocketServer {
fn handle(&mut self, msg: SessionMessage, _: &mut Context<Self>) {
let session_result = self.sessions.get(&msg.id);

if session_result.is_some() {
session_result.unwrap().do_send(Message(msg.message));
if let Some(session_result) = session_result {
session_result.do_send(Message(msg.message));
} else {
warn!("server tried to send message to unknown session {}", msg.id);
}
Expand Down
4 changes: 2 additions & 2 deletions users/src/actors/ws_session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,9 +116,9 @@ impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for WebsocketSession
if msg.starts_with("/login") {
// if there is a token after the command /login check whether the token is valid
// if token is valid set the session as authenticated and set the session id with the user id
if let Some(token) = msg.splitn(2, ' ').nth(1).filter(|s| !s.is_empty()) {
if let Some(token) = msg.split_once(' ').map(|x| x.1) {
match decode::<TokenClaims>(
&token,
token,
&DecodingKey::from_secret(self.config.jwt_secret.as_ref()),
&Validation::default(),
) {
Expand Down
14 changes: 7 additions & 7 deletions users/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ pub struct RepositoryError {
pub message: String,
}

impl Into<CommonError> for RepositoryError {
fn into(self) -> CommonError {
CommonError {
message: self.message,
impl From<RepositoryError> for CommonError {
fn from(val: RepositoryError) -> Self {
Self {
message: val.message,
code: 1,
}
}
Expand All @@ -33,10 +33,10 @@ pub struct BrokerError {
pub message: String,
}

impl Into<CommonError> for BrokerError {
fn into(self) -> CommonError {
impl From<BrokerError> for CommonError {
fn from(val: BrokerError) -> Self {
CommonError {
message: self.message,
message: val.message,
code: 2,
}
}
Expand Down
9 changes: 4 additions & 5 deletions users/src/handlers/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ pub async fn login_handler(
config: web::Data<Config>,
payload: Option<web::Json<LoginPayload>>,
) -> HttpResponse {
if let None = payload {
if payload.is_none() {
return HttpResponse::BadRequest().body("empty body");
}

Expand Down Expand Up @@ -92,7 +92,7 @@ pub async fn login_handler(

let cookie = Cookie::build("token", token.to_owned())
.path("/")
.max_age(ActixWebDuration::new(config.jwt_max_age.clone(), 0))
.max_age(ActixWebDuration::new(config.jwt_max_age, 0))
.http_only(true)
.finish();

Expand All @@ -107,10 +107,9 @@ pub async fn me_handler(
r: HttpRequest,
_: JwtMiddleware,
) -> HttpResponse {
let ext = r.extensions();
let user_id = ext.get::<uuid::Uuid>().unwrap();
let user_id = *r.extensions().get::<uuid::Uuid>().unwrap();

match user_service.get_by_id(user_id.clone()).await {
match user_service.get_by_id(user_id).await {
Ok(user) => HttpResponse::Ok().json(user),
Err(err) => {
error!("failed getting user {}: {}", user_id, err);
Expand Down
6 changes: 2 additions & 4 deletions users/src/handlers/health.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,11 @@ pub async fn get_health(pool: web::Data<utils::db::PgPool>) -> impl Responder {
services: service_status.clone(),
};

let http_response = if db_status == SERVICE_STATUS_OK {
if db_status == SERVICE_STATUS_OK {
HttpResponse::Ok().json(response)
} else {
HttpResponse::InternalServerError().json(response)
};

return http_response;
}
}

// #[cfg(test)]
Expand Down
2 changes: 1 addition & 1 deletion users/src/handlers/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ async fn create_message(
ws_server: Data<Addr<WebsocketServer>>,
payload: Option<Json<MessagePayload>>,
) -> HttpResponse {
if let None = payload {
if payload.is_none() {
return HttpResponse::BadRequest().body("empty body");
}

Expand Down
26 changes: 13 additions & 13 deletions users/src/handlers/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,10 @@ async fn get_users(user_service: web::Data<dyn UserService>) -> HttpResponse {
match result {
Err(err) => {
error!("failed getting users: {}", err);
return HttpResponse::InternalServerError().finish();
HttpResponse::InternalServerError().finish()
}
Ok(users) => return HttpResponse::Ok().json(users),
};
Ok(users) => HttpResponse::Ok().json(users),
}
}

#[get("/users/{id}")]
Expand All @@ -43,9 +43,9 @@ async fn get_user_by_id(
match result {
Err(err) => {
error!("failed getting user: {}", err);
return HttpResponse::InternalServerError().finish();
HttpResponse::InternalServerError().finish()
}
Ok(user) => return HttpResponse::Ok().json(user),
Ok(user) => HttpResponse::Ok().json(user),
}
}

Expand All @@ -54,7 +54,7 @@ async fn create_user(
user_service: web::Data<dyn UserService>,
payload: Option<web::Json<CreateUserPayload>>,
) -> HttpResponse {
if let None = payload {
if payload.is_none() {
return HttpResponse::BadRequest().body("empty body");
}

Expand All @@ -68,9 +68,9 @@ async fn create_user(
match user_service.create(name.unwrap(), password.unwrap()).await {
Err(err) => {
error!("failed creating user: {}", err);
return HttpResponse::InternalServerError().finish();
HttpResponse::InternalServerError().finish()
}
Ok(new_user) => return HttpResponse::Ok().json(new_user),
Ok(new_user) => HttpResponse::Ok().json(new_user),
}
}

Expand All @@ -80,7 +80,7 @@ async fn update_user(
payload: Option<web::Json<UpdateUserPayload>>,
id: web::Path<Uuid>,
) -> HttpResponse {
if let None = payload {
if payload.is_none() {
return HttpResponse::BadRequest().body("empty body");
}

Expand All @@ -94,9 +94,9 @@ async fn update_user(
match user_service.update(id.into_inner(), name.unwrap()).await {
Err(err) => {
error!("failed updating user: {}", err);
return HttpResponse::InternalServerError().finish();
HttpResponse::InternalServerError().finish()
}
Ok(updated_user) => return HttpResponse::Ok().json(updated_user),
Ok(updated_user) => HttpResponse::Ok().json(updated_user),
}
}

Expand All @@ -108,9 +108,9 @@ async fn delete_user(
match user_service.delete(id.into_inner()).await {
Err(err) => {
error!("failed deleting user: {}", err);
return HttpResponse::InternalServerError().finish();
HttpResponse::InternalServerError().finish()
}
Ok(_) => return HttpResponse::Ok().finish(),
Ok(_) => HttpResponse::Ok().finish(),
}
}

Expand Down
1 change: 0 additions & 1 deletion users/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ use users::app;
use users::config::Config;
use utils::logger::init_logger;


#[actix_web::main]
async fn main() -> std::io::Result<()> {
let config = Config::init();
Expand Down
8 changes: 4 additions & 4 deletions users/src/middlewares/jwt_auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,14 +59,14 @@ impl FromRequest for JwtMiddleware {
let user_id = uuid::Uuid::parse_str(&claims.sub).unwrap();
req.extensions_mut()
.insert::<uuid::Uuid>(user_id.to_owned());
return ready(Ok(JwtMiddleware { user_id }));
ready(Ok(JwtMiddleware { user_id }))
} else {
return ready(Err(json_error("Invalid token".to_string())));
ready(Err(json_error("Invalid token".to_string())))
}
} else {
return ready(Err(json_error(
ready(Err(json_error(
"You are not logged in, please provide token".to_string(),
)));
)))
}
}
}
2 changes: 1 addition & 1 deletion users/src/services/event_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ pub struct KafkaEventService {

impl KafkaEventService {
pub fn new(producer: FutureProducer) -> Self {
KafkaEventService { producer: producer }
KafkaEventService { producer }
}
}

Expand Down
5 changes: 1 addition & 4 deletions users/src/services/user_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,7 @@ pub struct UserServiceImpl {

impl UserServiceImpl {
pub fn new(repo: Arc<dyn UserRepository>, broker: Arc<dyn EventService>) -> Self {
UserServiceImpl {
repo: repo,
broker: broker,
}
UserServiceImpl { repo, broker }
}
}

Expand Down
Loading

0 comments on commit 8326f49

Please sign in to comment.