Skip to content

Commit

Permalink
chore: add server-config
Browse files Browse the repository at this point in the history
  • Loading branch information
ngutech21 committed Dec 25, 2023
1 parent 97b559f commit 3a07833
Show file tree
Hide file tree
Showing 5 changed files with 73 additions and 46 deletions.
9 changes: 5 additions & 4 deletions integrationtests/tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use tokio::time::{sleep_until, Instant};
#[test]
#[cfg(feature = "integration-tests")]
pub fn test_integration() -> anyhow::Result<()> {
use mokshamint::config::LightningFeeConfig;
use mokshamint::config::{LightningFeeConfig, ServerConfig};

let docker = clients::Cli::default();
let node = docker.run(Postgres::default());
Expand All @@ -37,6 +37,10 @@ pub fn test_integration() -> anyhow::Result<()> {
rt.block_on(async {
let mint = Mint::builder()
.with_private_key("my_private_key".to_string())
.with_server(ServerConfig {
host_port: "127.0.0.1:8686".parse().expect("invalid address"),
..Default::default()
})
.with_db(
format!(
"postgres://postgres:[email protected]:{}/moksha-mint",
Expand All @@ -53,9 +57,6 @@ pub fn test_integration() -> anyhow::Result<()> {

let result = mokshamint::server::run_server(
mint.await.expect("Can not connect to lightning backend"),
"127.0.0.1:8686".parse().expect("invalid address"),
None,
None,
)
.await;
assert!(result.is_ok());
Expand Down
20 changes: 5 additions & 15 deletions moksha-mint/src/bin/moksha-mint.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use mokshamint::{
config::{LightningFeeConfig, MintInfoConfig},
config::{LightningFeeConfig, MintInfoConfig, ServerConfig},
lightning::{
AlbyLightningSettings, LightningType, LnbitsLightningSettings, LndLightningSettings,
StrikeLightningSettings,
},
mint::MintBuilder,
};
use std::{env, fmt, net::SocketAddr, path::PathBuf};
use std::{env, fmt};

#[tokio::main]
pub async fn main() -> anyhow::Result<()> {
Expand All @@ -24,12 +24,6 @@ pub async fn main() -> anyhow::Result<()> {
};
}

let host_port: SocketAddr = env::var("MINT_HOST_PORT")
.unwrap_or_else(|_| "[::]:3338".to_string())
.parse()?;

let api_prefix = env::var("MINT_API_PREFIX").ok();

let ln_backend = get_env("MINT_LIGHTNING_BACKEND");
let ln_type = match ln_backend.as_str() {
"Lnbits" => {
Expand Down Expand Up @@ -66,23 +60,19 @@ pub async fn main() -> anyhow::Result<()> {
.expect("Please provide mint info");

let fee_config = LightningFeeConfig::from_env();
let server_config = ServerConfig::from_env();

let mint = MintBuilder::new()
.with_mint_info(mint_info_settings)
.with_server(server_config)
.with_private_key(get_env("MINT_PRIVATE_KEY"))
.with_db(get_env("MINT_DB_URL"))
.with_lightning(ln_type)
.with_fee(fee_config)
.build()
.await;

let serve_wallet_path = env::var("MINT_SERVE_WALLET_PATH");
let serve_wallet_path = match serve_wallet_path {
Ok(value) => Some(PathBuf::from(value)),
Err(_) => None,
};

mokshamint::server::run_server(mint?, host_port, serve_wallet_path, api_prefix).await
mokshamint::server::run_server(mint?).await
}

#[derive(Debug, PartialEq)]
Expand Down
34 changes: 33 additions & 1 deletion moksha-mint/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::env;
use std::{env, net::SocketAddr, path::PathBuf};

use serde_derive::{Deserialize, Serialize};

Expand All @@ -7,18 +7,50 @@ pub struct MintConfig {
pub info: MintInfoConfig,
pub build: BuildConfig,
pub lightning_fee: LightningFeeConfig,
pub server: ServerConfig,
}

impl MintConfig {
pub fn new(
info: MintInfoConfig,
build: BuildConfig,
lightning_fee: LightningFeeConfig,
server: ServerConfig,
) -> Self {
Self {
info,
build,
lightning_fee,
server,
}
}
}

#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct ServerConfig {
pub host_port: SocketAddr,
pub serve_wallet_path: Option<PathBuf>,
pub api_prefix: Option<String>,
}

impl Default for ServerConfig {
fn default() -> Self {
Self {
host_port: "[::]:3338".to_string().parse().expect("invalid host port"),
serve_wallet_path: None,
api_prefix: None,
}
}
}

impl ServerConfig {
pub fn from_env() -> Self {
let server_config_default = ServerConfig::default();

ServerConfig {
host_port: env_or_default("MINT_HOST_PORT", server_config_default.host_port),
serve_wallet_path: env::var("MINT_SERVE_WALLET_PATH").ok().map(PathBuf::from),
api_prefix: env::var("MINT_API_PREFIX").ok(),
}
}
}
Expand Down
10 changes: 9 additions & 1 deletion moksha-mint/src/mint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use moksha_core::{
};

use crate::{
config::{BuildConfig, LightningFeeConfig, MintConfig, MintInfoConfig},
config::{BuildConfig, LightningFeeConfig, MintConfig, MintInfoConfig, ServerConfig},
database::Database,
error::MokshaMintError,
lightning::{AlbyLightning, Lightning, LightningType, LnbitsLightning, StrikeLightning},
Expand Down Expand Up @@ -202,6 +202,7 @@ pub struct MintBuilder {
db_url: Option<String>,
fee_config: Option<LightningFeeConfig>,
mint_info_settings: Option<MintInfoConfig>,
server_config: Option<ServerConfig>,
}

impl MintBuilder {
Expand All @@ -214,6 +215,11 @@ impl MintBuilder {
self
}

pub fn with_server(mut self, server_config: ServerConfig) -> MintBuilder {
self.server_config = Some(server_config);
self
}

pub fn with_private_key(mut self, private_key: String) -> MintBuilder {
self.private_key = Some(private_key);
self
Expand Down Expand Up @@ -275,10 +281,12 @@ impl MintBuilder {
ln,
self.lightning_type.expect("Lightning backend not set"),
db,
// FIXME simplify config creation
MintConfig::new(
self.mint_info_settings.unwrap_or_default(),
BuildConfig::from_env(),
self.fee_config.expect("fee-config not set"),
self.server_config.unwrap_or_default(),
),
))
}
Expand Down
46 changes: 21 additions & 25 deletions moksha-mint/src/server.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
use std::collections::HashMap;
use std::net::SocketAddr;
use std::path::PathBuf;
use std::str::FromStr;

use crate::error::MokshaMintError;
Expand Down Expand Up @@ -46,12 +44,7 @@ use tracing_subscriber::util::SubscriberInitExt;

use utoipa::OpenApi;

pub async fn run_server(
mint: Mint,
addr: SocketAddr,
serve_wallet_path: Option<PathBuf>,
api_prefix: Option<String>,
) -> anyhow::Result<()> {
pub async fn run_server(mint: Mint) -> anyhow::Result<()> {
tracing_subscriber::registry()
.with(tracing_subscriber::fmt::layer())
.init();
Expand All @@ -62,19 +55,21 @@ pub async fn run_server(
if let Some(ref commithash) = mint.config.build.commit_hash {
info!("git commit-hash: {}", commithash);
}
if let Some(ref serve_wallet_path) = serve_wallet_path {
if let Some(ref serve_wallet_path) = mint.config.server.serve_wallet_path {
info!("serving wallet from path: {:?}", serve_wallet_path);
}
info!("listening on: {}", addr);
info!("listening on: {}", &mint.config.server.host_port);
info!("mint-info: {:?}", mint.config.info);
info!("lightning fee-reserve: {:?}", mint.config.lightning_fee);
info!("lightning-backend: {}", mint.lightning_type);

let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
let listener = tokio::net::TcpListener::bind(&mint.config.server.host_port)
.await
.unwrap();

axum::serve(
listener,
app(mint, serve_wallet_path, api_prefix)
app(mint)
.layer(
CorsLayer::new()
.allow_origin(Any)
Expand Down Expand Up @@ -141,7 +136,7 @@ pub async fn run_server(
)]
struct ApiDoc;

fn app(mint: Mint, serve_wallet_path: Option<PathBuf>, prefix: Option<String>) -> Router {
fn app(mint: Mint) -> Router {
let legacy_routes = Router::new()
.route("/keys", get(get_legacy_keys))
.route("/keysets", get(get_legacy_keysets))
Expand All @@ -167,7 +162,8 @@ fn app(mint: Mint, serve_wallet_path: Option<PathBuf>, prefix: Option<String>) -

let general_routes = Router::new().route("/health", get(get_health));

let prefix = prefix.unwrap_or_else(|| "".to_owned());
let server_config = mint.config.server.clone();
let prefix = server_config.api_prefix.unwrap_or_else(|| "".to_owned());

let router = Router::new()
.nest(&prefix, legacy_routes)
Expand All @@ -176,7 +172,7 @@ fn app(mint: Mint, serve_wallet_path: Option<PathBuf>, prefix: Option<String>) -
.with_state(mint)
.layer(TraceLayer::new_for_http());

if let Some(serve_wallet_path) = serve_wallet_path {
if let Some(ref serve_wallet_path) = server_config.serve_wallet_path {
return router.nest_service(
"/",
get_service(ServeDir::new(serve_wallet_path))
Expand Down Expand Up @@ -677,7 +673,7 @@ mod tests {

#[tokio::test]
async fn test_get_keys() -> anyhow::Result<()> {
let app = app(create_mock_mint(Default::default()), None, None);
let app = app(create_mock_mint(Default::default()));
let response = app
.oneshot(Request::builder().uri("/keys").body(Body::empty())?)
.await?;
Expand All @@ -691,7 +687,7 @@ mod tests {

#[tokio::test]
async fn test_get_keysets() -> anyhow::Result<()> {
let app = app(create_mock_mint(Default::default()), None, None);
let app = app(create_mock_mint(Default::default()));
let response = app
.oneshot(Request::builder().uri("/keysets").body(Body::empty())?)
.await?;
Expand All @@ -712,7 +708,7 @@ mod tests {
description_long: Some("A mint for testing long".to_string()),
..Default::default()
};
let app = app(create_mock_mint(mint_info_settings), None, None);
let app = app(create_mock_mint(mint_info_settings));
let response = app
.oneshot(Request::builder().uri("/info").body(Body::empty())?)
.await?;
Expand Down Expand Up @@ -752,7 +748,7 @@ mod tests {

#[tokio::test]
async fn test_get_keys_v1() -> anyhow::Result<()> {
let app = app(create_mock_mint(Default::default()), None, None);
let app = app(create_mock_mint(Default::default()));
let response = app
.oneshot(Request::builder().uri("/v1/keys").body(Body::empty())?)
.await?;
Expand All @@ -770,7 +766,7 @@ mod tests {

#[tokio::test]
async fn test_get_keysets_v1() -> anyhow::Result<()> {
let app = app(create_mock_mint(Default::default()), None, None);
let app = app(create_mock_mint(Default::default()));
let response = app
.oneshot(Request::builder().uri("/v1/keysets").body(Body::empty())?)
.await?;
Expand All @@ -787,7 +783,7 @@ mod tests {

#[tokio::test]
async fn test_get_v1_keys() -> anyhow::Result<()> {
let app = app(create_mock_mint(Default::default()), None, None);
let app = app(create_mock_mint(Default::default()));
let response = app
.oneshot(Request::builder().uri("/v1/keys").body(Body::empty())?)
.await?;
Expand All @@ -806,7 +802,7 @@ mod tests {

#[tokio::test]
async fn test_get_v1_keys_id_invalid() -> anyhow::Result<()> {
let app = app(create_mock_mint(Default::default()), None, None);
let app = app(create_mock_mint(Default::default()));
let response = app
.oneshot(
Request::builder()
Expand All @@ -821,7 +817,7 @@ mod tests {

#[tokio::test]
async fn test_get_v1_keys_id() -> anyhow::Result<()> {
let app = app(create_mock_mint(Default::default()), None, None);
let app = app(create_mock_mint(Default::default()));
let response = app
.oneshot(
Request::builder()
Expand All @@ -847,7 +843,7 @@ mod tests {

#[tokio::test]
async fn test_get_v1_keysets() -> anyhow::Result<()> {
let app = app(create_mock_mint(Default::default()), None, None);
let app = app(create_mock_mint(Default::default()));
let response = app
.oneshot(Request::builder().uri("/v1/keysets").body(Body::empty())?)
.await?;
Expand All @@ -865,7 +861,7 @@ mod tests {

#[tokio::test]
async fn test_get_health() -> anyhow::Result<()> {
let app = app(create_mock_mint(Default::default()), None, None);
let app = app(create_mock_mint(Default::default()));
let response = app
.oneshot(Request::builder().uri("/health").body(Body::empty())?)
.await?;
Expand Down

0 comments on commit 3a07833

Please sign in to comment.