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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
use deadpool_postgres::{Manager, ManagerConfig, RecyclingMethod};
use primitives::{
config::Environment,
postgres::{POSTGRES_DB, POSTGRES_HOST, POSTGRES_PASSWORD, POSTGRES_PORT, POSTGRES_USER},
};
use redis::{aio::MultiplexedConnection, IntoConnectionInfo};
use std::str::FromStr;
use tokio_postgres::{
types::{accepts, FromSql, Type},
NoTls,
};
pub mod accounting;
pub mod analytics;
pub mod campaign;
mod channel;
pub mod spendable;
pub mod validator_message;
pub use self::campaign::*;
pub use self::channel::*;
pub use tokio_postgres::Config as PostgresConfig;
pub use deadpool_postgres::PoolError;
pub use redis::RedisError;
pub type DbPool = deadpool_postgres::Pool;
pub struct TotalCount(pub u64);
impl<'a> FromSql<'a> for TotalCount {
fn from_sql(
ty: &Type,
raw: &'a [u8],
) -> Result<Self, Box<dyn std::error::Error + Sync + Send>> {
let str_slice = <&str as FromSql>::from_sql(ty, raw)?;
Ok(Self(u64::from_str(str_slice)?))
}
accepts!(VARCHAR, TEXT);
}
pub async fn redis_connection(
url: impl IntoConnectionInfo,
) -> Result<MultiplexedConnection, RedisError> {
let client = redis::Client::open(url)?;
client.get_multiplexed_async_connection().await
}
pub async fn postgres_connection(
config: tokio_postgres::Config,
) -> Result<DbPool, deadpool_postgres::BuildError> {
let mgr_config = ManagerConfig {
recycling_method: RecyclingMethod::Verified,
};
let manager = Manager::from_config(config, NoTls, mgr_config);
DbPool::builder(manager).build()
}
pub fn setup_migrations(environment: Environment) {
use migrant_lib::{Config, Direction, Migrator, Settings};
let settings = Settings::configure_postgres()
.database_user(POSTGRES_USER.as_str())
.database_password(POSTGRES_PASSWORD.as_str())
.database_host(POSTGRES_HOST.as_str())
.database_port(*POSTGRES_PORT)
.database_name(POSTGRES_DB.as_ref())
.build()
.expect("Should build migration settings");
let mut config = Config::with_settings(&settings);
config.setup().expect("Should setup Postgres connection");
config.use_cli_compatible_tags(true);
macro_rules! make_migration {
($tag:expr) => {
migrant_lib::EmbeddedMigration::with_tag($tag)
.up(include_str!(concat!("../migrations/", $tag, "/up.sql")))
.down(include_str!(concat!("../migrations/", $tag, "/down.sql")))
.boxed()
};
}
let migrations = vec![make_migration!("20190806011140_initial-tables")];
config
.use_migrations(&migrations)
.expect("Loading migrations failed");
let config = config.reload().expect("Should reload applied migrations");
if let Environment::Development = environment {
Migrator::with_config(&config)
.all(true)
.direction(Direction::Down)
.swallow_completion(true)
.apply()
.expect("Applying migrations failed");
}
let config = config.reload().expect("Should reload applied migrations");
Migrator::with_config(&config)
.swallow_completion(true)
.show_output(true)
.direction(Direction::Up)
.all(true)
.apply()
.expect("Applying migrations failed");
let _config = config
.reload()
.expect("Reloading config for migration failed");
}
#[cfg(any(test, feature = "test-util"))]
#[cfg_attr(docsrs, doc(cfg(feature = "test-util")))]
pub mod tests_postgres {
use std::{
ops::{Deref, DerefMut},
sync::atomic::{AtomicUsize, Ordering},
};
use deadpool::managed::{Manager as ManagerTrait, RecycleError, RecycleResult};
use deadpool_postgres::ManagerConfig;
use once_cell::sync::Lazy;
use primitives::postgres::POSTGRES_CONFIG;
use tokio_postgres::{NoTls, SimpleQueryMessage};
use async_trait::async_trait;
use thiserror::Error;
use super::{DbPool, PoolError};
pub type Pool = deadpool::managed::Pool<Manager>;
pub static DATABASE_POOL: Lazy<Pool> =
Lazy::new(|| create_pool("test").expect("Should create test pool"));
pub static MIGRATIONS: &[&str] = &["20190806011140_initial-tables"];
fn create_pool(db_prefix: &str) -> Result<Pool, Error> {
let manager_config = ManagerConfig {
recycling_method: deadpool_postgres::RecyclingMethod::Verified,
};
let manager = Manager::new(POSTGRES_CONFIG.clone(), manager_config, db_prefix)?;
Pool::builder(manager)
.max_size(15)
.build()
.map_err(|err| match err {
deadpool::managed::BuildError::Backend(err) => err,
deadpool::managed::BuildError::NoRuntimeSpecified(message) => {
Error::Build(deadpool::managed::BuildError::NoRuntimeSpecified(message))
}
})
}
pub struct Database {
pub name: String,
pub pool: deadpool_postgres::Pool,
}
impl Database {
pub fn new(name: String, pool: DbPool) -> Self {
Self { name, pool }
}
}
impl Deref for Database {
type Target = deadpool_postgres::Pool;
fn deref(&self) -> &deadpool_postgres::Pool {
&self.pool
}
}
impl DerefMut for Database {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.pool
}
}
impl AsRef<deadpool_postgres::Pool> for Database {
fn as_ref(&self) -> &deadpool_postgres::Pool {
&self.pool
}
}
impl AsMut<deadpool_postgres::Pool> for Database {
fn as_mut(&mut self) -> &mut deadpool_postgres::Pool {
&mut self.pool
}
}
#[derive(Debug, Error)]
pub enum Error {
#[error(transparent)]
Build(#[from] deadpool_postgres::BuildError),
#[error(transparent)]
Pool(#[from] PoolError),
}
impl From<tokio_postgres::Error> for Error {
fn from(err: tokio_postgres::Error) -> Self {
Error::Pool(PoolError::Backend(err))
}
}
pub struct Manager {
base_config: tokio_postgres::Config,
base_pool: deadpool_postgres::Pool,
manager_config: ManagerConfig,
index: AtomicUsize,
db_prefix: String,
}
impl Manager {
pub fn new(
base_config: tokio_postgres::Config,
manager_config: ManagerConfig,
db_prefix: &str,
) -> Result<Self, Error> {
let base_manager = deadpool_postgres::Manager::from_config(
base_config.clone(),
NoTls,
manager_config.clone(),
);
let base_pool = deadpool_postgres::Pool::builder(base_manager)
.max_size(15)
.build()?;
Ok(Self::new_with_pool(
base_pool,
base_config,
manager_config,
db_prefix,
))
}
pub fn new_with_pool(
base_pool: deadpool_postgres::Pool,
base_config: tokio_postgres::Config,
manager_config: ManagerConfig,
db_prefix: &str,
) -> Self {
Self {
base_config,
base_pool,
manager_config,
index: AtomicUsize::new(0),
db_prefix: db_prefix.into(),
}
}
}
#[async_trait]
impl ManagerTrait for Manager {
type Type = Database;
type Error = Error;
async fn create(&self) -> Result<Self::Type, Self::Error> {
let pool_index = self.index.fetch_add(1, Ordering::SeqCst);
let db_name = format!("{}_{}", self.db_prefix, pool_index);
let drop_db = format!("DROP DATABASE IF EXISTS {0} WITH (FORCE);", db_name);
let created_db = format!("CREATE DATABASE {0};", db_name);
let temp_client = self.base_pool.get().await.map_err(|err| {
match &err {
PoolError::Backend(backend_err) if backend_err.is_closed() => {
panic!("Closed PG Client connection of the base Pool!");
}
_ => {}
}
err
})?;
assert!(!self.base_pool.is_closed(), "Base Pool should never close");
assert!(
!self
.base_pool
.get()
.await
.expect("Should get connection")
.is_closed(),
"a base pool connection should never be closed"
);
let drop_db_result = temp_client.simple_query(drop_db.as_str()).await?;
assert_eq!(1, drop_db_result.len());
assert!(matches!(
drop_db_result[0],
SimpleQueryMessage::CommandComplete(..)
));
let create_db_result = temp_client.simple_query(created_db.as_str()).await?;
assert_eq!(1, create_db_result.len());
assert!(matches!(
create_db_result[0],
SimpleQueryMessage::CommandComplete(..)
));
let mut config = self.base_config.clone();
config.dbname(&db_name);
let manager =
deadpool_postgres::Manager::from_config(config, NoTls, self.manager_config.clone());
let pool = deadpool_postgres::Pool::builder(manager)
.max_size(15)
.build()
.map_err(|err| match err {
deadpool::managed::BuildError::Backend(err) => PoolError::Backend(err),
deadpool::managed::BuildError::NoRuntimeSpecified(_err) => {
PoolError::NoRuntimeSpecified
}
})?;
let _ = pool.get().await?;
Ok(Database::new(db_name, pool))
}
async fn recycle(&self, database: &mut Database) -> RecycleResult<Self::Error> {
let queries = "DROP SCHEMA public CASCADE; CREATE SCHEMA public;";
database.pool = {
let mut config = self.base_config.clone();
config.dbname(&database.name);
let manager = deadpool_postgres::Manager::from_config(
config,
NoTls,
self.manager_config.clone(),
);
deadpool_postgres::Pool::builder(manager)
.max_size(15)
.build()
.map_err(|err| RecycleError::Backend(Error::Build(err)))?
};
let result = database
.pool
.get()
.await
.map_err(|err| RecycleError::Backend(Error::Pool(err)))?
.simple_query(queries)
.await
.expect("Should not error");
assert_eq!(2, result.len());
assert!(matches!(result[0], SimpleQueryMessage::CommandComplete(..)));
assert!(matches!(result[1], SimpleQueryMessage::CommandComplete(..)));
Ok(())
}
}
pub async fn setup_test_migrations(pool: DbPool) -> Result<(), PoolError> {
let client = pool.get().await?;
let full_query: String = MIGRATIONS
.iter()
.map(|migration| {
use std::{env::current_dir, fs::read_to_string};
let full_path = current_dir().unwrap();
let mut file = full_path.parent().unwrap().to_path_buf();
file.push(format!("sentry/migrations/{}/up.sql", migration));
read_to_string(file).expect("File migration couldn't be read")
})
.collect();
Ok(client.batch_execute(&full_query).await?)
}
#[cfg(test)]
mod test {
use super::*;
#[tokio::test]
async fn test_postgres_pool() {
let pool = create_pool("testing_pool").expect("Should create testing_pool");
let database_1 = pool.get().await.expect("Should get");
let status = pool.status();
assert_eq!(status.size, 1);
assert_eq!(status.available, 0);
let database_2 = pool.get().await.expect("Should get");
let status = pool.status();
assert_eq!(status.size, 2);
assert_eq!(status.available, 0);
drop(database_1);
let status = pool.status();
assert_eq!(status.size, 2);
assert_eq!(status.available, 1);
drop(database_2);
let status = pool.status();
assert_eq!(status.size, 2);
assert_eq!(status.available, 2);
let database_3 = pool.get().await.expect("Should get");
let status = pool.status();
assert_eq!(status.size, 2);
assert_eq!(status.available, 1);
let database_4 = pool.get().await.expect("Should get");
let status = pool.status();
assert_eq!(status.size, 2);
assert_eq!(status.available, 0);
let database_5 = pool.get().await.expect("Should get");
let status = pool.status();
assert_eq!(status.size, 3);
assert_eq!(status.available, 0);
drop(database_3);
drop(database_4);
drop(database_5);
let status = pool.status();
assert_eq!(status.size, 3);
assert_eq!(status.available, 3);
}
}
}
#[cfg(any(test, feature = "test-util"))]
#[cfg_attr(docsrs, doc(cfg(feature = "test-util")))]
pub mod redis_pool {
use dashmap::DashMap;
use deadpool::managed::{Manager as ManagerTrait, RecycleResult};
use thiserror::Error;
use crate::db::redis_connection;
use async_trait::async_trait;
use once_cell::sync::Lazy;
use super::*;
pub use redis::cmd;
pub type Pool = deadpool::managed::Pool<Manager>;
pub static TESTS_POOL: Lazy<Pool> = Lazy::new(|| {
Pool::builder(Manager::new())
.max_size(Manager::CONNECTIONS.into())
.build()
.expect("Should build Pools for tests")
});
#[derive(Clone)]
pub struct Database {
available: bool,
index: u8,
pub connection: MultiplexedConnection,
}
impl std::ops::Deref for Database {
type Target = MultiplexedConnection;
fn deref(&self) -> &Self::Target {
&self.connection
}
}
impl std::ops::DerefMut for Database {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.connection
}
}
pub struct Manager {
connections: DashMap<u8, Option<Database>>,
}
impl Default for Manager {
fn default() -> Self {
Self::new()
}
}
impl Manager {
const CONNECTIONS: u8 = 16;
const URL: &'static str = "redis://127.0.0.1:6379/";
pub fn new() -> Self {
Self {
connections: (0..Self::CONNECTIONS)
.into_iter()
.map(|database_index| (database_index, None))
.collect(),
}
}
pub async fn flush_db(connection: &mut MultiplexedConnection) -> Result<String, Error> {
redis::cmd("FLUSHDB")
.query_async::<_, String>(connection)
.await
.map_err(Error::Redis)
}
}
#[derive(Debug, Error)]
pub enum Error {
#[error("A redis error occurred")]
Redis(#[from] RedisError),
#[error("Creation of new database connection failed")]
CreationFailed,
}
#[async_trait]
impl ManagerTrait for Manager {
type Type = Database;
type Error = Error;
async fn create(&self) -> Result<Self::Type, Self::Error> {
for mut record in self.connections.iter_mut() {
let database = record.value_mut().as_mut();
match database {
Some(database) if database.available => {
database.available = false;
return Ok(database.clone());
}
Some(database) if !database.available => continue,
_ => {
let mut redis_conn =
redis_connection(format!("{}{}", Self::URL, record.key()))
.await
.expect("Should connect");
Self::flush_db(&mut redis_conn).await.expect("Should flush");
let database = Database {
available: false,
index: *record.key(),
connection: redis_conn,
};
*record.value_mut() = Some(database.clone());
return Ok(database);
}
}
}
Err(Error::CreationFailed)
}
async fn recycle(&self, database: &mut Database) -> RecycleResult<Self::Error> {
let mut connection = redis_connection(format!("{}{}", Self::URL, database.index))
.await
.expect("Should connect");
let flush_result = Self::flush_db(&mut connection).await;
database.available = true;
database.connection = connection;
flush_result.expect("Should have flushed the redis DB successfully");
Ok(())
}
}
}