Skip to content

Commit b5b83a9

Browse files
committed
upgrade config
1 parent 6d9daf1 commit b5b83a9

5 files changed

Lines changed: 75 additions & 47 deletions

File tree

Cargo.toml

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,8 @@ log = "0.4"
1515
simplelog = "0.11"
1616
blake3 = "1.2"
1717
aes-gcm = "0.9"
18-
sysinfo = "0.21"
19-
once_cell = "1.8"
20-
config = "0.11"
18+
sysinfo = "0.23"
19+
once_cell = "1.10"
2120
dotenv = "0.15"
2221
hex = "0.4"
2322
bincode = "1.3"

src/layer.rs

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ use tdn::types::{
88
use domain_types::{LayerPeerEvent, LayerServerEvent};
99

1010
use crate::models::User;
11-
use crate::{DEFAULT_PROVIDER_NAME, DEFAULT_PROVIDER_PROXY};
1211

1312
/// Domain server to peer.
1413
#[inline]
@@ -28,11 +27,22 @@ pub(crate) struct Layer {
2827
pub base: PathBuf,
2928
pub name: String,
3029
pub pid: PeerId,
30+
pub proxy: bool,
3131
}
3232

3333
impl Layer {
34-
pub(crate) async fn new(base: PathBuf, name: String, pid: PeerId) -> Result<Layer> {
35-
Ok(Layer { base, name, pid })
34+
pub(crate) async fn new(
35+
base: PathBuf,
36+
name: String,
37+
pid: PeerId,
38+
proxy: bool,
39+
) -> Result<Layer> {
40+
Ok(Layer {
41+
base,
42+
name,
43+
pid,
44+
proxy,
45+
})
3646
}
3747

3848
pub(crate) async fn handle(&mut self, fgid: GroupId, msg: RecvType) -> Result<HandleResult> {
@@ -54,10 +64,7 @@ impl Layer {
5464

5565
match event {
5666
LayerPeerEvent::Check => {
57-
let status = LayerServerEvent::Status(
58-
DEFAULT_PROVIDER_NAME.to_owned(),
59-
DEFAULT_PROVIDER_PROXY,
60-
);
67+
let status = LayerServerEvent::Status(self.name.clone(), self.proxy);
6168

6269
add_server_layer(&mut results, addr, status, fgid)?;
6370
println!("------ DEBUG DOMAIN SERVICE IS OK");

src/main.rs

100644100755
Lines changed: 54 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -5,24 +5,48 @@ extern crate log;
55
extern crate anyhow;
66

77
use domain_types::DOMAIN_ID;
8+
use serde::{Deserialize, Serialize};
89
use simplelog::{CombinedLogger, Config as LogConfig, LevelFilter};
9-
use std::env::args;
10-
use std::path::PathBuf;
11-
use std::sync::Arc;
10+
use std::{env::args, path::PathBuf, sync::Arc};
1211
use tdn::{prelude::*, types::primitives::Result};
12+
use tdn_did::{generate_mnemonic, generate_peer, Count, Language};
1313
use tokio::sync::{mpsc::Sender, RwLock};
1414

1515
mod layer;
1616
mod models;
1717
mod rpc;
1818
mod storage;
1919

20-
pub const DEFAULT_PROVIDER_NAME: &'static str = "domain.esse";
21-
pub const DEFAULT_PROVIDER_PROXY: bool = true;
20+
const DEFAULT_PROVIDER_NAME: &'static str = "domain.esse";
21+
const DEFAULT_PROVIDER_PROXY: bool = true;
2222

23-
pub const DEFAULT_P2P_ADDR: &'static str = "0.0.0.0:7367"; // DEBUG CODE
24-
pub const DEFAULT_HTTP_ADDR: &'static str = "127.0.0.1:8003"; // DEBUG CODE
25-
pub const DEFAULT_LOG_FILE: &'static str = "esse.log.txt";
23+
const DEFAULT_P2P_ADDR: &'static str = "0.0.0.0:7350";
24+
const DEFAULT_HTTP_ADDR: &'static str = "127.0.0.1:7351";
25+
const DEFAULT_LOG_FILE: &'static str = "domain.log.txt";
26+
27+
/// parse custom config from config.toml.
28+
#[derive(Serialize, Deserialize, Debug)]
29+
pub struct CustomConfig {
30+
pub name: String,
31+
pub proxy: bool,
32+
pub mnemonic: String,
33+
}
34+
35+
fn custom_config_str(config: &CustomConfig) -> String {
36+
format!(
37+
r#"## Domain custom Config.
38+
## domain server name.
39+
name = "{}"
40+
41+
## domain is support proxy request/response.
42+
proxy = {}
43+
44+
## domain server default mnemonic words (keep PeerId same).
45+
mnemonic = "{}"
46+
"#,
47+
config.name, config.proxy, config.mnemonic
48+
)
49+
}
2650

2751
#[tokio::main]
2852
async fn main() {
@@ -46,22 +70,32 @@ pub async fn start(db_path: String) -> Result<()> {
4670
init_log(db_path.clone());
4771
info!("Core storage path {:?}", db_path);
4872

49-
// let _client = storage::connect_database()?;
50-
51-
let mut config = Config::load_save(db_path.clone()).await;
73+
let mut config = Config::default();
5274
config.db_path = Some(db_path.clone());
53-
// // use self sign to bootstrap peer.
54-
// if config.rpc_ws.is_none() {
55-
// // set default ws addr.
56-
// config.rpc_ws = Some(DEFAULT_WS_ADDR.parse().unwrap());
57-
// }
58-
config.rpc_ws = None;
5975
config.rpc_addr = DEFAULT_HTTP_ADDR.parse().unwrap();
6076
config.p2p_peer = Peer::socket(DEFAULT_P2P_ADDR.parse().unwrap());
6177
config.p2p_allowlist.append(&mut vec![Peer::socket(
6278
"1.15.156.199:7364".parse().unwrap(),
6379
)]);
6480
config.group_ids = vec![DOMAIN_ID];
81+
let config = Config::load_save(db_path.clone(), config).await?;
82+
let custom: Option<CustomConfig> = Config::load_custom(db_path.clone()).await;
83+
let CustomConfig {
84+
name,
85+
proxy,
86+
mnemonic,
87+
} = if let Some(custom) = custom {
88+
custom
89+
} else {
90+
let mnemonic = generate_mnemonic(Language::English, Count::Words12);
91+
let custom = CustomConfig {
92+
name: DEFAULT_PROVIDER_NAME.to_owned(),
93+
proxy: DEFAULT_PROVIDER_PROXY,
94+
mnemonic: mnemonic,
95+
};
96+
Config::append_custom(db_path.clone(), &custom_config_str(&custom)).await?;
97+
custom
98+
};
6599

66100
info!("Config RPC HTTP : {:?}", config.rpc_addr);
67101
info!(
@@ -71,13 +105,12 @@ pub async fn start(db_path: String) -> Result<()> {
71105
);
72106

73107
let _rand_secret = config.secret.clone();
74-
75-
let (peer_id, sender, mut recver) = start_with_config(config).await.unwrap();
108+
let pkey = generate_peer(Language::English, &mnemonic, 0, 0, None)?;
109+
let (peer_id, sender, mut recver) = start_with_config_and_key(config, pkey).await?;
76110
info!("Network Peer id : {}", peer_id.to_hex());
77-
let name = DEFAULT_PROVIDER_NAME.to_owned();
78111

79112
let layer = Arc::new(RwLock::new(
80-
layer::Layer::new(db_path, name, peer_id).await?,
113+
layer::Layer::new(db_path, name, peer_id, proxy).await?,
81114
));
82115

83116
let rpc_handler = rpc::new_rpc_handler(layer.clone());

src/rpc.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,8 @@ pub(crate) fn new_rpc_handler(layer: Arc<RwLock<Layer>>) -> RpcHandler<RpcState>
2020

2121
Ok(HandleResult::rpc(json!({
2222
"name": layer.name,
23-
"peer_id": layer.pid.to_hex()
23+
"peer_id": layer.pid.to_hex(),
24+
"proxy": layer.proxy,
2425
})))
2526
});
2627

src/storage.rs

Lines changed: 3 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
use config::Config as CFG;
21
use dotenv::dotenv;
32
use once_cell::sync::OnceCell;
43
use serde::Deserialize;
@@ -15,21 +14,10 @@ struct Config {
1514
}
1615

1716
impl Config {
18-
pub fn from_env() -> Result<Self> {
19-
let mut cfg = CFG::new();
20-
17+
pub fn from_env() -> Self {
2118
// database url.
2219
let database = env::var("DATABASE_URL").expect("DATABASE_URL missing");
23-
24-
cfg.set("database", database)
25-
.map_err(|_| anyhow!("set config error."))?;
26-
27-
// others.
28-
for (key, value) in env::vars() {
29-
cfg.set(&key, value)
30-
.map_err(|_| anyhow!("set config error."))?;
31-
}
32-
cfg.try_into().map_err(|_| anyhow!("config init error."))
20+
Config { database }
3321
}
3422
}
3523

@@ -44,7 +32,7 @@ pub async fn init(base: &PathBuf) -> Result<()> {
4432
init_local_files(base).await?;
4533

4634
dotenv().ok();
47-
let cfg = Config::from_env()?;
35+
let cfg = Config::from_env();
4836

4937
let pool = PgPoolOptions::new()
5038
.max_connections(5)

0 commit comments

Comments
 (0)