Line data Source code
1 : //! Local filesystem acting as a remote storage.
2 : //! Multiple API users can use the same "storage" of this kind by using different storage roots.
3 : //!
4 : //! This storage used in tests, but can also be used in cases when a certain persistent
5 : //! volume is mounted to the local FS.
6 :
7 : use std::{
8 : collections::HashSet,
9 : io::ErrorKind,
10 : num::NonZeroU32,
11 : time::{Duration, SystemTime, UNIX_EPOCH},
12 : };
13 :
14 : use anyhow::{bail, ensure, Context};
15 : use bytes::Bytes;
16 : use camino::{Utf8Path, Utf8PathBuf};
17 : use futures::stream::Stream;
18 : use tokio::{
19 : fs,
20 : io::{self, AsyncReadExt, AsyncSeekExt, AsyncWriteExt},
21 : };
22 : use tokio_util::{io::ReaderStream, sync::CancellationToken};
23 : use utils::crashsafe::path_with_suffix_extension;
24 :
25 : use crate::{
26 : Download, DownloadError, Listing, ListingMode, ListingObject, RemotePath, TimeTravelError,
27 : TimeoutOrCancel, REMOTE_STORAGE_PREFIX_SEPARATOR,
28 : };
29 :
30 : use super::{RemoteStorage, StorageMetadata};
31 : use crate::Etag;
32 :
33 : const LOCAL_FS_TEMP_FILE_SUFFIX: &str = "___temp";
34 :
35 : #[derive(Debug, Clone)]
36 : pub struct LocalFs {
37 : storage_root: Utf8PathBuf,
38 : timeout: Duration,
39 : }
40 :
41 : impl LocalFs {
42 : /// Attempts to create local FS storage, along with its root directory.
43 : /// Storage root will be created (if does not exist) and transformed into an absolute path (if passed as relative).
44 625 : pub fn new(mut storage_root: Utf8PathBuf, timeout: Duration) -> anyhow::Result<Self> {
45 625 : if !storage_root.exists() {
46 33 : std::fs::create_dir_all(&storage_root).with_context(|| {
47 0 : format!("Failed to create all directories in the given root path {storage_root:?}")
48 33 : })?;
49 592 : }
50 625 : if !storage_root.is_absolute() {
51 570 : storage_root = storage_root.canonicalize_utf8().with_context(|| {
52 0 : format!("Failed to represent path {storage_root:?} as an absolute path")
53 570 : })?;
54 55 : }
55 :
56 625 : Ok(Self {
57 625 : storage_root,
58 625 : timeout,
59 625 : })
60 625 : }
61 :
62 : // mirrors S3Bucket::s3_object_to_relative_path
63 240 : fn local_file_to_relative_path(&self, key: Utf8PathBuf) -> RemotePath {
64 240 : let relative_path = key
65 240 : .strip_prefix(&self.storage_root)
66 240 : .expect("relative path must contain storage_root as prefix");
67 240 : RemotePath(relative_path.into())
68 240 : }
69 :
70 117 : async fn read_storage_metadata(
71 117 : &self,
72 117 : file_path: &Utf8Path,
73 117 : ) -> anyhow::Result<Option<StorageMetadata>> {
74 117 : let metadata_path = storage_metadata_path(file_path);
75 117 : if metadata_path.exists() && metadata_path.is_file() {
76 6 : let metadata_string = fs::read_to_string(&metadata_path).await.with_context(|| {
77 0 : format!("Failed to read metadata from the local storage at '{metadata_path}'")
78 6 : })?;
79 :
80 6 : serde_json::from_str(&metadata_string)
81 6 : .with_context(|| {
82 0 : format!(
83 0 : "Failed to deserialize metadata from the local storage at '{metadata_path}'",
84 0 : )
85 6 : })
86 6 : .map(|metadata| Some(StorageMetadata(metadata)))
87 : } else {
88 111 : Ok(None)
89 : }
90 117 : }
91 :
92 : #[cfg(test)]
93 9 : async fn list_all(&self) -> anyhow::Result<Vec<RemotePath>> {
94 : use std::{future::Future, pin::Pin};
95 27 : fn get_all_files<'a, P>(
96 27 : directory_path: P,
97 27 : ) -> Pin<Box<dyn Future<Output = anyhow::Result<Vec<Utf8PathBuf>>> + Send + Sync + 'a>>
98 27 : where
99 27 : P: AsRef<Utf8Path> + Send + Sync + 'a,
100 27 : {
101 27 : Box::pin(async move {
102 27 : let directory_path = directory_path.as_ref();
103 27 : if directory_path.exists() {
104 27 : if directory_path.is_dir() {
105 27 : let mut paths = Vec::new();
106 27 : let mut dir_contents = fs::read_dir(directory_path).await?;
107 54 : while let Some(dir_entry) = dir_contents.next_entry().await? {
108 27 : let file_type = dir_entry.file_type().await?;
109 27 : let entry_path =
110 27 : Utf8PathBuf::from_path_buf(dir_entry.path()).map_err(|pb| {
111 0 : anyhow::Error::msg(format!(
112 0 : "non-Unicode path: {}",
113 0 : pb.to_string_lossy()
114 0 : ))
115 27 : })?;
116 27 : if file_type.is_symlink() {
117 0 : tracing::debug!("{entry_path:?} is a symlink, skipping")
118 27 : } else if file_type.is_dir() {
119 27 : paths.extend(get_all_files(&entry_path).await?.into_iter())
120 9 : } else {
121 9 : paths.push(entry_path);
122 9 : }
123 : }
124 27 : Ok(paths)
125 : } else {
126 0 : bail!("Path {directory_path:?} is not a directory")
127 : }
128 : } else {
129 0 : Ok(Vec::new())
130 : }
131 27 : })
132 27 : }
133 :
134 9 : Ok(get_all_files(&self.storage_root)
135 27 : .await?
136 9 : .into_iter()
137 9 : .map(|path| {
138 9 : path.strip_prefix(&self.storage_root)
139 9 : .context("Failed to strip storage root prefix")
140 9 : .and_then(RemotePath::new)
141 9 : .expect(
142 9 : "We list files for storage root, hence should be able to remote the prefix",
143 9 : )
144 9 : })
145 9 : .collect())
146 9 : }
147 :
148 : // recursively lists all files in a directory,
149 : // mirroring the `list_files` for `s3_bucket`
150 606 : async fn list_recursive(&self, folder: Option<&RemotePath>) -> anyhow::Result<Vec<RemotePath>> {
151 606 : let full_path = match folder {
152 600 : Some(folder) => folder.with_base(&self.storage_root),
153 6 : None => self.storage_root.clone(),
154 : };
155 :
156 : // If we were given a directory, we may use it as our starting point.
157 : // Otherwise, we must go up to the first ancestor dir that exists. This is because
158 : // S3 object list prefixes can be arbitrary strings, but when reading
159 : // the local filesystem we need a directory to start calling read_dir on.
160 606 : let mut initial_dir = full_path.clone();
161 606 :
162 606 : // If there's no trailing slash, we have to start looking from one above: even if
163 606 : // `initial_dir` is a directory, we should still list any prefixes in the parent
164 606 : // that start with the same string.
165 606 : if !full_path.to_string().ends_with('/') {
166 33 : initial_dir.pop();
167 573 : }
168 :
169 : loop {
170 : // Did we make it to the root?
171 2280 : if initial_dir.parent().is_none() {
172 0 : anyhow::bail!("list_files: failed to find valid ancestor dir for {full_path}");
173 2280 : }
174 2280 :
175 2280 : match fs::metadata(initial_dir.clone()).await {
176 606 : Ok(meta) if meta.is_dir() => {
177 606 : // We found a directory, break
178 606 : break;
179 : }
180 0 : Ok(_meta) => {
181 0 : // It's not a directory: strip back to the parent
182 0 : initial_dir.pop();
183 0 : }
184 1674 : Err(e) if e.kind() == ErrorKind::NotFound => {
185 1674 : // It's not a file that exists: strip the prefix back to the parent directory
186 1674 : initial_dir.pop();
187 1674 : }
188 0 : Err(e) => {
189 0 : // Unexpected I/O error
190 0 : anyhow::bail!(e)
191 : }
192 : }
193 : }
194 : // Note that Utf8PathBuf starts_with only considers full path segments, but
195 : // object prefixes are arbitrary strings, so we need the strings for doing
196 : // starts_with later.
197 606 : let prefix = full_path.as_str();
198 606 :
199 606 : let mut files = vec![];
200 606 : let mut directory_queue = vec![initial_dir];
201 1281 : while let Some(cur_folder) = directory_queue.pop() {
202 675 : let mut entries = cur_folder.read_dir_utf8()?;
203 1103 : while let Some(Ok(entry)) = entries.next() {
204 428 : let file_name = entry.file_name();
205 428 : let full_file_name = cur_folder.join(file_name);
206 428 : if full_file_name.as_str().starts_with(prefix) {
207 240 : let file_remote_path = self.local_file_to_relative_path(full_file_name.clone());
208 240 : files.push(file_remote_path);
209 240 : if full_file_name.is_dir() {
210 69 : directory_queue.push(full_file_name);
211 171 : }
212 188 : }
213 : }
214 : }
215 :
216 606 : Ok(files)
217 606 : }
218 :
219 8370 : async fn upload0(
220 8370 : &self,
221 8370 : data: impl Stream<Item = std::io::Result<Bytes>> + Send + Sync,
222 8370 : data_size_bytes: usize,
223 8370 : to: &RemotePath,
224 8370 : metadata: Option<StorageMetadata>,
225 8370 : cancel: &CancellationToken,
226 8370 : ) -> anyhow::Result<()> {
227 8370 : let target_file_path = to.with_base(&self.storage_root);
228 8370 : create_target_directory(&target_file_path).await?;
229 : // We need this dance with sort of durable rename (without fsyncs)
230 : // to prevent partial uploads. This was really hit when pageserver shutdown
231 : // cancelled the upload and partial file was left on the fs
232 : // NOTE: Because temp file suffix always the same this operation is racy.
233 : // Two concurrent operations can lead to the following sequence:
234 : // T1: write(temp)
235 : // T2: write(temp) -> overwrites the content
236 : // T1: rename(temp, dst) -> succeeds
237 : // T2: rename(temp, dst) -> fails, temp no longet exists
238 : // This can be solved by supplying unique temp suffix every time, but this situation
239 : // is not normal in the first place, the error can help (and helped at least once)
240 : // to discover bugs in upper level synchronization.
241 8361 : let temp_file_path =
242 8361 : path_with_suffix_extension(&target_file_path, LOCAL_FS_TEMP_FILE_SUFFIX);
243 8170 : let mut destination = io::BufWriter::new(
244 8361 : fs::OpenOptions::new()
245 8361 : .write(true)
246 8361 : .create(true)
247 8361 : .truncate(true)
248 8361 : .open(&temp_file_path)
249 7805 : .await
250 8170 : .with_context(|| {
251 0 : format!("Failed to open target fs destination at '{target_file_path}'")
252 8170 : })?,
253 : );
254 :
255 8170 : let from_size_bytes = data_size_bytes as u64;
256 8170 : let data = tokio_util::io::StreamReader::new(data);
257 8170 : let data = std::pin::pin!(data);
258 8170 : let mut buffer_to_read = data.take(from_size_bytes);
259 8170 :
260 8170 : // alternatively we could just write the bytes to a file, but local_fs is a testing utility
261 8170 : let copy = io::copy_buf(&mut buffer_to_read, &mut destination);
262 :
263 8170 : let bytes_read = tokio::select! {
264 : biased;
265 8170 : _ = cancel.cancelled() => {
266 3 : let file = destination.into_inner();
267 3 : // wait for the inflight operation(s) to complete so that there could be a next
268 3 : // attempt right away and our writes are not directed to their file.
269 3 : file.into_std().await;
270 :
271 : // TODO: leave the temp or not? leaving is probably less racy. enabled truncate at
272 : // least.
273 3 : fs::remove_file(temp_file_path).await.context("remove temp_file_path after cancellation or timeout")?;
274 3 : return Err(TimeoutOrCancel::Cancel.into());
275 : }
276 8170 : read = copy => read,
277 : };
278 :
279 8157 : let bytes_read =
280 8157 : bytes_read.with_context(|| {
281 0 : format!(
282 0 : "Failed to upload file (write temp) to the local storage at '{temp_file_path}'",
283 0 : )
284 8157 : })?;
285 :
286 8157 : if bytes_read < from_size_bytes {
287 3 : bail!("Provided stream was shorter than expected: {bytes_read} vs {from_size_bytes} bytes");
288 8154 : }
289 8154 : // Check if there is any extra data after the given size.
290 8154 : let mut from = buffer_to_read.into_inner();
291 8154 : let extra_read = from.read(&mut [1]).await?;
292 8152 : ensure!(
293 8152 : extra_read == 0,
294 6 : "Provided stream was larger than expected: expected {from_size_bytes} bytes",
295 : );
296 :
297 8146 : destination.flush().await.with_context(|| {
298 0 : format!(
299 0 : "Failed to upload (flush temp) file to the local storage at '{temp_file_path}'",
300 0 : )
301 8146 : })?;
302 :
303 8146 : fs::rename(temp_file_path, &target_file_path)
304 7724 : .await
305 8136 : .with_context(|| {
306 0 : format!(
307 0 : "Failed to upload (rename) file to the local storage at '{target_file_path}'",
308 0 : )
309 8136 : })?;
310 :
311 8136 : if let Some(storage_metadata) = metadata {
312 : // FIXME: we must not be using metadata much, since this would forget the old metadata
313 : // for new writes? or perhaps metadata is sticky; could consider removing if it's never
314 : // used.
315 3 : let storage_metadata_path = storage_metadata_path(&target_file_path);
316 3 : fs::write(
317 3 : &storage_metadata_path,
318 3 : serde_json::to_string(&storage_metadata.0)
319 3 : .context("Failed to serialize storage metadata as json")?,
320 : )
321 3 : .await
322 3 : .with_context(|| {
323 0 : format!(
324 0 : "Failed to write metadata to the local storage at '{storage_metadata_path}'",
325 0 : )
326 3 : })?;
327 8133 : }
328 :
329 8136 : Ok(())
330 8148 : }
331 : }
332 :
333 : impl RemoteStorage for LocalFs {
334 0 : fn list_streaming(
335 0 : &self,
336 0 : prefix: Option<&RemotePath>,
337 0 : mode: ListingMode,
338 0 : max_keys: Option<NonZeroU32>,
339 0 : cancel: &CancellationToken,
340 0 : ) -> impl Stream<Item = Result<Listing, DownloadError>> {
341 0 : let listing = self.list(prefix, mode, max_keys, cancel);
342 0 : futures::stream::once(listing)
343 0 : }
344 :
345 606 : async fn list(
346 606 : &self,
347 606 : prefix: Option<&RemotePath>,
348 606 : mode: ListingMode,
349 606 : max_keys: Option<NonZeroU32>,
350 606 : cancel: &CancellationToken,
351 606 : ) -> Result<Listing, DownloadError> {
352 606 : let op = async {
353 606 : let mut result = Listing::default();
354 :
355 : // Filter out directories: in S3 directories don't exist, only the keys within them do.
356 606 : let keys = self
357 606 : .list_recursive(prefix)
358 2277 : .await
359 606 : .map_err(DownloadError::Other)?;
360 606 : let objects = keys
361 606 : .into_iter()
362 606 : .filter_map(|k| {
363 240 : let path = k.with_base(&self.storage_root);
364 240 : if path.is_dir() {
365 69 : None
366 : } else {
367 171 : Some(ListingObject {
368 171 : key: k.clone(),
369 171 : // LocalFs is just for testing, so just specify a dummy time
370 171 : last_modified: SystemTime::now(),
371 171 : size: 0,
372 171 : })
373 : }
374 606 : })
375 606 : .collect();
376 606 :
377 606 : if let ListingMode::NoDelimiter = mode {
378 21 : result.keys = objects;
379 21 : } else {
380 585 : let mut prefixes = HashSet::new();
381 693 : for object in objects {
382 108 : let key = object.key;
383 : // If the part after the prefix includes a "/", take only the first part and put it in `prefixes`.
384 108 : let relative_key = if let Some(prefix) = prefix {
385 99 : let mut prefix = prefix.clone();
386 99 : // We only strip the dirname of the prefix, so that when we strip it from the start of keys we
387 99 : // end up with full file/dir names.
388 99 : let prefix_full_local_path = prefix.with_base(&self.storage_root);
389 99 : let has_slash = prefix.0.to_string().ends_with('/');
390 99 : let strip_prefix = if prefix_full_local_path.is_dir() && has_slash {
391 75 : prefix
392 : } else {
393 24 : prefix.0.pop();
394 24 : prefix
395 : };
396 :
397 99 : RemotePath::new(key.strip_prefix(&strip_prefix).unwrap()).unwrap()
398 : } else {
399 9 : key
400 : };
401 :
402 108 : let relative_key = format!("{}", relative_key);
403 108 : if relative_key.contains(REMOTE_STORAGE_PREFIX_SEPARATOR) {
404 105 : let first_part = relative_key
405 105 : .split(REMOTE_STORAGE_PREFIX_SEPARATOR)
406 105 : .next()
407 105 : .unwrap()
408 105 : .to_owned();
409 105 : prefixes.insert(first_part);
410 105 : } else {
411 3 : result.keys.push(ListingObject {
412 3 : key: RemotePath::from_string(&relative_key).unwrap(),
413 3 : // LocalFs is just for testing
414 3 : last_modified: SystemTime::now(),
415 3 : size: 0,
416 3 : });
417 3 : }
418 : }
419 585 : result.prefixes = prefixes
420 585 : .into_iter()
421 585 : .map(|s| RemotePath::from_string(&s).unwrap())
422 585 : .collect();
423 585 : }
424 :
425 606 : if let Some(max_keys) = max_keys {
426 0 : result.keys.truncate(max_keys.get() as usize);
427 606 : }
428 606 : Ok(result)
429 606 : };
430 :
431 606 : let timeout = async {
432 1878 : tokio::time::sleep(self.timeout).await;
433 0 : Err(DownloadError::Timeout)
434 0 : };
435 :
436 606 : let cancelled = async {
437 2083 : cancel.cancelled().await;
438 0 : Err(DownloadError::Cancelled)
439 0 : };
440 :
441 606 : tokio::select! {
442 606 : res = op => res,
443 606 : res = timeout => res,
444 606 : res = cancelled => res,
445 : }
446 606 : }
447 :
448 0 : async fn head_object(
449 0 : &self,
450 0 : key: &RemotePath,
451 0 : _cancel: &CancellationToken,
452 0 : ) -> Result<ListingObject, DownloadError> {
453 0 : let target_file_path = key.with_base(&self.storage_root);
454 0 : let metadata = file_metadata(&target_file_path).await?;
455 : Ok(ListingObject {
456 0 : key: key.clone(),
457 0 : last_modified: metadata.modified()?,
458 0 : size: metadata.len(),
459 : })
460 0 : }
461 :
462 8370 : async fn upload(
463 8370 : &self,
464 8370 : data: impl Stream<Item = std::io::Result<Bytes>> + Send + Sync,
465 8370 : data_size_bytes: usize,
466 8370 : to: &RemotePath,
467 8370 : metadata: Option<StorageMetadata>,
468 8370 : cancel: &CancellationToken,
469 8370 : ) -> anyhow::Result<()> {
470 8370 : let cancel = cancel.child_token();
471 8370 :
472 8370 : let op = self.upload0(data, data_size_bytes, to, metadata, &cancel);
473 8370 : let mut op = std::pin::pin!(op);
474 :
475 : // race the upload0 to the timeout; if it goes over, do a graceful shutdown
476 8370 : let (res, timeout) = tokio::select! {
477 8370 : res = &mut op => (res, false),
478 8370 : _ = tokio::time::sleep(self.timeout) => {
479 0 : cancel.cancel();
480 0 : (op.await, true)
481 : }
482 : };
483 :
484 12 : match res {
485 12 : Err(e) if timeout && TimeoutOrCancel::caused_by_cancel(&e) => {
486 0 : // we caused this cancel (or they happened simultaneously) -- swap it out to
487 0 : // Timeout
488 0 : Err(TimeoutOrCancel::Timeout.into())
489 : }
490 8148 : res => res,
491 : }
492 8148 : }
493 :
494 147 : async fn download(
495 147 : &self,
496 147 : from: &RemotePath,
497 147 : cancel: &CancellationToken,
498 147 : ) -> Result<Download, DownloadError> {
499 147 : let target_path = from.with_base(&self.storage_root);
500 :
501 147 : let file_metadata = file_metadata(&target_path).await?;
502 :
503 102 : let source = ReaderStream::new(
504 102 : fs::OpenOptions::new()
505 102 : .read(true)
506 102 : .open(&target_path)
507 100 : .await
508 102 : .with_context(|| {
509 0 : format!("Failed to open source file {target_path:?} to use in the download")
510 102 : })
511 102 : .map_err(DownloadError::Other)?,
512 : );
513 :
514 102 : let metadata = self
515 102 : .read_storage_metadata(&target_path)
516 3 : .await
517 102 : .map_err(DownloadError::Other)?;
518 :
519 102 : let cancel_or_timeout = crate::support::cancel_or_timeout(self.timeout, cancel.clone());
520 102 : let source = crate::support::DownloadStream::new(cancel_or_timeout, source);
521 102 :
522 102 : let etag = mock_etag(&file_metadata);
523 102 : Ok(Download {
524 102 : metadata,
525 102 : last_modified: file_metadata
526 102 : .modified()
527 102 : .map_err(|e| DownloadError::Other(anyhow::anyhow!(e).context("Reading mtime")))?,
528 102 : etag,
529 102 : download_stream: Box::pin(source),
530 : })
531 147 : }
532 :
533 21 : async fn download_byte_range(
534 21 : &self,
535 21 : from: &RemotePath,
536 21 : start_inclusive: u64,
537 21 : end_exclusive: Option<u64>,
538 21 : cancel: &CancellationToken,
539 21 : ) -> Result<Download, DownloadError> {
540 21 : if let Some(end_exclusive) = end_exclusive {
541 15 : if end_exclusive <= start_inclusive {
542 3 : return Err(DownloadError::Other(anyhow::anyhow!("Invalid range, start ({start_inclusive}) is not less than end_exclusive ({end_exclusive:?})")));
543 12 : };
544 12 : if start_inclusive == end_exclusive.saturating_sub(1) {
545 3 : return Err(DownloadError::Other(anyhow::anyhow!("Invalid range, start ({start_inclusive}) and end_exclusive ({end_exclusive:?}) difference is zero bytes")));
546 9 : }
547 6 : }
548 :
549 15 : let target_path = from.with_base(&self.storage_root);
550 15 : let file_metadata = file_metadata(&target_path).await?;
551 15 : let mut source = tokio::fs::OpenOptions::new()
552 15 : .read(true)
553 15 : .open(&target_path)
554 15 : .await
555 15 : .with_context(|| {
556 0 : format!("Failed to open source file {target_path:?} to use in the download")
557 15 : })
558 15 : .map_err(DownloadError::Other)?;
559 :
560 15 : let len = source
561 15 : .metadata()
562 15 : .await
563 15 : .context("query file length")
564 15 : .map_err(DownloadError::Other)?
565 15 : .len();
566 15 :
567 15 : source
568 15 : .seek(io::SeekFrom::Start(start_inclusive))
569 15 : .await
570 15 : .context("Failed to seek to the range start in a local storage file")
571 15 : .map_err(DownloadError::Other)?;
572 :
573 15 : let metadata = self
574 15 : .read_storage_metadata(&target_path)
575 3 : .await
576 15 : .map_err(DownloadError::Other)?;
577 :
578 15 : let source = source.take(end_exclusive.unwrap_or(len) - start_inclusive);
579 15 : let source = ReaderStream::new(source);
580 15 :
581 15 : let cancel_or_timeout = crate::support::cancel_or_timeout(self.timeout, cancel.clone());
582 15 : let source = crate::support::DownloadStream::new(cancel_or_timeout, source);
583 15 :
584 15 : let etag = mock_etag(&file_metadata);
585 15 : Ok(Download {
586 15 : metadata,
587 15 : last_modified: file_metadata
588 15 : .modified()
589 15 : .map_err(|e| DownloadError::Other(anyhow::anyhow!(e).context("Reading mtime")))?,
590 15 : etag,
591 15 : download_stream: Box::pin(source),
592 : })
593 21 : }
594 :
595 30 : async fn delete(&self, path: &RemotePath, _cancel: &CancellationToken) -> anyhow::Result<()> {
596 30 : let file_path = path.with_base(&self.storage_root);
597 30 : match fs::remove_file(&file_path).await {
598 27 : Ok(()) => Ok(()),
599 : // The file doesn't exist. This shouldn't yield an error to mirror S3's behaviour.
600 : // See https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteObject.html
601 : // > If there isn't a null version, Amazon S3 does not remove any objects but will still respond that the command was successful.
602 3 : Err(e) if e.kind() == ErrorKind::NotFound => Ok(()),
603 0 : Err(e) => Err(anyhow::anyhow!(e)),
604 : }
605 30 : }
606 :
607 18 : async fn delete_objects<'a>(
608 18 : &self,
609 18 : paths: &'a [RemotePath],
610 18 : cancel: &CancellationToken,
611 18 : ) -> anyhow::Result<()> {
612 36 : for path in paths {
613 18 : self.delete(path, cancel).await?
614 : }
615 18 : Ok(())
616 18 : }
617 :
618 0 : async fn copy(
619 0 : &self,
620 0 : from: &RemotePath,
621 0 : to: &RemotePath,
622 0 : _cancel: &CancellationToken,
623 0 : ) -> anyhow::Result<()> {
624 0 : let from_path = from.with_base(&self.storage_root);
625 0 : let to_path = to.with_base(&self.storage_root);
626 0 : create_target_directory(&to_path).await?;
627 0 : fs::copy(&from_path, &to_path).await.with_context(|| {
628 0 : format!(
629 0 : "Failed to copy file from '{from_path}' to '{to_path}'",
630 0 : from_path = from_path,
631 0 : to_path = to_path
632 0 : )
633 0 : })?;
634 0 : Ok(())
635 0 : }
636 :
637 0 : async fn time_travel_recover(
638 0 : &self,
639 0 : _prefix: Option<&RemotePath>,
640 0 : _timestamp: SystemTime,
641 0 : _done_if_after: SystemTime,
642 0 : _cancel: &CancellationToken,
643 0 : ) -> Result<(), TimeTravelError> {
644 0 : Err(TimeTravelError::Unimplemented)
645 0 : }
646 : }
647 :
648 120 : fn storage_metadata_path(original_path: &Utf8Path) -> Utf8PathBuf {
649 120 : path_with_suffix_extension(original_path, "metadata")
650 120 : }
651 :
652 8370 : async fn create_target_directory(target_file_path: &Utf8Path) -> anyhow::Result<()> {
653 8370 : let target_dir = match target_file_path.parent() {
654 8370 : Some(parent_dir) => parent_dir,
655 0 : None => bail!("File path '{target_file_path}' has no parent directory"),
656 : };
657 8370 : if !target_dir.exists() {
658 1201 : fs::create_dir_all(target_dir).await?;
659 7169 : }
660 8361 : Ok(())
661 8361 : }
662 :
663 162 : async fn file_metadata(file_path: &Utf8Path) -> Result<std::fs::Metadata, DownloadError> {
664 162 : tokio::fs::metadata(&file_path).await.map_err(|e| {
665 45 : if e.kind() == ErrorKind::NotFound {
666 45 : DownloadError::NotFound
667 : } else {
668 0 : DownloadError::BadInput(e.into())
669 : }
670 162 : })
671 162 : }
672 :
673 : // Use mtime as stand-in for ETag. We could calculate a meaningful one by md5'ing the contents of files we
674 : // read, but that's expensive and the local_fs test helper's whole reason for existence is to run small tests
675 : // quickly, with less overhead than using a mock S3 server.
676 117 : fn mock_etag(meta: &std::fs::Metadata) -> Etag {
677 117 : let mtime = meta.modified().expect("Filesystem mtime missing");
678 117 : format!("{}", mtime.duration_since(UNIX_EPOCH).unwrap().as_millis()).into()
679 117 : }
680 :
681 : #[cfg(test)]
682 : mod fs_tests {
683 : use super::*;
684 :
685 : use camino_tempfile::tempdir;
686 : use std::{collections::HashMap, io::Write};
687 :
688 9 : async fn read_and_check_metadata(
689 9 : storage: &LocalFs,
690 9 : remote_storage_path: &RemotePath,
691 9 : expected_metadata: Option<&StorageMetadata>,
692 9 : ) -> anyhow::Result<String> {
693 9 : let cancel = CancellationToken::new();
694 9 : let download = storage
695 9 : .download(remote_storage_path, &cancel)
696 21 : .await
697 9 : .map_err(|e| anyhow::anyhow!("Download failed: {e}"))?;
698 9 : ensure!(
699 9 : download.metadata.as_ref() == expected_metadata,
700 0 : "Unexpected metadata returned for the downloaded file"
701 : );
702 :
703 18 : let contents = aggregate(download.download_stream).await?;
704 :
705 9 : String::from_utf8(contents).map_err(anyhow::Error::new)
706 9 : }
707 :
708 : #[tokio::test]
709 3 : async fn upload_file() -> anyhow::Result<()> {
710 3 : let (storage, cancel) = create_storage()?;
711 3 :
712 17 : let target_path_1 = upload_dummy_file(&storage, "upload_1", None, &cancel).await?;
713 3 : assert_eq!(
714 9 : storage.list_all().await?,
715 3 : vec![target_path_1.clone()],
716 3 : "Should list a single file after first upload"
717 3 : );
718 3 :
719 18 : let target_path_2 = upload_dummy_file(&storage, "upload_2", None, &cancel).await?;
720 3 : assert_eq!(
721 9 : list_files_sorted(&storage).await?,
722 3 : vec![target_path_1.clone(), target_path_2.clone()],
723 3 : "Should list a two different files after second upload"
724 3 : );
725 3 :
726 3 : Ok(())
727 3 : }
728 :
729 : #[tokio::test]
730 3 : async fn upload_file_negatives() -> anyhow::Result<()> {
731 3 : let (storage, cancel) = create_storage()?;
732 3 :
733 3 : let id = RemotePath::new(Utf8Path::new("dummy"))?;
734 3 : let content = Bytes::from_static(b"12345");
735 12 : let content = move || futures::stream::once(futures::future::ready(Ok(content.clone())));
736 3 :
737 3 : // Check that you get an error if the size parameter doesn't match the actual
738 3 : // size of the stream.
739 3 : storage
740 3 : .upload(content(), 0, &id, None, &cancel)
741 3 : .await
742 3 : .expect_err("upload with zero size succeeded");
743 3 : storage
744 3 : .upload(content(), 4, &id, None, &cancel)
745 6 : .await
746 3 : .expect_err("upload with too short size succeeded");
747 3 : storage
748 3 : .upload(content(), 6, &id, None, &cancel)
749 6 : .await
750 3 : .expect_err("upload with too large size succeeded");
751 3 :
752 3 : // Correct size is 5, this should succeed.
753 9 : storage.upload(content(), 5, &id, None, &cancel).await?;
754 3 :
755 3 : Ok(())
756 3 : }
757 :
758 33 : fn create_storage() -> anyhow::Result<(LocalFs, CancellationToken)> {
759 33 : let storage_root = tempdir()?.path().to_path_buf();
760 33 : LocalFs::new(storage_root, Duration::from_secs(120)).map(|s| (s, CancellationToken::new()))
761 33 : }
762 :
763 : #[tokio::test]
764 3 : async fn download_file() -> anyhow::Result<()> {
765 3 : let (storage, cancel) = create_storage()?;
766 3 : let upload_name = "upload_1";
767 17 : let upload_target = upload_dummy_file(&storage, upload_name, None, &cancel).await?;
768 3 :
769 12 : let contents = read_and_check_metadata(&storage, &upload_target, None).await?;
770 3 : assert_eq!(
771 3 : dummy_contents(upload_name),
772 3 : contents,
773 3 : "We should upload and download the same contents"
774 3 : );
775 3 :
776 3 : let non_existing_path = "somewhere/else";
777 3 : match storage.download(&RemotePath::new(Utf8Path::new(non_existing_path))?, &cancel).await {
778 3 : Err(DownloadError::NotFound) => {} // Should get NotFound for non existing keys
779 3 : other => panic!("Should get a NotFound error when downloading non-existing storage files, but got: {other:?}"),
780 3 : }
781 3 : Ok(())
782 3 : }
783 :
784 : #[tokio::test]
785 3 : async fn download_file_range_positive() -> anyhow::Result<()> {
786 3 : let (storage, cancel) = create_storage()?;
787 3 : let upload_name = "upload_1";
788 18 : let upload_target = upload_dummy_file(&storage, upload_name, None, &cancel).await?;
789 3 :
790 3 : let full_range_download_contents =
791 12 : read_and_check_metadata(&storage, &upload_target, None).await?;
792 3 : assert_eq!(
793 3 : dummy_contents(upload_name),
794 3 : full_range_download_contents,
795 3 : "Download full range should return the whole upload"
796 3 : );
797 3 :
798 3 : let uploaded_bytes = dummy_contents(upload_name).into_bytes();
799 3 : let (first_part_local, second_part_local) = uploaded_bytes.split_at(3);
800 3 :
801 3 : let first_part_download = storage
802 3 : .download_byte_range(
803 3 : &upload_target,
804 3 : 0,
805 3 : Some(first_part_local.len() as u64),
806 3 : &cancel,
807 3 : )
808 12 : .await?;
809 3 : assert!(
810 3 : first_part_download.metadata.is_none(),
811 3 : "No metadata should be returned for no metadata upload"
812 3 : );
813 3 :
814 3 : let first_part_remote = aggregate(first_part_download.download_stream).await?;
815 3 : assert_eq!(
816 3 : first_part_local, first_part_remote,
817 3 : "First part bytes should be returned when requested"
818 3 : );
819 3 :
820 3 : let second_part_download = storage
821 3 : .download_byte_range(
822 3 : &upload_target,
823 3 : first_part_local.len() as u64,
824 3 : Some((first_part_local.len() + second_part_local.len()) as u64),
825 3 : &cancel,
826 3 : )
827 12 : .await?;
828 3 : assert!(
829 3 : second_part_download.metadata.is_none(),
830 3 : "No metadata should be returned for no metadata upload"
831 3 : );
832 3 :
833 3 : let second_part_remote = aggregate(second_part_download.download_stream).await?;
834 3 : assert_eq!(
835 3 : second_part_local, second_part_remote,
836 3 : "Second part bytes should be returned when requested"
837 3 : );
838 3 :
839 3 : let suffix_bytes = storage
840 3 : .download_byte_range(&upload_target, 13, None, &cancel)
841 12 : .await?
842 3 : .download_stream;
843 3 : let suffix_bytes = aggregate(suffix_bytes).await?;
844 3 : let suffix = std::str::from_utf8(&suffix_bytes)?;
845 3 : assert_eq!(upload_name, suffix);
846 3 :
847 3 : let all_bytes = storage
848 3 : .download_byte_range(&upload_target, 0, None, &cancel)
849 12 : .await?
850 3 : .download_stream;
851 3 : let all_bytes = aggregate(all_bytes).await?;
852 3 : let all_bytes = std::str::from_utf8(&all_bytes)?;
853 3 : assert_eq!(dummy_contents("upload_1"), all_bytes);
854 3 :
855 3 : Ok(())
856 3 : }
857 :
858 : #[tokio::test]
859 3 : async fn download_file_range_negative() -> anyhow::Result<()> {
860 3 : let (storage, cancel) = create_storage()?;
861 3 : let upload_name = "upload_1";
862 16 : let upload_target = upload_dummy_file(&storage, upload_name, None, &cancel).await?;
863 3 :
864 3 : let start = 1_000_000_000;
865 3 : let end = start + 1;
866 3 : match storage
867 3 : .download_byte_range(
868 3 : &upload_target,
869 3 : start,
870 3 : Some(end), // exclusive end
871 3 : &cancel,
872 3 : )
873 3 : .await
874 3 : {
875 3 : Ok(_) => panic!("Should not allow downloading wrong ranges"),
876 3 : Err(e) => {
877 3 : let error_string = e.to_string();
878 3 : assert!(error_string.contains("zero bytes"));
879 3 : assert!(error_string.contains(&start.to_string()));
880 3 : assert!(error_string.contains(&end.to_string()));
881 3 : }
882 3 : }
883 3 :
884 3 : let start = 10000;
885 3 : let end = 234;
886 3 : assert!(start > end, "Should test an incorrect range");
887 3 : match storage
888 3 : .download_byte_range(&upload_target, start, Some(end), &cancel)
889 3 : .await
890 3 : {
891 3 : Ok(_) => panic!("Should not allow downloading wrong ranges"),
892 3 : Err(e) => {
893 3 : let error_string = e.to_string();
894 3 : assert!(error_string.contains("Invalid range"));
895 3 : assert!(error_string.contains(&start.to_string()));
896 3 : assert!(error_string.contains(&end.to_string()));
897 3 : }
898 3 : }
899 3 :
900 3 : Ok(())
901 3 : }
902 :
903 : #[tokio::test]
904 3 : async fn delete_file() -> anyhow::Result<()> {
905 3 : let (storage, cancel) = create_storage()?;
906 3 : let upload_name = "upload_1";
907 18 : let upload_target = upload_dummy_file(&storage, upload_name, None, &cancel).await?;
908 3 :
909 3 : storage.delete(&upload_target, &cancel).await?;
910 9 : assert!(storage.list_all().await?.is_empty());
911 3 :
912 3 : storage
913 3 : .delete(&upload_target, &cancel)
914 3 : .await
915 3 : .expect("Should allow deleting non-existing storage files");
916 3 :
917 3 : Ok(())
918 3 : }
919 :
920 : #[tokio::test]
921 3 : async fn file_with_metadata() -> anyhow::Result<()> {
922 3 : let (storage, cancel) = create_storage()?;
923 3 : let upload_name = "upload_1";
924 3 : let metadata = StorageMetadata(HashMap::from([
925 3 : ("one".to_string(), "1".to_string()),
926 3 : ("two".to_string(), "2".to_string()),
927 3 : ]));
928 3 : let upload_target =
929 21 : upload_dummy_file(&storage, upload_name, Some(metadata.clone()), &cancel).await?;
930 3 :
931 3 : let full_range_download_contents =
932 15 : read_and_check_metadata(&storage, &upload_target, Some(&metadata)).await?;
933 3 : assert_eq!(
934 3 : dummy_contents(upload_name),
935 3 : full_range_download_contents,
936 3 : "We should upload and download the same contents"
937 3 : );
938 3 :
939 3 : let uploaded_bytes = dummy_contents(upload_name).into_bytes();
940 3 : let (first_part_local, _) = uploaded_bytes.split_at(3);
941 3 :
942 3 : let partial_download_with_metadata = storage
943 3 : .download_byte_range(
944 3 : &upload_target,
945 3 : 0,
946 3 : Some(first_part_local.len() as u64),
947 3 : &cancel,
948 3 : )
949 15 : .await?;
950 3 : let first_part_remote = aggregate(partial_download_with_metadata.download_stream).await?;
951 3 : assert_eq!(
952 3 : first_part_local,
953 3 : first_part_remote.as_slice(),
954 3 : "First part bytes should be returned when requested"
955 3 : );
956 3 :
957 3 : assert_eq!(
958 3 : partial_download_with_metadata.metadata,
959 3 : Some(metadata),
960 3 : "We should get the same metadata back for partial download"
961 3 : );
962 3 :
963 3 : Ok(())
964 3 : }
965 :
966 : #[tokio::test]
967 3 : async fn list() -> anyhow::Result<()> {
968 3 : // No delimiter: should recursively list everything
969 3 : let (storage, cancel) = create_storage()?;
970 16 : let child = upload_dummy_file(&storage, "grandparent/parent/child", None, &cancel).await?;
971 3 : let child_sibling =
972 18 : upload_dummy_file(&storage, "grandparent/parent/child_sibling", None, &cancel).await?;
973 18 : let uncle = upload_dummy_file(&storage, "grandparent/uncle", None, &cancel).await?;
974 3 :
975 3 : let listing = storage
976 3 : .list(None, ListingMode::NoDelimiter, None, &cancel)
977 3 : .await?;
978 3 : assert!(listing.prefixes.is_empty());
979 3 : assert_eq!(
980 3 : listing
981 3 : .keys
982 3 : .into_iter()
983 9 : .map(|o| o.key)
984 3 : .collect::<HashSet<_>>(),
985 3 : HashSet::from([uncle.clone(), child.clone(), child_sibling.clone()])
986 3 : );
987 3 :
988 3 : // Delimiter: should only go one deep
989 3 : let listing = storage
990 3 : .list(None, ListingMode::WithDelimiter, None, &cancel)
991 3 : .await?;
992 3 :
993 3 : assert_eq!(
994 3 : listing.prefixes,
995 3 : [RemotePath::from_string("timelines").unwrap()].to_vec()
996 3 : );
997 3 : assert!(listing.keys.is_empty());
998 3 :
999 3 : // Delimiter & prefix with a trailing slash
1000 3 : let listing = storage
1001 3 : .list(
1002 3 : Some(&RemotePath::from_string("timelines/some_timeline/grandparent/").unwrap()),
1003 3 : ListingMode::WithDelimiter,
1004 3 : None,
1005 3 : &cancel,
1006 3 : )
1007 3 : .await?;
1008 3 : assert_eq!(
1009 3 : listing.keys.into_iter().map(|o| o.key).collect::<Vec<_>>(),
1010 3 : [RemotePath::from_string("uncle").unwrap()].to_vec()
1011 3 : );
1012 3 : assert_eq!(
1013 3 : listing.prefixes,
1014 3 : [RemotePath::from_string("parent").unwrap()].to_vec()
1015 3 : );
1016 3 :
1017 3 : // Delimiter and prefix without a trailing slash
1018 3 : let listing = storage
1019 3 : .list(
1020 3 : Some(&RemotePath::from_string("timelines/some_timeline/grandparent").unwrap()),
1021 3 : ListingMode::WithDelimiter,
1022 3 : None,
1023 3 : &cancel,
1024 3 : )
1025 3 : .await?;
1026 3 : assert_eq!(listing.keys, vec![]);
1027 3 : assert_eq!(
1028 3 : listing.prefixes,
1029 3 : [RemotePath::from_string("grandparent").unwrap()].to_vec()
1030 3 : );
1031 3 :
1032 3 : // Delimiter and prefix that's partway through a path component
1033 3 : let listing = storage
1034 3 : .list(
1035 3 : Some(&RemotePath::from_string("timelines/some_timeline/grandp").unwrap()),
1036 3 : ListingMode::WithDelimiter,
1037 3 : None,
1038 3 : &cancel,
1039 3 : )
1040 3 : .await?;
1041 3 : assert_eq!(listing.keys, vec![]);
1042 3 : assert_eq!(
1043 3 : listing.prefixes,
1044 3 : [RemotePath::from_string("grandparent").unwrap()].to_vec()
1045 3 : );
1046 3 :
1047 3 : Ok(())
1048 3 : }
1049 :
1050 : #[tokio::test]
1051 3 : async fn list_part_component() -> anyhow::Result<()> {
1052 3 : // No delimiter: should recursively list everything
1053 3 : let (storage, cancel) = create_storage()?;
1054 3 :
1055 3 : // Imitates what happens in a tenant path when we have an unsharded path and a sharded path, and do a listing
1056 3 : // of the unsharded path: although there is a "directory" at the unsharded path, it should be handled as
1057 3 : // a freeform prefix.
1058 3 : let _child_a =
1059 18 : upload_dummy_file(&storage, "grandparent/tenant-01/child", None, &cancel).await?;
1060 3 : let _child_b =
1061 18 : upload_dummy_file(&storage, "grandparent/tenant/child", None, &cancel).await?;
1062 3 :
1063 3 : // Delimiter and prefix that's partway through a path component
1064 3 : let listing = storage
1065 3 : .list(
1066 3 : Some(
1067 3 : &RemotePath::from_string("timelines/some_timeline/grandparent/tenant").unwrap(),
1068 3 : ),
1069 3 : ListingMode::WithDelimiter,
1070 3 : None,
1071 3 : &cancel,
1072 3 : )
1073 3 : .await?;
1074 3 : assert_eq!(listing.keys, vec![]);
1075 3 :
1076 3 : let mut found_prefixes = listing.prefixes.clone();
1077 3 : found_prefixes.sort();
1078 3 : assert_eq!(
1079 3 : found_prefixes,
1080 3 : [
1081 3 : RemotePath::from_string("tenant").unwrap(),
1082 3 : RemotePath::from_string("tenant-01").unwrap(),
1083 3 : ]
1084 3 : .to_vec()
1085 3 : );
1086 3 :
1087 3 : Ok(())
1088 3 : }
1089 :
1090 : #[tokio::test]
1091 3 : async fn overwrite_shorter_file() -> anyhow::Result<()> {
1092 3 : let (storage, cancel) = create_storage()?;
1093 3 :
1094 3 : let path = RemotePath::new("does/not/matter/file".into())?;
1095 3 :
1096 3 : let body = Bytes::from_static(b"long file contents is long");
1097 3 : {
1098 3 : let len = body.len();
1099 3 : let body =
1100 3 : futures::stream::once(futures::future::ready(std::io::Result::Ok(body.clone())));
1101 11 : storage.upload(body, len, &path, None, &cancel).await?;
1102 3 : }
1103 3 :
1104 6 : let read = aggregate(storage.download(&path, &cancel).await?.download_stream).await?;
1105 3 : assert_eq!(body, read);
1106 3 :
1107 3 : let shorter = Bytes::from_static(b"shorter body");
1108 3 : {
1109 3 : let len = shorter.len();
1110 3 : let body =
1111 3 : futures::stream::once(futures::future::ready(std::io::Result::Ok(shorter.clone())));
1112 9 : storage.upload(body, len, &path, None, &cancel).await?;
1113 3 : }
1114 3 :
1115 6 : let read = aggregate(storage.download(&path, &cancel).await?.download_stream).await?;
1116 3 : assert_eq!(shorter, read);
1117 3 : Ok(())
1118 3 : }
1119 :
1120 : #[tokio::test]
1121 3 : async fn cancelled_upload_can_later_be_retried() -> anyhow::Result<()> {
1122 3 : let (storage, cancel) = create_storage()?;
1123 3 :
1124 3 : let path = RemotePath::new("does/not/matter/file".into())?;
1125 3 :
1126 3 : let body = Bytes::from_static(b"long file contents is long");
1127 3 : {
1128 3 : let len = body.len();
1129 3 : let body =
1130 3 : futures::stream::once(futures::future::ready(std::io::Result::Ok(body.clone())));
1131 3 : let cancel = cancel.child_token();
1132 3 : cancel.cancel();
1133 3 : let e = storage
1134 3 : .upload(body, len, &path, None, &cancel)
1135 9 : .await
1136 3 : .unwrap_err();
1137 3 :
1138 3 : assert!(TimeoutOrCancel::caused_by_cancel(&e));
1139 3 : }
1140 3 :
1141 3 : {
1142 3 : let len = body.len();
1143 3 : let body =
1144 3 : futures::stream::once(futures::future::ready(std::io::Result::Ok(body.clone())));
1145 8 : storage.upload(body, len, &path, None, &cancel).await?;
1146 3 : }
1147 3 :
1148 6 : let read = aggregate(storage.download(&path, &cancel).await?.download_stream).await?;
1149 3 : assert_eq!(body, read);
1150 3 :
1151 3 : Ok(())
1152 3 : }
1153 :
1154 36 : async fn upload_dummy_file(
1155 36 : storage: &LocalFs,
1156 36 : name: &str,
1157 36 : metadata: Option<StorageMetadata>,
1158 36 : cancel: &CancellationToken,
1159 36 : ) -> anyhow::Result<RemotePath> {
1160 36 : let from_path = storage
1161 36 : .storage_root
1162 36 : .join("timelines")
1163 36 : .join("some_timeline")
1164 36 : .join(name);
1165 36 : let (file, size) = create_file_for_upload(&from_path, &dummy_contents(name)).await?;
1166 :
1167 36 : let relative_path = from_path
1168 36 : .strip_prefix(&storage.storage_root)
1169 36 : .context("Failed to strip storage root prefix")
1170 36 : .and_then(RemotePath::new)
1171 36 : .with_context(|| {
1172 0 : format!(
1173 0 : "Failed to resolve remote part of path {:?} for base {:?}",
1174 0 : from_path, storage.storage_root
1175 0 : )
1176 36 : })?;
1177 :
1178 36 : let file = tokio_util::io::ReaderStream::new(file);
1179 36 :
1180 36 : storage
1181 36 : .upload(file, size, &relative_path, metadata, cancel)
1182 177 : .await?;
1183 36 : Ok(relative_path)
1184 36 : }
1185 :
1186 36 : async fn create_file_for_upload(
1187 36 : path: &Utf8Path,
1188 36 : contents: &str,
1189 36 : ) -> anyhow::Result<(fs::File, usize)> {
1190 36 : std::fs::create_dir_all(path.parent().unwrap())?;
1191 36 : let mut file_for_writing = std::fs::OpenOptions::new()
1192 36 : .write(true)
1193 36 : .create_new(true)
1194 36 : .open(path)?;
1195 36 : write!(file_for_writing, "{}", contents)?;
1196 36 : drop(file_for_writing);
1197 36 : let file_size = path.metadata()?.len() as usize;
1198 36 : Ok((
1199 36 : fs::OpenOptions::new().read(true).open(&path).await?,
1200 36 : file_size,
1201 : ))
1202 36 : }
1203 :
1204 54 : fn dummy_contents(name: &str) -> String {
1205 54 : format!("contents for {name}")
1206 54 : }
1207 :
1208 3 : async fn list_files_sorted(storage: &LocalFs) -> anyhow::Result<Vec<RemotePath>> {
1209 9 : let mut files = storage.list_all().await?;
1210 3 : files.sort_by(|a, b| a.0.cmp(&b.0));
1211 3 : Ok(files)
1212 3 : }
1213 :
1214 33 : async fn aggregate(
1215 33 : stream: impl Stream<Item = std::io::Result<Bytes>>,
1216 33 : ) -> anyhow::Result<Vec<u8>> {
1217 : use futures::stream::StreamExt;
1218 33 : let mut out = Vec::new();
1219 33 : let mut stream = std::pin::pin!(stream);
1220 66 : while let Some(res) = stream.next().await {
1221 33 : out.extend_from_slice(&res?[..]);
1222 : }
1223 33 : Ok(out)
1224 33 : }
1225 : }
|