rskit_cache_redis/
config.rs1use std::fmt;
2use std::time::Duration;
3
4use rskit_util::SecretString;
5use serde::{Deserialize, Serialize};
6
7#[derive(Clone, Deserialize, Serialize)]
9pub struct Config {
10 #[serde(default = "default_host")]
12 pub host: String,
13 #[serde(default = "default_port")]
15 pub port: u16,
16 pub password: Option<SecretString>,
18 #[serde(default)]
20 pub database: u8,
21 #[serde(default = "default_connect_timeout", with = "duration_seconds")]
23 pub connect_timeout: Duration,
24 pub key_prefix: Option<String>,
26}
27
28impl fmt::Debug for Config {
29 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30 f.debug_struct("Config")
31 .field("host", &self.host)
32 .field("port", &self.port)
33 .field("password", &self.password.as_ref().map(|_| "<redacted>"))
34 .field("database", &self.database)
35 .field("connect_timeout", &self.connect_timeout)
36 .field("key_prefix", &self.key_prefix)
37 .finish()
38 }
39}
40
41impl Default for Config {
42 fn default() -> Self {
43 Self {
44 host: default_host(),
45 port: default_port(),
46 password: None,
47 database: 0,
48 connect_timeout: default_connect_timeout(),
49 key_prefix: None,
50 }
51 }
52}
53
54impl Config {
55 pub(crate) fn connection_url(&self) -> String {
56 match &self.password {
57 Some(pw) => format!(
58 "redis://:{}@{}:{}/{}",
59 pw.expose(),
60 self.host,
61 self.port,
62 self.database
63 ),
64 None => format!("redis://{}:{}/{}", self.host, self.port, self.database),
65 }
66 }
67}
68
69fn default_host() -> String {
70 "127.0.0.1".to_owned()
71}
72
73fn default_port() -> u16 {
74 6379
75}
76
77fn default_connect_timeout() -> Duration {
78 Duration::from_secs(5)
79}
80
81mod duration_seconds {
82 use std::time::Duration;
83
84 use serde::{Deserialize, Deserializer, Serializer};
85
86 pub fn deserialize<'de, D>(deserializer: D) -> Result<Duration, D::Error>
87 where
88 D: Deserializer<'de>,
89 {
90 u64::deserialize(deserializer).map(Duration::from_secs)
91 }
92
93 pub fn serialize<S>(duration: &Duration, serializer: S) -> Result<S::Ok, S::Error>
94 where
95 S: Serializer,
96 {
97 serializer.serialize_u64(duration.as_secs())
98 }
99}