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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
use bytes::Bytes;
use flate2::read::GzDecoder;
use futures::{future, prelude::*, Async};
use futures_cpupool::{CpuFuture, CpuPool};
use sha1::Sha1;
use std::{
cmp,
fs::File,
io::{self, Seek, SeekFrom, Write},
path::Path,
};
use tar::Archive;
lazy_static! {
static ref FILE_HANDLER: FilePoolHandler = FilePoolHandler::default();
}
#[derive(Clone)]
struct FilePoolHandler {
pool: CpuPool,
}
impl Default for FilePoolHandler {
fn default() -> FilePoolHandler {
FilePoolHandler {
pool: CpuPool::new_num_cpus(),
}
}
}
struct WriteToFile {
file: File,
x: Bytes,
pos: u64,
}
impl FilePoolHandler {
pub fn write_to_file(&self, msg: WriteToFile) -> impl Future<Item = (), Error = String> {
write_chunk_on_pool(msg.file, msg.x, msg.pos, self.pool.clone()).map_err(|e| e.to_string())
}
pub fn read_file(&self, msg: ReadFile) -> impl Stream<Item = Bytes, Error = String> {
future::result(match msg.range {
Some(range) => ChunkedReadFile::new_ranged(msg.file, self.pool.clone(), range),
None => ChunkedReadFile::new(msg.file, self.pool.clone()),
}).flatten_stream()
}
pub fn untar_archive<P: AsRef<Path> + ToOwned>(
&self,
mut archive: Archive<GzDecoder<File>>,
output_path: P,
) -> impl Future<Item = (), Error = String> {
let out = output_path.as_ref().to_owned();
self.pool
.spawn_fn(move || archive.unpack(out).map_err(|e| e.to_string()))
}
}
fn write_chunk_on_pool(
mut file: File,
x: Bytes,
pos: u64,
pool: CpuPool,
) -> impl Future<Item = (), Error = io::Error> {
pool.spawn_fn(move || {
future::result(file.seek(SeekFrom::Start(pos)))
.and_then(move |_| file.write(x.as_ref()).and_then(|_| Ok(())))
})
}
struct ReadFile {
file: File,
range: Option<(u64, u64)>,
}
struct WithPositions<S: Stream<Item = Bytes, Error = String>> {
stream: S,
pos: u64,
}
impl<S: Stream<Item = Bytes, Error = String>> WithPositions<S> {
pub fn new(a: S) -> WithPositions<S> {
Self { stream: a, pos: 0 }
}
}
impl<S: Stream<Item = Bytes, Error = String>> Stream for WithPositions<S> {
type Item = (Bytes, u64);
type Error = String;
fn poll(&mut self) -> Result<Async<Option<(Bytes, u64)>>, String> {
match self.stream.poll() {
Ok(Async::Ready(Some(x))) => {
let len = x.len() as u64;
let res = Ok(Async::Ready(Some((x, self.pos))));
self.pos += len;
res
}
Ok(Async::Ready(None)) => Ok(Async::Ready(None)),
Ok(Async::NotReady) => Ok(Async::NotReady),
Err(e) => Err(e),
}
}
}
use std::fmt::Debug;
fn stream_with_positions<Ins: Stream<Item = Bytes, Error = E>, P: AsRef<Path>, E: Debug>(
input_stream: Ins,
path: P,
) -> impl Stream<Item = (Bytes, u64, File), Error = String> {
future::result(File::create(path).map_err(|e| format!("File creation error: {:?}", e)))
.and_then(|file| {
Ok(WithPositions::new(
input_stream.map_err(|e: E| format!("Input stream error {:?}", e)),
).and_then(move |(x, pos)| {
file.try_clone()
.and_then(|file| Ok((x, pos, file)))
.map_err(|e| format!("File clone error {:?}", e))
}))
}).flatten_stream()
}
pub fn write_async_with_sha1<Ins: Stream<Item = Bytes, Error = E>, P: AsRef<Path>, E: Debug>(
input_stream: Ins,
path: P,
) -> impl Future<Item = String, Error = String> {
stream_with_positions(input_stream, path)
.fold(Sha1::new(), move |mut sha, (x, pos, file)| {
sha.update(x.as_ref());
write_bytes(x, pos, file).and_then(|_| Ok(sha))
}).and_then(|sha| Ok(sha.digest().to_string()))
}
pub fn write_async<Ins: Stream<Item = Bytes, Error = E>, P: AsRef<Path>, E: Debug>(
input_stream: Ins,
path: P,
) -> impl Future<Item = (), Error = String> {
stream_with_positions(input_stream, path).for_each(|(x, pos, file)| write_bytes(x, pos, file))
}
fn write_bytes(x: Bytes, pos: u64, file: File) -> impl Future<Item = (), Error = String> {
let msg = WriteToFile { file, x, pos };
FILE_HANDLER
.write_to_file(msg)
.map_err(|e| format!("FileWriter error: {}", e))
}
pub fn read_async<P: AsRef<Path>>(path: P) -> impl Stream<Item = Bytes, Error = String> {
let file_fut = future::result(File::open(path));
file_fut
.map_err(|e| e.to_string())
.and_then(|file| Ok(ReadFile { file, range: None }))
.and_then(|read| Ok(FILE_HANDLER.read_file(read)))
.flatten_stream()
}
pub struct ChunkedReadFile {
size: u64,
offset: u64,
cpu_pool: CpuPool,
file: Option<File>,
fut: Option<CpuFuture<(File, Bytes), io::Error>>,
counter: u64,
}
impl ChunkedReadFile {
pub fn new(file: File, pool: CpuPool) -> Result<ChunkedReadFile, String> {
Ok(ChunkedReadFile {
size: file.metadata().map_err(|e| e.to_string())?.len(),
offset: 0,
cpu_pool: pool,
file: Some(file),
fut: None,
counter: 0,
})
}
pub fn new_ranged(
file: File,
pool: CpuPool,
range: (u64, u64),
) -> Result<ChunkedReadFile, String> {
let len = file.metadata().map_err(|e| e.to_string())?.len();
if range.0 >= range.1 || range.1 > len {
return Err("Invalid range".to_string());
}
Ok(ChunkedReadFile {
size: range.1,
offset: range.0,
cpu_pool: pool,
file: Some(file),
fut: None,
counter: 0,
})
}
}
impl Stream for ChunkedReadFile {
type Item = Bytes;
type Error = String;
fn poll(&mut self) -> Poll<Option<Bytes>, String> {
use std::io::Read;
if self.fut.is_some() {
return match self
.fut
.as_mut()
.unwrap()
.poll()
.map_err(|e| e.to_string())?
{
Async::Ready((file, bytes)) => {
self.fut.take();
self.file = Some(file);
self.offset += bytes.len() as u64;
self.counter += bytes.len() as u64;
Ok(Async::Ready(Some(bytes)))
}
Async::NotReady => Ok(Async::NotReady),
};
}
let size = self.size;
let offset = self.offset;
let counter = self.counter;
if size == counter {
Ok(Async::Ready(None))
} else {
let mut file = self.file.take().expect("Use after completion");
self.fut = Some(self.cpu_pool.spawn_fn(move || {
let max_bytes: usize;
max_bytes = cmp::min(size.saturating_sub(counter), 65_536) as usize;
let mut buf = Vec::with_capacity(max_bytes);
file.seek(io::SeekFrom::Start(offset))?;
let nbytes = io::Read::by_ref(&mut file)
.take(max_bytes as u64)
.read_to_end(&mut buf)?;
if nbytes == 0 {
return Err(io::ErrorKind::UnexpectedEof.into());
}
Ok((file, Bytes::from(buf)))
}));
self.poll()
}
}
}
pub fn untgz_async<P: AsRef<Path> + ToOwned>(
input_path: P,
output_path: P,
) -> impl Future<Item = (), Error = String> {
future::result(File::open(input_path))
.map_err(|e| e.to_string())
.and_then(|file| {
let decoder = GzDecoder::new(file);
let archive = Archive::new(decoder);
FILE_HANDLER.untar_archive(archive, output_path)
})
}
#[cfg(test)]
mod tests {
use actix::{Arbiter, System};
use bytes::Bytes;
use files::write_async_with_sha1;
use futures::{prelude::*, stream};
use std::path::PathBuf;
#[test]
#[ignore]
fn it_works() {
let stream = stream::iter_ok::<_, ()>(1..300).map(|a| Bytes::from(format!("{:?} ", a)));
let _ = System::run(|| {
Arbiter::spawn(
write_async_with_sha1(stream, PathBuf::from("Hello World!")).then(|r| {
println!("{:?}", r);
Ok(System::current().stop())
}),
)
});
}
}