Repository navigation
Expand file tree
/
Copy pathlocal.rs
More file actions
2343 lines (2034 loc) · 81.8 KB
/
Copy pathlocal.rs
File metadata and controls
2343 lines (2034 loc) · 81.8 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
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//! An object store implementation for a local filesystem
use std::fs::{File, Metadata, OpenOptions, metadata, symlink_metadata};
use std::io::{ErrorKind, Read, Seek, SeekFrom, Write};
use std::ops::Range;
#[cfg(target_family = "unix")]
use std::os::unix::fs::FileExt;
#[cfg(target_family = "windows")]
use std::os::windows::fs::FileExt;
use std::sync::Arc;
use std::time::SystemTime;
use std::{collections::BTreeSet, io};
use std::{collections::VecDeque, path::PathBuf};
use async_trait::async_trait;
use bytes::Bytes;
use chrono::{DateTime, Utc};
use futures_util::{FutureExt, TryStreamExt};
use futures_util::{StreamExt, stream::BoxStream};
use parking_lot::Mutex;
use url::Url;
use walkdir::{DirEntry, WalkDir};
use crate::{
Attributes, GetOptions, GetResult, GetResultPayload, ListResult, MultipartUpload, ObjectMeta,
ObjectStore, PutMode, PutMultipartOptions, PutOptions, PutPayload, PutResult, Result,
UploadPart, maybe_spawn_blocking,
path::{Path, absolute_path_to_url},
util::{InvalidGetRange, merge_ranges},
};
use crate::{CopyMode, CopyOptions, RenameOptions, RenameTargetMode};
/// A specialized `Error` for filesystem object store-related errors
#[derive(Debug, thiserror::Error)]
pub(crate) enum Error {
#[error("Unable to walk dir: {}", source)]
UnableToWalkDir { source: walkdir::Error },
#[error("Unable to access metadata for {}: {}", path, source)]
Metadata {
source: Box<dyn std::error::Error + Send + Sync + 'static>,
path: String,
},
#[error("Unable to copy data to file: {}", source)]
UnableToCopyDataToFile { source: io::Error },
#[error("Unable to rename file: {}", source)]
UnableToRenameFile { source: io::Error },
#[error("Unable to create dir {}: {}", path.display(), source)]
UnableToCreateDir { source: io::Error, path: PathBuf },
#[error("Unable to create file {}: {}", path.display(), source)]
UnableToCreateFile { source: io::Error, path: PathBuf },
#[error("Unable to delete file {}: {}", path.display(), source)]
UnableToDeleteFile { source: io::Error, path: PathBuf },
#[error("Unable to open file {}: {}", path.display(), source)]
UnableToOpenFile { source: io::Error, path: PathBuf },
#[error("Unable to read data from file {}: {}", path.display(), source)]
UnableToReadBytes { source: io::Error, path: PathBuf },
#[error("Out of range of file {}, expected: {}, actual: {}", path.display(), expected, actual)]
OutOfRange {
path: PathBuf,
expected: u64,
actual: u64,
},
#[error("Requested range was invalid")]
InvalidRange { source: InvalidGetRange },
#[error("Unable to copy file from {} to {}: {}", from.display(), to.display(), source)]
UnableToCopyFile {
from: PathBuf,
to: PathBuf,
source: io::Error,
},
#[error("NotFound")]
NotFound { path: PathBuf, source: io::Error },
#[error("Error seeking file {}: {}", path.display(), source)]
Seek { source: io::Error, path: PathBuf },
#[error("Unable to convert URL \"{}\" to filesystem path", url)]
InvalidUrl { url: Url },
#[error("AlreadyExists")]
AlreadyExists { path: String, source: io::Error },
#[error("Unable to canonicalize filesystem root: {}", path.display())]
UnableToCanonicalize { path: PathBuf, source: io::Error },
#[error("Filenames containing trailing '/#\\d+/' are not supported: {}", path)]
InvalidPath { path: String },
#[error("Unable to sync data to disk for {}: {}", path.display(), source)]
UnableToSyncFile { source: io::Error, path: PathBuf },
#[error("Upload aborted")]
Aborted,
}
impl From<Error> for super::Error {
fn from(source: Error) -> Self {
match source {
Error::NotFound { path, source } => Self::NotFound {
path: path.to_string_lossy().to_string(),
source: source.into(),
},
Error::AlreadyExists { path, source } => Self::AlreadyExists {
path,
source: source.into(),
},
_ => Self::Generic {
store: "LocalFileSystem",
source: Box::new(source),
},
}
}
}
/// Explicitly close a file, checking for errors that would be silently ignored by Rust's `File::drop()`.
///
/// On network filesystems (e.g. NFS), `close()` can fail and indicate data loss.
fn close_file(file: File) -> std::result::Result<(), io::Error> {
#[cfg(target_family = "unix")]
{
use std::os::fd::IntoRawFd;
close_fd(file.into_raw_fd())
}
#[cfg(target_family = "windows")]
{
use std::os::windows::io::IntoRawHandle;
close_handle(file.into_raw_handle())
}
#[cfg(not(any(target_family = "unix", target_family = "windows")))]
{
drop(file);
Ok(())
}
}
#[cfg(target_family = "unix")]
fn close_fd(fd: std::os::fd::RawFd) -> std::result::Result<(), io::Error> {
nix::unistd::close(fd).map_err(|e| e.into())
}
#[cfg(target_family = "windows")]
fn close_handle(handle: std::os::windows::io::RawHandle) -> std::result::Result<(), io::Error> {
// SAFETY: `handle` must be an owned handle, except when testing invalid handle errors.
match unsafe { windows_sys::Win32::Foundation::CloseHandle(handle) } {
0 => Err(io::Error::last_os_error()),
_ => Ok(()),
}
}
/// Local filesystem storage providing an [`ObjectStore`] interface to files on
/// local disk. Can optionally be created with a directory prefix
///
/// # Path Semantics
///
/// This implementation follows the [file URI] scheme outlined in [RFC 3986]. In
/// particular paths are delimited by `/`
///
/// [file URI]: https://en.wikipedia.org/wiki/File_URI_scheme
/// [RFC 3986]: https://www.rfc-editor.org/rfc/rfc3986
///
/// # Path Semantics
///
/// [`LocalFileSystem`] will expose the path semantics of the underlying filesystem, which may
/// have additional restrictions beyond those enforced by [`Path`].
///
/// For example:
///
/// * Windows forbids certain filenames, e.g. `COM0`,
/// * Windows forbids folders with trailing `.`
/// * Windows forbids certain ASCII characters, e.g. `<` or `|`
/// * OS X forbids filenames containing `:`
/// * Leading `-` are discouraged on Unix systems where they may be interpreted as CLI flags
/// * Filesystems may have restrictions on the maximum path or path segment length
/// * Filesystem support for non-ASCII characters is inconsistent
///
/// Additionally some filesystems, such as NTFS, are case-insensitive, whilst others like
/// FAT don't preserve case at all. Further some filesystems support non-unicode character
/// sequences, such as unpaired UTF-16 surrogates, and [`LocalFileSystem`] will error on
/// encountering such sequences.
///
/// Finally, filenames matching the regex `/.*#\d+/`, e.g. `foo.parquet#123`, are not supported
/// by [`LocalFileSystem`] as they are used to provide atomic writes. Such files will be ignored
/// for listing operations, and attempting to address such a file will error.
///
/// # Tokio Compatibility
///
/// Tokio discourages performing blocking IO on a tokio worker thread, however,
/// no major operating systems have stable async file APIs. Therefore if called from
/// a tokio context, this will use [`tokio::runtime::Handle::spawn_blocking`] to dispatch
/// IO to a blocking thread pool, much like `tokio::fs` does under-the-hood.
///
/// If not called from a tokio context, this will perform IO on the current thread with
/// no additional complexity or overheads
///
/// # Symlinks
///
/// [`LocalFileSystem`] will follow symlinks as normal, however, it is worth noting:
///
/// * Broken symlinks will be silently ignored by listing operations
/// * No effort is made to prevent breaking symlinks when deleting files
/// * Symlinks that resolve to paths outside the root **will** be followed
/// * Mutating a file through one or more symlinks will mutate the underlying file
/// * Deleting a path that resolves to a symlink will only delete the symlink
///
/// # Cross-Filesystem Copy
///
/// [`LocalFileSystem::copy_opts`] is implemented using [`std::fs::hard_link`], and therefore
/// does not support copying across filesystem boundaries.
///
#[derive(Clone, Debug)]
pub struct LocalFileSystem {
config: Arc<Config>,
// if you want to delete empty directories when deleting files
automatic_cleanup: bool,
// if true, fsync written files and their parent directories after writes
fsync: bool,
}
#[derive(Debug)]
struct Config {
root: Url,
}
impl std::fmt::Display for LocalFileSystem {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "LocalFileSystem({})", self.config.root)
}
}
impl Default for LocalFileSystem {
fn default() -> Self {
Self::new()
}
}
impl LocalFileSystem {
/// Create new filesystem storage with no prefix
pub fn new() -> Self {
Self {
config: Arc::new(Config {
root: Url::parse("file:///").unwrap(),
}),
automatic_cleanup: false,
fsync: false,
}
}
/// Create new filesystem storage with `prefix` applied to all paths
///
/// Returns an error if the path does not exist
///
pub fn new_with_prefix(prefix: impl AsRef<std::path::Path>) -> Result<Self> {
let path = std::fs::canonicalize(&prefix).map_err(|source| {
let path = prefix.as_ref().into();
Error::UnableToCanonicalize { source, path }
})?;
Ok(Self {
config: Arc::new(Config {
root: absolute_path_to_url(path)?,
}),
automatic_cleanup: false,
fsync: false,
})
}
/// Return an absolute filesystem path of the given file location
pub fn path_to_filesystem(&self, location: &Path) -> Result<PathBuf> {
self.config.path_to_filesystem(location)
}
/// Enable automatic cleanup of empty directories when deleting files
pub fn with_automatic_cleanup(mut self, automatic_cleanup: bool) -> Self {
self.automatic_cleanup = automatic_cleanup;
self
}
/// Enable `fsync` after writes for durability
///
/// When enabled, [`LocalFileSystem`] calls [`File::sync_all`] on written files and fsyncs
/// the affected parent directories before a write operation
/// ([`put_opts`](ObjectStore::put_opts), [`copy_opts`](ObjectStore::copy_opts),
/// [`rename_opts`](ObjectStore::rename_opts), and multipart upload completion) returns
/// success. This guarantees that both the file contents and the directory entries pointing
/// to them are durable on stable storage, matching the implicit durability contract of
/// remote object stores such as S3 or GCS.
///
/// This trades write throughput for durability and is **disabled by default**.
///
/// Note that directory fsync is only performed on Unix; on other platforms (e.g. Windows)
/// it is a no-op, as directories cannot be portably opened and synced.
pub fn with_fsync(mut self, fsync: bool) -> Self {
self.fsync = fsync;
self
}
}
impl Config {
/// Return an absolute filesystem path of the given location
fn prefix_to_filesystem(&self, location: &Path) -> Result<PathBuf> {
let mut url = self.root.clone();
url.path_segments_mut()
.expect("url path")
// technically not necessary as Path ignores empty segments
// but avoids creating paths with "//" which look odd in error messages.
.pop_if_empty()
.extend(location.parts());
url.to_file_path()
.map_err(|_| Error::InvalidUrl { url }.into())
}
/// Return an absolute filesystem path of the given file location
fn path_to_filesystem(&self, location: &Path) -> Result<PathBuf> {
if !is_valid_file_path(location) {
let path = location.as_ref().into();
let error = Error::InvalidPath { path };
return Err(error.into());
}
let path = self.prefix_to_filesystem(location)?;
#[cfg(target_os = "windows")]
let path = {
let path = path.to_string_lossy();
// Assume the first char is the drive letter and the next is a colon.
let mut out = String::new();
let drive = &path[..2]; // The drive letter and colon (e.g., "C:")
let filepath = &path[2..].replace(':', "%3A"); // Replace subsequent colons
out.push_str(drive);
out.push_str(filepath);
PathBuf::from(out)
};
Ok(path)
}
/// Resolves the provided absolute filesystem path to a [`Path`] prefix
fn filesystem_to_path(&self, location: &std::path::Path) -> Result<Path> {
Ok(Path::from_absolute_path_with_base(
location,
Some(&self.root),
)?)
}
}
fn is_valid_file_path(path: &Path) -> bool {
match path.filename() {
Some(p) => match p.split_once('#') {
Some((_, suffix)) if !suffix.is_empty() => {
// Valid if contains non-digits
!suffix.as_bytes().iter().all(|x| x.is_ascii_digit())
}
_ => true,
},
None => false,
}
}
#[async_trait]
impl ObjectStore for LocalFileSystem {
async fn put_opts(
&self,
location: &Path,
payload: PutPayload,
opts: PutOptions,
) -> Result<PutResult> {
if matches!(opts.mode, PutMode::Update(_)) {
return Err(crate::Error::NotImplemented {
operation: "`put_opts` with mode `PutMode::Update`".into(),
implementer: self.to_string(),
});
}
if !opts.attributes.is_empty() {
return Err(crate::Error::NotImplemented {
operation: "`put_opts` with `opts.attributes` specified".into(),
implementer: self.to_string(),
});
}
let path = self.path_to_filesystem(location)?;
let fsync = self.fsync;
maybe_spawn_blocking(move || {
let (mut file, staging_path) = new_staged_upload(&path, fsync)?;
let mut e_tag = None;
let err = match payload.iter().try_for_each(|x| file.write_all(x)) {
Ok(_) => {
let metadata = file.metadata().map_err(|e| Error::Metadata {
source: e.into(),
path: path.to_string_lossy().to_string(),
})?;
e_tag = Some(get_etag(&metadata));
// Atomically publish the staged file. When fsync is enabled the publish
// helpers flush the file's contents and the destination's parent directory to
// disk first, so a successful return is durable; the fsync calls are bundled
// into the helpers so a file-system modification can never be left unsynced.
match opts.mode {
PutMode::Overwrite => {
finish_staged_rename(file, &staging_path, &path, fsync).err()
}
PutMode::Create => {
finish_staged_hard_link(file, &staging_path, &path, fsync).err()
}
PutMode::Update(_) => unreachable!(),
}
}
Err(source) => Some(Error::UnableToCopyDataToFile { source }.into()),
};
if let Some(err) = err {
let _ = std::fs::remove_file(&staging_path); // Attempt to cleanup
return Err(err);
}
Ok(PutResult {
e_tag,
version: None,
extensions: Default::default(),
})
})
.await
}
async fn put_multipart_opts(
&self,
location: &Path,
opts: PutMultipartOptions,
) -> Result<Box<dyn MultipartUpload>> {
if !opts.attributes.is_empty() {
return Err(crate::Error::NotImplemented {
operation: "`put_multipart_opts` with `opts.attributes` specified".into(),
implementer: self.to_string(),
});
}
let dest = self.path_to_filesystem(location)?;
let (file, src) = new_staged_upload(&dest, self.fsync)?;
Ok(Box::new(LocalUpload::new(src, dest, file, self.fsync)))
}
async fn get_opts(&self, location: &Path, options: GetOptions) -> Result<GetResult> {
let location = location.clone();
let path = self.path_to_filesystem(&location)?;
maybe_spawn_blocking(move || {
let file = open_file(&path)?;
let metadata = open_metadata(&file, &path)?;
let meta = convert_metadata(metadata, location);
options.check_preconditions(&meta)?;
let range = match options.range {
Some(r) => r
.as_range(meta.size)
.map_err(|source| Error::InvalidRange { source })?,
None => 0..meta.size,
};
Ok(GetResult {
payload: GetResultPayload::File(file, path),
attributes: Attributes::default(),
range,
meta,
extensions: Default::default(),
})
})
.await
}
async fn get_ranges(&self, location: &Path, ranges: &[Range<u64>]) -> Result<Vec<Bytes>> {
let path = self.path_to_filesystem(location)?;
let ranges = ranges.to_vec();
maybe_spawn_blocking(move || {
// We do not read the metadata here, but error in `read_range` if necessary
let mut file = File::open(&path).map_err(|e| map_open_error(e, &path))?;
// Coalesce only contiguous/overlapping ranges (gap 0), so we never
// read bytes that weren't requested while still collapsing adjacent
// ranges into fewer reads.
let fetch_ranges = merge_ranges(&ranges, 0);
// Fast path: nothing coalesced, read each range directly in order.
if fetch_ranges.len() == ranges.len() {
return ranges
.iter()
.map(|r| read_range(&mut file, &path, r.clone()))
.collect();
}
let fetched = fetch_ranges
.iter()
.map(|r| read_range(&mut file, &path, r.clone()))
.collect::<Result<Vec<_>>>()?;
Ok(ranges
.iter()
.map(|range| {
let idx = fetch_ranges.partition_point(|v| v.start <= range.start) - 1;
let fetch_range = &fetch_ranges[idx];
let fetch_bytes = &fetched[idx];
let start = (range.start - fetch_range.start) as usize;
let end = (range.end - fetch_range.start) as usize;
fetch_bytes.slice(start..end.min(fetch_bytes.len()))
})
.collect())
})
.await
}
fn delete_stream(
&self,
locations: BoxStream<'static, Result<Path>>,
) -> BoxStream<'static, Result<Path>> {
let config = Arc::clone(&self.config);
let automatic_cleanup = self.automatic_cleanup;
locations
.map(move |location| {
let config = Arc::clone(&config);
maybe_spawn_blocking(move || {
let location = location?;
// `with_fsync` does not apply to standalone deletes; only create-mode rename
// fsyncs its internal source removal as part of the durable copy-and-delete.
Self::delete_location(config, automatic_cleanup, &location, false)?;
Ok(location)
})
})
.buffered(10)
.boxed()
}
fn list(&self, prefix: Option<&Path>) -> BoxStream<'static, Result<ObjectMeta>> {
Self::list_with_maybe_offset(Arc::clone(&self.config), prefix, None)
}
fn list_with_offset(
&self,
prefix: Option<&Path>,
offset: &Path,
) -> BoxStream<'static, Result<ObjectMeta>> {
Self::list_with_maybe_offset(Arc::clone(&self.config), prefix, Some(offset))
}
async fn list_with_delimiter(&self, prefix: Option<&Path>) -> Result<ListResult> {
let config = Arc::clone(&self.config);
let prefix = prefix.cloned().unwrap_or_default();
let resolved_prefix = config.prefix_to_filesystem(&prefix)?;
maybe_spawn_blocking(move || {
let walkdir = WalkDir::new(&resolved_prefix)
.min_depth(1)
.max_depth(1)
.follow_links(true);
let mut common_prefixes = BTreeSet::new();
let mut objects = Vec::new();
for entry_res in walkdir.into_iter().map(convert_walkdir_result) {
if let Some(entry) = entry_res? {
let is_directory = entry.file_type().is_dir();
let entry_location = config.filesystem_to_path(entry.path())?;
if !is_directory && !is_valid_file_path(&entry_location) {
continue;
}
let mut parts = match entry_location.prefix_match(&prefix) {
Some(parts) => parts,
None => continue,
};
let common_prefix = match parts.next() {
Some(p) => p,
None => continue,
};
drop(parts);
if is_directory {
common_prefixes.insert(prefix.clone().join(common_prefix));
} else if let Some(metadata) = convert_entry(entry, entry_location)? {
objects.push(metadata);
}
}
}
Ok(ListResult {
common_prefixes: common_prefixes.into_iter().collect(),
objects,
extensions: Default::default(),
})
})
.await
}
async fn copy_opts(&self, from: &Path, to: &Path, options: CopyOptions) -> Result<()> {
let CopyOptions {
mode,
extensions: _,
} = options;
let from = self.path_to_filesystem(from)?;
let to = self.path_to_filesystem(to)?;
let fsync = self.fsync;
match mode {
CopyMode::Overwrite => {
let mut id = 0;
// In order to make this atomic we:
//
// - hard link to a hidden temporary file
// - atomically rename this temporary file into place
//
// This is necessary because hard_link returns an error if the destination already exists
maybe_spawn_blocking(move || {
loop {
let staged = staged_upload_path(&to, &id.to_string());
// Stage via a temporary hard link; the source is already durable so the
// staging link itself needs no fsync (the publish rename below fsyncs the
// shared parent directory).
match std::fs::hard_link(&from, &staged) {
// `rename` bundles in the fsync of `to`'s parent directory.
Ok(_) => match rename(&staged, &to, fsync) {
Ok(_) => return Ok(()),
Err(source) => {
let _ = std::fs::remove_file(&staged); // Attempt to clean up
return Err(Error::UnableToCopyFile { from, to, source }.into());
}
},
Err(source) => match source.kind() {
ErrorKind::AlreadyExists => id += 1,
ErrorKind::NotFound => match from.exists() {
true => create_parent_dirs(&to, source, fsync)?,
false => {
return Err(Error::NotFound { path: from, source }.into());
}
},
_ => {
return Err(Error::UnableToCopyFile { from, to, source }.into());
}
},
}
}
})
.await
}
CopyMode::Create => {
maybe_spawn_blocking(move || {
loop {
// The source is an existing object that is already durable, so no file
// sync is needed; `hard_link` bundles in the fsync of `to`'s parent dir.
match hard_link(&from, &to, fsync) {
Ok(_) => return Ok(()),
Err(source) => match source.kind() {
ErrorKind::AlreadyExists => {
return Err(Error::AlreadyExists {
path: to.to_str().unwrap().to_string(),
source,
}
.into());
}
ErrorKind::NotFound => match from.exists() {
true => create_parent_dirs(&to, source, fsync)?,
false => {
return Err(Error::NotFound { path: from, source }.into());
}
},
_ => {
return Err(Error::UnableToCopyFile { from, to, source }.into());
}
},
}
}
})
.await
}
}
}
async fn rename_opts(&self, from: &Path, to: &Path, options: RenameOptions) -> Result<()> {
let RenameOptions {
target_mode,
extensions,
} = options;
match target_mode {
// optimized implementation
RenameTargetMode::Overwrite => {
let from = self.path_to_filesystem(from)?;
let to = self.path_to_filesystem(to)?;
let fsync = self.fsync;
maybe_spawn_blocking(move || {
loop {
// Unlike multipart `complete`, there is no freshly written file to
// `sync_all` here: `from` is an existing, already-durable object and a
// rename only mutates directory entries. `rename` bundles in the fsync of
// both affected directories (destination, and source if it differs).
match rename(&from, &to, fsync) {
Ok(_) => return Ok(()),
Err(source) => match source.kind() {
ErrorKind::NotFound => match from.exists() {
true => create_parent_dirs(&to, source, fsync)?,
false => {
return Err(Error::NotFound { path: from, source }.into());
}
},
_ => {
return Err(Error::UnableToCopyFile { from, to, source }.into());
}
},
}
}
})
.await
}
// fall-back to copy & delete
RenameTargetMode::Create => {
self.copy_opts(
from,
to,
CopyOptions {
mode: CopyMode::Create,
extensions,
},
)
.await?;
let config = Arc::clone(&self.config);
let automatic_cleanup = self.automatic_cleanup;
let fsync = self.fsync;
let from = from.clone();
maybe_spawn_blocking(move || {
Self::delete_location(config, automatic_cleanup, &from, fsync)
})
.await?;
Ok(())
}
}
}
}
impl LocalFileSystem {
fn delete_location(
config: Arc<Config>,
automatic_cleanup: bool,
location: &Path,
fsync: bool,
) -> Result<()> {
let path = config.path_to_filesystem(location)?;
if let Err(e) = std::fs::remove_file(&path) {
Err(match e.kind() {
ErrorKind::NotFound => Error::NotFound { path, source: e }.into(),
_ => Error::UnableToDeleteFile { path, source: e }.into(),
})
} else {
if fsync {
fsync_parent_dir(&path).map_err(|source| Error::UnableToSyncFile {
source,
path: path.clone(),
})?;
}
if !automatic_cleanup {
return Ok(());
}
let root = &config.root;
let root = root
.to_file_path()
.map_err(|_| Error::InvalidUrl { url: root.clone() })?;
// here we will try to traverse up and delete an empty dir if possible until we reach the root or get an error
let mut parent = path.parent();
while let Some(loc) = parent {
if loc != root && std::fs::remove_dir(loc).is_ok() {
parent = loc.parent();
} else {
break;
}
}
Ok(())
}
}
fn list_with_maybe_offset(
config: Arc<Config>,
prefix: Option<&Path>,
maybe_offset: Option<&Path>,
) -> BoxStream<'static, Result<ObjectMeta>> {
let root_path = match prefix {
Some(prefix) => match config.prefix_to_filesystem(prefix) {
Ok(path) => path,
Err(e) => return futures_util::future::ready(Err(e)).into_stream().boxed(),
},
None => config.root.to_file_path().unwrap(),
};
let walkdir = WalkDir::new(root_path)
// Don't include the root directory itself
.min_depth(1)
.follow_links(true);
let maybe_offset = maybe_offset.cloned();
let s = walkdir.into_iter().flat_map(move |result_dir_entry| {
// Apply offset filter before proceeding, to reduce statx file system calls
// This matters for NFS mounts
if let (Some(offset), Ok(entry)) = (maybe_offset.as_ref(), result_dir_entry.as_ref()) {
let location = config.filesystem_to_path(entry.path());
match location {
Ok(path) if path <= *offset => return None,
Err(e) => return Some(Err(e)),
_ => {}
}
}
let entry = match convert_walkdir_result(result_dir_entry).transpose()? {
Ok(entry) => entry,
Err(e) => return Some(Err(e)),
};
if !entry.path().is_file() {
return None;
}
match config.filesystem_to_path(entry.path()) {
Ok(path) => match is_valid_file_path(&path) {
true => convert_entry(entry, path).transpose(),
false => None,
},
Err(e) => Some(Err(e)),
}
});
// If no tokio context, return iterator directly as no
// need to perform chunked spawn_blocking reads
if tokio::runtime::Handle::try_current().is_err() {
return futures_util::stream::iter(s).boxed();
}
// Otherwise list in batches of CHUNK_SIZE
const CHUNK_SIZE: usize = 1024;
let buffer = VecDeque::with_capacity(CHUNK_SIZE);
futures_util::stream::try_unfold((s, buffer), |(mut s, mut buffer)| async move {
if buffer.is_empty() {
(s, buffer) = tokio::task::spawn_blocking(move || {
for _ in 0..CHUNK_SIZE {
match s.next() {
Some(r) => buffer.push_back(r),
None => break,
}
}
(s, buffer)
})
.await?;
}
match buffer.pop_front() {
Some(Err(e)) => Err(e),
Some(Ok(meta)) => Ok(Some((meta, (s, buffer)))),
None => Ok(None),
}
})
.boxed()
}
}
/// Creates the parent directories of `path` or returns an error based on `source` if no parent
///
/// When `fsync` is true, every directory created here is fsynced, up to and including the first
/// pre-existing ancestor (whose entry list also changed), so the new directory entries are durable.
fn create_parent_dirs(path: &std::path::Path, source: io::Error, fsync: bool) -> Result<()> {
let parent = path.parent().ok_or_else(|| {
let path = path.to_path_buf();
Error::UnableToCreateFile { path, source }
})?;
// Record the deepest already-existing ancestor *before* creating any directories, so that
// afterwards we know exactly which directories are new and need to be fsynced.
let first_existing = fsync.then(|| {
let mut dir = parent;
while !dir.exists() {
match dir.parent() {
Some(p) => dir = p,
None => break,
}
}
dir.to_path_buf()
});
std::fs::create_dir_all(parent).map_err(|source| {
let path = parent.into();
Error::UnableToCreateDir { source, path }
})?;
if let Some(first_existing) = first_existing {
// Walk from `parent` up to `first_existing`, fsyncing each directory whose entries changed.
let mut dir = parent;
loop {
fsync_dir(dir).map_err(|source| Error::UnableToSyncFile {
source,
path: dir.into(),
})?;
if dir == first_existing {
break;
}
dir = match dir.parent() {
Some(p) => p,
None => break,
};
}
}
Ok(())
}
/// Renames `from` to `to`, then — when `fsync` is enabled — fsyncs the destination's parent
/// directory (and the source's too, if it differs) so the moved directory entries are durable.
///
/// The directory fsync is bundled in deliberately: every durable rename goes through here, so the
/// post-rename fsync can never be forgotten at an individual call site.
fn rename(from: &std::path::Path, to: &std::path::Path, fsync: bool) -> io::Result<()> {
std::fs::rename(from, to)?;
if fsync {
fsync_parent_dir(to)?;
// A cross-directory move also removes an entry from the source directory.
if from.parent() != to.parent() {
fsync_parent_dir(from)?;
}
}
Ok(())
}
/// Hard-links `original` to `link`, then — when `fsync` is enabled — fsyncs `link`'s parent
/// directory so the new directory entry is durable.
///
/// As with [`rename`], the directory fsync is bundled in so it cannot be forgotten at a call site.
fn hard_link(original: &std::path::Path, link: &std::path::Path, fsync: bool) -> io::Result<()> {
std::fs::hard_link(original, link)?;
if fsync {
fsync_parent_dir(link)?;
}
Ok(())
}
/// Durably publishes the freshly-written staging file `file` (located at `src`) to `dest` via a
/// rename.
///
/// When `fsync` is enabled, the file's contents are flushed before — and `dest`'s parent
/// directory after — the rename, so a successful return is durable. The file is always closed
/// before the rename (checking for close errors): required for NFS error detection and for some
/// FUSE filesystems (e.g. Blobfuse) that only commit the data on close.
fn finish_staged_rename(
file: File,
src: &std::path::Path,
dest: &std::path::Path,
fsync: bool,
) -> Result<()> {
sync_and_close(file, src, fsync)?;
rename(src, dest, fsync).map_err(|source| Error::UnableToRenameFile { source })?;
Ok(())
}
/// Like [`finish_staged_rename`] but publishes via a hard link (`PutMode::Create` semantics): the
/// staging file is linked to `dest` and then removed. Returns [`Error::AlreadyExists`] if `dest`
/// already exists.
fn finish_staged_hard_link(
file: File,