Skip to content

Commit

Permalink
chore: run fmt and add manual workflow test
Browse files Browse the repository at this point in the history
  • Loading branch information
nikola-bozin-org committed May 3, 2024
1 parent 59472d6 commit eb3dd11
Show file tree
Hide file tree
Showing 18 changed files with 113 additions and 84 deletions.
15 changes: 15 additions & 0 deletions .github/workflows/manual-workflow.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
name: Manual Trigger Workflow

on:
workflow_dispatch:

jobs:
build:
runs-on: ubuntu-latest

steps:
- name: Checkout code
uses: actions/checkout@v2

- name: Run a one-line script
run: echo "This workflow was manually triggered."
13 changes: 10 additions & 3 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 Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ sqlx = { version = "0.7.4", features = ["postgres","runtime-tokio-rustls"] }
uuid = { version = "1.7.0", features = ["v4", "fast-rng"] }
redis = { version = "0.25.3", features = ["tokio-comp"] }
redis-macros = "0.3.0"
base64="0.22.1"

[profile.release]
strip = true # Remove symbols from binary
Expand Down
1 change: 0 additions & 1 deletion src/db/connect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ use tracing_fast_dev::tfd;

pub type Database = sqlx::Pool<sqlx::Postgres>;


#[derive(Debug)]
pub enum Error {
FailedConnectingToDatabase { error: String },
Expand Down
4 changes: 2 additions & 2 deletions src/db/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
mod queries;
mod connect;
mod queries;

pub use queries::*;
pub use connect::*;
pub use queries::*;
4 changes: 2 additions & 2 deletions src/db/queries.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use crate::models::Wisdom;
use super::connect::Database;
use crate::models::Wisdom;

pub async fn _get_wisdoms(db: &Database) -> Result<Vec<Wisdom>, sqlx::Error> {
tracing_fast_dev::tfd().info("GET_WISDOMS_INTERNAL", "QUERY");
let wisdoms: Vec<Wisdom> = sqlx::query_as("SELECT * from wisdoms")
.fetch_all(db)
.await?;
Ok(wisdoms)
}
}
24 changes: 15 additions & 9 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,25 @@
mod constants;
mod state;
mod db;
mod routes;
mod models;
mod middlewares;
mod helpers;
mod middlewares;
mod models;
mod routes;
mod state;

use db::connect;
use state::AppState;
use std::{env, net::SocketAddr, sync::Arc};
use db::connect;

use axum::{middleware, Extension, Router};
use tokio::net::TcpListener;
use middlewares::response_mapper;
use tokio::net::TcpListener;

#[tokio::main]
async fn main() {
let _ = dotenv::dotenv();
let database_url = env::var("DATABASE_URL").unwrap_or_else(|_| panic!("Missing required environment variable: {}","DATABASE_URL"));

let database_url = env::var("DATABASE_URL")
.unwrap_or_else(|_| panic!("Missing required environment variable: {}", "DATABASE_URL"));

let tfd = tracing_fast_dev::tfd();

tfd.info("wisdomia", "INITIALIZATION");
Expand All @@ -43,5 +44,10 @@ async fn main() {
.layer(middleware::from_fn(middlewares::rate_limit))
.layer(middleware::map_response(response_mapper));

axum::serve(listener, router.into_make_service_with_connect_info::<SocketAddr>()).await.unwrap();
axum::serve(
listener,
router.into_make_service_with_connect_info::<SocketAddr>(),
)
.await
.unwrap();
}
5 changes: 2 additions & 3 deletions src/middlewares/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
mod response_mapper_mw;
mod rate_limiter;

mod response_mapper_mw;

pub use rate_limiter::*;
pub use response_mapper_mw::*;
pub use response_mapper_mw::*;
9 changes: 4 additions & 5 deletions src/middlewares/rate_limiter/mod.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
mod error;
mod rate_limit_info;
mod rate_limit_mw;
mod rate_limiter_config;
mod rate_limit_info;
mod redis_interactor;
mod error;


pub use error::*;
pub use rate_limit_info::*;
pub use rate_limit_mw::*;
pub use rate_limiter_config::*;
pub use rate_limit_info::*;
pub use error::*;
4 changes: 2 additions & 2 deletions src/middlewares/rate_limiter/rate_limit_info.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use redis_macros::{FromRedisValue, ToRedisArgs};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize,FromRedisValue,ToRedisArgs,PartialEq,Eq,Debug)]
#[derive(Serialize, Deserialize, FromRedisValue, ToRedisArgs, PartialEq, Eq, Debug)]
pub struct RateLimitInfo {
pub limit: i32,
}
}
13 changes: 8 additions & 5 deletions src/middlewares/rate_limiter/rate_limit_mw.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
use std::net::SocketAddr;

use axum::{extract::{ConnectInfo, Request}, middleware::Next, response::Response};

use axum::{
extract::{ConnectInfo, Request},
middleware::Next,
response::Response,
};

pub async fn rate_limit(
ConnectInfo(ip_addr): ConnectInfo<SocketAddr>,
mut req: Request,
next: Next,
)-> Response {
println!("Rate limiter hit with ip: {}",ip_addr);
) -> Response {
println!("Rate limiter hit with ip: {}", ip_addr);
next.run(req).await
}
}
30 changes: 14 additions & 16 deletions src/middlewares/rate_limiter/rate_limiter_config.rs
Original file line number Diff line number Diff line change
@@ -1,31 +1,29 @@
use std::time::Duration;


