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

Better config #16

Merged
merged 4 commits into from
Sep 5, 2023
Merged
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
54 changes: 54 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Build container
FROM debian:buster AS builder
FROM debian:bookworm AS builder

RUN apt-get update && apt-get install -y curl libssl-dev libpq-dev build-essential pkg-config

Expand All @@ -12,7 +12,7 @@ ADD . ./
RUN cargo build --release

# Deploy container
FROM debian:buster
FROM debian:bookworm

RUN apt-get update && apt-get install -y libssl-dev libpq-dev ca-certificates

Expand Down
6 changes: 5 additions & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,11 @@ services:
- RUST_LOG=info
- KEPLER_ADDRESS=0.0.0.0
- KEPLER_PORT=8000
- DATABASE_URL=postgres://kepler:kepler@db/kepler
- DB_HOST=db
- DB_PORT=5432
- DB_USER=kepler
- DB_PASSWORD=kepler
- DB_DATABASE=kepler
ports:
- "8000:8000"

Expand Down
4 changes: 3 additions & 1 deletion kepler/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ license.workspace = true
[dependencies]
domain-db = { path = "../domain-db" }

clap = {version = "4.3.15", features = ["derive"]}
clap = { version = "4.3.15", features = ["derive"] }
env_logger = "0.10.0"
log = "0.4.19"
serde = { version = "1.0.171", features = ["derive"] }
Expand All @@ -23,3 +23,5 @@ tracing-subscriber = { version = "0.3.17 ", features = ["env-filter"] }
tracing-actix-web = "0.7.5"
anyhow = "1.0.72"
serde_json = "1.0.103"
config = { version = "0.13.3", default-features = false }
dotenvy = "0.15.7"
4 changes: 2 additions & 2 deletions kepler/src/api/mod.rs → kepler/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ mod telemetry;
pub use telemetry::init_logger;

pub struct ApiConfig {
pub host: String,
pub address: String,
pub port: u16,
pub repository: PostgresRepository,
}
Expand All @@ -44,7 +44,7 @@ pub fn run(api_config: ApiConfig) -> Result<Server, anyhow::Error> {
.wrap(Cors::permissive())
.wrap(tracing_actix_web::TracingLogger::default())
})
.bind((api_config.host, api_config.port))?
.bind((api_config.address, api_config.port))?
.run();
Ok(server)
}
Expand Down
45 changes: 45 additions & 0 deletions kepler/src/configuration.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
use config::{Config, Environment};
use serde::Deserialize;

#[derive(Deserialize, Clone, Debug)]
pub struct ApiSettings {
pub address: String,
pub port: u16,
}

impl ApiSettings {
pub fn try_from_env() -> Result<Self, config::ConfigError> {
Config::builder()
.set_default("address", "0.0.0.0")?
.set_default("port", 8000)?
.add_source(Environment::with_prefix("KEPLER").prefix_separator("_"))
.build()?
.try_deserialize::<Self>()
}
}

#[derive(Deserialize, Clone, Debug)]
pub struct DatabaseSettings {
host: String,
port: u16,
user: String,
password: String,
database: String,
}

impl DatabaseSettings {
pub fn try_from_env() -> Result<Self, config::ConfigError> {
Config::builder()
.set_default("port", 5432)?
.add_source(Environment::with_prefix("DB").prefix_separator("_"))
.build()?
.try_deserialize::<Self>()
}

pub fn connection_string(&self) -> String {
format!(
"postgres://{}:{}@{}:{}/{}",
self.user, self.password, self.host, self.port, self.database
)
}
}
16 changes: 0 additions & 16 deletions kepler/src/lib.rs

This file was deleted.

49 changes: 30 additions & 19 deletions kepler/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,28 @@
use anyhow::{bail, Context, Result};
use clap::{Parser, Subcommand};
use domain_db::{cve_sources::nist, db};
use dotenvy::dotenv;
use env_logger::Env;
use std::{env, fs, path::Path};
use lazy_static::lazy_static;
use std::{fs, path::Path};

use kepler::api::{self, ApiConfig};
mod api;
mod configuration;

use crate::api::ApiConfig;
use crate::configuration::{ApiSettings, DatabaseSettings};

#[actix_web::main]
async fn main() -> Result<()> {
let opts = Opts::parse();

dotenv().ok();

// Repository
let repository = {
let database_url = env::var("DATABASE_URL")
.context("DATABASE_URL environment variable has not specified.")?;
db::PostgresRepository::new(&database_url, "./migrations")
let db_settings = DatabaseSettings::try_from_env()?;

db::PostgresRepository::new(&db_settings.connection_string(), "./migrations")
.context("Cannot connect to database")?
};

Expand Down Expand Up @@ -70,22 +78,12 @@ async fn main() -> Result<()> {
}
},
None => {
let host = env::var("KEPLER_ADDRESS")
.map_err(|_| "Invalid or missing custom address")
.unwrap_or_else(|err| {
log::warn!("{}. Using default 0.0.0.0", err);
"0.0.0.0".to_string()
});
let port = env::var("KEPLER_PORT")
.map_err(|_| "Invalid or missing custom port")
.and_then(|s| s.parse::<u16>().map_err(|_| "Failed to parse custom port"))
.unwrap_or_else(|err| {
log::warn!("{}. Using default 8000", err);
8000
});
let ApiSettings { address, port } = ApiSettings::try_from_env()?;

log::info!("Start listening on {}:{}...", address, port);

let api_config = ApiConfig {
host,
address,
port,
repository,
};
Expand Down Expand Up @@ -198,3 +196,16 @@ fn report_message(num_records: u32) -> String {
format!("{num_records} new records created")
}
}

fn version() -> &'static str {
#[cfg(debug_assertions)]
lazy_static! {
static ref VERSION: String = format!("{}+dev", env!("CARGO_PKG_VERSION"));
}

#[cfg(not(debug_assertions))]
lazy_static! {
static ref VERSION: String = env!("CARGO_PKG_VERSION").to_string();
}
&VERSION
}
Loading