Skip to content

Commit 5fd2563

Browse files
committed
wip
1 parent d66db4c commit 5fd2563

File tree

3 files changed

+134
-23
lines changed

3 files changed

+134
-23
lines changed

template/_base/src/config.rs.liquid

Lines changed: 93 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2,30 +2,101 @@ use once_cell::sync::Lazy;
22
use serde::Deserialize;
33
use std::{fs::File, io::Read, path::Path};
44

5-
#[derive(Debug, Deserialize)]
6-
pub struct Configs {
7-
pub server: Server,
8-
pub log: Log,
9-
pub database: DataBase,
10-
pub cert: Cert,
11-
pub jwt: Jwt,
5+
6+
7+
#[derive(Clone, Debug, Deserialize)]
8+
pub struct ServerConfig {
9+
pub tls: Option<TlsConfig>,
10+
11+
#[serde(default = "default_listen_addr")]
12+
pub listen_addr: String,
13+
pub db: DbConfig,
14+
15+
pub jwt_secret: Option<String>,
16+
#[serde(default = "default_log")]
17+
pub log: String,
18+
19+
pub auto_acme: Option<String>,
20+
#[serde(default = "false_value")]
21+
pub enable_tls: bool,
1222
}
1323

14-
#[derive(Debug, Deserialize)]
15-
pub struct Server {
16-
pub name: String,
17-
pub address: String,
18-
pub cors_allow_origin: Vec<String>,
19-
pub ssl: bool,
24+
#[derive(Clone, Debug, Default)]
25+
pub struct AllowedOrigins(Vec<String>);
26+
impl AllowedOrigins {
27+
pub fn from_env() -> anyhow::Result<Self> {
28+
let allowed_origins = required_var("WEB_ALLOWED_ORIGINS")?
29+
.split(',')
30+
.map(ToString::to_string)
31+
.collect();
32+
33+
Ok(Self(allowed_origins))
34+
}
35+
36+
pub fn contains(&self, value: &HeaderValue) -> bool {
37+
self.0.iter().any(|it| it == value)
38+
}
2039
}
2140

22-
#[derive(Debug, Deserialize)]
23-
pub struct DataBase {
24-
pub database_url: String,
41+
#[derive(Clone, Debug, Deserialize)]
42+
pub struct TlsConfig {
43+
pub certs: String,
44+
pub key: String,
45+
}
46+
fn default_db_pooll_size() -> u32 {
47+
10
48+
}
49+
fn default_tcp_timeout() -> u64 {
50+
10000
51+
}
52+
fn default_connection_timeout() -> u64 {
53+
30000
54+
}
55+
fn default_statement_timeout() -> u64 {
56+
30000
57+
}
58+
fn default_helper_threads() -> usize {
59+
10
60+
}
61+
62+
#[derive(Deserialize, Serialize, Clone, Debug)]
63+
pub struct DbConfig {
64+
/// Settings for the primary database. This is usually writeable, but will be read-only in
65+
/// some configurations.
66+
/// An optional follower database. Always read-only.
67+
pub url: String,
68+
#[serde(default = "default_db_pooll_size")]
69+
pub pool_size: u32,
70+
pub min_idle: Option<u32>,
71+
72+
/// Number of seconds to wait for unacknowledged TCP packets before treating the connection as
73+
/// broken. This value will determine how long crates.io stays unavailable in case of full
74+
/// packet loss between the application and the database: setting it too high will result in an
75+
/// unnecessarily long outage (before the unhealthy database logic kicks in), while setting it
76+
/// too low might result in healthy connections being dropped.
77+
#[serde(default = "default_tcp_timeout")]
78+
pub tcp_timeout: u64,
79+
/// Time to wait for a connection to become available from the connection
80+
/// pool before returning an error.
81+
/// Time to wait for a connection to become available from the connection
82+
/// pool before returning an error.
83+
#[serde(default = "default_connection_timeout")]
84+
pub connection_timeout: u64,
85+
/// Time to wait for a query response before canceling the query and
86+
/// returning an error.
87+
#[serde(default = "default_statement_timeout")]
88+
pub statement_timeout: u64,
89+
/// Number of threads to use for asynchronous operations such as connection
90+
/// creation.
91+
#[serde(default = "default_helper_threads")]
92+
pub helper_threads: usize,
93+
/// Whether to enforce that all the database connections are encrypted with TLS.
94+
#[serde(default = "false_value")]
95+
pub enforce_tls: bool,
2596
}
2697

2798
#[derive(Debug, Deserialize)]
28-
pub struct Log {
99+
pub struct LogConfig {
29100
pub filter_level: String,
30101
pub with_ansi: bool,
31102
pub to_stdout: bool,
@@ -93,3 +164,8 @@ fn get_cert_key() -> CertKey {
93164
fn get_string<P: AsRef<Path>>(path: P) -> Vec<u8> {
94165
std::fs::read(path).expect("{{config_error_read_failed}}")
95166
}
167+
168+
169+
fn default_listen_addr() -> String {
170+
"127.0.0.1:8008".into()
171+
}

template/_base/src/main.rs.liquid

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,24 @@ mod routers;
2626

2727
#[tokio::main]
2828
async fn main() {
29+
30+
if let Err(e) = dotenv() {
31+
println!("dotenv error: {:?}", e);
32+
}
33+
34+
let raw_config = Figment::new()
35+
.merge(Toml::file(Env::var("PALPO_CONFIG").as_deref().unwrap_or("palpo.toml")))
36+
.merge(Env::prefixed("PALPO_").global());
37+
38+
39+
let conf = match raw_config.extract::<ServerConfig>() {
40+
Ok(s) => s,
41+
Err(e) => {
42+
eprintln!("It looks like your config is invalid. The following error occurred: {e}");
43+
std::process::exit(1);
44+
}
45+
};
46+
2947
//{{main_log_message}}
3048
let _guard = clia_tracing_config::build()
3149
.filter_level(&CFG.log.filter_level)
@@ -37,7 +55,29 @@ async fn main() {
3755
.init();
3856
tracing::info!("log level: {}", &CFG.log.filter_level);
3957

40-
init_db_conn().await;
58+
59+
60+
let db_primary = {
61+
let db_connection_config = ConnectionConfig {
62+
statement_timeout: conf.db.statement_timeout,
63+
};
64+
65+
let db_config = r2d2::Pool::builder()
66+
.max_size(conf.db.pool_size)
67+
.min_idle(conf.db.min_idle)
68+
.connection_timeout(Duration::from_millis(conf.db.connection_timeout))
69+
.connection_customizer(Box::new(db_connection_config))
70+
.thread_pool(thread_pool.clone());
71+
72+
DieselPool::new(&conf.db.url, &conf.db, db_config).unwrap()
73+
};
74+
crate::db::DIESEL_POOL
75+
.set(db_primary)
76+
.expect("diesel pool should be set");
77+
let enable_tls = conf.enable_tls;
78+
crate::config::CONFIG.set(conf).expect("config should be set");
79+
crate::db::migrate();
80+
4181

4282
let router = router();
4383
let service: Service = router.into();

template/diesel/src/db.rs.liquid

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -29,11 +29,7 @@ pub fn establish_connection() -> MysqlConnection {
2929
pub static DB_POOL: OnceCell<PgPool> = OnceCell::new();
3030
pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
3131

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

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

0 commit comments

Comments
 (0)