-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstorage.rs
159 lines (140 loc) · 4.78 KB
/
storage.rs
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
use anyhow::{anyhow, bail, Error, Result};
use std::{
fs::{create_dir_all, remove_file, rename, File},
io::{Read, Write},
path::{PathBuf, MAIN_SEPARATOR},
str::FromStr,
thread,
time::{Duration, SystemTime, UNIX_EPOCH},
};
const TMP_SUFFIX: &str = ".tmp";
const META_SUFFIX: &str = ".meta";
pub struct Item {
pub file: File,
pub path: PathBuf,
pub mime: String,
// pub id: u64,
}
impl Item {
// Constructors
/// Build new `Self` from URL (request)
/// * e.g. 123 -> /directory/1/2/3
pub fn from_url(url: &str, directory: &str) -> Result<Self> {
let s = match url.rfind('/') {
Some(pos) => match url.get(pos + 1..) {
Some(u) => u.parse::<u64>()?,
None => bail!("Invalid request"),
},
None => bail!("ID not found"),
}
.to_string();
let mut p = String::with_capacity(s.len());
for (i, d) in s.chars().enumerate() {
if i > 0 {
p.push(MAIN_SEPARATOR)
}
p.push(d)
}
let path = PathBuf::from_str(&format!(
"{}{MAIN_SEPARATOR}{p}",
directory.trim_end_matches(MAIN_SEPARATOR),
))?;
Ok(Self {
file: File::open(&path)?,
mime: read_meta(path.to_str().unwrap())?,
path,
})
}
/// Create new `Self` with unique pathname in the root `directory`
pub fn create(directory: &str, mime: String) -> Result<Self> {
loop {
// generate file id from current unix time
let id = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
// build optimized fs path:
// add directory separator after every digit to keep up to 10 files per directory
let path = PathBuf::from(format!(
"{}{MAIN_SEPARATOR}{}{TMP_SUFFIX}",
directory.trim_end_matches(MAIN_SEPARATOR),
id.to_string().chars().fold(String::new(), |mut acc, c| {
if !acc.is_empty() {
acc.push(MAIN_SEPARATOR);
}
acc.push(c);
acc
})
));
// recursively create directories
// * parent directory is expected
create_dir_all(path.parent().unwrap())?;
// build `Self`
match File::create_new(&path) {
// make sure slot is not taken (by another thread)
Ok(file) => {
return Ok(Self {
file,
path,
mime,
// id
});
}
Err(_) => {
println!("[warning] Could not init location: {:?}", path.to_str());
// find free slot after some delay..
thread::sleep(Duration::from_secs(1));
continue;
}
}
}
}
// Actions
/// Commit changes, return permanent Self
pub fn commit(mut self) -> Result<Self, (Self, Error)> {
match self.path.to_str() {
Some(old) => match old.strip_suffix(TMP_SUFFIX) {
Some(new) => match rename(old, new) {
Ok(()) => {
self.path = match PathBuf::from_str(new) {
Ok(path) => path,
Err(e) => return Err((self, anyhow!(e))),
};
match self.write_meta() {
Ok(()) => Ok(self),
Err(e) => Err((self, anyhow!(e))),
}
}
Err(e) => Err((self, anyhow!(e))),
},
None => Err((self, anyhow!("Unexpected suffix"))),
},
None => Err((self, anyhow!("Unexpected file path"))),
}
}
/// Delete `Self`, cleanup FS
pub fn delete(self) -> Result<()> {
Ok(remove_file(self.path)?)
}
// Getters
/// Shared helper to build public URI
pub fn to_uri(&self, directory: &str) -> String {
self.path
.to_str()
.unwrap()
.replace(directory, "")
.replace("/", "")
}
// System
fn write_meta(&self) -> Result<()> {
Ok(File::create_new(meta_path(self.path.to_str().unwrap()))?
.write_all(self.mime.as_bytes())?)
}
}
// Tools
fn meta_path(path: &str) -> String {
format!("{}{META_SUFFIX}", path)
}
fn read_meta(path: &str) -> Result<String> {
let mut buffer = String::new();
File::open(meta_path(path))?.read_to_string(&mut buffer)?;
Ok(buffer)
}
// * @TODO move `meta` feature to separated struct impl on complete