Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce cdk-database #550

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ jobs:
-p cdk --no-default-features --features mint,
-p cdk --no-default-features --features "mint swagger",
-p cdk-redb,
-p cdk-database,
-p cdk-sqlite,
-p cdk-axum --no-default-features,
-p cdk-axum --no-default-features --features swagger,
Expand Down
16 changes: 16 additions & 0 deletions crates/cdk-database/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
[package]
name = "cdk-database"
version = "0.6.1"
edition = "2021"
description = "CDK database engine selection crate"

[features]
mint = ["cdk-sqlite/mint", "cdk-redb/mint"]
wallet = ["cdk-sqlite/wallet", "cdk-redb/wallet"]
default = ["mint", "wallet"]

[dependencies]
cdk-common = { path = "../cdk-common" }
cdk-sqlite = { path = "../cdk-sqlite", default-features = false }
cdk-redb = { path = "../cdk-redb", default-features = false }
serde = { version = "1.0.217", features = ["derive"] }
59 changes: 59 additions & 0 deletions crates/cdk-database/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
//! CDK-Database instance
//!
//! This crate will create a database instance based on the provided engine.
use std::path::PathBuf;
use std::sync::Arc;

use cdk_redb::MintRedbDatabase;
use cdk_sqlite::MintSqliteDatabase;
use serde::{Deserialize, Serialize};

/// Database engine definition
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
#[serde(rename_all = "lowercase")]
pub enum DatabaseEngine {
#[default]
Sqlite,
Redb,
}

impl std::str::FromStr for DatabaseEngine {
type Err = String;

fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"sqlite" => Ok(DatabaseEngine::Sqlite),
"redb" => Ok(DatabaseEngine::Redb),
_ => Err(format!("Unknown database engine: {}", s)),
}
}
}

impl DatabaseEngine {
/// Convert the database instance into a mint database
pub async fn mint<P: Into<PathBuf>>(
self,
work_dir: P,
) -> Result<
Arc<
dyn cdk_common::database::MintDatabase<Err = cdk_common::database::Error>
+ Sync
+ Send
+ 'static,
>,
cdk_common::database::Error,
> {
match self {
DatabaseEngine::Sqlite => {
let sql_db_path = work_dir.into().join("cdk-mintd.sqlite");
let db = MintSqliteDatabase::new(&sql_db_path).await?;
db.migrate().await;
Ok(Arc::new(db))
}
DatabaseEngine::Redb => {
let redb_path = work_dir.into().join("cdk-mintd.redb");
Ok(Arc::new(MintRedbDatabase::new(&redb_path)?))
}
}
}
}
7 changes: 1 addition & 6 deletions crates/cdk-mintd/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,9 @@ axum = "0.6.20"
cdk = { path = "../cdk", version = "0.6.0", default-features = false, features = [
"mint",
] }
cdk-redb = { path = "../cdk-redb", version = "0.6.0", default-features = false, features = [
"mint",
] }
cdk-sqlite = { path = "../cdk-sqlite", version = "0.6.0", default-features = false, features = [
"mint",
] }
cdk-cln = { path = "../cdk-cln", version = "0.6.0", default-features = false }
cdk-lnbits = { path = "../cdk-lnbits", version = "0.6.0", default-features = false }
cdk-database = { path = "../cdk-database" }
cdk-phoenixd = { path = "../cdk-phoenixd", version = "0.6.0", default-features = false }
cdk-lnd = { path = "../cdk-lnd", version = "0.6.0", default-features = false }
cdk-fake-wallet = { path = "../cdk-fake-wallet", version = "0.6.0", default-features = false }
Expand Down
21 changes: 1 addition & 20 deletions crates/cdk-mintd/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::path::PathBuf;
use cdk::nuts::{CurrencyUnit, PublicKey};
use cdk::Amount;
use cdk_axum::cache;
use cdk_database::DatabaseEngine;
use config::{Config, ConfigError, File};
use serde::{Deserialize, Serialize};

