Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
chrislearn committed Jan 18, 2025
1 parent 0685b28 commit 3585141
Show file tree
Hide file tree
Showing 10 changed files with 276 additions and 20 deletions.
39 changes: 39 additions & 0 deletions template/_base/src/config/db.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
use once_cell::sync::Lazy;
use serde::Deserialize;
use std::{fs::File, io::Read, path::Path};

#[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_pool_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,
}
104 changes: 104 additions & 0 deletions template/_base/src/config/mod.rs.liquid
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
use once_cell::sync::Lazy;
use serde::Deserialize;
use std::{fs::File, io::Read, path::Path};


pub static CONFIG: OnceLock<ServerConfig> = OnceLock::new();

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

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

pub db: DbConfig,
pub log: LogConfig,
}

#[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(Clone, Debug, Deserialize)]
pub struct TlsConfig {
pub cert: String,
pub key: String,

pub auto_acme: Option<String>,
}
fn default_db_pool_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
}

pub fn default_true() -> bool {
true
}
pub fn default_false() -> bool {
false
}

#[derive(Debug, Deserialize)]
pub struct Jwt {
pub jwt_secret: String,
pub jwt_exp: i64,
}

#[derive(Debug, Deserialize)]
pub struct Cert {
/// cert
pub cert: String,
/// key
pub key: String,
}

pub struct CertKey {
pub cert: Vec<u8>,
pub key: Vec<u8>,
}

impl CertKey {
pub fn new(cert: Vec<u8>, key: Vec<u8>) -> Self {
Self { cert, key }
}
}
fn get_cert_key() -> CertKey {
let cert = get_string(&CFG.cert.cert);
let key = get_string(&CFG.cert.key);
CertKey::new(cert, key)
}

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()
}
11 changes: 0 additions & 11 deletions templates/classic/_base/.env.liquid

This file was deleted.

File renamed without changes.
11 changes: 11 additions & 0 deletions templates/classic/_base/config.toml.liquid
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
listen_addr = "127.0.0.1:8008"

[db]
url = "postgres://postgres:[email protected]:5432/{{project_name}}"
pool_size = 1

[jwt]

[log]
file_name = "app.log"
rolling = "daily"
5 changes: 3 additions & 2 deletions templates/classic/_base/src/config/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ 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.
#[serde(alias = "database_url")]
pub url: String,
#[serde(default = "default_db_pooll_size")]
#[serde(default = "default_db_pool_size")]
pub pool_size: u32,
pub min_idle: Option<u32>,

Expand Down Expand Up @@ -41,7 +42,7 @@ pub struct DbConfig {
fn default_helper_threads() -> usize {
10
}
fn default_db_pooll_size() -> u32 {
fn default_db_pool_size() -> u32 {
10
}
fn default_tcp_timeout() -> u64 {
Expand Down
4 changes: 2 additions & 2 deletions templates/classic/_base/src/config/log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const FORMAT_COMPACT: &str = "compact";
const FORMAT_JSON: &str = "json";
const FORMAT_FULL: &str = "full";

#[derive(Deserialize, Clone, Debug)]
#[derive(Deserialize, Default, Clone, Debug)]
pub struct LogConfig {
#[serde(default = "default_filter_level")]
pub filter_level: String,
Expand Down Expand Up @@ -46,7 +46,7 @@ fn default_directory() -> String {
"./logs".into()
}
fn default_file_name() -> String {
"main.log".into()
"app.log".into()
}
fn default_rolling() -> String {
"daily".into()
Expand Down
108 changes: 108 additions & 0 deletions templates/classic/_base/src/config/mod.rs.liquid
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
use std::sync::OnceLock;
use std::{fs::File, io::Read, path::Path};

use serde::Deserialize;
use salvo::http::HeaderValue;

use crate::config;


pub static CONFIG: OnceLock<ServerConfig> = OnceLock::new();

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

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

pub db: DbConfig,
pub log: LogConfig,
}

#[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(Clone, Debug, Deserialize)]
pub struct TlsConfig {
pub cert: String,
pub key: String,

pub auto_acme: Option<String>,
}
fn default_db_pool_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
}

pub fn default_true() -> bool {
true
}
pub fn default_false() -> bool {
false
}

#[derive(Debug, Deserialize)]
pub struct Jwt {
pub jwt_secret: String,
pub jwt_exp: i64,
}

#[derive(Debug, Deserialize)]
pub struct Cert {
/// cert
pub cert: String,
/// key
pub key: String,
}

pub struct CertKey {
pub cert: Vec<u8>,
pub key: Vec<u8>,
}

impl CertKey {
pub fn new(cert: Vec<u8>, key: Vec<u8>) -> Self {
Self { cert, key }
}
}
fn get_cert_key() -> CertKey {
let cert = get_string(&config().cert.cert);
let key = get_string(&config()cert.key);
CertKey::new(cert, key)
}

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()
}
9 changes: 9 additions & 0 deletions templates/classic/diesel/.env.liquid
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@

{%- if db_type == "postgres" %}
DATABASE_URL=postgresql://postgres:root@localhost/{{project_name}}
{%- endif %}
{%- if db_type == "sqlite" %}
DATABASE_URL="sqlite:data/{{project_name}}.db"
{%- endif %}
{%- if db_type == "mysql" %}
DATABASE_URL="mysql://root:root@localhost/{{project_name}}"
5 changes: 0 additions & 5 deletions templates/classic/diesel/src/db/mod.rs.liquid
Original file line number Diff line number Diff line change
Expand Up @@ -89,11 +89,6 @@ impl CustomizeConnection<PgConnection, r2d2::Error> for ConnectionConfig {
))
.execute(conn)
.map_err(r2d2::Error::QueryError)?;
// if self.read_only {
// sql_query("SET default_transaction_read_only = 't'")
// .execute(conn)
// .map_err(r2d2::Error::QueryError)?;
// }
Ok(())
}
}

0 comments on commit 3585141

Please sign in to comment.