1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
#![feature(proc_macro_hygiene, decl_macro)]
#![deny(missing_docs)]
#![allow(clippy::pedantic)]
extern crate rocket;
pub mod api;
#[allow(missing_docs)]
pub mod model;
mod parse;
use std::str::FromStr;
use std::{
collections::HashMap,
fs::{metadata, File},
io::{BufRead, BufReader, Result},
path::{Path, PathBuf},
sync::{Arc, RwLock},
time::SystemTime,
};
pub type ArcMap<T> = Arc<HashMap<u64, T>>;
pub trait ThreadSafeErr: std::error::Error + Sync + Send + 'static {}
pub trait Resource<T: UniqueID> {
fn load(&self) -> Result<Arc<HashMap<u64, T>>>;
}
pub trait UniqueID {
fn id(&self) -> u64;
}
pub trait Query<T> {
fn is_match(&self, t: &T) -> bool;
fn matching_elements<'a>(&self, a: impl IntoIterator<Item = &'a T>) -> Vec<&'a T> {
a.into_iter().filter(|t| self.is_match(t)).collect()
}
}
impl<F: Fn(&T) -> bool, T> Query<T> for F {
fn is_match(&self, t: &T) -> bool {
(self)(t)
}
}
#[derive(Debug)]
pub struct FileResource<T: std::str::FromStr + Clone> {
path: PathBuf,
cached_at: RwLock<std::time::SystemTime>,
cache: RwLock<Arc<HashMap<u64, T>>>,
}
impl<T> FileResource<T>
where
T: FromStr + Clone + UniqueID,
T::Err: ThreadSafeErr,
{
pub fn new(path: impl AsRef<Path>) -> Result<Self> {
let path = path.as_ref().to_owned();
let cached_at = RwLock::new(metadata(&path)?.modified()?);
let cache = RwLock::new(Arc::new(build_cache(&path)?));
Ok(Self { path, cached_at, cache })
}
}
fn build_cache<T>(p: impl AsRef<Path>) -> Result<HashMap<u64, T>>
where
T: FromStr + UniqueID,
T::Err: std::error::Error + Sync + Send + 'static,
{
let mut cache = HashMap::new();
for line_res in BufReader::new(File::open(p)?).lines() {
let line = line_res?;
match line.trim() {
line if line.is_empty() => continue,
line => match line.parse::<T>() {
Ok(t) => cache.insert(t.id(), t),
Err(err) => return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, Box::new(err))),
},
};
}
Ok(cache)
}
impl<T> Resource<T> for FileResource<T>
where
T: FromStr + Clone + UniqueID + Sync + Send,
T::Err: ThreadSafeErr,
{
fn load(&self) -> Result<Arc<HashMap<u64, T>>> {
let last_modified: SystemTime = metadata(&self.path)?.modified()?;
let need_cache_reload = *self.cached_at.read().expect("thread failure") < last_modified;
if need_cache_reload {
*Arc::make_mut(&mut self.cache.write().unwrap()) = build_cache(&self.path)?;
*self.cached_at.write().unwrap() = last_modified;
};
Ok(self.cache.read().unwrap().clone())
}
}
impl<E: std::error::Error + Sync + Send + 'static> ThreadSafeErr for E {}
impl<T> Resource<T> for &FileResource<T>
where
T: FromStr + Clone + UniqueID + Sync + Send,
T::Err: ThreadSafeErr,
{
fn load(&self) -> Result<Arc<HashMap<u64, T>>> {
let last_modified: SystemTime = metadata(&self.path)?.modified()?;
let need_cache_reload = *self.cached_at.read().expect("thread failure") < last_modified;
if need_cache_reload {
*Arc::make_mut(&mut self.cache.write().unwrap()) = build_cache(&self.path)?;
*self.cached_at.write().unwrap() = last_modified;
};
Ok(self.cache.read().unwrap().clone())
}
}
impl<'r, T> Resource<T> for rocket::State<'r, FileResource<T>>
where
T: Clone + UniqueID + Send + Sync + FromStr,
T::Err: ThreadSafeErr,
{
fn load(&self) -> Result<Arc<HashMap<u64, T>>> {
(*self.inner()).load()
}
}
impl UniqueID for model::User {
fn id(&self) -> u64 {
self.uid
}
}
impl UniqueID for model::Group {
fn id(&self) -> u64 {
self.gid
}
}