qubit_fs/async_file_system.rs
1// =============================================================================
2// Copyright (c) 2026 Haixing Hu.
3//
4// SPDX-License-Identifier: Apache-2.0
5//
6// Licensed under the Apache License, Version 2.0.
7// =============================================================================
8//! Asynchronous filesystem facade construction boundary.
9
10use std::sync::Arc;
11
12use crate::copy::AsyncCopyFailure;
13use crate::copy::AsyncCopyOperation;
14use crate::copy::CopyAssessment;
15use crate::copy::CopyFailureState;
16use crate::copy::CopyOptions;
17use crate::copy::CopyOutcome;
18use crate::copy::CopyStats;
19use crate::directory::AsyncDirectoryOperation;
20use crate::directory::AsyncDirectoryStream;
21use crate::directory::CreateDirectoryOptions;
22use crate::directory::CreateDirectoryOutcome;
23use crate::directory::DeleteOptions;
24use crate::directory::DeleteOutcome;
25use crate::directory::ListOptions;
26use crate::directory::ListScope;
27use crate::error::FsError;
28use crate::error::FsErrorKind;
29use crate::error::FsOperation;
30use crate::error::FsResult;
31use crate::error::OpenFailure;
32use crate::error::OpenFailureStage;
33use crate::facade::facade_core::FacadeCore;
34use crate::metadata::FileMetadata;
35use crate::metadata::FileSystemCapability;
36use crate::metadata::FileSystemProperties;
37use crate::path::Path;
38use crate::read::AsyncFileReader;
39use crate::read::AsyncRandomAccessReader;
40use crate::read::AsyncReadOperation;
41use crate::read::RandomAccessReadPolicy;
42use crate::read::ReadOptions;
43use crate::rename::RenameFailure;
44use crate::rename::RenameFailureState;
45use crate::rename::RenameOptions;
46use crate::rename::RenameOutcome;
47use crate::rename::validate_rename_outcome;
48use crate::spi::AsyncFileSystemSpi;
49use crate::spi::CreateDirectoryRequest;
50use crate::spi::DeleteDirectoryRequest;
51use crate::spi::DeleteFileRequest;
52use crate::spi::OpenReaderRequest;
53use crate::spi::OpenWriterRequest;
54use crate::spi::ProviderOperation;
55use crate::spi::RenameRequest;
56use crate::spi::ResolvedCreateDirectoryOptions;
57use crate::spi::ResolvedDeleteOptions;
58use crate::spi::ResolvedReadOptions;
59use crate::spi::ResolvedRenameOptions;
60use crate::spi::ResolvedWriteOptions;
61use crate::spi::StatRequest;
62use crate::temp::AsyncTempDirectory;
63use crate::temp::AsyncTempFile;
64use crate::temp::PersistOptions;
65use crate::temp::RejectedAsyncTempResource;
66use crate::temp::TempOptions;
67use crate::write::AsyncFileWriter;
68use crate::write::AsyncWriteAllOperation;
69use crate::write::AsyncWriteAllOperationFailure;
70use crate::write::RejectedAsyncWriter;
71use crate::write::WriteOptions;
72
73/// Application-facing asynchronous filesystem facade.
74///
75/// It validates provider boundaries, exposes asynchronous operations, and owns
76/// the cancellation-safe copy operation entry point.
77///
78/// # Examples
79///
80/// Applications obtain their configured facade from a provider or registry
81/// integration. The function below reads at most three bytes; the result may
82/// be shorter when the file contains fewer bytes.
83///
84/// ```rust
85/// use qubit_fs::{AsyncFileSystem, FsResult, Path};
86/// use qubit_fs::read::ReadOptions;
87///
88/// async fn read_report_prefix(filesystem: &AsyncFileSystem, path: &Path) -> FsResult<Vec<u8>> {
89/// let prefix = filesystem.read_prefix(path, ReadOptions::default(), 3).await?;
90/// Ok(prefix.into_bytes())
91/// }
92/// ```
93#[derive(Clone)]
94pub struct AsyncFileSystem {
95 /// Provider implementation receiving validated asynchronous requests.
96 spi: Arc<dyn AsyncFileSystemSpi>,
97 /// Shared immutable state and deterministic preflight policy.
98 core: Arc<FacadeCore>,
99}
100
101impl AsyncFileSystem {
102 /// Constructs a facade and caches one validated provider snapshot.
103 ///
104 /// # Type Parameters
105 ///
106 /// - `S`: Concrete provider SPI implementation type.
107 ///
108 /// # Parameters
109 ///
110 /// - `spi`: Provider implementation whose properties and operations back
111 /// this facade.
112 #[inline]
113 pub fn from_spi<S>(spi: S) -> FsResult<Self>
114 where
115 S: AsyncFileSystemSpi + 'static,
116 {
117 Self::from_shared_spi(Arc::new(spi))
118 }
119
120 /// Constructs a facade from a shared provider implementation.
121 ///
122 /// # Parameters
123 ///
124 /// - `spi`: Provider implementation whose properties and operations back
125 /// this facade.
126 #[inline]
127 pub fn from_shared_spi(spi: Arc<dyn AsyncFileSystemSpi>) -> FsResult<Self> {
128 let core = FacadeCore::new(spi.properties())?;
129 Ok(Self {
130 spi,
131 core: Arc::new(core),
132 })
133 }
134
135 /// Returns the immutable property snapshot without provider I/O.
136 #[inline]
137 #[must_use]
138 pub fn properties(&self) -> &FileSystemProperties {
139 self.core.properties()
140 }
141
142 /// Validates a write request without opening a provider session.
143 ///
144 /// # Parameters
145 ///
146 /// - `path`: Logical path of the resource involved in this operation.
147 /// - `options`: Write behavior and guarantees to validate before provider
148 /// work begins.
149 pub fn validate_write(&self, path: &Path, options: &WriteOptions) -> FsResult<()> {
150 self.core.validate_write_request(path, options)
151 }
152
153 /// Assesses copy routes without performing provider I/O.
154 ///
155 /// # Parameters
156 ///
157 /// - `source`: Logical path of the source resource.
158 /// - `target`: Destination logical path affected by the operation.
159 /// - `options`: Copy route, conflict, consistency, and metadata guarantees
160 /// requested by the caller.
161 ///
162 /// # Errors
163 /// Returns an invalid-options or requirement error when no provider or
164 /// stream execution route can satisfy the request.
165 pub fn assess_copy(&self, source: &Path, target: &Path, options: &CopyOptions) -> FsResult<CopyAssessment> {
166 self.core.assess_copy(source, target, options)
167 }
168
169 /// Returns shared deterministic facade policy to operation objects.
170 #[inline]
171 pub(crate) fn core(&self) -> &FacadeCore {
172 &self.core
173 }
174
175 /// Returns the asynchronous provider implementation to operation objects.
176 #[inline]
177 pub(crate) fn spi(&self) -> &dyn AsyncFileSystemSpi {
178 self.spi.as_ref()
179 }
180
181 /// Asynchronously reads metadata after local validation completes.
182 ///
183 /// # Parameters
184 ///
185 /// - `path`: Logical path of the resource involved in this operation.
186 ///
187 /// # Errors
188 /// Returns a validation, provider, or provider-contract error when the
189 /// path cannot be read or the response identifies another path.
190 pub async fn stat(&self, path: &Path) -> FsResult<FileMetadata> {
191 self.validate_path(path, FsOperation::Stat)?;
192 let response = self
193 .spi
194 .stat(StatRequest::new(path, ()))
195 .await
196 .map_err(|error| self.enrich(error, path, FsOperation::Stat))?;
197 if response.path() != path {
198 return Err(self.contract_error(path, "provider returned metadata for a different path"));
199 }
200 Ok(response.into_metadata())
201 }
202
203 /// Asynchronously reports whether the path exists.
204 ///
205 /// # Parameters
206 ///
207 /// - `path`: Logical path of the resource involved in this operation.
208 ///
209 /// # Errors
210 /// Returns the original filesystem error for failures other than an
211 /// explicit `NotFound` response.
212 pub async fn exists(&self, path: &Path) -> FsResult<bool> {
213 match self.stat(path).await {
214 Ok(_) => Ok(true),
215 Err(error) if error.kind() == FsErrorKind::NotFound => Ok(false),
216 Err(error) => Err(error.with_operation(FsOperation::Exists)),
217 }
218 }
219
220 /// Asynchronously opens a validated directory stream.
221 ///
222 /// # Parameters
223 ///
224 /// - `scope`: Requested directory or namespace listing scope.
225 /// - `options`: Selection, recursion, page-size, and deadline settings for
226 /// the listing.
227 ///
228 /// # Errors
229 /// Returns an invalid-options, missing-capability, or provider error when
230 /// the scope or options cannot be served.
231 pub async fn list(&self, scope: &ListScope, options: ListOptions) -> FsResult<AsyncDirectoryStream> {
232 AsyncDirectoryOperation::new(self).list(scope, options).await
233 }
234
235 /// Asynchronously opens a validated reader and verifies its identity.
236 ///
237 /// # Parameters
238 ///
239 /// - `path`: Logical path of the resource involved in this operation.
240 /// - `options`: Read behavior and limits for opening or consuming the
241 /// resource.
242 ///
243 /// # Errors
244 /// Returns a validation, capability, provider, or provider-contract error
245 /// when the reader cannot be opened safely.
246 pub async fn open_reader(&self, path: &Path, options: ReadOptions) -> FsResult<AsyncFileReader> {
247 self.open_reader_resolved(path, ResolvedReadOptions::new(options)).await
248 }
249
250 /// Opens a facade-validated asynchronous reader with an internal hint.
251 ///
252 /// # Parameters
253 ///
254 /// - `path`: Logical path of the resource involved in this operation.
255 /// - `resolved`: Validated read options and the facade’s resolved
256 /// read-planning hints.
257 pub(crate) async fn open_reader_resolved(
258 &self,
259 path: &Path,
260 resolved: ResolvedReadOptions,
261 ) -> FsResult<AsyncFileReader> {
262 let options = resolved.options().clone();
263 self.validate_path(path, FsOperation::OpenReader)?;
264 options
265 .validate_against(self.properties().capabilities())
266 .map_err(|error| self.enrich(error, path, FsOperation::OpenReader))?;
267 self.properties()
268 .limits()
269 .validate_read_range(path, options.length())
270 .map_err(|error| self.enrich(error, path, FsOperation::OpenReader))?;
271 self.require(FileSystemCapability::Read, FsOperation::OpenReader, path)?;
272 let opened = self
273 .spi
274 .open_reader(OpenReaderRequest::new(path, resolved))
275 .await
276 .map_err(|error| self.enrich(error, path, FsOperation::OpenReader))?;
277 self.validate_opened_info(opened.info(), path)?;
278 Ok(opened.into_reader())
279 }
280
281 /// Opens a complete file for explicit-offset reads on one opened object.
282 /// The observed length is an upper bound, not a content snapshot.
283 ///
284 /// # Parameters
285 /// - `path`: Logical file path to open.
286 /// - `options`: Read options. Only no offset or offset zero, no length, and
287 /// no checksum validation are accepted; version conditions are kept.
288 ///
289 /// # Returns
290 /// A handle whose reads use the object opened by the provider.
291 ///
292 /// # Errors
293 /// Returns path/option errors, missing read or operation errors, the
294 /// provider open error, or a provider-contract error for mismatched
295 /// identity, missing metadata, non-file kind, or unknown length.
296 pub async fn open_random_access_reader(
297 &self,
298 path: &Path,
299 options: ReadOptions,
300 ) -> FsResult<AsyncRandomAccessReader> {
301 self.validate_path(path, FsOperation::OpenReader)?;
302 RandomAccessReadPolicy::validate_open(&options).map_err(|e| self.enrich(e, path, FsOperation::OpenReader))?;
303 RandomAccessReadPolicy::validate_capabilities(&options, self.properties().capabilities())
304 .map_err(|e| self.enrich(e, path, FsOperation::OpenReader))?;
305 self.require(FileSystemCapability::Read, FsOperation::OpenReader, path)?;
306 if !self.core.provider_supports(ProviderOperation::OpenRandomAccessReader) {
307 return Err(self.enrich(
308 FsError::new(
309 FsErrorKind::UnsupportedOperation,
310 FsOperation::OpenReader,
311 "provider does not implement random-access sessions",
312 ),
313 path,
314 FsOperation::OpenReader,
315 ));
316 }
317 let opened = self
318 .spi
319 .open_random_access_reader(OpenReaderRequest::new(path, ResolvedReadOptions::new(options)))
320 .await
321 .map_err(|e| self.enrich(e, path, FsOperation::OpenReader))?;
322 let (info, session) = opened.into_parts();
323 self.validate_opened_info(&info, path)?;
324 let len = RandomAccessReadPolicy::opened_len(info.metadata())
325 .map_err(|e| self.enrich(e, path, FsOperation::OpenReader))?;
326 Ok(AsyncRandomAccessReader::new(
327 info,
328 len,
329 self.properties().limits().max_read_range_bytes(),
330 self.properties().info().provider_id().to_owned(),
331 session,
332 ))
333 }
334
335 /// Asynchronously reads an entire file while enforcing a strict byte cap.
336 ///
337 /// The cap applies to bytes actually read, even when opened metadata
338 /// overestimates the resource length.
339 ///
340 /// Long aggregate reads may periodically return
341 /// [`std::task::Poll::Pending`] even when the provider remains ready.
342 /// This gives the executor an opportunity to schedule other tasks and
343 /// observe cancellation. It does not bound the time spent in a single
344 /// provider poll or guarantee a scheduling order; cancellation cannot
345 /// interrupt a provider poll already in progress. The byte cap bounds
346 /// the result size, not elapsed time.
347 ///
348 /// # Parameters
349 ///
350 /// - `path`: Logical path of the resource involved in this operation.
351 /// - `options`: Read behavior and limits for opening or consuming the
352 /// resource.
353 /// - `max_bytes`: Maximum number of bytes this operation may return or
354 /// consume.
355 ///
356 /// # Errors
357 /// Returns the reader or read error when validation, opening, or bounded
358 /// reading fails.
359 pub async fn read_all(&self, path: &Path, options: ReadOptions, max_bytes: usize) -> FsResult<Vec<u8>> {
360 AsyncReadOperation::new(self).read_all(path, options, max_bytes).await
361 }
362
363 /// Asynchronously reads at most max_bytes from a file.
364 ///
365 /// Long aggregate reads may periodically return
366 /// [`std::task::Poll::Pending`] even when the provider remains ready.
367 /// This gives the executor an opportunity to schedule other tasks and
368 /// observe cancellation. It does not bound the time spent in a single
369 /// provider poll or guarantee a scheduling order; cancellation cannot
370 /// interrupt a provider poll already in progress. The byte cap bounds
371 /// the result size, not elapsed time.
372 ///
373 /// # Parameters
374 ///
375 /// - `path`: Logical path of the resource involved in this operation.
376 /// - `options`: Read behavior and limits for opening or consuming the
377 /// resource.
378 /// - `max_bytes`: Maximum number of bytes this operation may return or
379 /// consume.
380 ///
381 /// # Errors
382 /// Returns the reader or read error when validation, opening, or bounded
383 /// reading fails.
384 pub async fn read_prefix(
385 &self,
386 path: &Path,
387 options: ReadOptions,
388 max_bytes: usize,
389 ) -> FsResult<crate::read::PrefixReadOutcome> {
390 AsyncReadOperation::new(self)
391 .read_prefix(path, options, max_bytes)
392 .await
393 }
394
395 /// Asynchronously opens a validated writer and verifies its identity.
396 ///
397 /// An [`OpenFailure`] identifies where the attempt stopped:
398 /// [`OpenFailureStage::Preflight`] means local validation rejected it
399 /// before provider I/O; [`OpenFailureStage::ProviderOpen`] means the
400 /// provider returned an error before an opened envelope; and
401 /// [`OpenFailureStage::OutcomeValidation`] means an opened envelope failed
402 /// identity validation. The last stage can retain a [`RejectedAsyncWriter`]
403 /// that owns an isolated session with abort-only cleanup authority. Handle
404 /// that recovery explicitly with `abort_async`; dropping the failure or
405 /// receiving no recovery does not prove that no side effect occurred.
406 /// Keep the typed failure intact when recovery matters instead of using `?`
407 /// to discard it.
408 ///
409 /// # Parameters
410 ///
411 /// - `path`: Logical path of the resource involved in this operation.
412 /// - `options`: Write behavior and guarantees to validate before provider
413 /// work begins.
414 ///
415 /// # Errors
416 /// Returns the contextual error, opening stage, and any isolated recovery
417 /// session when validation, provider opening, or outcome validation fails.
418 pub async fn open_writer(
419 &self,
420 path: &Path,
421 options: WriteOptions,
422 ) -> Result<AsyncFileWriter, OpenFailure<RejectedAsyncWriter>> {
423 self.core
424 .validate_write_request(path, &options)
425 .map_err(|error| OpenFailure::new(error, OpenFailureStage::Preflight, None))?;
426 let atomicity = options.atomicity();
427 let durability = options.durability();
428 let opened = self
429 .spi
430 .open_writer(OpenWriterRequest::new(path, ResolvedWriteOptions::new(options)))
431 .await
432 .map_err(|error| {
433 OpenFailure::new(
434 self.enrich(error, path, FsOperation::OpenWriter),
435 OpenFailureStage::ProviderOpen,
436 None,
437 )
438 })?;
439 let (info, session) = opened.into_parts();
440 if let Err(error) = self.validate_opened_info(&info, path) {
441 return Err(OpenFailure::new(
442 error,
443 OpenFailureStage::OutcomeValidation,
444 Some(RejectedAsyncWriter::new(
445 session,
446 self.properties().info().provider_id(),
447 Some(path.clone()),
448 )),
449 ));
450 }
451 Ok(AsyncFileWriter::new(
452 info,
453 session,
454 atomicity,
455 durability,
456 self.properties().info().provider_id(),
457 self.properties().limits().max_write_bytes().maximum(),
458 ))
459 }
460
461 /// Begins an owning asynchronous whole-file write operation.
462 ///
463 /// Moves `path`, `bytes`, and `options` into the request and retains a
464 /// clone of this filesystem. Construction performs no provider I/O.
465 /// Keep the operation outside the cancellation scope and cancel only
466 /// its `execute` future so publication facts and recovery
467 /// responsibility remain available.
468 ///
469 /// # Parameters
470 ///
471 /// - `path`: Logical path of the resource involved in this operation.
472 /// - `bytes`: Payload to write as one complete resource.
473 /// - `options`: Write behavior and guarantees to validate before provider
474 /// work begins.
475 ///
476 /// # Returns
477 ///
478 /// A ready operation that no longer borrows the caller's filesystem or
479 /// payload. The payload is released after execution ends or is cancelled.
480 ///
481 /// # Errors
482 ///
483 /// Returns a `NotPublished` failure with zero confirmed bytes if the path,
484 /// capabilities, options, or payload size fail local validation. Rejected
485 /// construction consumes and releases the payload.
486 pub fn begin_write_all(
487 &self,
488 path: Path,
489 bytes: Vec<u8>,
490 options: WriteOptions,
491 ) -> Result<AsyncWriteAllOperation, AsyncWriteAllOperationFailure> {
492 self.core.validate_write_request(&path, &options).map_err(|error| {
493 AsyncWriteAllOperationFailure::new(error, crate::write::WriteFailureState::NotPublished, 0)
494 })?;
495 self.properties()
496 .limits()
497 .validate_write_size(&path, bytes.len())
498 .map_err(|error| {
499 AsyncWriteAllOperationFailure::new(
500 self.core.enrich(error, Some(&path), FsOperation::Write),
501 crate::write::WriteFailureState::NotPublished,
502 0,
503 )
504 })?;
505 Ok(AsyncWriteAllOperation::new(self.clone(), path, bytes, options))
506 }
507
508 /// Asynchronously creates a directory after local validation.
509 ///
510 /// # Parameters
511 ///
512 /// - `path`: Logical path of the resource involved in this operation.
513 /// - `options`: Options that define the operation and its requested
514 /// guarantees.
515 ///
516 /// # Errors
517 /// Returns a validation, capability, provider, or provider-contract error
518 /// when the directory cannot be created as requested.
519 pub async fn create_directory(
520 &self,
521 path: &Path,
522 options: CreateDirectoryOptions,
523 ) -> FsResult<CreateDirectoryOutcome> {
524 self.validate_path(path, FsOperation::CreateDir)?;
525 self.require(FileSystemCapability::CreateDirectory, FsOperation::CreateDir, path)?;
526 let exists_ok = options.exists_ok();
527 let outcome = self
528 .spi
529 .create_directory(CreateDirectoryRequest::new(
530 path,
531 ResolvedCreateDirectoryOptions::new(options),
532 ))
533 .await
534 .map_err(|error| self.enrich(error, path, FsOperation::CreateDir))?;
535 if outcome.already_existed() && !exists_ok {
536 return Err(self.core.contract_error(
537 path,
538 FsOperation::CreateDir,
539 "provider accepted an existing directory without exists_ok",
540 ));
541 }
542 Ok(outcome)
543 }
544
545 /// Asynchronously deletes a file after local validation.
546 ///
547 /// # Parameters
548 ///
549 /// - `path`: Logical path of the resource involved in this operation.
550 /// - `options`: Deletion behavior, including whether a missing target is
551 /// acceptable.
552 ///
553 /// # Errors
554 /// Returns a validation, capability, provider, or provider-contract error
555 /// when deletion cannot be confirmed.
556 #[inline]
557 pub async fn delete_file(&self, path: &Path, options: DeleteOptions) -> FsResult<DeleteOutcome> {
558 self.delete(path, options, false).await
559 }
560
561 /// Asynchronously deletes a directory after local validation.
562 ///
563 /// # Parameters
564 ///
565 /// - `path`: Logical path of the resource involved in this operation.
566 /// - `options`: Deletion behavior, including whether a missing target is
567 /// acceptable.
568 ///
569 /// # Errors
570 /// Returns a validation, capability, provider, or provider-contract error
571 /// when deletion cannot be confirmed.
572 #[inline]
573 pub async fn delete_directory(&self, path: &Path, options: DeleteOptions) -> FsResult<DeleteOutcome> {
574 self.delete(path, options, true).await
575 }
576
577 /// Renames one resource through the single asynchronous provider primitive.
578 ///
579 /// # Parameters
580 ///
581 /// - `source`: Logical path of the source resource.
582 /// - `target`: Destination logical path affected by the operation.
583 /// - `options`: Overwrite, atomicity, and durability requirements for the
584 /// rename.
585 ///
586 /// # Errors
587 /// Returns [`RenameFailure`] with the confirmed transition state when
588 /// validation, provider execution, or outcome validation fails.
589 pub async fn rename(
590 &self,
591 source: &Path,
592 target: &Path,
593 options: RenameOptions,
594 ) -> Result<RenameOutcome, RenameFailure> {
595 if let Err(error) = self.rename_preflight(source, target, &options) {
596 return Err(self.contextual_rename_failure(error, RenameFailureState::Unchanged, source, target));
597 }
598 match self
599 .spi
600 .rename(RenameRequest::new(
601 source,
602 target,
603 ResolvedRenameOptions::new(options.clone()),
604 ))
605 .await
606 {
607 Ok(outcome) => match validate_rename_outcome(&outcome, &options, source, target) {
608 Some(violation) => Err(self.contextual_rename_failure(
609 self.contract_error(source, violation.message),
610 violation.state,
611 source,
612 target,
613 )),
614 None => Ok(outcome),
615 },
616 Err(failure) => {
617 let (error, state) = failure.into_parts();
618 Err(self.contextual_rename_failure(error, state, source, target))
619 }
620 }
621 }
622
623 /// Asynchronously creates a temporary file and validates its provider
624 /// identity.
625 ///
626 /// # Parameters
627 ///
628 /// - `options`: Parent, naming, and parent-creation settings for the
629 /// temporary resource.
630 ///
631 /// # Errors
632 /// Returns [`OpenFailure`] when preflight, provider creation, or temporary
633 /// identity validation fails.
634 pub async fn create_temp_file(
635 &self,
636 options: TempOptions,
637 ) -> Result<AsyncTempFile, OpenFailure<RejectedAsyncTempResource>> {
638 let parent = options.parent().cloned();
639 self.core
640 .validate_temp_parent(parent.as_ref())
641 .map_err(|error| OpenFailure::new(error, OpenFailureStage::Preflight, None))?;
642 self.core
643 .require(FileSystemCapability::TempFile, FsOperation::CreateTemp, parent.as_ref())
644 .map_err(|error| OpenFailure::new(error, OpenFailureStage::Preflight, None))?;
645 let opened = self
646 .spi
647 .create_temp_file(crate::spi::CreateTempFileRequest::new(options))
648 .await
649 .map_err(|error| {
650 OpenFailure::new(
651 self.core.enrich(error, parent.as_ref(), FsOperation::CreateTemp),
652 OpenFailureStage::ProviderOpen,
653 None,
654 )
655 })?;
656 let (info, session) = opened.into_parts();
657 if let Err(cause) = self.validate_temp_info(&info, crate::metadata::FileKind::File, parent.as_ref()) {
658 let error = FsError::with_source(
659 FsErrorKind::ProviderContractViolation,
660 FsOperation::ValidateProviderOutcome,
661 "provider returned an invalid temporary identity",
662 cause,
663 )
664 .with_provider(self.properties().info().provider_id());
665 let error = match parent.as_ref() {
666 Some(path) => error.with_path(path.clone()),
667 None => error,
668 };
669 return Err(OpenFailure::new(
670 error,
671 OpenFailureStage::OutcomeValidation,
672 Some(RejectedAsyncTempResource::new(
673 session,
674 self.properties().info().provider_id(),
675 parent,
676 )),
677 ));
678 }
679 Ok(AsyncTempFile::new(
680 self.clone(),
681 info.path().clone(),
682 session,
683 "temporary file",
684 ))
685 }
686
687 /// Asynchronously creates a temporary directory and validates its identity.
688 ///
689 /// # Parameters
690 ///
691 /// - `options`: Parent, naming, and parent-creation settings for the
692 /// temporary resource.
693 ///
694 /// # Errors
695 /// Returns [`OpenFailure`] when preflight, provider creation, or temporary
696 /// identity validation fails.
697 pub async fn create_temp_directory(
698 &self,
699 options: TempOptions,
700 ) -> Result<AsyncTempDirectory, OpenFailure<RejectedAsyncTempResource>> {
701 let parent = options.parent().cloned();
702 self.core
703 .validate_temp_parent(parent.as_ref())
704 .map_err(|error| OpenFailure::new(error, OpenFailureStage::Preflight, None))?;
705 self.core
706 .require(
707 FileSystemCapability::TempDirectory,
708 FsOperation::CreateTemp,
709 parent.as_ref(),
710 )
711 .map_err(|error| OpenFailure::new(error, OpenFailureStage::Preflight, None))?;
712 let opened = self
713 .spi
714 .create_temp_directory(crate::spi::CreateTempDirectoryRequest::new(options))
715 .await
716 .map_err(|error| {
717 OpenFailure::new(
718 self.core.enrich(error, parent.as_ref(), FsOperation::CreateTemp),
719 OpenFailureStage::ProviderOpen,
720 None,
721 )
722 })?;
723 let (info, session) = opened.into_parts();
724 if let Err(cause) = self.validate_temp_info(&info, crate::metadata::FileKind::Directory, parent.as_ref()) {
725 let error = FsError::with_source(
726 FsErrorKind::ProviderContractViolation,
727 FsOperation::ValidateProviderOutcome,
728 "provider returned an invalid temporary identity",
729 cause,
730 )
731 .with_provider(self.properties().info().provider_id());
732 let error = match parent.as_ref() {
733 Some(path) => error.with_path(path.clone()),
734 None => error,
735 };
736 return Err(OpenFailure::new(
737 error,
738 OpenFailureStage::OutcomeValidation,
739 Some(RejectedAsyncTempResource::new(
740 session,
741 self.properties().info().provider_id(),
742 parent,
743 )),
744 ));
745 }
746 Ok(AsyncTempDirectory::new(self.clone(), info.path().clone(), session))
747 }
748
749 /// Begins a copy after synchronous path, option, and capability preflight.
750 ///
751 /// This method performs no provider I/O. Provider work begins only when
752 /// [`AsyncCopyOperation::execute`] is polled.
753 /// Keep the returned operation outside the cancellation scope and cancel
754 /// only its `execute` future. The operation then remains available to
755 /// inspect publication state and take any retained writer recovery.
756 ///
757 /// # Parameters
758 ///
759 /// - `source`: Logical path of the source resource.
760 /// - `target`: Destination logical path affected by the operation.
761 /// - `options`: Copy route, conflict, consistency, and metadata guarantees
762 /// requested by the caller.
763 ///
764 /// # Errors
765 /// Returns [`AsyncCopyFailure`] when local preflight rejects the request.
766 #[allow(clippy::result_large_err)]
767 pub fn begin_copy(
768 &self,
769 source: Path,
770 target: Path,
771 options: CopyOptions,
772 ) -> Result<AsyncCopyOperation, AsyncCopyFailure> {
773 self.copy_preflight(&source, &target, &options).map_err(|error| {
774 self.contextual_copy_failure(
775 error,
776 CopyFailureState::Unchanged,
777 CopyStats::default(),
778 &source,
779 &target,
780 )
781 })?;
782 let symlink_policy = options
783 .symlink_policy_override()
784 .unwrap_or(self.properties().symlink_policy());
785 Ok(AsyncCopyOperation::new(
786 self.clone(),
787 source,
788 target,
789 options,
790 symlink_policy,
791 ))
792 }
793
794 /// Rechecks provider-reported success against requested copy guarantees.
795 ///
796 /// # Parameters
797 ///
798 /// - `outcome`: Provider-reported copy outcome to validate against the
799 /// request.
800 /// - `options`: Copy route, conflict, consistency, and metadata guarantees
801 /// requested by the caller.
802 /// - `source`: Logical path of the source resource.
803 /// - `target`: Destination logical path affected by the operation.
804 #[allow(clippy::result_large_err)]
805 pub(crate) fn verify_completed_copy(
806 &self,
807 outcome: CopyOutcome,
808 options: &CopyOptions,
809 source: &Path,
810 target: &Path,
811 ) -> Result<CopyOutcome, AsyncCopyFailure> {
812 if let Some(message) = outcome.contract_violation(options) {
813 return Err(self.contextual_copy_failure(
814 FsError::new(FsErrorKind::ProviderContractViolation, FsOperation::Copy, message),
815 outcome.violation_failure_state(options),
816 *outcome.stats(),
817 source,
818 target,
819 ));
820 }
821 Ok(outcome)
822 }
823
824 /// Performs all no-I/O copy validation required before an operation exists.
825 ///
826 /// # Parameters
827 ///
828 /// - `source`: Logical path of the source resource.
829 /// - `target`: Destination logical path affected by the operation.
830 /// - `options`: Copy route, conflict, consistency, and metadata guarantees
831 /// requested by the caller.
832 fn copy_preflight(&self, source: &Path, target: &Path, options: &CopyOptions) -> FsResult<()> {
833 self.validate_path(source, FsOperation::Copy)?;
834 self.validate_path(target, FsOperation::Copy)?;
835 options
836 .validate_against(self.properties().capabilities())
837 .map_err(|error| {
838 self.enrich(error, source, FsOperation::Copy)
839 .with_target(target.clone())
840 })?;
841 if source == target {
842 return Err(FsError::new(
843 crate::error::FsErrorKind::InvalidOptions,
844 FsOperation::Copy,
845 "copy source and target must differ",
846 )
847 .with_path(source.clone())
848 .with_target(target.clone()));
849 }
850 Ok(())
851 }
852
853 /// Performs no-I/O validation for the single rename primitive.
854 ///
855 /// # Parameters
856 ///
857 /// - `source`: Logical path of the source resource.
858 /// - `target`: Destination logical path affected by the operation.
859 /// - `options`: Overwrite, atomicity, and durability requirements for the
860 /// rename.
861 fn rename_preflight(&self, source: &Path, target: &Path, options: &RenameOptions) -> FsResult<()> {
862 self.validate_path(source, FsOperation::Rename)?;
863 self.validate_path(target, FsOperation::Rename)?;
864 options
865 .validate_against(self.properties().capabilities())
866 .map_err(|error| {
867 self.enrich(error, source, FsOperation::Rename)
868 .with_target(target.clone())
869 })?;
870 self.require(FileSystemCapability::Rename, FsOperation::Rename, source)?;
871 if source == target {
872 return Err(FsError::new(
873 FsErrorKind::InvalidOptions,
874 FsOperation::Rename,
875 "rename source and target must differ",
876 )
877 .with_path(source.clone())
878 .with_target(target.clone()));
879 }
880 Ok(())
881 }
882
883 /// Dispatches the selected deletion primitive after local validation.
884 ///
885 /// # Parameters
886 ///
887 /// - `path`: Logical path of the resource involved in this operation.
888 /// - `options`: Deletion behavior, including whether a missing target is
889 /// acceptable.
890 /// - `directory`: Whether the delete request targets a directory.
891 async fn delete(&self, path: &Path, options: DeleteOptions, directory: bool) -> FsResult<DeleteOutcome> {
892 self.validate_path(path, FsOperation::Delete)?;
893 options
894 .validate_against(self.properties().capabilities())
895 .map_err(|error| self.enrich(error, path, FsOperation::Delete))?;
896 self.require(FileSystemCapability::Delete, FsOperation::Delete, path)?;
897 let missing_ok = options.missing_ok();
898 let request_options = ResolvedDeleteOptions::new(options);
899 let outcome = if directory {
900 self.spi
901 .delete_directory(DeleteDirectoryRequest::new(path, request_options))
902 .await
903 } else {
904 self.spi
905 .delete_file(DeleteFileRequest::new(path, request_options))
906 .await
907 }
908 .map_err(|error| self.enrich(error, path, FsOperation::Delete))?;
909 if outcome.already_missing() && !missing_ok {
910 return Err(self.core.contract_error(
911 path,
912 FsOperation::Delete,
913 "provider accepted a missing target without missing_ok",
914 ));
915 }
916 Ok(outcome)
917 }
918
919 /// Validates a logical path against the cached provider snapshot.
920 ///
921 /// # Parameters
922 ///
923 /// - `path`: Logical path of the resource involved in this operation.
924 /// - `operation`: Filesystem operation used for validation or error
925 /// context.
926 fn validate_path(&self, path: &Path, operation: FsOperation) -> FsResult<()> {
927 self.core.validate_path(path, operation)
928 }
929
930 /// Requires a provider-advertised capability before operation creation.
931 ///
932 /// # Parameters
933 ///
934 /// - `capability`: Capability required before provider work can begin.
935 /// - `operation`: Filesystem operation used for validation or error
936 /// context.
937 /// - `path`: Logical path of the resource involved in this operation.
938 pub(crate) fn require(
939 &self,
940 capability: FileSystemCapability,
941 operation: FsOperation,
942 path: &Path,
943 ) -> FsResult<()> {
944 self.core.require(capability, operation, Some(path))
945 }
946
947 /// Contextualizes a copy failure with its source, target, and provider
948 /// facts.
949 ///
950 /// # Parameters
951 ///
952 /// - `error`: Filesystem error whose kind, source, and established facts
953 /// are retained.
954 /// - `state`: Operation state used to classify confirmed side effects.
955 /// - `stats`: Copy progress statistics reported by the operation.
956 /// - `source`: Logical path of the source resource.
957 /// - `target`: Destination logical path affected by the operation.
958 pub(crate) fn contextual_copy_failure(
959 &self,
960 error: FsError,
961 state: CopyFailureState,
962 stats: CopyStats,
963 source: &Path,
964 target: &Path,
965 ) -> AsyncCopyFailure {
966 AsyncCopyFailure::new(
967 error.with_operation(FsOperation::Copy).with_missing_context(
968 source,
969 Some(target),
970 self.properties().info().provider_id(),
971 ),
972 state,
973 stats,
974 )
975 }
976
977 /// Adds source, target, and provider facts to an asynchronous rename
978 /// failure.
979 ///
980 /// # Parameters
981 ///
982 /// - `error`: Filesystem error whose kind, source, and established facts
983 /// are retained.
984 /// - `state`: Operation state used to classify confirmed side effects.
985 /// - `source`: Logical path of the source resource.
986 /// - `target`: Destination logical path affected by the operation.
987 fn contextual_rename_failure(
988 &self,
989 error: FsError,
990 state: RenameFailureState,
991 source: &Path,
992 target: &Path,
993 ) -> RenameFailure {
994 RenameFailure::new(
995 error.with_operation(FsOperation::Rename).with_missing_context(
996 source,
997 Some(target),
998 self.properties().info().provider_id(),
999 ),
1000 state,
1001 )
1002 }
1003
1004 /// Adds missing public context to a provider error.
1005 ///
1006 /// # Parameters
1007 ///
1008 /// - `error`: Filesystem error whose kind, source, and established facts
1009 /// are retained.
1010 /// - `path`: Logical path of the resource involved in this operation.
1011 /// - `operation`: Filesystem operation used for validation or error
1012 /// context.
1013 fn enrich(&self, error: FsError, path: &Path, operation: FsOperation) -> FsError {
1014 self.core.enrich(error, Some(path), operation)
1015 }
1016
1017 /// Creates a provider-contract violation bound to the requested path.
1018 ///
1019 /// # Parameters
1020 ///
1021 /// - `path`: Logical path of the resource involved in this operation.
1022 /// - `message`: Diagnostic message for the constructed filesystem error.
1023 fn contract_error(&self, path: &Path, message: &'static str) -> FsError {
1024 self.core
1025 .contract_error(path, FsOperation::ValidateProviderOutcome, message)
1026 }
1027
1028 /// Validates a provider-opened handle identity before exposing it to
1029 /// callers.
1030 ///
1031 /// # Parameters
1032 ///
1033 /// - `info`: Opened-resource identity and metadata returned by the
1034 /// provider.
1035 /// - `path`: Logical path of the resource involved in this operation.
1036 fn validate_opened_info(&self, info: &crate::metadata::OpenedFileInfo, path: &Path) -> FsResult<()> {
1037 self.core.validate_opened_info(info, path)
1038 }
1039
1040 /// Validates a provider-created temporary resource before exposing it.
1041 ///
1042 /// # Parameters
1043 ///
1044 /// - `info`: Opened-resource identity and metadata returned by the
1045 /// provider.
1046 /// - `expected_kind`: Resource kind required for the opened object.
1047 /// - `requested_parent`: Optional parent location supplied for temporary
1048 /// creation.
1049 fn validate_temp_info(
1050 &self,
1051 info: &crate::metadata::OpenedFileInfo,
1052 expected_kind: crate::metadata::FileKind,
1053 requested_parent: Option<&Path>,
1054 ) -> FsResult<()> {
1055 self.core.validate_temp_info(info, expected_kind, requested_parent)
1056 }
1057
1058 /// Performs no-I/O preflight for asynchronous temporary persistence.
1059 ///
1060 /// # Parameters
1061 ///
1062 /// - `source`: Logical path of the source resource.
1063 /// - `target`: Destination logical path affected by the operation.
1064 /// - `options`: Options that define the operation and its requested
1065 /// guarantees.
1066 pub(crate) fn preflight_temp_persist(
1067 &self,
1068 source: &Path,
1069 target: &Path,
1070 options: &PersistOptions,
1071 ) -> FsResult<()> {
1072 self.validate_path(source, FsOperation::PersistTemp).map_err(|error| {
1073 self.enrich(error, source, FsOperation::PersistTemp)
1074 .with_failure_path(source.clone())
1075 .with_path(source.clone())
1076 .with_target(target.clone())
1077 })?;
1078 self.validate_path(target, FsOperation::PersistTemp).map_err(|error| {
1079 self.enrich(error, source, FsOperation::PersistTemp)
1080 .with_failure_target(target.clone())
1081 .with_path(source.clone())
1082 .with_target(target.clone())
1083 })?;
1084 options
1085 .validate_against(self.properties().capabilities())
1086 .map_err(|error| {
1087 self.enrich(error, source, FsOperation::PersistTemp)
1088 .with_target(target.clone())
1089 })
1090 }
1091
1092 /// Validates a provider-generated target reported by temporary keep.
1093 ///
1094 /// # Parameters
1095 ///
1096 /// - `source`: Logical path of the source resource.
1097 /// - `target`: Destination logical path affected by the operation.
1098 pub(crate) fn validate_temp_keep_target(&self, source: &Path, target: &Path) -> FsResult<()> {
1099 self.validate_path(target, FsOperation::KeepTemp).map_err(|_| {
1100 self.contract_error(
1101 source,
1102 "provider returned a temporary keep target with an invalid logical path",
1103 )
1104 .with_target(target.clone())
1105 })
1106 }
1107}