Skip to content

Commit

Permalink
feat: sucessfully set and retrieve basic data from redis
Browse files Browse the repository at this point in the history
  • Loading branch information
nikola-bozin-org committed Apr 22, 2024
1 parent e9a4f5b commit ad1cc85
Show file tree
Hide file tree
Showing 4 changed files with 95 additions and 4 deletions.
26 changes: 24 additions & 2 deletions Cargo.lock

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

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ serde_json = "1.0.112"
dotenv = "0.15.0"
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","json"] }
redis = { version = "0.25.3", features = ["tokio-comp"] }
redis-macros = "0.3.0"

[profile.release]
strip = true # Remove symbols from binary
Expand Down
3 changes: 2 additions & 1 deletion src/middlewares/rate_limiter/rate_limit_info.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use redis_macros::{FromRedisValue, ToRedisArgs};
use serde::{Deserialize, Serialize};

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

use redis::{aio::MultiplexedConnection, AsyncCommands, Client};

use super::{RateLimitInfo, Result};

pub trait RedisInteractor{
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

}


impl RedisInteractor 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()
}

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(); // TODO, why ,,() ?

}
}


#[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")
}

#[tokio::test]
async fn test_new() {
let _db = setup_test_db().await;
// If no panic and no error, assume successful connection and client creation
}

#[tokio::test]
async fn test_set_and_get_data() {
let mut db = setup_test_db().await;
let test_ip = SocketAddr::from_str("127.0.0.1:8080").unwrap();
let rate_limit_info = RateLimitInfo { limit: 10 };

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.");
}
}

0 comments on commit ad1cc85

Please sign in to comment.