Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
chrislearn committed Jan 15, 2025
1 parent d66db4c commit 5fd2563
Show file tree
Hide file tree
Showing 3 changed files with 134 additions and 23 deletions.
110 changes: 93 additions & 17 deletions template/_base/src/config.rs.liquid
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,101 @@ use once_cell::sync::Lazy;
use serde::Deserialize;
use std::{fs::File, io::Read, path::Path};

#[derive(Debug, Deserialize)]
pub struct Configs {
pub server: Server,
pub log: Log,
pub database: DataBase,
pub cert: Cert,
pub jwt: Jwt,


#[derive(Clone, Debug, Deserialize)]
pub struct ServerConfig {
pub tls: Option<TlsConfig>,

#[serde(default = "default_listen_addr")]
pub listen_addr: String,
pub db: DbConfig,

pub jwt_secret: Option<String>,
#[serde(default = "default_log")]
pub log: String,

pub auto_acme: Option<String>,
#[serde(default = "false_value")]
pub enable_tls: bool,
}

#[derive(Debug, Deserialize)]
pub struct Server {
pub name: String,
pub address: String,
pub cors_allow_origin: Vec<String>,
pub ssl: bool,
#[derive(Clone, Debug, Default)]
pub struct AllowedOrigins(Vec<String>);
impl AllowedOrigins {
pub fn from_env() -> anyhow::Result<Self> {
let allowed_origins = required_var("WEB_ALLOWED_ORIGINS")?
.split(',')
.map(ToString::to_string)
.collect();

Ok(Self(allowed_origins))
}

pub fn contains(&self, value: &HeaderValue) -> bool {
self.0.iter().any(|it| it == value)
}
}

#[derive(Debug, Deserialize)]
pub struct DataBase {
pub database_url: String,
#[derive(Clone, Debug, Deserialize)]
pub struct TlsConfig {
pub certs: String,
pub key: String,
}
fn default_db_pooll_size() -> u32 {
10
}
fn default_tcp_timeout() -> u64 {
10000
}
fn default_connection_timeout() -> u64 {
30000
}
fn default_statement_timeout() -> u64 {
30000
}
fn default_helper_threads() -> usize {
10
}

#[derive(Deserialize, Serialize, Clone, Debug)]
pub struct DbConfig {
/// Settings for the primary database. This is usually writeable, but will be read-only in
/// some configurations.
/// An optional follower database. Always read-only.
pub url: String,
#[serde(default = "default_db_pooll_size")]
pub pool_size: u32,
pub min_idle: Option<u32>,

/// Number of seconds to wait for unacknowledged TCP packets before treating the connection as
/// broken. This value will determine how long crates.io stays unavailable in case of full
/// packet loss between the application and the database: setting it too high will result in an
/// unnecessarily long outage (before the unhealthy database logic kicks in), while setting it
/// too low might result in healthy connections being dropped.
#[serde(default = "default_tcp_timeout")]
pub tcp_timeout: u64,
/// Time to wait for a connection to become available from the connection
/// pool before returning an error.
/// Time to wait for a connection to become available from the connection
/// pool before returning an error.
#[serde(default = "default_connection_timeout")]
pub connection_timeout: u64,
/// Time to wait for a query response before canceling the query and
/// returning an error.
#[serde(default = "default_statement_timeout")]
pub statement_timeout: u64,
/// Number of threads to use for asynchronous operations such as connection
/// creation.
#[serde(default = "default_helper_threads")]
pub helper_threads: usize,
/// Whether to enforce that all the database connections are encrypted with TLS.
#[serde(default = "false_value")]
pub enforce_tls: bool,
}

#[derive(Debug, Deserialize)]
pub struct Log {
pub struct LogConfig {
pub filter_level: String,
pub with_ansi: bool,
pub to_stdout: bool,
Expand Down Expand Up @@ -93,3 +164,8 @@ fn get_cert_key() -> CertKey {
fn get_string<P: AsRef<Path>>(path: P) -> Vec<u8> {
std::fs::read(path).expect("{{config_error_read_failed}}")
}


fn default_listen_addr() -> String {
"127.0.0.1:8008".into()
}
42 changes: 41 additions & 1 deletion template/_base/src/main.rs.liquid
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,24 @@ mod routers;

#[tokio::main]
async fn main() {

if let Err(e) = dotenv() {
println!("dotenv error: {:?}", e);
}

let raw_config = Figment::new()
.merge(Toml::file(Env::var("PALPO_CONFIG").as_deref().unwrap_or("palpo.toml")))
.merge(Env::prefixed("PALPO_").global());


let conf = match raw_config.extract::<ServerConfig>() {
Ok(s) => s,
Err(e) => {
eprintln!("It looks like your config is invalid. The following error occurred: {e}");
std::process::exit(1);
}
};

//{{main_log_message}}
let _guard = clia_tracing_config::build()
.filter_level(&CFG.log.filter_level)
Expand All @@ -37,7 +55,29 @@ async fn main() {
.init();
tracing::info!("log level: {}", &CFG.log.filter_level);

init_db_conn().await;


let db_primary = {
let db_connection_config = ConnectionConfig {
statement_timeout: conf.db.statement_timeout,
};

let db_config = r2d2::Pool::builder()
.max_size(conf.db.pool_size)
.min_idle(conf.db.min_idle)
.connection_timeout(Duration::from_millis(conf.db.connection_timeout))
.connection_customizer(Box::new(db_connection_config))
.thread_pool(thread_pool.clone());

DieselPool::new(&conf.db.url, &conf.db, db_config).unwrap()
};
crate::db::DIESEL_POOL
.set(db_primary)
.expect("diesel pool should be set");
let enable_tls = conf.enable_tls;
crate::config::CONFIG.set(conf).expect("config should be set");
crate::db::migrate();


let router = router();
let service: Service = router.into();
Expand Down
5 changes: 0 additions & 5 deletions template/diesel/src/db.rs.liquid
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,7 @@ pub fn establish_connection() -> MysqlConnection {
pub static DB_POOL: OnceCell<PgPool> = OnceCell::new();
pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!();

// pub fn connect()? -> PgConnection {
// PgConnection::establish(&crate::database_url()).expect("connect database error")
// }
pub fn connect() -> Result<PooledConnection<ConnectionManager<PgConnection>>, PoolError> {
// println!("==========get db conn");
DB_POOL.get().unwrap().get()
}

Expand All @@ -46,5 +42,4 @@ pub fn establish_connection() -> MysqlConnection {
println!("Has pending migration: {}", conn.has_pending_migration(MIGRATIONS).unwrap());
conn.run_pending_migrations(MIGRATIONS).expect("migrate db should worked");
}

{% endif %}

0 comments on commit 5fd2563

Please sign in to comment.