From a9630ecdc459068ca51ee2d7be3837d609840842 Mon Sep 17 00:00:00 2001 From: rtkay123 Date: Mon, 9 Feb 2026 17:54:46 +0200 Subject: feat: connect to database --- lib/shared-svc/src/cache/key.rs | 27 +++++++++++++++++++++++++++ lib/shared-svc/src/cache/mod.rs | 3 +++ lib/shared-svc/src/database/mod.rs | 16 ++++++++++++++++ lib/shared-svc/src/lib.rs | 9 ++++++++- 4 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 lib/shared-svc/src/cache/key.rs create mode 100644 lib/shared-svc/src/database/mod.rs (limited to 'lib/shared-svc/src') diff --git a/lib/shared-svc/src/cache/key.rs b/lib/shared-svc/src/cache/key.rs new file mode 100644 index 0000000..756b7d0 --- /dev/null +++ b/lib/shared-svc/src/cache/key.rs @@ -0,0 +1,27 @@ +use redis::{ToRedisArgs, ToSingleRedisArg}; + +#[derive(Clone, Copy)] +pub enum CacheKey<'a> { + Session(&'a str), +} + +impl CacheKey<'_> { + pub fn key(&self) -> &str { + match self { + CacheKey::Session(_) => "session:*", + } + } +} + +impl ToRedisArgs for CacheKey<'_> { + fn write_redis_args(&self, out: &mut W) + where + W: ?Sized + redis::RedisWrite, + { + out.write_arg_fmt(match self { + CacheKey::Session(id) => format!("session:{id}"), + }) + } +} + +impl ToSingleRedisArg for CacheKey<'_> {} diff --git a/lib/shared-svc/src/cache/mod.rs b/lib/shared-svc/src/cache/mod.rs index cd15463..90cab04 100644 --- a/lib/shared-svc/src/cache/mod.rs +++ b/lib/shared-svc/src/cache/mod.rs @@ -1,6 +1,9 @@ mod cluster; mod config; +mod key; mod sentinel; +pub use key::*; +pub use redis; pub use sentinel::SentinelConfig; pub use config::*; diff --git a/lib/shared-svc/src/database/mod.rs b/lib/shared-svc/src/database/mod.rs new file mode 100644 index 0000000..bbc1ba3 --- /dev/null +++ b/lib/shared-svc/src/database/mod.rs @@ -0,0 +1,16 @@ +use sqlx::PgPool; +use tracing::{debug, error}; +use url::Url; + +use crate::ServiceError; + +pub async fn connect(url: &Url, pool_size: u32) -> Result { + let host = url.host_str(); + debug!(host = host, "connecting to database"); + + Ok(sqlx::postgres::PgPoolOptions::new() + .max_connections(pool_size) + .connect(url.as_str()) + .await + .inspect_err(|e| error!("{e}"))?) +} diff --git a/lib/shared-svc/src/lib.rs b/lib/shared-svc/src/lib.rs index 92d9c32..d4852a5 100644 --- a/lib/shared-svc/src/lib.rs +++ b/lib/shared-svc/src/lib.rs @@ -1,12 +1,19 @@ #[cfg(feature = "cache")] pub mod cache; +#[cfg(feature = "database")] +pub mod database; + use thiserror::Error; #[derive(Error, Debug)] pub enum ServiceError { - #[error("data store disconnected")] + #[error("cache error")] + #[cfg(feature = "cache")] Cache(#[from] redis::RedisError), + #[error("database error")] + #[cfg(feature = "database")] + Database(#[from] sqlx::Error), #[error("the data for key `{0}` is not available")] Redaction(String), #[error("invalid header (expected {expected:?}, found {found:?})")] -- cgit v1.2.3