-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfiles.patch
More file actions
840 lines (795 loc) · 34.6 KB
/
files.patch
File metadata and controls
840 lines (795 loc) · 34.6 KB
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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
diff --git a/crates/openfiles-cli/src/main.rs b/crates/openfiles-cli/src/main.rs
index f3040e8..f662825 100644
--- a/crates/openfiles-cli/src/main.rs
+++ b/crates/openfiles-cli/src/main.rs
@@ -61,7 +61,9 @@ fn load_config(path: Option<PathBuf>) -> Result<OpenFilesConfig> {
async fn engine(config: OpenFilesConfig) -> Result<OpenFilesEngine> {
let backend = build_backend(&config.backend)?;
- OpenFilesEngine::new(config, backend).await.map_err(Into::into)
+ OpenFilesEngine::new(config, backend)
+ .await
+ .map_err(Into::into)
}
#[tokio::main]
diff --git a/crates/openfiles-core/src/backend/local.rs b/crates/openfiles-core/src/backend/local.rs
index 94f6a24..63a2c65 100644
--- a/crates/openfiles-core/src/backend/local.rs
+++ b/crates/openfiles-core/src/backend/local.rs
@@ -4,7 +4,11 @@ use crate::types::{normalize_path, now_ns, FileKind};
use async_trait::async_trait;
use bytes::Bytes;
use sha2::{Digest, Sha256};
-use std::{collections::HashMap, ops::Range, path::{Path, PathBuf}};
+use std::{
+ collections::HashMap,
+ ops::Range,
+ path::{Path, PathBuf},
+};
use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
#[derive(Clone, Debug)]
@@ -28,7 +32,12 @@ impl LocalFsBackend {
hex::encode(h.finalize())
}
- fn walk(root: &Path, base: &Path, prefix: &str, out: &mut Vec<ObjectMeta>) -> std::io::Result<()> {
+ fn walk(
+ root: &Path,
+ base: &Path,
+ prefix: &str,
+ out: &mut Vec<ObjectMeta>,
+ ) -> std::io::Result<()> {
if !base.exists() {
return Ok(());
}
@@ -104,7 +113,12 @@ impl ObjectBackend for LocalFsBackend {
Ok(Bytes::from(buf))
}
- async fn write(&self, key: &str, data: Bytes, _metadata: HashMap<String, String>) -> Result<ObjectVersion> {
+ async fn write(
+ &self,
+ key: &str,
+ data: Bytes,
+ _metadata: HashMap<String, String>,
+ ) -> Result<ObjectVersion> {
let path = self.full_path(key)?;
if let Some(parent) = path.parent() {
tokio::fs::create_dir_all(parent).await?;
@@ -144,7 +158,8 @@ impl ObjectBackend for LocalFsBackend {
async fn list(&self, prefix: &str) -> Result<Vec<ObjectMeta>> {
let root = self.root.clone();
- let prefix = normalize_path(prefix).unwrap_or_else(|_| prefix.trim_start_matches('/').to_string());
+ let prefix =
+ normalize_path(prefix).unwrap_or_else(|_| prefix.trim_start_matches('/').to_string());
tokio::task::spawn_blocking(move || {
let mut out = Vec::new();
Self::walk(&root, &root, &prefix, &mut out)?;
diff --git a/crates/openfiles-core/src/backend/mod.rs b/crates/openfiles-core/src/backend/mod.rs
index 8ec0373..6230c34 100644
--- a/crates/openfiles-core/src/backend/mod.rs
+++ b/crates/openfiles-core/src/backend/mod.rs
@@ -37,7 +37,12 @@ pub trait ObjectBackend: Send + Sync + 'static {
async fn head(&self, key: &str) -> Result<Option<ObjectMeta>>;
async fn read(&self, key: &str) -> Result<Bytes>;
async fn read_range(&self, key: &str, range: Range<u64>) -> Result<Bytes>;
- async fn write(&self, key: &str, data: Bytes, metadata: HashMap<String, String>) -> Result<ObjectVersion>;
+ async fn write(
+ &self,
+ key: &str,
+ data: Bytes,
+ metadata: HashMap<String, String>,
+ ) -> Result<ObjectVersion>;
async fn delete(&self, key: &str) -> Result<()>;
async fn copy(&self, from: &str, to: &str) -> Result<()>;
async fn list(&self, prefix: &str) -> Result<Vec<ObjectMeta>>;
diff --git a/crates/openfiles-core/src/backend/opendal_backend.rs b/crates/openfiles-core/src/backend/opendal_backend.rs
index fa5f5e7..e9a1405 100644
--- a/crates/openfiles-core/src/backend/opendal_backend.rs
+++ b/crates/openfiles-core/src/backend/opendal_backend.rs
@@ -18,7 +18,11 @@ impl OpendalBackend {
}
fn meta_from_entry(path: String, meta: opendal::Metadata) -> ObjectMeta {
- let kind = if meta.is_dir() { FileKind::Directory } else { FileKind::File };
+ let kind = if meta.is_dir() {
+ FileKind::Directory
+ } else {
+ FileKind::File
+ };
ObjectMeta {
key: path,
size: meta.content_length(),
@@ -51,7 +55,12 @@ impl ObjectBackend for OpendalBackend {
Ok(Bytes::from(data.to_vec()))
}
- async fn write(&self, key: &str, data: Bytes, _metadata: HashMap<String, String>) -> Result<ObjectVersion> {
+ async fn write(
+ &self,
+ key: &str,
+ data: Bytes,
+ _metadata: HashMap<String, String>,
+ ) -> Result<ObjectVersion> {
self.op.write(key, data.to_vec()).await?;
let head = self.head(key).await?;
Ok(ObjectVersion {
diff --git a/crates/openfiles-core/src/cache.rs b/crates/openfiles-core/src/cache.rs
index 3acceed..21b8fa7 100644
--- a/crates/openfiles-core/src/cache.rs
+++ b/crates/openfiles-core/src/cache.rs
@@ -226,7 +226,12 @@ impl Cache {
}
}
- pub async fn mark_clean(&self, path: &str, etag: Option<String>, version: Option<String>) -> Result<()> {
+ pub async fn mark_clean(
+ &self,
+ path: &str,
+ etag: Option<String>,
+ version: Option<String>,
+ ) -> Result<()> {
let mut entry = self
.get(path)
.ok_or_else(|| OpenFilesError::NotFound(path.to_string()))?;
diff --git a/crates/openfiles-core/src/engine.rs b/crates/openfiles-core/src/engine.rs
index 3b35751..3fb47f5 100644
--- a/crates/openfiles-core/src/engine.rs
+++ b/crates/openfiles-core/src/engine.rs
@@ -2,7 +2,9 @@ use crate::backend::{ObjectBackend, ObjectMeta};
use crate::cache::{Cache, CacheEntry};
use crate::config::OpenFilesConfig;
use crate::error::{OpenFilesError, Result};
-use crate::metadata::{decode_user_metadata, encode_user_metadata, is_internal_key, sidecar_key, SidecarMetadata};
+use crate::metadata::{
+ decode_user_metadata, encode_user_metadata, is_internal_key, sidecar_key, SidecarMetadata,
+};
use crate::types::{
dir_prefix, display_path, file_name, normalize_path, now_ns, DirEntry, FileKind, FileStat,
ImportDataRule, ImportTrigger, PosixMetadata,
@@ -46,7 +48,10 @@ impl OpenFilesEngine {
fn path_from_key(&self, key: &str) -> String {
let prefix = self.config.normalized_prefix();
- key.strip_prefix(&prefix).unwrap_or(key).trim_matches('/').to_string()
+ key.strip_prefix(&prefix)
+ .unwrap_or(key)
+ .trim_matches('/')
+ .to_string()
}
fn matching_import_rule(&self, path: &str) -> ImportDataRule {
@@ -83,14 +88,17 @@ impl OpenFilesEngine {
async fn write_sidecar(&self, key: &str, posix: PosixMetadata) -> Result<()> {
let side = sidecar_key(key);
let bytes = serde_json::to_vec_pretty(&SidecarMetadata::new(posix))?;
- self.backend.write(&side, Bytes::from(bytes), HashMap::new()).await?;
+ self.backend
+ .write(&side, Bytes::from(bytes), HashMap::new())
+ .await?;
Ok(())
}
async fn import_meta_from_object(&self, path: &str, obj: &ObjectMeta) -> Result<CacheEntry> {
let posix = match self.read_sidecar(&obj.key, path).await? {
Some(m) => m,
- None => decode_user_metadata(path, &obj.metadata).unwrap_or_else(|| PosixMetadata::new_file(path)),
+ None => decode_user_metadata(path, &obj.metadata)
+ .unwrap_or_else(|| PosixMetadata::new_file(path)),
};
let mut entry = CacheEntry::from_posix(path.to_string(), obj.key.clone(), posix, obj.size);
entry.etag = obj.etag.clone();
@@ -172,7 +180,9 @@ impl OpenFilesEngine {
dirs.insert(child_path);
} else {
let entry = self.import_meta_from_object(&rel, &obj).await?;
- if rule.trigger == ImportTrigger::OnDirectoryFirstAccess && obj.size < rule.size_less_than {
+ if rule.trigger == ImportTrigger::OnDirectoryFirstAccess
+ && obj.size < rule.size_less_than
+ {
if !entry.cached_data {
let data = self.backend.read(&obj.key).await?;
let mut cached = entry.clone();
@@ -206,7 +216,11 @@ impl OpenFilesEngine {
continue;
}
if let Some((dir, _)) = child_rel.split_once('/') {
- let child_path = if normalized.is_empty() { dir.to_string() } else { format!("{normalized}/{dir}") };
+ let child_path = if normalized.is_empty() {
+ dir.to_string()
+ } else {
+ format!("{normalized}/{dir}")
+ };
dirs.insert(child_path);
} else {
files.insert(
@@ -254,10 +268,15 @@ impl OpenFilesEngine {
}
let rule = self.matching_import_rule(&normalized);
- if len >= self.config.cache.direct_read_threshold_bytes || stat.size >= self.config.cache.direct_read_threshold_bytes {
+ if len >= self.config.cache.direct_read_threshold_bytes
+ || stat.size >= self.config.cache.direct_read_threshold_bytes
+ {
if rule.trigger == ImportTrigger::OnFileAccess && stat.size < rule.size_less_than {
let all = self.backend.read(&key).await?;
- let mut entry = self.cache.get(&normalized).ok_or_else(|| OpenFilesError::NotFound(path.to_string()))?;
+ let mut entry = self
+ .cache
+ .get(&normalized)
+ .ok_or_else(|| OpenFilesError::NotFound(path.to_string()))?;
self.cache.write_data(&key, all.clone()).await?;
entry.cached_data = true;
entry.last_access_ns = now_ns();
@@ -268,7 +287,10 @@ impl OpenFilesEngine {
}
let all = self.backend.read(&key).await?;
- let mut entry = self.cache.get(&normalized).ok_or_else(|| OpenFilesError::NotFound(path.to_string()))?;
+ let mut entry = self
+ .cache
+ .get(&normalized)
+ .ok_or_else(|| OpenFilesError::NotFound(path.to_string()))?;
self.cache.write_data(&key, all.clone()).await?;
entry.cached_data = true;
entry.last_access_ns = now_ns();
@@ -289,7 +311,8 @@ impl OpenFilesEngine {
let key = self.key_for_path(&normalized)?;
let head = self.backend.head(&key).await?;
let posix = PosixMetadata::new_file(display_path(&normalized));
- let mut entry = CacheEntry::from_posix(normalized.clone(), key.clone(), posix, data.len() as u64);
+ let mut entry =
+ CacheEntry::from_posix(normalized.clone(), key.clone(), posix, data.len() as u64);
entry.cached_data = true;
entry.dirty = true;
entry.base_etag = head.as_ref().and_then(|h| h.etag.clone());
@@ -308,7 +331,12 @@ impl OpenFilesEngine {
let normalized = normalize_path(path)?;
let key = self.key_for_path(&normalized)?;
let mut entry = self.cache.get(&normalized).unwrap_or_else(|| {
- let mut e = CacheEntry::from_posix(normalized.clone(), key.clone(), PosixMetadata::new_file(display_path(&normalized)), 0);
+ let mut e = CacheEntry::from_posix(
+ normalized.clone(),
+ key.clone(),
+ PosixMetadata::new_file(display_path(&normalized)),
+ 0,
+ );
e.base_etag = None;
e.base_version = None;
e
@@ -329,8 +357,17 @@ impl OpenFilesEngine {
if from_stat.kind == FileKind::Directory {
let entries = self.list_dir(&from_norm).await?;
for child in entries {
- let rel = child.path.trim_start_matches('/').strip_prefix(&from_norm).unwrap_or("").trim_start_matches('/');
- let target = if rel.is_empty() { to_norm.clone() } else { format!("{to_norm}/{rel}") };
+ let rel = child
+ .path
+ .trim_start_matches('/')
+ .strip_prefix(&from_norm)
+ .unwrap_or("")
+ .trim_start_matches('/');
+ let target = if rel.is_empty() {
+ to_norm.clone()
+ } else {
+ format!("{to_norm}/{rel}")
+ };
self.rename_path(&child.path, &target).await?;
}
return Ok(());
@@ -356,7 +393,9 @@ impl OpenFilesEngine {
let remote_changed = match (&head, &entry.base_etag, &entry.base_version) {
(Some(h), Some(base), _) if h.etag.as_ref() != Some(base) => true,
(Some(h), _, Some(base)) if h.version.as_ref() != Some(base) => true,
- (Some(_), None, None) if entry.base_etag.is_none() && entry.base_version.is_none() => false,
+ (Some(_), None, None) if entry.base_etag.is_none() && entry.base_version.is_none() => {
+ false
+ }
_ => false,
};
if remote_changed {
@@ -428,7 +467,12 @@ impl OpenFilesEngine {
}
pub async fn expire_cache(&self) -> Result<u64> {
- let days = self.config.sync.expiration.days_after_last_access.clamp(1, 365) as u128;
+ let days = self
+ .config
+ .sync
+ .expiration
+ .days_after_last_access
+ .clamp(1, 365) as u128;
let cutoff = now_ns().saturating_sub(days * 24 * 60 * 60 * 1_000_000_000u128);
self.cache.expire_data_older_than_ns(cutoff).await
}
diff --git a/crates/openfiles-core/src/vendor.rs b/crates/openfiles-core/src/vendor.rs
index 2ed8ac8..7d9af7f 100644
--- a/crates/openfiles-core/src/vendor.rs
+++ b/crates/openfiles-core/src/vendor.rs
@@ -52,7 +52,11 @@ fn build_opendal_backend(config: &BackendConfig) -> Result<Arc<dyn ObjectBackend
}
let operator = match config.provider {
- ProviderKind::AwsS3 | ProviderKind::S3Compatible | ProviderKind::Storj | ProviderKind::Minio | ProviderKind::NetappStorageGrid => {
+ ProviderKind::AwsS3
+ | ProviderKind::S3Compatible
+ | ProviderKind::Storj
+ | ProviderKind::Minio
+ | ProviderKind::NetappStorageGrid => {
let mut builder = services::S3::default();
apply_s3_common(&mut builder, config);
Operator::new(builder)?.finish()
diff --git a/crates/openfiles-core/tests/local_engine.rs b/crates/openfiles-core/tests/local_engine.rs
index 1ecfe8b..7a5b400 100644
--- a/crates/openfiles-core/tests/local_engine.rs
+++ b/crates/openfiles-core/tests/local_engine.rs
@@ -12,11 +12,17 @@ async fn write_flush_list_and_read_local_backend() {
let backend = build_backend(&cfg.backend).unwrap();
let engine = OpenFilesEngine::new(cfg, backend).await.unwrap();
- engine.write_file("/a/b/hello.txt", Bytes::from_static(b"hello")).await.unwrap();
+ engine
+ .write_file("/a/b/hello.txt", Bytes::from_static(b"hello"))
+ .await
+ .unwrap();
let entries = engine.list_dir("/a/b").await.unwrap();
assert_eq!(entries.len(), 1);
assert_eq!(entries[0].path, "/a/b/hello.txt");
- assert_eq!(engine.read_all("/a/b/hello.txt").await.unwrap(), Bytes::from_static(b"hello"));
+ assert_eq!(
+ engine.read_all("/a/b/hello.txt").await.unwrap(),
+ Bytes::from_static(b"hello")
+ );
}
#[tokio::test]
@@ -29,8 +35,14 @@ async fn rename_is_copy_delete_semantics() {
let backend = build_backend(&cfg.backend).unwrap();
let engine = OpenFilesEngine::new(cfg, backend).await.unwrap();
- engine.write_file("/old.txt", Bytes::from_static(b"data")).await.unwrap();
+ engine
+ .write_file("/old.txt", Bytes::from_static(b"data"))
+ .await
+ .unwrap();
engine.rename_path("/old.txt", "/new.txt").await.unwrap();
assert!(engine.stat("/old.txt").await.is_err());
- assert_eq!(engine.read_all("/new.txt").await.unwrap(), Bytes::from_static(b"data"));
+ assert_eq!(
+ engine.read_all("/new.txt").await.unwrap(),
+ Bytes::from_static(b"data")
+ );
}
diff --git a/crates/openfiles-fuse/src/main.rs b/crates/openfiles-fuse/src/main.rs
index 9bc526f..eeb7291 100644
--- a/crates/openfiles-fuse/src/main.rs
+++ b/crates/openfiles-fuse/src/main.rs
@@ -15,7 +15,9 @@ struct Args {
#[tokio::main]
async fn main() -> Result<()> {
tracing_subscriber::fmt()
- .with_env_filter(std::env::var("RUST_LOG").unwrap_or_else(|_| "openfiles_fuse=info".to_string()))
+ .with_env_filter(
+ std::env::var("RUST_LOG").unwrap_or_else(|_| "openfiles_fuse=info".to_string()),
+ )
.init();
let args = Args::parse();
let config = OpenFilesConfig::from_toml_file(&args.config)
@@ -56,7 +58,10 @@ async fn mount(engine: OpenFilesEngine, mountpoint: PathBuf, foreground: bool) -
#[cfg(feature = "fuse")]
mod fuse_impl {
use bytes::Bytes;
- use fuser::{FileAttr, FileType, Filesystem, ReplyAttr, ReplyCreate, ReplyData, ReplyDirectory, ReplyEmpty, ReplyEntry, ReplyOpen, ReplyWrite, Request};
+ use fuser::{
+ FileAttr, FileType, Filesystem, ReplyAttr, ReplyCreate, ReplyData, ReplyDirectory,
+ ReplyEmpty, ReplyEntry, ReplyOpen, ReplyWrite, Request,
+ };
use openfiles_core::{DirEntry, FileKind, FileStat, OpenFilesEngine};
use std::collections::HashMap;
use std::ffi::OsStr;
@@ -107,7 +112,11 @@ mod fuse_impl {
fn join(parent: &str, name: &OsStr) -> String {
let name = name.to_string_lossy();
- if parent == "/" { format!("/{name}") } else { format!("{parent}/{name}") }
+ if parent == "/" {
+ format!("/{name}")
+ } else {
+ format!("{parent}/{name}")
+ }
}
fn attr(&self, stat: FileStat) -> FileAttr {
@@ -117,8 +126,10 @@ mod fuse_impl {
FileKind::File => FileType::RegularFile,
FileKind::Symlink => FileType::Symlink,
};
- let mtime = UNIX_EPOCH + Duration::from_nanos(stat.mtime_ns.min(u64::MAX as u128) as u64);
- let ctime = UNIX_EPOCH + Duration::from_nanos(stat.ctime_ns.min(u64::MAX as u128) as u64);
+ let mtime =
+ UNIX_EPOCH + Duration::from_nanos(stat.mtime_ns.min(u64::MAX as u128) as u64);
+ let ctime =
+ UNIX_EPOCH + Duration::from_nanos(stat.ctime_ns.min(u64::MAX as u128) as u64);
FileAttr {
ino,
size: stat.size,
@@ -129,7 +140,11 @@ mod fuse_impl {
crtime: ctime,
kind,
perm: (stat.mode & 0o7777) as u16,
- nlink: if matches!(stat.kind, FileKind::Directory) { 2 } else { 1 },
+ nlink: if matches!(stat.kind, FileKind::Directory) {
+ 2
+ } else {
+ 1
+ },
uid: stat.uid,
gid: stat.gid,
rdev: 0,
@@ -148,7 +163,10 @@ mod fuse_impl {
impl Filesystem for OpenFilesFuse {
fn lookup(&mut self, _req: &Request<'_>, parent: u64, name: &OsStr, reply: ReplyEntry) {
- let Some(parent_path) = self.path_for(parent) else { reply.error(libc::ENOENT); return; };
+ let Some(parent_path) = self.path_for(parent) else {
+ reply.error(libc::ENOENT);
+ return;
+ };
let path = Self::join(&parent_path, name);
match self.entry_attr(&path) {
Some(attr) => reply.entry(&TTL, &attr, 0),
@@ -157,22 +175,38 @@ mod fuse_impl {
}
fn getattr(&mut self, _req: &Request<'_>, ino: u64, _fh: Option<u64>, reply: ReplyAttr) {
- let Some(path) = self.path_for(ino) else { reply.error(libc::ENOENT); return; };
+ let Some(path) = self.path_for(ino) else {
+ reply.error(libc::ENOENT);
+ return;
+ };
match self.entry_attr(&path) {
Some(attr) => reply.attr(&TTL, &attr),
None => reply.error(libc::ENOENT),
}
}
- fn readdir(&mut self, _req: &Request<'_>, ino: u64, _fh: u64, offset: i64, mut reply: ReplyDirectory) {
- let Some(path) = self.path_for(ino) else { reply.error(libc::ENOENT); return; };
+ fn readdir(
+ &mut self,
+ _req: &Request<'_>,
+ ino: u64,
+ _fh: u64,
+ offset: i64,
+ mut reply: ReplyDirectory,
+ ) {
+ let Some(path) = self.path_for(ino) else {
+ reply.error(libc::ENOENT);
+ return;
+ };
if offset == 0 {
let _ = reply.add(ino, 1, FileType::Directory, ".");
let _ = reply.add(1, 2, FileType::Directory, "..");
}
let entries: Vec<DirEntry> = match self.rt.block_on(self.engine.list_dir(&path)) {
Ok(v) => v,
- Err(_) => { reply.error(libc::ENOENT); return; }
+ Err(_) => {
+ reply.error(libc::ENOENT);
+ return;
+ }
};
for (i, entry) in entries.into_iter().enumerate().skip(offset.max(0) as usize) {
let ino = self.ino_for(&entry.path);
@@ -181,7 +215,9 @@ mod fuse_impl {
FileKind::File => FileType::RegularFile,
FileKind::Symlink => FileType::Symlink,
};
- if reply.add(ino, (i + 3) as i64, ty, entry.name) { break; }
+ if reply.add(ino, (i + 3) as i64, ty, entry.name) {
+ break;
+ }
}
reply.ok();
}
@@ -190,34 +226,91 @@ mod fuse_impl {
reply.opened(0, 0);
}
- fn read(&mut self, _req: &Request<'_>, ino: u64, _fh: u64, offset: i64, size: u32, _flags: i32, _lock_owner: Option<u64>, reply: ReplyData) {
- let Some(path) = self.path_for(ino) else { reply.error(libc::ENOENT); return; };
- match self.rt.block_on(self.engine.read_range(&path, offset.max(0) as u64, size as u64)) {
+ fn read(
+ &mut self,
+ _req: &Request<'_>,
+ ino: u64,
+ _fh: u64,
+ offset: i64,
+ size: u32,
+ _flags: i32,
+ _lock_owner: Option<u64>,
+ reply: ReplyData,
+ ) {
+ let Some(path) = self.path_for(ino) else {
+ reply.error(libc::ENOENT);
+ return;
+ };
+ match self.rt.block_on(
+ self.engine
+ .read_range(&path, offset.max(0) as u64, size as u64),
+ ) {
Ok(bytes) => reply.data(&bytes),
Err(_) => reply.error(libc::EIO),
}
}
- fn write(&mut self, _req: &Request<'_>, ino: u64, _fh: u64, offset: i64, data: &[u8], _write_flags: u32, _flags: i32, _lock_owner: Option<u64>, reply: ReplyWrite) {
- let Some(path) = self.path_for(ino) else { reply.error(libc::ENOENT); return; };
+ fn write(
+ &mut self,
+ _req: &Request<'_>,
+ ino: u64,
+ _fh: u64,
+ offset: i64,
+ data: &[u8],
+ _write_flags: u32,
+ _flags: i32,
+ _lock_owner: Option<u64>,
+ reply: ReplyWrite,
+ ) {
+ let Some(path) = self.path_for(ino) else {
+ reply.error(libc::ENOENT);
+ return;
+ };
let existing = if offset > 0 {
- self.rt.block_on(self.engine.read_all(&path)).unwrap_or_default().to_vec()
- } else { Vec::new() };
+ self.rt
+ .block_on(self.engine.read_all(&path))
+ .unwrap_or_default()
+ .to_vec()
+ } else {
+ Vec::new()
+ };
let mut merged = existing;
let start = offset.max(0) as usize;
- if merged.len() < start { merged.resize(start, 0); }
- if merged.len() < start + data.len() { merged.resize(start + data.len(), 0); }
+ if merged.len() < start {
+ merged.resize(start, 0);
+ }
+ if merged.len() < start + data.len() {
+ merged.resize(start + data.len(), 0);
+ }
merged[start..start + data.len()].copy_from_slice(data);
- match self.rt.block_on(self.engine.write_file(&path, Bytes::from(merged))) {
+ match self
+ .rt
+ .block_on(self.engine.write_file(&path, Bytes::from(merged)))
+ {
Ok(()) => reply.written(data.len() as u32),
Err(_) => reply.error(libc::EIO),
}
}
- fn create(&mut self, _req: &Request<'_>, parent: u64, name: &OsStr, _mode: u32, _umask: u32, _flags: i32, reply: ReplyCreate) {
- let Some(parent_path) = self.path_for(parent) else { reply.error(libc::ENOENT); return; };
+ fn create(
+ &mut self,
+ _req: &Request<'_>,
+ parent: u64,
+ name: &OsStr,
+ _mode: u32,
+ _umask: u32,
+ _flags: i32,
+ reply: ReplyCreate,
+ ) {
+ let Some(parent_path) = self.path_for(parent) else {
+ reply.error(libc::ENOENT);
+ return;
+ };
let path = Self::join(&parent_path, name);
- match self.rt.block_on(self.engine.write_file(&path, Bytes::new())) {
+ match self
+ .rt
+ .block_on(self.engine.write_file(&path, Bytes::new()))
+ {
Ok(()) => match self.entry_attr(&path) {
Some(attr) => reply.created(&TTL, &attr, 0, 0, 0),
None => reply.error(libc::EIO),
@@ -227,7 +320,10 @@ mod fuse_impl {
}
fn unlink(&mut self, _req: &Request<'_>, parent: u64, name: &OsStr, reply: ReplyEmpty) {
- let Some(parent_path) = self.path_for(parent) else { reply.error(libc::ENOENT); return; };
+ let Some(parent_path) = self.path_for(parent) else {
+ reply.error(libc::ENOENT);
+ return;
+ };
let path = Self::join(&parent_path, name);
match self.rt.block_on(self.engine.delete_path(&path)) {
Ok(()) => reply.ok(),
@@ -235,9 +331,24 @@ mod fuse_impl {
}
}
- fn rename(&mut self, _req: &Request<'_>, parent: u64, name: &OsStr, newparent: u64, newname: &OsStr, _flags: u32, reply: ReplyEmpty) {
- let Some(parent_path) = self.path_for(parent) else { reply.error(libc::ENOENT); return; };
- let Some(new_parent_path) = self.path_for(newparent) else { reply.error(libc::ENOENT); return; };
+ fn rename(
+ &mut self,
+ _req: &Request<'_>,
+ parent: u64,
+ name: &OsStr,
+ newparent: u64,
+ newname: &OsStr,
+ _flags: u32,
+ reply: ReplyEmpty,
+ ) {
+ let Some(parent_path) = self.path_for(parent) else {
+ reply.error(libc::ENOENT);
+ return;
+ };
+ let Some(new_parent_path) = self.path_for(newparent) else {
+ reply.error(libc::ENOENT);
+ return;
+ };
let from = Self::join(&parent_path, name);
let to = Self::join(&new_parent_path, newname);
match self.rt.block_on(self.engine.rename_path(&from, &to)) {
@@ -246,7 +357,14 @@ mod fuse_impl {
}
}
- fn flush(&mut self, _req: &Request<'_>, _ino: u64, _fh: u64, _lock_owner: u64, reply: ReplyEmpty) {
+ fn flush(
+ &mut self,
+ _req: &Request<'_>,
+ _ino: u64,
+ _fh: u64,
+ _lock_owner: u64,
+ reply: ReplyEmpty,
+ ) {
match self.rt.block_on(self.engine.flush()) {
Ok(_) => reply.ok(),
Err(_) => reply.error(libc::EIO),
diff --git a/crates/openfiles-server/src/main.rs b/crates/openfiles-server/src/main.rs
index 43f1e78..be43615 100644
--- a/crates/openfiles-server/src/main.rs
+++ b/crates/openfiles-server/src/main.rs
@@ -8,7 +8,11 @@ use axum::{
Json, Router,
};
use clap::Parser;
-use openfiles_core::{sync::{spawn_background_sync, BackgroundSyncConfig}, vendor::build_backend, OpenFilesConfig, OpenFilesEngine};
+use openfiles_core::{
+ sync::{spawn_background_sync, BackgroundSyncConfig},
+ vendor::build_backend,
+ OpenFilesConfig, OpenFilesEngine,
+};
use serde::Deserialize;
use std::{net::SocketAddr, path::PathBuf, sync::Arc, time::Duration};
use tower_http::trace::TraceLayer;
@@ -38,7 +42,11 @@ impl IntoResponse for ApiError {
openfiles_core::OpenFilesError::Unsupported(_) => StatusCode::NOT_IMPLEMENTED,
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
- (status, Json(serde_json::json!({ "error": self.0.to_string() }))).into_response()
+ (
+ status,
+ Json(serde_json::json!({ "error": self.0.to_string() })),
+ )
+ .into_response()
}
}
@@ -59,22 +67,36 @@ async fn health() -> &'static str {
}
fn slash(path: String) -> String {
- if path.is_empty() { "/".to_string() } else { format!("/{path}") }
+ if path.is_empty() {
+ "/".to_string()
+ } else {
+ format!("/{path}")
+ }
}
-async fn stat(State(state): State<AppState>, Path(path): Path<String>) -> Result<Json<openfiles_core::FileStat>, ApiError> {
+async fn stat(
+ State(state): State<AppState>,
+ Path(path): Path<String>,
+) -> Result<Json<openfiles_core::FileStat>, ApiError> {
Ok(Json(state.engine.stat(&slash(path)).await?))
}
-async fn stat_root(State(state): State<AppState>) -> Result<Json<openfiles_core::FileStat>, ApiError> {
+async fn stat_root(
+ State(state): State<AppState>,
+) -> Result<Json<openfiles_core::FileStat>, ApiError> {
Ok(Json(state.engine.stat("/").await?))
}
-async fn list(State(state): State<AppState>, Path(path): Path<String>) -> Result<Json<Vec<openfiles_core::DirEntry>>, ApiError> {
+async fn list(
+ State(state): State<AppState>,
+ Path(path): Path<String>,
+) -> Result<Json<Vec<openfiles_core::DirEntry>>, ApiError> {
Ok(Json(state.engine.list_dir(&slash(path)).await?))
}
-async fn list_root(State(state): State<AppState>) -> Result<Json<Vec<openfiles_core::DirEntry>>, ApiError> {
+async fn list_root(
+ State(state): State<AppState>,
+) -> Result<Json<Vec<openfiles_core::DirEntry>>, ApiError> {
Ok(Json(state.engine.list_dir("/").await?))
}
@@ -101,18 +123,29 @@ async fn write_file(
Ok(Json(serde_json::json!({ "ok": true, "path": p })))
}
-async fn delete_file(State(state): State<AppState>, Path(path): Path<String>) -> Result<Json<serde_json::Value>, ApiError> {
+async fn delete_file(
+ State(state): State<AppState>,
+ Path(path): Path<String>,
+) -> Result<Json<serde_json::Value>, ApiError> {
let p = slash(path);
state.engine.delete_path(&p).await?;
Ok(Json(serde_json::json!({ "ok": true, "path": p })))
}
#[derive(Debug, Deserialize)]
-struct RenameBody { from: String, to: String }
+struct RenameBody {
+ from: String,
+ to: String,
+}
-async fn rename(State(state): State<AppState>, Json(body): Json<RenameBody>) -> Result<Json<serde_json::Value>, ApiError> {
+async fn rename(
+ State(state): State<AppState>,
+ Json(body): Json<RenameBody>,
+) -> Result<Json<serde_json::Value>, ApiError> {
state.engine.rename_path(&body.from, &body.to).await?;
- Ok(Json(serde_json::json!({ "ok": true, "from": body.from, "to": body.to })))
+ Ok(Json(
+ serde_json::json!({ "ok": true, "from": body.from, "to": body.to }),
+ ))
}
async fn flush(State(state): State<AppState>) -> Result<Json<serde_json::Value>, ApiError> {
@@ -128,7 +161,10 @@ async fn expire(State(state): State<AppState>) -> Result<Json<serde_json::Value>
#[tokio::main]
async fn main() -> Result<()> {
tracing_subscriber::fmt()
- .with_env_filter(std::env::var("RUST_LOG").unwrap_or_else(|_| "openfiles_server=info,tower_http=info".to_string()))
+ .with_env_filter(
+ std::env::var("RUST_LOG")
+ .unwrap_or_else(|_| "openfiles_server=info,tower_http=info".to_string()),
+ )
.init();
let args = Args::parse();
@@ -139,10 +175,15 @@ async fn main() -> Result<()> {
let flush_interval = Duration::from_secs(config.sync.export_batch_window_secs.max(1));
let _sync = spawn_background_sync(
engine.clone(),
- BackgroundSyncConfig { flush_interval, ..Default::default() },
+ BackgroundSyncConfig {
+ flush_interval,
+ ..Default::default()
+ },
);
- let state = AppState { engine: Arc::new(engine) };
+ let state = AppState {
+ engine: Arc::new(engine),
+ };
let app = Router::new()
.route("/healthz", get(health))
.route("/v1/stat", get(stat_root))
diff --git a/crates/openfiles-wasmcloud-host/src/main.rs b/crates/openfiles-wasmcloud-host/src/main.rs
index 8ca4a6a..35bcae5 100644
--- a/crates/openfiles-wasmcloud-host/src/main.rs
+++ b/crates/openfiles-wasmcloud-host/src/main.rs
@@ -25,13 +25,19 @@ enum Command {
/// Validate backend credentials and cache configuration.
Validate,
/// Print a wasmCloud manifest that mounts an OpenFiles volume into a component.
- Manifest { #[arg(long, default_value = "/mnt/openfiles")] mount: String },
+ Manifest {
+ #[arg(long, default_value = "/mnt/openfiles")]
+ mount: String,
+ },
}
#[tokio::main]
async fn main() -> Result<()> {
tracing_subscriber::fmt()
- .with_env_filter(std::env::var("RUST_LOG").unwrap_or_else(|_| "openfiles_wasmcloud_host=info".to_string()))
+ .with_env_filter(
+ std::env::var("RUST_LOG")
+ .unwrap_or_else(|_| "openfiles_wasmcloud_host=info".to_string()),
+ )
.init();
let args = Args::parse();
let config = OpenFilesConfig::from_toml_file(&args.config)
@@ -49,7 +55,8 @@ async fn main() -> Result<()> {
}
fn print_manifest(config: &OpenFilesConfig, mount: &str) {
- println!(r#"# Generated OpenFiles wasmCloud workload manifest excerpt.
+ println!(
+ r#"# Generated OpenFiles wasmCloud workload manifest excerpt.
# 1. Run openfiles-server or openfiles-fuse as a sidecar/init container.
# 2. Mount the resulting directory into the wasmCloud host.
# 3. Grant the component a WASI filesystem preopen at the same path.
@@ -95,5 +102,8 @@ spec:
env:
OPENFILES_MOUNT: "{mount}"
OPENFILES_FS_ID: "{fs_id}"
-"#, mount = mount, fs_id = config.fs_id);
+"#,
+ mount = mount,
+ fs_id = config.fs_id
+ );
}