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