Skip to content

Commit

Permalink
Merge pull request #15 from viz-rs/afit_rpitit
Browse files Browse the repository at this point in the history
refactor: AFIT & RPITIT
  • Loading branch information
fundon authored Jan 2, 2024
2 parents 77374ba + c413852 commit 77b3621
Show file tree
Hide file tree
Showing 12 changed files with 115 additions and 120 deletions.
25 changes: 13 additions & 12 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,34 +8,35 @@ members = [
resolver = "2"

[workspace.package]
version = "0.5.1"
version = "0.6.0"
authors = ["Fangdun Tsai <[email protected]>"]
edition = "2021"
license = "MIT OR Apache-2.0"
documentation = "https://docs.rs/sessions"
homepage = "https://github.com/viz-rs/sessions"
repository = "https://github.com/viz-rs/sessions"
rust-version = "1.75"

[workspace.dependencies]
sessions = { version = "0.5.0", path = "sessions" }
sessions-core = { version = "0.5.0", path = "sessions-core" }
sessions-memory = { version = "0.5.0", path = "sessions-memory" }
sessions-redis = { version = "0.5.0", path = "sessions-redis" }
sessions = { version = "0.6.0", path = "sessions" }
sessions-core = { version = "0.6.0", path = "sessions-core" }
sessions-memory = { version = "0.6.0", path = "sessions-memory" }
sessions-redis = { version = "0.6.0", path = "sessions-redis" }

anyhow = "1.0"
async-trait = "0.1"
nano-id = "0.3"
serde = "1.0"
serde_json = "1.0"
thiserror = "1.0"

futures-executor = "0.3"
tokio = { version = "1", features = ["macros"] }
redis = { version = "0.23", default-features = false, features = [
redis = { version = "0.24", default-features = false, features = [
"aio",
"connection-manager",
] }

anyhow = "1.0"
nano-id = "0.3"

futures-executor = "0.3"
tokio = { version = "1", features = ["macros"] }

[workspace.metadata.docs.rs]
all-features = true
rustdoc-args = ["--cfg", "docsrs"]
Expand Down
2 changes: 0 additions & 2 deletions sessions-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,5 @@ readme = "README.md"
session = []

[dependencies]
async-trait.workspace = true
serde.workspace = true
serde_json.workspace = true
thiserror.workspace = true
15 changes: 0 additions & 15 deletions sessions-core/src/error.rs

This file was deleted.

11 changes: 5 additions & 6 deletions sessions-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,16 @@ pub const CHANGED: u8 = 3;
/// A data state
pub type Data = std::collections::BTreeMap<String, serde_json::Value>;

mod error;
mod state;
pub use state::State;

mod storage;
pub use storage::Storage;

mod store;
pub use store::Store;

pub use async_trait::async_trait;
pub use error::Error;
pub use serde_json::Value;
pub use state::State;
pub use storage::Storage;
pub use store::Store;

#[cfg(feature = "session")]
mod session;
Expand Down
30 changes: 19 additions & 11 deletions sessions-core/src/session.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
use std::{
fmt,
io::{Error, ErrorKind, Result},
sync::{
atomic::{AtomicU8, Ordering},
Arc, RwLock,
},
};

use serde::{de::DeserializeOwned, Serialize};
use serde_json::{from_value, to_value, Value};

use crate::{Data, Error, State, CHANGED, PURGED, RENEWED, UNCHANGED};
use crate::{Data, State, CHANGED, PURGED, RENEWED, UNCHANGED};

/// Session
#[derive(Clone)]
Expand Down Expand Up @@ -39,24 +39,24 @@ impl Session {
}

/// Gets a value by the key
pub fn get<T>(&self, key: &str) -> Result<Option<T>, Error>
pub fn get<T>(&self, key: &str) -> Result<Option<T>>
where
T: DeserializeOwned,
{
match self
.lock_data()
.read()
.map_err(|e| Error::RwLock(e.to_string()))?
.map_err(into_io_error)?
.get(key)
.cloned()
{
Some(t) => from_value(t).map(Some).map_err(Error::Json),
Some(t) => serde_json::from_value(t).map(Some).map_err(Into::into),
None => Ok(None),
}
}

/// Sets a value by the key
pub fn set<T>(&self, key: &str, val: T) -> Result<(), Error>
pub fn set<T>(&self, key: &str, val: T) -> Result<()>
where
T: Serialize,
{
Expand All @@ -68,14 +68,17 @@ impl Session {
if status == UNCHANGED {
self.status().store(CHANGED, Ordering::SeqCst);
}
d.insert(key.into(), to_value(val).map_err(Error::Json)?);
d.insert(
key.into(),
serde_json::to_value(val).map_err(into_io_error)?,
);
}
}
Ok(())
}

/// Removes a value
pub fn remove(&self, key: &str) -> Option<Value> {
pub fn remove(&self, key: &str) -> Option<serde_json::Value> {
let status = self.status().load(Ordering::Acquire);
// not allowed `PURGED`
if status != PURGED {
Expand All @@ -95,7 +98,7 @@ impl Session {
where
T: DeserializeOwned,
{
self.remove(key).and_then(|t| from_value(t).ok())
serde_json::from_value(self.remove(key)?).ok()
}

/// Clears the state
Expand Down Expand Up @@ -135,10 +138,10 @@ impl Session {
}

/// Gets all raw key-value data from the session
pub fn data(&self) -> Result<Data, Error> {
pub fn data(&self) -> Result<Data> {
self.lock_data()
.read()
.map_err(|e| Error::RwLock(e.to_string()))
.map_err(into_io_error)
.map(|d| d.clone())
}
}
Expand All @@ -148,3 +151,8 @@ impl fmt::Debug for Session {
self.state.fmt(f)
}
}

#[inline]
fn into_io_error<E: std::error::Error>(e: E) -> Error {
Error::new(ErrorKind::Other, e.to_string())
}
29 changes: 14 additions & 15 deletions sessions-core/src/storage.rs
Original file line number Diff line number Diff line change
@@ -1,26 +1,25 @@
use std::time::Duration;
use std::{future::Future, io::Result, time::Duration};

use crate::{async_trait, Data, Error};
use crate::Data;

/// A Storage Trait
#[async_trait]
pub trait Storage: Send + Sync {
/// Get a data from storage by the key
async fn get(&self, key: &str) -> Result<Option<Data>, Error>;
/// Gets a [`Data`] from storage by the key
fn get(&self, key: &str) -> impl Future<Output = Result<Option<Data>>> + Send;

/// Set a session to storage
async fn set(&self, key: &str, val: Data, exp: &Duration) -> Result<(), Error>;
/// Sets a session [`Data`] into storage
fn set(&self, key: &str, val: Data, exp: &Duration) -> impl Future<Output = Result<()>> + Send;

/// Remove a data from storage by the key
async fn remove(&self, key: &str) -> Result<(), Error>;
/// Removes a data from storage by the key
fn remove(&self, key: &str) -> impl Future<Output = Result<()>> + Send;

/// Reset the storage and remove all keys
async fn reset(&self) -> Result<(), Error> {
Ok(())
/// Resets the storage and remove all keys
fn reset(&self) -> impl Future<Output = Result<()>> + Send {
async { Ok(()) }
}

/// Close the connection
async fn close(&self) -> Result<(), Error> {
Ok(())
/// Closes the connection
fn close(&self) -> impl Future<Output = Result<()>> + Send {
async { Ok(()) }
}
}
12 changes: 6 additions & 6 deletions sessions-core/src/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,6 @@ impl<S, G, V> Store<S, G, V> {
}
}

impl<S, G, V> fmt::Debug for Store<S, G, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Config").finish()
}
}

impl<S, G, V> AsRef<S> for Store<S, G, V> {
fn as_ref(&self) -> &S {
&self.storage
Expand All @@ -44,3 +38,9 @@ impl<S, G, V> Deref for Store<S, G, V> {
&self.storage
}
}

impl<S, G, V> fmt::Debug for Store<S, G, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Store").finish()
}
}
43 changes: 21 additions & 22 deletions sessions-memory/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
use std::{
collections::HashMap,
io::{Error, ErrorKind, Result},
sync::{Arc, RwLock},
time::{Duration, Instant},
};

use sessions_core::{async_trait, Data, Error, Storage};
use sessions_core::{Data, Storage};

#[derive(Debug, Clone)]
pub struct State(Instant, Data);
Expand All @@ -23,26 +24,25 @@ pub struct MemoryStorage {
impl MemoryStorage {
#[must_use]
pub fn new() -> Self {
Self {
inner: Arc::default(),
}
Self::default()
}

/// Gets a reference to the underlying data.
#[must_use]
pub fn data(&self) -> &RwLock<HashMap<String, State>> {
pub fn get_ref(&self) -> &RwLock<HashMap<String, State>> {
&self.inner
}
}

#[async_trait]
impl Storage for MemoryStorage {
async fn get(&self, key: &str) -> Result<Option<Data>, Error> {
async fn get(&self, key: &str) -> Result<Option<Data>> {
let state = self
.data()
.get_ref()
.read()
.map_err(|e| Error::RwLock(e.to_string()))?
.map_err(into_io_error)?
.get(key)
.cloned();

if let Some(State(time, data)) = state {
if time >= Instant::now() {
return Ok(Some(data));
Expand All @@ -53,27 +53,26 @@ impl Storage for MemoryStorage {
Ok(None)
}

async fn set(&self, key: &str, val: Data, exp: &Duration) -> Result<(), Error> {
self.data()
async fn set(&self, key: &str, val: Data, exp: &Duration) -> Result<()> {
self.get_ref()
.write()
.map_err(|e| Error::RwLock(e.to_string()))?
.map_err(into_io_error)?
.insert(key.to_string(), State::new(Instant::now() + *exp, val));
Ok(())
}

async fn remove(&self, key: &str) -> Result<(), Error> {
self.data()
.write()
.map_err(|e| Error::RwLock(e.to_string()))?
.remove(key);
async fn remove(&self, key: &str) -> Result<()> {
self.get_ref().write().map_err(into_io_error)?.remove(key);
Ok(())
}

async fn reset(&self) -> Result<(), Error> {
self.data()
.write()
.map_err(|e| Error::RwLock(e.to_string()))?
.clear();
async fn reset(&self) -> Result<()> {
self.get_ref().write().map_err(into_io_error)?.clear();
Ok(())
}
}

#[inline]
fn into_io_error<E: std::error::Error>(e: E) -> Error {
Error::new(ErrorKind::Other, e.to_string())
}
Loading

0 comments on commit 77b3621

Please sign in to comment.