pub trait RateLimiter {
fn new(requests_amount:u32,limit:Duration)->Self;
fn set_requests_amount(&mut self,requests_amount:u32);
fn set_limit(&mut self, limit:Duration);
fn new(requests_amount: u32, limit: Duration) -> Self;
fn set_requests_amount(&mut self, requests_amount: u32);
fn set_limit(&mut self, limit: Duration);
}

pub struct RateLimiterConfig {
pub requests_amount:u32,
pub limit:Duration,
pub requests_amount: u32,
pub limit: Duration,
}

impl RateLimiter for RateLimiterConfig {
fn new(requests_amount:u32,limit:Duration) -> Self {
fn new(requests_amount: u32, limit: Duration) -> Self {
Self {
requests_amount,
limit
limit,
}
}

fn set_requests_amount(&mut self,requests_amount:u32) {
self.requests_amount=requests_amount;
}

fn set_limit(&mut self, limit:Duration) {
self.limit=limit;

fn set_requests_amount(&mut self, requests_amount: u32) {
self.requests_amount = requests_amount;
}

}
fn set_limit(&mut self, limit: Duration) {
self.limit = limit;
}
}
52 changes: 31 additions & 21 deletions src/middlewares/rate_limiter/redis_interactor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,47 +4,53 @@ use redis::{aio::MultiplexedConnection, AsyncCommands, Client};

use super::{RateLimitInfo, Result};

pub trait RateLimiterRedisInteractor{
async fn new(redis_url:String)->Result<Self> where Self:Sized;
async fn get_data(&mut self,ip_addr:SocketAddr)-> Option<RateLimitInfo> ;
async fn set_data(&mut self,ip_addr:SocketAddr,rate_limit_info:&RateLimitInfo);
pub trait RateLimiterRedisInteractor {
async fn new(redis_url: String) -> Result<Self>
where
Self: Sized;
async fn get_data(&mut self, ip_addr: SocketAddr) -> Option<RateLimitInfo>;
async fn set_data(&mut self, ip_addr: SocketAddr, rate_limit_info: &RateLimitInfo);
}

pub struct RedisRateLimiterDb{
pub client:Client,
pub connection:MultiplexedConnection

pub struct RedisRateLimiterDb {
pub client: Client,
pub connection: MultiplexedConnection,
}


impl RateLimiterRedisInteractor for RedisRateLimiterDb{
async fn new(redis_url:String)->Result<Self> {
impl RateLimiterRedisInteractor for RedisRateLimiterDb {
async fn new(redis_url: String) -> Result<Self> {
let client = Client::open(redis_url)?;
let connection = client.get_multiplexed_async_connection().await?;
Ok(Self { client, connection })
}

async fn get_data(&mut self, ip_addr: SocketAddr) -> Option<RateLimitInfo> {
let key = ip_addr.to_string();
self.connection.get::<String,Option<RateLimitInfo>>(key).await.unwrap()
self.connection
.get::<String, Option<RateLimitInfo>>(key)
.await
.unwrap()
}

async fn set_data(&mut self, ip_addr: SocketAddr,rate_limit_info:&RateLimitInfo) {
let key = ip_addr.to_string();
self.connection.set::<String, &RateLimitInfo, ()>(key, rate_limit_info).await.unwrap();

async fn set_data(&mut self, ip_addr: SocketAddr, rate_limit_info: &RateLimitInfo) {
let key = ip_addr.to_string();
self.connection
.set::<String, &RateLimitInfo, ()>(key, rate_limit_info)
.await
.unwrap();
}
}


#[cfg(test)]
mod tests {
use super::*;
use std::str::FromStr;

async fn setup_test_db() -> RedisRateLimiterDb {
let redis_url = "redis://localhost:6379/15"; // using database 15 for testing
RedisRateLimiterDb::new(redis_url.to_string()).await.expect("Failed to create test Redis client")
RedisRateLimiterDb::new(redis_url.to_string())
.await
.expect("Failed to create test Redis client")
}

#[tokio::test]
Expand All @@ -62,6 +68,10 @@ mod tests {
db.set_data(test_ip, &rate_limit_info).await;
let retrieved_data = db.get_data(test_ip).await;

assert_eq!(Some(rate_limit_info), retrieved_data, "Retrieved data does not match the set data.");
assert_eq!(
Some(rate_limit_info),
retrieved_data,
"Retrieved data does not match the set data."
);
}
}
}
5 changes: 2 additions & 3 deletions src/middlewares/response_mapper_mw.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
use uuid::Uuid;
use serde_json::json;
use axum::{
http::{Method, StatusCode, Uri},
response::{IntoResponse, Response},
Json,
};

use serde_json::json;
use uuid::Uuid;

pub async fn response_mapper(uri: Uri, method: Method, response: Response) -> Response {
tracing_fast_dev::tfd().info("RESPONSE_MAPPER", "MIDDLEWARE");
Expand Down
2 changes: 1 addition & 1 deletion src/models/wisdom.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@ use sqlx::prelude::FromRow;
pub struct Wisdom {
pub id: i32,
pub description: String,
}
}
7 changes: 2 additions & 5 deletions src/routes/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,12 @@ mod wisdoms;

use axum::Router;


pub fn routes() -> Router {
Router::new().merge(_routes())
}

fn _routes() -> Router {
let mut router = Router::new();
router = router
.merge(dbg::routes())
.merge(wisdoms::routes());
router = router.merge(dbg::routes()).merge(wisdoms::routes());
router
}
}
Loading

0 comments on commit eb3dd11

Please sign in to comment.