Skip to main content

weirdnet_push/server/
store.rs

1use crate::api::Transport;
2use crate::error::{Error, Result};
3use crate::handle::{ControlSecret, WakeHandle};
4use serde::{Deserialize, Serialize};
5use std::collections::HashMap;
6use std::io::Write;
7use std::path::{Path, PathBuf};
8use std::sync::Mutex;
9
10/// One device registration.
11#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
12pub struct Registration {
13    /// How to reach it.
14    pub transport: Transport,
15    /// SHA-256 of the control secret, hex.
16    pub control: String,
17    /// Unix seconds.
18    pub created: u64,
19}
20
21impl Registration {
22    pub(crate) fn new(transport: Transport, control: &ControlSecret) -> Self {
23        let created = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
24        Self { transport, control: control.digest(), created }
25    }
26}
27
28/// Registrations by handle digest, in a JSON file written atomically on every change.
29#[derive(Debug)]
30pub struct Store {
31    path: PathBuf,
32    max: usize,
33    map: Mutex<HashMap<String, Registration>>,
34}
35
36impl Store {
37    /// Opens (or creates) the file.
38    pub fn open(path: &Path, max: usize) -> Result<Self> {
39        let map = match std::fs::read(path) {
40            Ok(b) => serde_json::from_slice(&b).map_err(|e| Error::Invalid(format!("{}: {e}", path.display())))?,
41            Err(e) if e.kind() == std::io::ErrorKind::NotFound => HashMap::new(),
42            Err(e) => return Err(e.into()),
43        };
44        Ok(Self { path: path.to_path_buf(), max, map: Mutex::new(map) })
45    }
46
47    fn save(&self, map: &HashMap<String, Registration>) -> Result<()> {
48        let dir = self.path.parent().unwrap_or(Path::new("."));
49        std::fs::create_dir_all(dir)?;
50        let tmp = self.path.with_extension("tmp");
51        let mut f = std::fs::File::create(&tmp)?;
52        #[cfg(unix)]
53        {
54            use std::os::unix::fs::PermissionsExt;
55            f.set_permissions(std::fs::Permissions::from_mode(0o600))?;
56        }
57        f.write_all(&serde_json::to_vec(map).unwrap())?;
58        f.sync_all()?;
59        std::fs::rename(&tmp, &self.path)?;
60        Ok(())
61    }
62
63    /// How many registrations there are.
64    pub fn len(&self) -> usize {
65        self.map.lock().unwrap().len()
66    }
67
68    /// True if there are none.
69    pub fn is_empty(&self) -> bool {
70        self.len() == 0
71    }
72
73    /// The registration for a handle.
74    pub fn get(&self, h: &WakeHandle) -> Option<Registration> {
75        self.map.lock().unwrap().get(&h.digest()).cloned()
76    }
77
78    pub(crate) fn insert(&self, h: &WakeHandle, r: Registration) -> Result<()> {
79        let mut m = self.map.lock().unwrap();
80        if m.len() >= self.max {
81            return Err(Error::Invalid("this server is full".into()));
82        }
83        m.insert(h.digest(), r);
84        self.save(&m)
85    }
86
87    pub(crate) fn replace(&self, old: &WakeHandle, new: &WakeHandle, r: Registration) -> Result<()> {
88        let mut m = self.map.lock().unwrap();
89        m.remove(&old.digest()).ok_or(Error::Gone)?;
90        m.insert(new.digest(), r);
91        self.save(&m)
92    }
93
94    pub(crate) fn remove(&self, h: &WakeHandle) -> Result<()> {
95        let mut m = self.map.lock().unwrap();
96        if m.remove(&h.digest()).is_some() {
97            self.save(&m)?;
98        }
99        Ok(())
100    }
101}