Expand Down Expand Up @@ -149,26 +150,6 @@ fn default_max_delay_time() -> u64 {
3
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
#[serde(rename_all = "lowercase")]
pub enum DatabaseEngine {
#[default]
Sqlite,
Redb,
}

impl std::str::FromStr for DatabaseEngine {
type Err = String;

fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"sqlite" => Ok(DatabaseEngine::Sqlite),
"redb" => Ok(DatabaseEngine::Redb),
_ => Err(format!("Unknown database engine: {}", s)),
}
}
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Database {
pub engine: DatabaseEngine,
Expand Down
15 changes: 8 additions & 7 deletions crates/cdk-mintd/src/env_vars.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@ use std::str::FromStr;

use anyhow::{anyhow, bail, Result};
use cdk::nuts::CurrencyUnit;
use cdk_database::DatabaseEngine;

use crate::config::{
Cln, Database, DatabaseEngine, FakeWallet, Info, LNbits, Ln, LnBackend, Lnd, MintInfo,
Phoenixd, Settings, Strike,
Cln, Database, FakeWallet, Info, LNbits, Ln, LnBackend, Lnd, MintInfo, Phoenixd, Settings,
Strike,
};

pub const ENV_WORK_DIR: &str = "CDK_MINTD_WORK_DIR";
Expand Down Expand Up @@ -72,15 +73,15 @@ pub const ENV_FAKE_WALLET_MIN_DELAY: &str = "CDK_MINTD_FAKE_WALLET_MIN_DELAY";
pub const ENV_FAKE_WALLET_MAX_DELAY: &str = "CDK_MINTD_FAKE_WALLET_MAX_DELAY";

impl Settings {
pub fn from_env(&mut self) -> Result<Self> {
pub fn from_env(mut self) -> Result<Self> {
if let Ok(database) = env::var(DATABASE_ENV_VAR) {
let engine = DatabaseEngine::from_str(&database).map_err(|err| anyhow!(err))?;
self.database = Database { engine };
}

self.info = self.info.clone().from_env();
self.mint_info = self.mint_info.clone().from_env();
self.ln = self.ln.clone().from_env();
self.info = self.info.from_env();
self.mint_info = self.mint_info.from_env();
self.ln = self.ln.from_env();

match self.ln.ln_backend {
LnBackend::Cln => {
Expand All @@ -104,7 +105,7 @@ impl Settings {
LnBackend::None => bail!("Ln backend must be set"),
}

Ok(self.clone())
Ok(self)
}
}

Expand Down
24 changes: 3 additions & 21 deletions crates/cdk-mintd/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ use axum::middleware::Next;
use axum::response::Response;
use axum::{middleware, Router};
use bip39::Mnemonic;
use cdk::cdk_database::{self, MintDatabase};
use cdk::cdk_lightning;
use cdk::cdk_lightning::MintLightning;
use cdk::mint::{MintBuilder, MintMeltLimits};
Expand All @@ -25,11 +24,9 @@ use cdk::nuts::{ContactInfo, CurrencyUnit, MintVersion, PaymentMethod};
use cdk::types::LnKey;
use cdk_axum::cache::HttpCache;
use cdk_mintd::cli::CLIArgs;
use cdk_mintd::config::{self, DatabaseEngine, LnBackend};
use cdk_mintd::config::{self, LnBackend};
use cdk_mintd::env_vars::ENV_WORK_DIR;
use cdk_mintd::setup::LnBackendSetup;
use cdk_redb::MintRedbDatabase;
use cdk_sqlite::MintSqliteDatabase;
use clap::Parser;
use tokio::sync::Notify;
use tower_http::compression::CompressionLayer;
Expand Down Expand Up @@ -76,7 +73,7 @@ async fn main() -> anyhow::Result<()> {

let mut mint_builder = MintBuilder::new();

let mut settings = if config_file_arg.exists() {
let settings = if config_file_arg.exists() {
config::Settings::new(Some(config_file_arg))
} else {
tracing::info!("Config file does not exist. Attempting to read env vars");
Expand All @@ -86,22 +83,7 @@ async fn main() -> anyhow::Result<()> {
// This check for any settings defined in ENV VARs
// ENV VARS will take **priority** over those in the config
let settings = settings.from_env()?;

let localstore: Arc<dyn MintDatabase<Err = cdk_database::Error> + Send + Sync> =
match settings.database.engine {
DatabaseEngine::Sqlite => {
let sql_db_path = work_dir.join("cdk-mintd.sqlite");
let sqlite_db = MintSqliteDatabase::new(&sql_db_path).await?;

sqlite_db.migrate().await;

Arc::new(sqlite_db)
}
DatabaseEngine::Redb => {
let redb_path = work_dir.join("cdk-mintd.redb");
Arc::new(MintRedbDatabase::new(&redb_path)?)
}
};
let localstore = settings.database.engine.clone().mint(&work_dir).await?;

mint_builder = mint_builder.with_localstore(localstore);

Expand Down
Loading