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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
use std::collections::HashMap;
use std::fmt::Debug;
use std::fmt::Formatter;
use std::io::Result;
use std::path::PathBuf;
use std::sync::Arc;
use anyhow::anyhow;
use async_trait::async_trait;
use futures::io::AsyncReadExt;
use futures::io::Cursor;
use http::Uri;
use redis::aio::ConnectionManager;
use redis::AsyncCommands;
use redis::Client;
use redis::ConnectionAddr;
use redis::ConnectionInfo;
use redis::RedisConnectionInfo;
use time::OffsetDateTime;
use super::dir_stream::DirStream;
use super::error::new_async_connection_error;
use super::error::new_deserialize_metadata_error;
use super::error::new_exec_async_cmd_error;
use super::error::new_serialize_metadata_error;
use super::v0_children_prefix;
use super::v0_content_prefix;
use super::v0_meta_prefix;
use crate::error::new_other_backend_error;
use crate::error::new_other_object_error;
use crate::ops::OpCreate;
use crate::ops::OpDelete;
use crate::ops::OpList;
use crate::ops::OpRead;
use crate::ops::OpStat;
use crate::ops::OpWrite;
use crate::ops::Operation;
use crate::path::build_abs_path;
use crate::path::normalize_root;
use crate::Accessor;
use crate::BytesReader;
use crate::ObjectMetadata;
use crate::ObjectMode;
use crate::ObjectStreamer;
const DEFAULT_REDIS_ENDPOINT: &str = "tcp://127.0.0.1:6379";
const DEFAULT_REDIS_PORT: u16 = 6379;
#[derive(Clone, Default)]
pub struct Builder {
endpoint: Option<String>,
username: Option<String>,
password: Option<String>,
root: Option<String>,
db: i64,
}
impl Builder {
pub fn endpoint(&mut self, endpoint: &str) -> &mut Self {
if !endpoint.is_empty() {
self.endpoint = Some(endpoint.to_owned());
}
self
}
pub fn username(&mut self, username: &str) -> &mut Self {
if !username.is_empty() {
self.username = Some(username.to_owned());
}
self
}
pub fn password(&mut self, password: &str) -> &mut Self {
if !password.is_empty() {
self.password = Some(password.to_owned());
}
self
}
pub fn db(&mut self, db: i64) -> &mut Self {
self.db = db;
self
}
pub fn root(&mut self, root: &str) -> &mut Self {
if !root.is_empty() {
self.root = Some(root.to_owned());
}
self
}
pub fn build(&mut self) -> Result<Backend> {
let endpoint = self
.endpoint
.clone()
.unwrap_or_else(|| DEFAULT_REDIS_ENDPOINT.to_string());
let ep_url = endpoint.parse::<Uri>().map_err(|e| {
new_other_backend_error(
HashMap::from([("endpoint".to_string(), endpoint.clone())]),
anyhow!("endpoint is invalid: {:?}", e),
)
})?;
let con_addr = match ep_url.scheme_str() {
Some("tcp") | Some("redis") | None => {
let host = ep_url
.host()
.map(|h| h.to_string())
.unwrap_or_else(|| "127.0.0.1".to_string());
let port = ep_url.port_u16().unwrap_or(DEFAULT_REDIS_PORT);
ConnectionAddr::Tcp(host, port)
}
Some("unix") | Some("redis+unix") => {
let path = PathBuf::from(ep_url.path());
ConnectionAddr::Unix(path)
}
Some(s) => {
return Err(new_other_backend_error(
HashMap::from([("endpoint".to_string(), endpoint)]),
anyhow!("invalid or unsupported URL scheme: {}", s),
))
}
};
let redis_info = RedisConnectionInfo {
db: self.db,
username: self.username.clone(),
password: self.password.clone(),
};
let con_info = ConnectionInfo {
addr: con_addr,
redis: redis_info,
};
let client = Client::open(con_info).map_err(|e| {
new_other_backend_error(
HashMap::from([
("endpoint".to_string(), endpoint),
("db".to_string(), self.db.to_string()),
(
"username".to_string(),
self.username
.clone()
.unwrap_or_else(|| "<None>".to_string()),
),
]),
anyhow!("establish redis client error: {:?}", e),
)
})?;
let root = normalize_root(
self.root
.clone()
.unwrap_or_else(|| "/".to_string())
.as_str(),
);
Ok(Backend { client, root })
}
}
impl Debug for Builder {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let mut ds = f.debug_struct("Builder");
ds.field("db", &self.db.to_string());
ds.field("root", &self.root);
if let Some(endpoint) = self.endpoint.clone() {
ds.field("endpoint", &endpoint);
}
if let Some(username) = self.username.clone() {
ds.field("username", &username);
}
if self.password.is_some() {
ds.field("password", &"<redacted>");
}
ds.finish()
}
}
#[derive(Clone)]
pub struct Backend {
client: Client,
root: String,
}
impl Backend {
async fn remove(con: &mut ConnectionManager, abs_path: &str) -> Result<()> {
let m_path = v0_meta_prefix(abs_path);
let c_path = v0_content_prefix(abs_path);
let s_path = v0_children_prefix(abs_path);
con.del(&[m_path, c_path, s_path])
.await
.map_err(|err| new_exec_async_cmd_error(err, Operation::Delete, abs_path))
}
async fn mkdir_current(con: &mut ConnectionManager, to_create: &str, path: &str) -> Result<()> {
let metadata = ObjectMetadata::new(ObjectMode::DIR);
let to_create = if !to_create.ends_with('/') {
to_create.to_string() + "/"
} else {
to_create.to_string()
};
let path = path.to_string();
let bin = bincode::serialize(&metadata)
.map_err(|err| new_serialize_metadata_error(err, Operation::Create, path.as_str()))?;
let m_path = v0_meta_prefix(to_create.as_str());
con.set(m_path, bin)
.await
.map_err(|err| new_exec_async_cmd_error(err, Operation::Create, path.as_str()))?;
Ok(())
}
async fn mkdir(con: &mut ConnectionManager, to_create: &str, path: &str) -> Result<()> {
let path = path.to_string();
Backend::mkdir_current(con, to_create, path.as_str()).await?;
let mut current = to_create.to_string();
while let Some(parent) = PathBuf::from(current).parent() {
let p = parent.display().to_string() + "/";
let this_generation = v0_children_prefix(p.as_str());
con.sadd(this_generation, to_create)
.await
.map_err(|err| new_exec_async_cmd_error(err, Operation::Create, path.as_str()))?;
let parent_metadata_path = v0_meta_prefix(p.as_str());
if con
.exists(parent_metadata_path)
.await
.map_err(|err| new_exec_async_cmd_error(err, Operation::Create, path.as_str()))?
{
break;
}
Backend::mkdir_current(con, p.as_str(), path.as_str()).await?;
current = p;
}
Ok(())
}
}
impl Backend {
pub(crate) fn from_iter(it: impl Iterator<Item = (String, String)>) -> Result<Self> {
let mut builder = Builder::default();
for (k, v) in it {
let v = v.as_str();
match k.as_ref() {
"root" => builder.root(v),
"endpoint" => builder.endpoint(v),
"username" => builder.username(v),
"password" => builder.password(v),
"db" => match v.parse::<i64>() {
Ok(num) => builder.db(num),
_ => continue,
},
_ => continue,
};
}
builder.build()
}
}
impl Debug for Backend {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let mut ds = f.debug_struct("Backend");
ds.field("root", &self.root);
let info = self.client.get_connection_info();
ds.field("addr", &info.addr);
ds.field("db", &info.redis.db);
if let Some(username) = info.redis.username.clone() {
ds.field("user", &username);
}
if info.redis.password.is_some() {
ds.field("password", &"<redacted>");
}
ds.finish()
}
}
#[async_trait]
impl Accessor for Backend {
async fn create(&self, path: &str, args: OpCreate) -> Result<()> {
let mut path = path.to_string();
let mut con = self
.client
.get_tokio_connection_manager()
.await
.map_err(|e| new_async_connection_error(e, Operation::Create, path.as_str()))?;
let mut meta = ObjectMetadata::new(args.mode());
if args.mode() == ObjectMode::FILE {
let last_modified = OffsetDateTime::now_utc();
meta.set_last_modified(last_modified);
} else if args.mode() == ObjectMode::DIR && !path.ends_with('/') {
path += "/";
}
let abs_path = build_abs_path(self.root.as_str(), path.as_str());
let m_path = v0_meta_prefix(abs_path.as_str());
let bin = bincode::serialize(&meta)
.map_err(|err| new_serialize_metadata_error(err, Operation::Create, path.as_str()))?;
if let Some(parent) = PathBuf::from(abs_path).parent() {
let p = parent.display().to_string();
Backend::mkdir(&mut con, p.as_str(), path.as_str()).await?;
}
con.set(m_path, bin)
.await
.map_err(|err| new_exec_async_cmd_error(err, Operation::Write, path.as_str()))
}
async fn read(&self, path: &str, args: OpRead) -> Result<BytesReader> {
let c_path = v0_content_prefix(build_abs_path(self.root.as_str(), path).as_str());
let path = path.to_string();
let from = args.offset().map_or_else(|| 0, |offset| offset as isize);
let to = args.size().map_or_else(|| -1, |size| size as isize + from);
let mut con = self
.client
.get_tokio_connection_manager()
.await
.map_err(|e| new_async_connection_error(e, Operation::Read, path.as_str()))?;
let gr = con
.getrange::<&str, Vec<u8>>(c_path.as_str(), from, to)
.await
.map_err(|e| new_exec_async_cmd_error(e, Operation::Read, path.as_str()))?;
let cur = Cursor::new(gr);
Ok(Box::new(cur) as BytesReader)
}
async fn write(&self, path: &str, args: OpWrite, r: BytesReader) -> Result<u64> {
let abs_path = build_abs_path(self.root.as_str(), path);
let path = path.to_string();
if path.ends_with('/') {
return Err(new_other_object_error(
Operation::Write,
path.as_str(),
anyhow!("cannot write to directory"),
));
}
let mut con = self
.client
.get_tokio_connection_manager()
.await
.map_err(|e| new_async_connection_error(e, Operation::Write, path.as_str()))?;
let c_path = v0_content_prefix(abs_path.as_str());
let size = args.size();
let mut reader = r;
let mut buf = vec![];
let content_length = reader.read_to_end(&mut buf).await?;
con.set(c_path, buf)
.await
.map_err(|e| new_exec_async_cmd_error(e, Operation::Write, &path))?;
let m_path = v0_meta_prefix(abs_path.as_str());
let mut meta = ObjectMetadata::new(ObjectMode::FILE);
meta.set_content_length(content_length as u64);
meta.set_last_modified(OffsetDateTime::now_utc());
let bin = bincode::serialize(&meta)
.map_err(|e| new_serialize_metadata_error(e, Operation::Write, path.as_str()))?;
con.set(m_path, bin)
.await
.map_err(|e| new_exec_async_cmd_error(e, Operation::Write, path.as_str()))?;
Ok(size)
}
async fn stat(&self, path: &str, _args: OpStat) -> Result<ObjectMetadata> {
let abs_path = build_abs_path(self.root.as_str(), path);
let path = path.to_string();
let mut con = self
.client
.get_tokio_connection_manager()
.await
.map_err(|e| new_async_connection_error(e, Operation::Stat, path.as_str()))?;
let m_path = v0_meta_prefix(abs_path.as_str());
let bin: Vec<u8> = con
.get(m_path)
.await
.map_err(|e| new_exec_async_cmd_error(e, Operation::Stat, path.as_str()))?;
bincode::deserialize(&bin[..])
.map_err(|e| new_deserialize_metadata_error(e, Operation::Stat, path.as_str()))
}
async fn delete(&self, path: &str, _args: OpDelete) -> Result<()> {
let path = path.to_string();
let abs_path = build_abs_path(self.root.as_str(), path.as_str());
let mut con = self
.client
.get_tokio_connection_manager()
.await
.map_err(|err| new_async_connection_error(err, Operation::Delete, path.as_str()))?;
let children = v0_children_prefix(abs_path.as_str());
let mut child_iter = con
.sscan::<String, String>(children)
.await
.map_err(|err| new_exec_async_cmd_error(err, Operation::Delete, path.as_str()))?;
if child_iter.next_item().await.is_some() {
return Err(new_other_object_error(
Operation::Delete,
path.as_str(),
anyhow!("Directory not empty!"),
));
}
Backend::remove(&mut con, abs_path.as_str()).await?;
if let Some(parent) = PathBuf::from(abs_path.clone()).parent() {
let this_generation = v0_children_prefix(parent.display().to_string().as_str()) + "/";
con.srem(this_generation, &abs_path)
.await
.map_err(|err| new_exec_async_cmd_error(err, Operation::Delete, path.as_str()))?;
}
Ok(())
}
async fn list(&self, path: &str, _args: OpList) -> Result<ObjectStreamer> {
let path = build_abs_path(self.root.as_str(), path);
let con = self
.client
.get_tokio_connection_manager()
.await
.map_err(|err| new_exec_async_cmd_error(err, Operation::List, path.as_str()))?;
Ok(Box::new(DirStream::new(
Arc::new(self.clone()),
con,
path.as_str(),
)))
}
}
#[cfg(test)]
mod redis_test {
use time::OffsetDateTime;
use super::Builder;
use crate::ObjectMetadata;
use crate::ObjectMode;
const TIMESTAMP: i64 = 7355608;
const CONTENT_LENGTH: u64 = 123456;
#[test]
fn test_generate_bincode() {
let mut meta = ObjectMetadata::new(ObjectMode::DIR);
println!(
"serialized directory metadata: {:?}",
bincode::serialize(&meta).unwrap()
);
meta.set_mode(ObjectMode::FILE);
let datetime = OffsetDateTime::from_unix_timestamp(TIMESTAMP).unwrap();
meta.set_last_modified(datetime);
meta.set_content_length(CONTENT_LENGTH);
println!(
"serialized file metadata: {:?}",
bincode::serialize(&meta).unwrap()
);
}
#[test]
fn test_deserialize() {
let bin = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
let res = bincode::deserialize(&bin);
assert!(res.is_ok());
let meta: ObjectMetadata = res.unwrap();
assert_eq!(
meta.mode(),
ObjectMode::DIR,
"Got unexpected mode: {:?}",
meta.mode()
);
assert_eq!(
meta.last_modified(),
None,
"Got unexpected timestamp: {:?}",
meta.last_modified()
);
assert_eq!(
meta.content_length(),
0,
"Got unexpected content_length: {}",
meta.content_length()
);
assert_eq!(
meta.content_md5(),
None,
"Got unexpected content_md5: {:?}",
meta.content_md5()
);
assert_eq!(meta.etag(), None, "Got unexpected etag: {:?}", meta.etag());
let last_modified = OffsetDateTime::from_unix_timestamp(TIMESTAMP).unwrap();
let bin = [
0, 0, 0, 0, 64, 226, 1, 0, 0, 0, 0, 0, 0, 1, 178, 7, 0, 0, 86, 0, 3, 13, 28, 0, 0, 0,
0, 0, 0, 0, 0,
];
let res = bincode::deserialize(&bin);
assert!(res.is_ok());
let meta: ObjectMetadata = res.unwrap();
assert_eq!(
meta.mode(),
ObjectMode::FILE,
"Got unexpected mode: {:?}",
meta.mode()
);
assert_eq!(
meta.last_modified(),
Some(last_modified),
"Got unexpected timestamp: {:?}",
meta.last_modified()
);
assert_eq!(
meta.content_length(),
CONTENT_LENGTH,
"Got unexpected content_length: {}",
meta.content_length()
);
assert_eq!(
meta.content_md5(),
None,
"Got unexpected content_md5: {:?}",
meta.content_md5()
);
assert_eq!(meta.etag(), None, "Got unexpected etag: {:?}", meta.etag());
}
#[test]
fn test_parse_url() {
let invalid_scheme = "http://example.com";
let mut builder = Builder::default();
builder.endpoint(invalid_scheme);
let res = builder.build();
assert!(res.is_err());
}
}