Skip to content

Commit

Permalink
Merge pull request #97
Browse files Browse the repository at this point in the history
Added Redis as caching
  • Loading branch information
gfusee authored Oct 22, 2024
2 parents 65161f4 + dc02e4e commit 816b02f
Show file tree
Hide file tree
Showing 9 changed files with 443 additions and 21 deletions.
3 changes: 2 additions & 1 deletion caching/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,11 @@ repository = "https://github.com/gfusee/novax"

[dependencies]
serde = "1.0.180"
rmp-serde = "1.1.2"
tokio = "1.29.1"
async-trait = "0.1.72"
redis = { version = "0.27.4", features = ["aio", "tokio-comp"] }
novax = { path = "../core", version = "0.1.13" }
rmp-serde = "=1.1.2"

[dev-dependencies]
thread_local = "1.1.7"
29 changes: 25 additions & 4 deletions caching/src/date/get_current_timestamp.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
pub(crate) fn get_timestamp_of_next_block(current_timestamp: Duration) -> Result<Duration, NovaXError> {
pub(crate) fn get_timestamp_of_next_block(current_timestamp: &Duration) -> Result<Duration, NovaXError> {
let mut timestamp = current_timestamp.as_secs() + 1;
while timestamp % 6 != 0 {
timestamp += 1
Expand All @@ -7,6 +7,26 @@ pub(crate) fn get_timestamp_of_next_block(current_timestamp: Duration) -> Result
Ok(Duration::from_secs(timestamp))
}

pub(crate) trait GetDuration {
fn get_duration_timestamp(&self, current_timestamp: &Duration) -> Result<Duration, NovaXError>;
fn get_duration_from_now(&self, current_timestamp: &Duration) -> Result<Duration, NovaXError> {
Ok(self.get_duration_timestamp(current_timestamp)? - *current_timestamp)
}
}

impl GetDuration for CachingDurationStrategy {
fn get_duration_timestamp(&self, current_timestamp: &Duration) -> Result<Duration, NovaXError> {
match self {
CachingDurationStrategy::EachBlock => {
get_timestamp_of_next_block(current_timestamp)
}
CachingDurationStrategy::Duration(duration) => {
Ok(*current_timestamp + *duration)
}
}
}
}

#[cfg(not(test))]
mod implementation {
use std::time::{Duration, SystemTime, UNIX_EPOCH};
Expand All @@ -26,6 +46,7 @@ pub(crate) use implementation::get_current_timestamp;

#[cfg(test)]
pub(crate) use implementation::set_mock_time;
use novax::caching::CachingDurationStrategy;
use novax::errors::NovaXError;

#[cfg(test)]
Expand Down Expand Up @@ -62,23 +83,23 @@ mod tests {

#[test]
fn test_get_timestamp_of_next_block_start_of_block() {
let result = get_timestamp_of_next_block(Duration::from_secs(6)).unwrap();
let result = get_timestamp_of_next_block(&Duration::from_secs(6)).unwrap();
let expected = Duration::from_secs(12);

assert_eq!(result, expected);
}

#[test]
fn test_get_timestamp_of_next_block_mid_of_block() {
let result = get_timestamp_of_next_block(Duration::from_secs(8)).unwrap();
let result = get_timestamp_of_next_block(&Duration::from_secs(8)).unwrap();
let expected = Duration::from_secs(12);

assert_eq!(result, expected);
}

#[test]
fn test_get_timestamp_of_next_block_end_of_block() {
let result = get_timestamp_of_next_block(Duration::from_secs(11)).unwrap();
let result = get_timestamp_of_next_block(&Duration::from_secs(11)).unwrap();
let expected = Duration::from_secs(12);

assert_eq!(result, expected);
Expand Down
1 change: 1 addition & 0 deletions caching/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ pub mod local;
pub(crate) mod date;
pub mod multi;
pub mod locked;
pub mod redis;
30 changes: 14 additions & 16 deletions caching/src/local/caching_local.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
use async_trait::async_trait;
use std::sync::Arc;
use std::collections::HashMap;
use std::future::Future;
use std::sync::Arc;
use std::time::Duration;
use serde::Serialize;

use async_trait::async_trait;
use serde::de::DeserializeOwned;
use serde::Serialize;
use tokio::sync::Mutex;

use novax::caching::{CachingDurationStrategy, CachingStrategy};
use novax::errors::NovaXError;
use novax::errors::CachingError;
use crate::date::get_current_timestamp::{get_current_timestamp, get_timestamp_of_next_block};
use novax::errors::NovaXError;

use crate::date::get_current_timestamp::{get_current_timestamp, GetDuration};

#[derive(Clone, Debug)]
pub struct CachingLocal {
Expand Down Expand Up @@ -38,15 +41,7 @@ impl CachingLocal {
}

async fn set_value<T: Serialize + DeserializeOwned>(&self, key: u64, value: &T) -> Result<(), NovaXError> {
let current_timestamp = get_current_timestamp()?;
let expiration_timestamp = match self.duration_strategy {
CachingDurationStrategy::EachBlock => {
get_timestamp_of_next_block(current_timestamp)?
}
CachingDurationStrategy::Duration(duration) => {
current_timestamp + duration
}
};
let expiration_timestamp = self.duration_strategy.get_duration_timestamp(&get_current_timestamp()?)?;
self.expiration_timestamp_map.lock().await.insert(key, expiration_timestamp);

let Ok(serialized) = rmp_serde::to_vec(value) else { return Err(CachingError::UnableToSerialize.into())};
Expand All @@ -66,7 +61,9 @@ impl CachingStrategy for CachingLocal {
Ok(None)
} else {
let Some(encoded_value) = self.value_map.lock().await.get(&key).cloned() else { return Ok(None) };
let Ok(value) = rmp_serde::from_slice(&encoded_value) else { return Err(CachingError::UnableToDeserialize.into()) };
let Ok(value) = rmp_serde::from_slice(&encoded_value) else {
return Err(CachingError::UnableToDeserialize.into())
};

Ok(Some(value))
}
Expand Down Expand Up @@ -109,8 +106,10 @@ impl CachingStrategy for CachingLocal {
#[cfg(test)]
mod test {
use std::time::Duration;

use novax::caching::{CachingDurationStrategy, CachingStrategy};
use novax::errors::NovaXError;

use crate::date::get_current_timestamp::set_mock_time;
use crate::local::caching_local::CachingLocal;

Expand Down Expand Up @@ -155,7 +154,6 @@ mod test {
let result = caching.get_cache::<String>(key).await?;
let expected = Some("test".to_string());


assert_eq!(result, expected);

Ok(())
Expand Down
Loading

0 comments on commit 816b02f

Please sign in to comment.