use serde::{Deserialize, Serialize};
use std::{
env,
fs::{create_dir_all, read_to_string},
io::{self, Write},
path::{Path, PathBuf},
};
use tempfile::NamedTempFile;
use time::OffsetDateTime;
#[cfg(unix)]
use std::fs::File;
#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct OpenOrder {
pub order_ref: String,
pub perm_id: Option<i64>,
#[serde(with = "time::serde::timestamp")]
pub created_at: OffsetDateTime,
#[serde(default, with = "time::serde::timestamp::option")]
pub last_cancelled_at: Option<OffsetDateTime>,
}
#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct State {
pub open_orders: Vec<OpenOrder>,
}
fn path() -> Option<PathBuf> {
dirs::data_local_dir()
.or_else(|| {
env::var("LOCALAPPDATA").ok().map(Into::into)
})
.map(|path| path.join("stockholm/state.yml"))
}
pub fn initial() -> State {
State {
open_orders: Vec::new(),
}
}
pub fn load() -> io::Result<State> {
if let Some(path) = path() {
let yaml = read_to_string(path)?;
yaml_serde::from_str(&yaml).map_err(io::Error::other)
} else {
Err(io::Error::other("Unable to locate data directory."))
}
}
pub fn save(state: &State) -> io::Result<()> {
if let Some(path) = path() {
let payload = yaml_serde::to_string(state).unwrap();
let directories: Vec<&Path> = path
.parent()
.unwrap()
.ancestors()
.map(|directory| {
if directory.as_os_str().is_empty() {
Path::new(".")
} else {
directory
}
})
.collect();
#[cfg(unix)]
let missing = directories
.iter()
.take_while(|directory| !directory.exists())
.count();
create_dir_all(directories[0])?;
let mut temp_file = NamedTempFile::new_in(directories[0])?;
temp_file.write_all(payload.as_bytes())?;
temp_file.as_file().sync_all()?;
temp_file.persist(&path)?;
#[cfg(unix)]
for directory in directories.iter().take(missing + 1) {
File::open(directory)?.sync_all()?;
}
} else {
return Err(io::Error::other("Unable to locate data directory."));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::State;
#[test]
fn load_orders_without_cancellation_timestamps() {
let state: State = yaml_serde::from_str(
"open_orders:\n- order_ref: stockholm:test\n perm_id: null\n created_at: 0\n",
)
.unwrap();
assert_eq!(state.open_orders.len(), 1);
assert_eq!(state.open_orders[0].last_cancelled_at, None);
}
}