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
|
use std::{fmt::Debug, path::Path, sync::Arc};
use axum::extract::FromRef;
use sqlx::PgPool;
use crate::Error;
pub type KVStore = rocksdb::OptimisticTransactionDB<rocksdb::MultiThreaded>;
#[derive(Debug, Clone, FromRef)]
pub struct AppState {
pub pool: PgPool,
pub kv_store: Arc<rocksdb::OptimisticTransactionDB<rocksdb::MultiThreaded>>,
}
impl AppState {
pub async fn new<P>(uri: String, path: P) -> Result<Self, Error>
where
P: AsRef<Path>,
{
Ok(Self {
pool: Self::init_pool(uri).await?,
kv_store: Arc::new(Self::init_kv_store(path).unwrap()),
})
}
pub fn with_pool<P>(pool: PgPool, path: P) -> Self
where
P: AsRef<Path>,
{
Self {
pool,
kv_store: Arc::new(Self::init_kv_store(path).unwrap()),
}
}
pub async fn init_pool(uri: String) -> Result<PgPool, sqlx::Error> {
tracing::debug!("Attempting to connect to database...");
let pool = sqlx::postgres::PgPoolOptions::new()
.max_connections(10)
.connect(&uri)
.await?;
tracing::info!("Connected to database: {uri}");
sqlx::migrate!().run(&pool).await?;
Ok(pool)
}
pub fn init_kv_store<P>(
path: P,
) -> Result<rocksdb::OptimisticTransactionDB<rocksdb::MultiThreaded>, rocksdb::Error>
where
P: AsRef<Path>,
{
let mut opts = rocksdb::Options::default();
opts.create_if_missing(true);
rocksdb::OptimisticTransactionDB::open(&opts, path)
}
}
|