aurelin_framework/cache/
redis.rs1use std::time::Duration;
2
3use async_trait::async_trait;
4use fred::{
5 bytes::Bytes,
6 clients::Client,
7 interfaces::{ClientLike, KeysInterface, LuaInterface},
8 prelude::{Builder, Config},
9 types::{ClusterHash, CustomCommand, Expiration, SetOptions},
10};
11
12use super::{Error, Store};
13
14const RELEASE_LOCK: &str = include_str!("scripts/release_lock.lua");
15const REFRESH_LOCK: &str = include_str!("scripts/refresh_lock.lua");
16
17#[derive(Clone)]
19pub struct RedisStore {
20 client: Client,
21}
22
23impl RedisStore {
24 pub async fn connect(url: &str) -> Result<Self, Error> {
26 let config = Config::from_url(url)?;
27 let client = Builder::from_config(config).build()?;
28 client.init().await?;
29 Ok(Self { client })
30 }
31
32 pub fn from_client(client: Client) -> Self {
34 Self { client }
35 }
36
37 pub fn client(&self) -> &Client {
39 &self.client
40 }
41}
42
43#[async_trait]
44impl Store for RedisStore {
45 async fn get(&self, key: &str) -> Result<Option<Vec<u8>>, Error> {
46 let value: Option<Bytes> = self.client.get(key).await?;
47 Ok(value.map(|value| value.to_vec()))
48 }
49
50 async fn put(&self, key: &str, value: Vec<u8>, ttl: Option<Duration>) -> Result<(), Error> {
51 let _: String = self.client.set(key, value, expiration(ttl), None, false).await?;
52 Ok(())
53 }
54
55 async fn add(&self, key: &str, value: Vec<u8>, ttl: Option<Duration>) -> Result<bool, Error> {
56 let result: Option<String> = self.client.set(key, value, expiration(ttl), Some(SetOptions::NX), false).await?;
57 Ok(result.is_some())
58 }
59
60 async fn pull(&self, key: &str) -> Result<Option<Vec<u8>>, Error> {
61 let value: Option<Bytes> = self.client.getdel(key).await?;
62 Ok(value.map(|value| value.to_vec()))
63 }
64
65 async fn increment(&self, key: &str, amount: i64) -> Result<i64, Error> {
66 Ok(self.client.incr_by(key, amount).await?)
67 }
68
69 async fn touch(&self, key: &str, ttl: Duration) -> Result<bool, Error> {
70 let result: i64 = self.client.pexpire(key, milliseconds(ttl), None).await?;
71 Ok(result == 1)
72 }
73
74 async fn forget(&self, key: &str) -> Result<bool, Error> {
75 let removed: i64 = self.client.del(key).await?;
76 Ok(removed > 0)
77 }
78
79 async fn flush(&self) -> Result<(), Error> {
80 let command = CustomCommand::new_static("FLUSHDB", ClusterHash::Random, false);
81 let _: String = self.client.custom(command, Vec::<String>::new()).await?;
82 Ok(())
83 }
84
85 async fn acquire_lock(&self, key: &str, owner: &str, ttl: Option<Duration>) -> Result<bool, Error> {
86 let result: Option<String> = self.client.set(key, owner, expiration(ttl), Some(SetOptions::NX), false).await?;
87 Ok(result.is_some())
88 }
89
90 async fn release_lock(&self, key: &str, owner: &str) -> Result<bool, Error> {
91 let released: i64 = self.client.eval(RELEASE_LOCK, vec![key], vec![owner]).await?;
92 Ok(released == 1)
93 }
94
95 async fn force_release_lock(&self, key: &str) -> Result<(), Error> {
96 let _: i64 = self.client.del(key).await?;
97 Ok(())
98 }
99
100 async fn refresh_lock(&self, key: &str, owner: &str, ttl: Option<Duration>) -> Result<bool, Error> {
101 let ttl = ttl.map_or(0, milliseconds).to_string();
102 let refreshed: i64 = self.client.eval(REFRESH_LOCK, vec![key], vec![owner, &ttl]).await?;
103 Ok(refreshed == 1)
104 }
105
106 async fn lock_owner(&self, key: &str) -> Result<Option<String>, Error> {
107 Ok(self.client.get(key).await?)
108 }
109}
110
111fn expiration(ttl: Option<Duration>) -> Option<Expiration> {
112 ttl.map(|ttl| Expiration::PX(milliseconds(ttl)))
113}
114
115fn milliseconds(duration: Duration) -> i64 {
116 i64::try_from(duration.as_millis()).unwrap_or(i64::MAX).max(1)
117}