Skip to content

Commit 77b3621

Browse files
authored
Merge pull request #15 from viz-rs/afit_rpitit
refactor: AFIT & RPITIT
2 parents 77374ba + c413852 commit 77b3621

File tree

12 files changed

+115
-120
lines changed

12 files changed

+115
-120
lines changed

Cargo.toml

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -8,34 +8,35 @@ members = [
88
resolver = "2"
99

1010
[workspace.package]
11-
version = "0.5.1"
11+
version = "0.6.0"
1212
authors = ["Fangdun Tsai <cfddream@gmail.com>"]
1313
edition = "2021"
1414
license = "MIT OR Apache-2.0"
1515
documentation = "https://docs.rs/sessions"
1616
homepage = "https://github.com/viz-rs/sessions"
1717
repository = "https://github.com/viz-rs/sessions"
18+
rust-version = "1.75"
1819

1920
[workspace.dependencies]
20-
sessions = { version = "0.5.0", path = "sessions" }
21-
sessions-core = { version = "0.5.0", path = "sessions-core" }
22-
sessions-memory = { version = "0.5.0", path = "sessions-memory" }
23-
sessions-redis = { version = "0.5.0", path = "sessions-redis" }
21+
sessions = { version = "0.6.0", path = "sessions" }
22+
sessions-core = { version = "0.6.0", path = "sessions-core" }
23+
sessions-memory = { version = "0.6.0", path = "sessions-memory" }
24+
sessions-redis = { version = "0.6.0", path = "sessions-redis" }
2425

25-
anyhow = "1.0"
26-
async-trait = "0.1"
27-
nano-id = "0.3"
2826
serde = "1.0"
2927
serde_json = "1.0"
30-
thiserror = "1.0"
3128

32-
futures-executor = "0.3"
33-
tokio = { version = "1", features = ["macros"] }
34-
redis = { version = "0.23", default-features = false, features = [
29+
redis = { version = "0.24", default-features = false, features = [
3530
"aio",
3631
"connection-manager",
3732
] }
3833

34+
anyhow = "1.0"
35+
nano-id = "0.3"
36+
37+
futures-executor = "0.3"
38+
tokio = { version = "1", features = ["macros"] }
39+
3940
[workspace.metadata.docs.rs]
4041
all-features = true
4142
rustdoc-args = ["--cfg", "docsrs"]

sessions-core/Cargo.toml

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,5 @@ readme = "README.md"
1414
session = []
1515

1616
[dependencies]
17-
async-trait.workspace = true
1817
serde.workspace = true
1918
serde_json.workspace = true
20-
thiserror.workspace = true

sessions-core/src/error.rs

Lines changed: 0 additions & 15 deletions
This file was deleted.

sessions-core/src/lib.rs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,17 +17,16 @@ pub const CHANGED: u8 = 3;
1717
/// A data state
1818
pub type Data = std::collections::BTreeMap<String, serde_json::Value>;
1919

20-
mod error;
2120
mod state;
21+
pub use state::State;
22+
2223
mod storage;
24+
pub use storage::Storage;
25+
2326
mod store;
27+
pub use store::Store;
2428

25-
pub use async_trait::async_trait;
26-
pub use error::Error;
2729
pub use serde_json::Value;
28-
pub use state::State;
29-
pub use storage::Storage;
30-
pub use store::Store;
3130

3231
#[cfg(feature = "session")]
3332
mod session;

sessions-core/src/session.rs

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
use std::{
22
fmt,
3+
io::{Error, ErrorKind, Result},
34
sync::{
45
atomic::{AtomicU8, Ordering},
56
Arc, RwLock,
67
},
78
};
89

910
use serde::{de::DeserializeOwned, Serialize};
10-
use serde_json::{from_value, to_value, Value};
1111

12-
use crate::{Data, Error, State, CHANGED, PURGED, RENEWED, UNCHANGED};
12+
use crate::{Data, State, CHANGED, PURGED, RENEWED, UNCHANGED};
1313

1414
/// Session
1515
#[derive(Clone)]
@@ -39,24 +39,24 @@ impl Session {
3939
}
4040

4141
/// Gets a value by the key
42-
pub fn get<T>(&self, key: &str) -> Result<Option<T>, Error>
42+
pub fn get<T>(&self, key: &str) -> Result<Option<T>>
4343
where
4444
T: DeserializeOwned,
4545
{
4646
match self
4747
.lock_data()
4848
.read()
49-
.map_err(|e| Error::RwLock(e.to_string()))?
49+
.map_err(into_io_error)?
5050
.get(key)
5151
.cloned()
5252
{
53-
Some(t) => from_value(t).map(Some).map_err(Error::Json),
53+
Some(t) => serde_json::from_value(t).map(Some).map_err(Into::into),
5454
None => Ok(None),
5555
}
5656
}
5757

5858
/// Sets a value by the key
59-
pub fn set<T>(&self, key: &str, val: T) -> Result<(), Error>
59+
pub fn set<T>(&self, key: &str, val: T) -> Result<()>
6060
where
6161
T: Serialize,
6262
{
@@ -68,14 +68,17 @@ impl Session {
6868
if status == UNCHANGED {
6969
self.status().store(CHANGED, Ordering::SeqCst);
7070
}
71-
d.insert(key.into(), to_value(val).map_err(Error::Json)?);
71+
d.insert(
72+
key.into(),
73+
serde_json::to_value(val).map_err(into_io_error)?,
74+
);
7275
}
7376
}
7477
Ok(())
7578
}
7679

7780
/// Removes a value
78-
pub fn remove(&self, key: &str) -> Option<Value> {
81+
pub fn remove(&self, key: &str) -> Option<serde_json::Value> {
7982
let status = self.status().load(Ordering::Acquire);
8083
// not allowed `PURGED`
8184
if status != PURGED {
@@ -95,7 +98,7 @@ impl Session {
9598
where
9699
T: DeserializeOwned,
97100
{
98-
self.remove(key).and_then(|t| from_value(t).ok())
101+
serde_json::from_value(self.remove(key)?).ok()
99102
}
100103

101104
/// Clears the state
@@ -135,10 +138,10 @@ impl Session {
135138
}
136139

137140
/// Gets all raw key-value data from the session
138-
pub fn data(&self) -> Result<Data, Error> {
141+
pub fn data(&self) -> Result<Data> {
139142
self.lock_data()
140143
.read()
141-
.map_err(|e| Error::RwLock(e.to_string()))
144+
.map_err(into_io_error)
142145
.map(|d| d.clone())
143146
}
144147
}
@@ -148,3 +151,8 @@ impl fmt::Debug for Session {
148151
self.state.fmt(f)
149152
}
150153
}
154+
155+
#[inline]
156+
fn into_io_error<E: std::error::Error>(e: E) -> Error {
157+
Error::new(ErrorKind::Other, e.to_string())
158+
}

sessions-core/src/storage.rs

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,25 @@
1-
use std::time::Duration;
1+
use std::{future::Future, io::Result, time::Duration};
22

3-
use crate::{async_trait, Data, Error};
3+
use crate::Data;
44

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

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

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

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

22-
/// Close the connection
23-
async fn close(&self) -> Result<(), Error> {
24-
Ok(())
21+
/// Closes the connection
22+
fn close(&self) -> impl Future<Output = Result<()>> + Send {
23+
async { Ok(()) }
2524
}
2625
}

sessions-core/src/store.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,12 +25,6 @@ impl<S, G, V> Store<S, G, V> {
2525
}
2626
}
2727

28-
impl<S, G, V> fmt::Debug for Store<S, G, V> {
29-
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30-
f.debug_struct("Config").finish()
31-
}
32-
}
33-
3428
impl<S, G, V> AsRef<S> for Store<S, G, V> {
3529
fn as_ref(&self) -> &S {
3630
&self.storage
@@ -44,3 +38,9 @@ impl<S, G, V> Deref for Store<S, G, V> {
4438
&self.storage
4539
}
4640
}
41+
42+
impl<S, G, V> fmt::Debug for Store<S, G, V> {
43+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44+
f.debug_struct("Store").finish()
45+
}
46+
}

sessions-memory/src/lib.rs

Lines changed: 21 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
use std::{
22
collections::HashMap,
3+
io::{Error, ErrorKind, Result},
34
sync::{Arc, RwLock},
45
time::{Duration, Instant},
56
};
67

7-
use sessions_core::{async_trait, Data, Error, Storage};
8+
use sessions_core::{Data, Storage};
89

910
#[derive(Debug, Clone)]
1011
pub struct State(Instant, Data);
@@ -23,26 +24,25 @@ pub struct MemoryStorage {
2324
impl MemoryStorage {
2425
#[must_use]
2526
pub fn new() -> Self {
26-
Self {
27-
inner: Arc::default(),
28-
}
27+
Self::default()
2928
}
3029

30+
/// Gets a reference to the underlying data.
3131
#[must_use]
32-
pub fn data(&self) -> &RwLock<HashMap<String, State>> {
32+
pub fn get_ref(&self) -> &RwLock<HashMap<String, State>> {
3333
&self.inner
3434
}
3535
}
3636

37-
#[async_trait]
3837
impl Storage for MemoryStorage {
39-
async fn get(&self, key: &str) -> Result<Option<Data>, Error> {
38+
async fn get(&self, key: &str) -> Result<Option<Data>> {
4039
let state = self
41-
.data()
40+
.get_ref()
4241
.read()
43-
.map_err(|e| Error::RwLock(e.to_string()))?
42+
.map_err(into_io_error)?
4443
.get(key)
4544
.cloned();
45+
4646
if let Some(State(time, data)) = state {
4747
if time >= Instant::now() {
4848
return Ok(Some(data));
@@ -53,27 +53,26 @@ impl Storage for MemoryStorage {
5353
Ok(None)
5454
}
5555

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

64-
async fn remove(&self, key: &str) -> Result<(), Error> {
65-
self.data()
66-
.write()
67-
.map_err(|e| Error::RwLock(e.to_string()))?
68-
.remove(key);
64+
async fn remove(&self, key: &str) -> Result<()> {
65+
self.get_ref().write().map_err(into_io_error)?.remove(key);
6966
Ok(())
7067
}
7168

72-
async fn reset(&self) -> Result<(), Error> {
73-
self.data()
74-
.write()
75-
.map_err(|e| Error::RwLock(e.to_string()))?
76-
.clear();
69+
async fn reset(&self) -> Result<()> {
70+
self.get_ref().write().map_err(into_io_error)?.clear();
7771
Ok(())
7872
}
7973
}
74+
75+
#[inline]
76+
fn into_io_error<E: std::error::Error>(e: E) -> Error {
77+
Error::new(ErrorKind::Other, e.to_string())
78+
}

0 commit comments

Comments
 (0)