1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
use std::sync::Arc;
use sqlx::PgPool;
use stack_up::{
Configuration,
cache::{RedisConnection, RedisManager},
};
use tonic::Status;
use tracing::error;
use crate::cnfg::LocalConfig;
#[derive(Clone)]
pub struct AppHandle(Arc<AppState>);
impl std::ops::Deref for AppHandle {
type Target = Arc<AppState>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[derive(Clone)]
pub struct Services {
pub postgres: PgPool,
pub cache: RedisManager,
}
impl Services {
pub fn new(postgres: PgPool, cache: RedisManager) -> Self {
Self { postgres, cache }
}
}
pub struct AppState {
pub services: Services,
pub local_config: LocalConfig,
}
impl AppState {
pub async fn create(
services: Services,
configuration: &Configuration,
) -> Result<AppHandle, anyhow::Error> {
let local_config: LocalConfig = serde_json::from_value(configuration.misc.clone())?;
Ok(AppHandle(Arc::new(Self {
services,
local_config,
})))
}
pub async fn cache(&self) -> Result<RedisConnection, tonic::Status> {
let cache = self
.services
.cache
.get()
.await
.inspect_err(|e| error!("{e}"))
.map_err(|_e| Status::internal("storage not ready"))?;
Ok(cache)
}
}
|