Save states asynchronously

pull/5/head
Frank Denis 5 years ago
parent 360172601f
commit f0c6235d33

@ -2,13 +2,12 @@ use crate::crypto::*;
use crate::dnscrypt_certs::*;
use crate::errors::*;
use std::fs::{File, OpenOptions};
use std::fs::File;
use std::io::prelude::*;
use std::mem;
use std::net::{IpAddr, SocketAddr};
use std::path::{Path, PathBuf};
#[cfg(unix)]
use std::os::unix::fs::OpenOptionsExt;
use tokio::prelude::*;
#[derive(Serialize, Deserialize, Debug)]
pub struct DNSCryptConfig {
@ -70,16 +69,16 @@ impl State {
}
}
pub fn save<P: AsRef<Path>>(&self, path: P) -> Result<(), Error> {
let mut fpb = OpenOptions::new();
let mut fpb = fpb.create(true).write(true);
#[cfg(unix)]
{
fpb = fpb.mode(0o600);
}
let mut fp = fpb.open(path.as_ref())?;
pub async fn async_save<P: AsRef<Path>>(&self, path: P) -> Result<(), Error> {
let path_tmp = path.as_ref().with_extension("tmp");
let mut fpb = tokio::fs::OpenOptions::new();
let fpb = fpb.create(true).write(true);
let mut fp = fpb.open(&path_tmp).await?;
let state_bin = toml::to_vec(&self)?;
fp.write_all(&state_bin)?;
fp.write_all(&state_bin).await?;
fp.sync_data().await?;
mem::drop(fp);
tokio::fs::rename(path_tmp, path).await?;
Ok(())
}

@ -145,7 +145,10 @@ impl DNSCryptEncryptionParamsUpdater {
provider_kp: self.globals.provider_kp.clone(),
dnscrypt_encryption_params_set: new_params_set.iter().map(|x| (**x).clone()).collect(),
};
let _ = state.save(&self.globals.state_file);
let state_file = self.globals.state_file.to_path_buf();
self.globals.runtime.spawn(async move {
let _ = state.async_save(state_file).await;
});
*self.globals.dnscrypt_encryption_params_set.write() = Arc::new(new_params_set);
}

@ -47,8 +47,6 @@ use privdrop::PrivDrop;
use rand::prelude::*;
use std::collections::vec_deque::VecDeque;
use std::convert::TryFrom;
use std::fs::File;
use std::io::prelude::*;
use std::mem;
use std::net::SocketAddr;
use std::sync::atomic::{AtomicU32, Ordering};
@ -412,12 +410,16 @@ fn main() -> Result<(), Error> {
pd.apply()?;
}
let mut runtime_builder = tokio::runtime::Builder::new();
runtime_builder.name_prefix("encrypted-dns-");
let runtime = Arc::new(runtime_builder.build()?);
let state_file = &config.state_file;
let state = match State::from_file(state_file) {
Err(_) => {
println!("No state file found... creating a new provider key");
let state = State::new();
state.save(state_file)?;
runtime.block_on(state.async_save(state_file))?;
state
}
Ok(state) => {
@ -450,9 +452,7 @@ fn main() -> Result<(), Error> {
.into_iter()
.map(Arc::new)
.collect::<Vec<_>>();
let mut runtime_builder = tokio::runtime::Builder::new();
runtime_builder.name_prefix("encrypted-dns-");
let runtime = Arc::new(runtime_builder.build()?);
let globals = Arc::new(Globals {
runtime: runtime.clone(),
state_file: state_file.to_path_buf(),

Loading…
Cancel
Save