diff rust/src/params.rs @ 624:2710649ab71e rust

read/write params local file. untested
author Matt Johnston <matt@ucc.asn.au>
date Sun, 16 Apr 2017 23:29:27 +0800
parents 8136a6b99866
children efcbe0d3afd6
line wrap: on
line diff
--- a/rust/src/params.rs	Sun Apr 16 22:50:20 2017 +0800
+++ b/rust/src/params.rs	Sun Apr 16 23:29:27 2017 +0800
@@ -3,6 +3,7 @@
 extern crate rand;
 extern crate serde_json;
 extern crate base64;
+extern crate atomicwrites;
 
 use std::time::Duration;
 use std::io;
@@ -11,6 +12,8 @@
 use std::sync::{Arc,Mutex};
 use std::error::Error;
 use std::cell::{Cell,RefCell};
+use std::fs::File;
+use std::io::Read;
 
 use tokio_core::reactor::Interval;
 use tokio_core::reactor::Handle;
@@ -49,12 +52,15 @@
             }
     }
 
+    fn try_load(filename: &str) -> Result<Params, TemplogError> {
+        let mut s = String::new();
+        File::open(filename)?.read_to_string(&mut s)?;
+        Ok(serde_json::from_str(&s)?)
+    }
+
     pub fn load(config: &Config) -> Params {
-        // generate random epoch on success.
-        // TODO: return failure? or just return default() ?
-        let mut p = Params::defaults();
-
-        unimplemented!();
+        Self::try_load(&config.PARAMS_FILE)
+            .unwrap_or_else(|_| Params::defaults())
     }
 }
 
@@ -128,6 +134,7 @@
                 let mut le = self.last_etag.borrow_mut();
                 *le = r.etag;
                 if le.split('-').next().unwrap() == &self.epoch {
+                    self.write_params(&r.params);
                     Ok(r.params)
                 } else {
                     Err(TemplogError::new(&format!("Bad epoch from server '{}' expected '{}'", *le, self.epoch)))
@@ -143,6 +150,13 @@
         }
     }
 
+    fn write_params(&self, params: &Params) {
+        let p = atomicwrites::AtomicFile::new(&self.config.PARAMS_FILE, atomicwrites::AllowOverwrite);
+        p.write(|f| {
+            serde_json::to_writer(f, params)
+        });
+    }
+
     fn step(rself: Rc<Self>) -> Box<Future<Item=Params, Error=TemplogError>> {
 
         if rself.session.borrow().is_none() {