qubit_fs/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//! Validating synchronous filesystem facade.
9
10use std::sync::Arc;
11
12use crate::copy::CopyAssessment;
13use crate::copy::CopyFailure;
14use crate::copy::CopyOperation;
15use crate::copy::CopyOptions;
16use crate::copy::CopyOutcome;
17use crate::directory::CreateDirectoryOptions;
18use crate::directory::CreateDirectoryOutcome;
19use crate::directory::DeleteOptions;
20use crate::directory::DeleteOutcome;
21use crate::directory::DirectoryOperation;
22use crate::directory::DirectoryStream;
23use crate::directory::ListOptions;
24use crate::directory::ListScope;
25use crate::error::FsError;
26use crate::error::FsErrorKind;
27use crate::error::FsOperation;
28use crate::error::FsResult;
29use crate::error::OpenFailure;
30use crate::error::OpenFailureStage;
31use crate::facade::facade_core::FacadeCore;
32use crate::metadata::FileKind;
33use crate::metadata::FileMetadata;
34use crate::metadata::FileSystemCapability;
35use crate::metadata::FileSystemProperties;
36use crate::metadata::OpenedFileInfo;
37use crate::metadata::WriteOutcome;
38use crate::path::Path;
39use crate::read::FileReader;
40use crate::read::PrefixReadOutcome;
41use crate::read::RandomAccessReadPolicy;
42use crate::read::RandomAccessReader;
43use crate::read::ReadOperation;
44use crate::read::ReadOptions;
45use crate::rename::RenameFailure;
46use crate::rename::RenameFailureState;
47use crate::rename::RenameOptions;
48use crate::rename::RenameOutcome;
49use crate::rename::validate_rename_outcome;
50use crate::spi::CreateDirectoryRequest;
51use crate::spi::CreateTempDirectoryRequest;
52use crate::spi::CreateTempFileRequest;
53use crate::spi::DeleteDirectoryRequest;
54use crate::spi::DeleteFileRequest;
55use crate::spi::FileSystemSpi;
56use crate::spi::OpenReaderRequest;
57use crate::spi::OpenWriterRequest;
58use crate::spi::ProviderOperation;
59use crate::spi::RenameRequest;
60use crate::spi::ResolvedCreateDirectoryOptions;
61use crate::spi::ResolvedDeleteOptions;
62use crate::spi::ResolvedReadOptions;
63use crate::spi::ResolvedRenameOptions;
64use crate::spi::ResolvedWriteOptions;
65use crate::spi::StatRequest;
66use crate::temp::PersistOptions;
67use crate::temp::RejectedTempResource;
68use crate::temp::TempDirectory;
69use crate::temp::TempFile;
70use crate::temp::TempOptions;
71use crate::write::FileWriter;
72use crate::write::RejectedWriter;
73use crate::write::WriteAllFailure;
74use crate::write::WriteOperation;
75use crate::write::WriteOptions;
76
77/// Application-facing synchronous filesystem facade.
78///
79/// # Examples
80///
81/// Applications obtain their configured facade from a provider or registry
82/// integration. The function below reads at most three bytes; the result may
83/// be shorter when the file contains fewer bytes.
84///
85/// ```rust
86/// use qubit_fs::{FileSystem, FsResult, Path};
87/// use qubit_fs::read::ReadOptions;
88///
89/// fn read_report_prefix(filesystem: &FileSystem, path: &Path) -> FsResult<Vec<u8>> {
90/// let prefix = filesystem.read_prefix(path, ReadOptions::default(), 3)?;
91/// Ok(prefix.into_bytes())
92/// }
93/// ```
94#[derive(Clone)]
95pub struct FileSystem {
96 /// Provider implementation receiving validated synchronous requests.
97 spi: Arc<dyn FileSystemSpi>,
98 /// Shared immutable state and deterministic preflight policy.
99 core: Arc<FacadeCore>,
100}
101
102impl FileSystem {
103 /// Constructs a facade and caches the provider's single validated property
104 /// snapshot.
105 ///
106 /// # Type Parameters
107 ///
108 /// - `S`: Concrete provider SPI implementation type.
109 ///
110 /// # Parameters
111 /// - `spi`: Provider implementation whose properties and operations back
112 /// the facade.
113 ///
114 /// # Returns
115 /// The facade when the provider property snapshot is valid.
116 ///
117 /// # Errors
118 /// Returns the provider property validation error when its snapshot is
119 /// inconsistent.
120 #[inline]
121 pub fn from_spi<S>(spi: S) -> FsResult<Self>
122 where
123 S: FileSystemSpi + 'static,
124 {
125 Self::from_shared_spi(Arc::new(spi))
126 }
127
128 /// Constructs a facade from a shared provider implementation.
129 ///
130 /// # Parameters
131 /// - `spi`: Shared provider implementation retained by the facade.
132 ///
133 /// # Returns
134 /// The facade when the provider property snapshot is valid.
135 ///
136 /// # Errors
137 /// Returns the provider property validation error when its snapshot is
138 /// inconsistent.
139 #[inline]
140 pub fn from_shared_spi(spi: Arc<dyn FileSystemSpi>) -> FsResult<Self> {
141 let core = FacadeCore::new(spi.properties())?;
142 Ok(Self {
143 spi,
144 core: Arc::new(core),
145 })
146 }
147
148 /// Returns the immutable property snapshot without provider I/O.
149 ///
150 /// # Returns
151 /// The validated properties captured when this facade was constructed.
152 #[inline]
153 #[must_use]
154 pub fn properties(&self) -> &FileSystemProperties {
155 self.core.properties()
156 }
157
158 /// Assesses copy routes without performing provider I/O.
159 ///
160 /// # Errors
161 /// Returns an invalid-options or requirement error when no provider or
162 /// stream execution route can satisfy the request.
163 ///
164 /// # Parameters
165 /// - `source`: Logical source path.
166 /// - `target`: Logical destination path.
167 /// - `options`: Copy policy to assess.
168 ///
169 /// # Returns
170 /// The selected route and the first statically rejected fallback, when one
171 /// exists.
172 pub fn assess_copy(&self, source: &Path, target: &Path, options: &CopyOptions) -> FsResult<CopyAssessment> {
173 self.core.assess_copy(source, target, options)
174 }
175
176 /// Reads metadata after all local validation succeeds.
177 ///
178 /// # Errors
179 /// Returns the provider or validation error when `path` is invalid, the
180 /// provider cannot stat it, or the provider returns a mismatched path.
181 ///
182 /// # Parameters
183 /// - `path`: Logical resource path to inspect.
184 ///
185 /// # Returns
186 /// Metadata for the requested path after provider identity validation.
187 pub fn stat(&self, path: &Path) -> FsResult<FileMetadata> {
188 self.validate_path(path, FsOperation::Stat)?;
189 let response = self
190 .spi
191 .stat(StatRequest::new(path, ()))
192 .map_err(|error| self.enrich(error, path, FsOperation::Stat))?;
193 if response.path() != path {
194 return Err(self.contract_error(
195 path,
196 FsOperation::ValidateProviderOutcome,
197 "provider returned metadata for a different path",
198 ));
199 }
200 Ok(response.into_metadata())
201 }
202
203 /// Returns `false` only for an explicit not-found response.
204 ///
205 /// # Errors
206 /// Returns the original filesystem error for validation, provider, or
207 /// provider-contract failures other than `NotFound`.
208 ///
209 /// # Parameters
210 /// - `path`: Logical resource path to check.
211 ///
212 /// # Returns
213 /// `true` when metadata is returned, or `false` for an explicit not-found
214 /// response.
215 pub fn exists(&self, path: &Path) -> FsResult<bool> {
216 match self.stat(path) {
217 Ok(_) => Ok(true),
218 Err(error) if error.kind() == FsErrorKind::NotFound => Ok(false),
219 Err(error) => Err(error.with_operation(FsOperation::Exists)),
220 }
221 }
222
223 /// Copies `source` to `target` through an optional provider fast path and a
224 /// safe stream fallback.
225 ///
226 /// # Errors
227 /// Returns [`CopyFailure`] with a recovery state. A provider failure is
228 /// never retried; only an explicit provider decline can select the
229 /// facade's allowlisted fallback.
230 ///
231 /// # Parameters
232 /// - `source`: Logical resource to copy.
233 /// - `target`: Logical destination path.
234 /// - `options`: Copy behavior and fallback policy.
235 ///
236 /// # Returns
237 /// The confirmed copy outcome.
238 #[allow(clippy::result_large_err)]
239 pub fn copy(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<CopyOutcome, CopyFailure> {
240 CopyOperation::new(self, source, target, options).execute()
241 }
242
243 /// Renames one resource through exactly one provider rename primitive.
244 ///
245 /// # Errors
246 /// Returns [`RenameFailure`] with the provider-confirmed transition state.
247 /// This method never implements rename through copy and delete.
248 ///
249 /// # Parameters
250 /// - `source`: Existing logical resource path.
251 /// - `target`: Destination logical path.
252 /// - `options`: Rename policy passed to the provider.
253 ///
254 /// # Returns
255 /// The provider-confirmed rename outcome.
256 pub fn rename(&self, source: &Path, target: &Path, options: RenameOptions) -> Result<RenameOutcome, RenameFailure> {
257 if let Err(error) = self.rename_preflight(source, target, &options) {
258 return Err(self.contextualize_rename_failure(
259 RenameFailure::new(error, RenameFailureState::Unchanged),
260 source,
261 target,
262 ));
263 }
264 match self.spi.rename(RenameRequest::new(
265 source,
266 target,
267 ResolvedRenameOptions::new(options.clone()),
268 )) {
269 Ok(outcome) => match validate_rename_outcome(&outcome, &options, source, target) {
270 Some(violation) => Err(RenameFailure::new(
271 self.contract_error(source, FsOperation::Rename, violation.message)
272 .with_target(target.clone()),
273 violation.state,
274 )),
275 None => Ok(outcome),
276 },
277 Err(failure) => {
278 let (error, state) = failure.into_parts();
279 Err(RenameFailure::new(
280 error.with_operation(FsOperation::Rename).with_missing_context(
281 source,
282 Some(target),
283 self.properties().info().provider_id(),
284 ),
285 state,
286 ))
287 }
288 }
289 }
290
291 /// Opens a provider directory stream after local option validation.
292 ///
293 /// # Errors
294 /// Returns an invalid-options, missing-capability, or provider error when
295 /// the scope or options cannot be served.
296 ///
297 /// # Parameters
298 /// - `scope`: Directory scope to enumerate.
299 /// - `options`: Listing behavior and limits.
300 ///
301 /// # Returns
302 /// A stream of validated directory entries.
303 pub fn list(&self, scope: &ListScope, options: ListOptions) -> FsResult<DirectoryStream> {
304 DirectoryOperation::new(self).list(scope, options)
305 }
306
307 /// Opens a provider reader after local option validation.
308 ///
309 /// # Errors
310 /// Returns an invalid-path, unsupported-capability, provider, or
311 /// provider-contract error when the reader cannot be opened safely.
312 ///
313 /// # Parameters
314 /// - `path`: Logical file path to open.
315 /// - `options`: Read range and behavior.
316 ///
317 /// # Returns
318 /// A reader bound to the validated provider handle.
319 pub fn open_reader(&self, path: &Path, options: ReadOptions) -> FsResult<FileReader> {
320 self.open_reader_resolved(path, ResolvedReadOptions::new(options))
321 }
322
323 /// Opens a complete file for explicit-offset reads on one opened object.
324 /// The observed length is an upper bound, not a content snapshot.
325 ///
326 /// # Parameters
327 /// - `path`: Logical file path to open.
328 /// - `options`: Read options. Only no offset or offset zero, no length, and
329 /// no checksum validation are accepted; version conditions are kept.
330 ///
331 /// # Returns
332 /// A handle whose reads use the object opened by the provider.
333 ///
334 /// # Errors
335 /// Returns path/option errors, missing read or operation errors, the
336 /// provider open error, or a provider-contract error for mismatched
337 /// identity, missing metadata, non-file kind, or unknown length.
338 pub fn open_random_access_reader(&self, path: &Path, options: ReadOptions) -> FsResult<RandomAccessReader> {
339 self.validate_path(path, FsOperation::OpenReader)?;
340 RandomAccessReadPolicy::validate_open(&options).map_err(|e| self.enrich(e, path, FsOperation::OpenReader))?;
341 RandomAccessReadPolicy::validate_capabilities(&options, self.properties().capabilities())
342 .map_err(|e| self.enrich(e, path, FsOperation::OpenReader))?;
343 self.require(FileSystemCapability::Read, FsOperation::OpenReader, path)?;
344 if !self.core.provider_supports(ProviderOperation::OpenRandomAccessReader) {
345 return Err(self.enrich(
346 FsError::new(
347 FsErrorKind::UnsupportedOperation,
348 FsOperation::OpenReader,
349 "provider does not implement random-access sessions",
350 ),
351 path,
352 FsOperation::OpenReader,
353 ));
354 }
355 let opened = self
356 .spi
357 .open_random_access_reader(OpenReaderRequest::new(path, ResolvedReadOptions::new(options)))
358 .map_err(|e| self.enrich(e, path, FsOperation::OpenReader))?;
359 let (info, session) = opened.into_parts();
360 self.validate_opened_info(&info, path)?;
361 let len = RandomAccessReadPolicy::opened_len(info.metadata())
362 .map_err(|e| self.enrich(e, path, FsOperation::OpenReader))?;
363 Ok(RandomAccessReader::new(
364 info,
365 len,
366 self.properties().limits().max_read_range_bytes(),
367 self.properties().info().provider_id().to_owned(),
368 session,
369 ))
370 }
371
372 /// Opens a provider writer after local option validation.
373 ///
374 /// # Errors
375 /// Returns [`OpenFailure`] identifying preflight, provider-open, or
376 /// provider-contract failure; a retained rejected writer is available when
377 /// provider cleanup is required.
378 ///
379 /// # Parameters
380 /// - `path`: Logical file path to open for writing.
381 /// - `options`: Write and publication behavior.
382 ///
383 /// # Returns
384 /// The writer, or an `OpenFailure` retaining cleanup state when needed.
385 pub fn open_writer(&self, path: &Path, options: WriteOptions) -> Result<FileWriter, OpenFailure<RejectedWriter>> {
386 self.core
387 .validate_write_request(path, &options)
388 .map_err(|error| OpenFailure::new(error, OpenFailureStage::Preflight, None))?;
389 let atomicity = options.atomicity();
390 let durability = options.durability();
391 let opened = self
392 .spi
393 .open_writer(OpenWriterRequest::new(path, ResolvedWriteOptions::new(options)))
394 .map_err(|error| {
395 OpenFailure::new(
396 self.enrich(error, path, FsOperation::OpenWriter),
397 OpenFailureStage::ProviderOpen,
398 None,
399 )
400 })?;
401 let (info, session) = opened.into_parts();
402 if let Err(error) = self.validate_opened_info(&info, path) {
403 return Err(OpenFailure::new(
404 error,
405 OpenFailureStage::OutcomeValidation,
406 Some(RejectedWriter::new(
407 session,
408 self.properties().info().provider_id(),
409 Some(path.clone()),
410 )),
411 ));
412 }
413 Ok(FileWriter::new(
414 info,
415 session,
416 atomicity,
417 durability,
418 self.properties().info().provider_id(),
419 self.properties().limits().max_write_bytes().maximum(),
420 ))
421 }
422
423 /// Creates a temporary file and binds its provider session to this facade.
424 ///
425 /// # Errors
426 /// Returns [`OpenFailure`] when preflight, provider creation, or temporary
427 /// identity validation fails; the recovery value may retain cleanup work.
428 ///
429 /// # Parameters
430 /// - `options`: Parent and naming policy for the temporary file.
431 ///
432 /// # Returns
433 /// A temporary file handle bound to this facade.
434 pub fn create_temp_file(&self, options: TempOptions) -> Result<TempFile, OpenFailure<RejectedTempResource>> {
435 let parent = options.parent().cloned();
436 self.core
437 .validate_temp_parent(parent.as_ref())
438 .map_err(|error| OpenFailure::new(error, OpenFailureStage::Preflight, None))?;
439 self.core
440 .require(FileSystemCapability::TempFile, FsOperation::CreateTemp, parent.as_ref())
441 .map_err(|error| OpenFailure::new(error, OpenFailureStage::Preflight, None))?;
442 let opened = self
443 .spi
444 .create_temp_file(CreateTempFileRequest::new(options))
445 .map_err(|error| {
446 OpenFailure::new(
447 self.core.enrich(error, parent.as_ref(), FsOperation::CreateTemp),
448 OpenFailureStage::ProviderOpen,
449 None,
450 )
451 })?;
452 let (info, session) = opened.into_parts();
453 if let Err(cause) = self.validate_temp_info(&info, FileKind::File, parent.as_ref()) {
454 let error = FsError::with_source(
455 FsErrorKind::ProviderContractViolation,
456 FsOperation::ValidateProviderOutcome,
457 "provider returned an invalid temporary identity",
458 cause,
459 )
460 .with_provider(self.properties().info().provider_id());
461 let error = match parent.as_ref() {
462 Some(path) => error.with_path(path.clone()),
463 None => error,
464 };
465 return Err(OpenFailure::new(
466 error,
467 OpenFailureStage::OutcomeValidation,
468 Some(RejectedTempResource::new(
469 session,
470 self.properties().info().provider_id(),
471 parent,
472 )),
473 ));
474 }
475 Ok(TempFile::new(self.clone(), info.path().clone(), session))
476 }
477
478 /// Creates a temporary directory and binds its provider session to this
479 /// facade.
480 ///
481 /// # Errors
482 /// Returns [`OpenFailure`] when preflight, provider creation, or temporary
483 /// identity validation fails; the recovery value may retain cleanup work.
484 ///
485 /// # Parameters
486 /// - `options`: Parent and naming policy for the temporary directory.
487 ///
488 /// # Returns
489 /// A temporary directory handle bound to this facade.
490 pub fn create_temp_directory(
491 &self,
492 options: TempOptions,
493 ) -> Result<TempDirectory, OpenFailure<RejectedTempResource>> {
494 let parent = options.parent().cloned();
495 self.core
496 .validate_temp_parent(parent.as_ref())
497 .map_err(|error| OpenFailure::new(error, OpenFailureStage::Preflight, None))?;
498 self.core
499 .require(
500 FileSystemCapability::TempDirectory,
501 FsOperation::CreateTemp,
502 parent.as_ref(),
503 )
504 .map_err(|error| OpenFailure::new(error, OpenFailureStage::Preflight, None))?;
505 let opened = self
506 .spi
507 .create_temp_directory(CreateTempDirectoryRequest::new(options))
508 .map_err(|error| {
509 OpenFailure::new(
510 self.core.enrich(error, parent.as_ref(), FsOperation::CreateTemp),
511 OpenFailureStage::ProviderOpen,
512 None,
513 )
514 })?;
515 let (info, session) = opened.into_parts();
516 if let Err(cause) = self.validate_temp_info(&info, FileKind::Directory, parent.as_ref()) {
517 let error = FsError::with_source(
518 FsErrorKind::ProviderContractViolation,
519 FsOperation::ValidateProviderOutcome,
520 "provider returned an invalid temporary identity",
521 cause,
522 )
523 .with_provider(self.properties().info().provider_id());
524 let error = match parent.as_ref() {
525 Some(path) => error.with_path(path.clone()),
526 None => error,
527 };
528 return Err(OpenFailure::new(
529 error,
530 OpenFailureStage::OutcomeValidation,
531 Some(RejectedTempResource::new(
532 session,
533 self.properties().info().provider_id(),
534 parent,
535 )),
536 ));
537 }
538 Ok(TempDirectory::new(self.clone(), info.path().clone(), session))
539 }
540
541 /// Creates a directory after local path validation.
542 ///
543 /// # Errors
544 /// Returns an invalid-path, missing-capability, provider, or provider-
545 /// contract error when the directory cannot be created as requested.
546 ///
547 /// # Parameters
548 /// - `path`: Logical directory path to create.
549 /// - `options`: Creation and parent handling policy.
550 ///
551 /// # Returns
552 /// The provider-confirmed directory creation outcome.
553 pub fn create_directory(&self, path: &Path, options: CreateDirectoryOptions) -> FsResult<CreateDirectoryOutcome> {
554 self.validate_path(path, FsOperation::CreateDir)?;
555 self.require(FileSystemCapability::CreateDirectory, FsOperation::CreateDir, path)?;
556 let exists_ok = options.exists_ok();
557 let outcome = self
558 .spi
559 .create_directory(CreateDirectoryRequest::new(
560 path,
561 ResolvedCreateDirectoryOptions::new(options),
562 ))
563 .map_err(|error| self.enrich(error, path, FsOperation::CreateDir))?;
564 if outcome.already_existed() && !exists_ok {
565 return Err(self.contract_error(
566 path,
567 FsOperation::CreateDir,
568 "provider accepted an existing directory without exists_ok",
569 ));
570 }
571 Ok(outcome)
572 }
573
574 /// Deletes a file after local option validation.
575 ///
576 /// # Errors
577 /// Returns an invalid-options, missing-capability, provider, or
578 /// provider-contract error when deletion cannot be confirmed.
579 ///
580 /// # Parameters
581 /// - `path`: Logical file path to delete.
582 /// - `options`: Deletion policy.
583 ///
584 /// # Returns
585 /// The provider-confirmed deletion outcome.
586 #[inline]
587 pub fn delete_file(&self, path: &Path, options: DeleteOptions) -> FsResult<DeleteOutcome> {
588 self.delete(path, options, false)
589 }
590
591 /// Deletes a directory after local option validation.
592 ///
593 /// # Errors
594 /// Returns an invalid-options, missing-capability, provider, or
595 /// provider-contract error when deletion cannot be confirmed.
596 ///
597 /// # Parameters
598 /// - `path`: Logical directory path to delete.
599 /// - `options`: Deletion policy.
600 ///
601 /// # Returns
602 /// The provider-confirmed deletion outcome.
603 #[inline]
604 pub fn delete_directory(&self, path: &Path, options: DeleteOptions) -> FsResult<DeleteOutcome> {
605 self.delete(path, options, true)
606 }
607
608 /// Reads one file into memory up to `max_bytes` after opening a reader.
609 ///
610 /// The byte cap applies to bytes actually read, even when opened metadata
611 /// overestimates the resource length.
612 ///
613 /// # Errors
614 /// Returns the reader or read error when validation, opening, or bounded
615 /// reading fails.
616 ///
617 /// # Parameters
618 /// - `path`: Logical file path to read.
619 /// - `options`: Read range and behavior.
620 /// - `max_bytes`: Maximum number of bytes allowed in memory.
621 ///
622 /// # Returns
623 /// The complete contents when the file fits within the byte cap.
624 pub fn read_all(&self, path: &Path, options: ReadOptions, max_bytes: usize) -> FsResult<Vec<u8>> {
625 ReadOperation::new(self).read_all(path, options, max_bytes)
626 }
627
628 /// Reads at most max_bytes from a file without requiring a complete read.
629 ///
630 /// # Errors
631 /// Returns the reader or read error when validation, opening, or bounded
632 /// reading fails.
633 ///
634 /// # Parameters
635 /// - `path`: Logical file path to read.
636 /// - `options`: Read range and behavior.
637 /// - `max_bytes`: Maximum number of bytes to consume.
638 ///
639 /// # Returns
640 /// The bytes read and the termination reason, which distinguishes end of
641 /// file from reaching the byte limit.
642 pub fn read_prefix(&self, path: &Path, options: ReadOptions, max_bytes: usize) -> FsResult<PrefixReadOutcome> {
643 ReadOperation::new(self).read_prefix(path, options, max_bytes)
644 }
645
646 /// Writes all bytes and retains the writer if transfer or commit fails.
647 ///
648 /// # Errors
649 /// Returns [`WriteAllFailure`] with the confirmed byte count and retained
650 /// writer when validation, transfer, or publication fails.
651 ///
652 /// # Parameters
653 /// - `path`: Logical destination path.
654 /// - `bytes`: Complete payload to write.
655 /// - `options`: Write and publication behavior.
656 ///
657 /// # Returns
658 /// The confirmed write outcome, or a failure retaining the writer and
659 /// confirmed transfer state.
660 pub fn write_all(&self, path: &Path, bytes: &[u8], options: WriteOptions) -> Result<WriteOutcome, WriteAllFailure> {
661 WriteOperation::new(self).write_all(path, bytes, options)
662 }
663
664 /// Validates a write request without opening a provider session.
665 ///
666 /// # Parameters
667 /// - `path`: Logical destination path to validate.
668 /// - `options`: Write configuration checked against cached capabilities and
669 /// limits.
670 ///
671 /// # Returns
672 /// `Ok(())` when the request is locally valid.
673 ///
674 /// # Errors
675 /// Returns the path, option, capability, or limit validation error.
676 pub fn validate_write(&self, path: &Path, options: &WriteOptions) -> FsResult<()> {
677 self.core.validate_write_request(path, options)
678 }
679
680 /// Returns shared deterministic facade policy to operation objects.
681 ///
682 /// # Returns
683 /// The cached policy shared by internal operation objects.
684 #[inline]
685 pub(crate) fn core(&self) -> &FacadeCore {
686 &self.core
687 }
688
689 /// Returns the synchronous provider implementation to operation objects.
690 ///
691 /// # Returns
692 /// The provider implementation retained by this facade.
693 #[inline]
694 pub(crate) fn spi(&self) -> &dyn FileSystemSpi {
695 self.spi.as_ref()
696 }
697
698 /// Opens a facade-validated reader with an internal resolved option hint.
699 ///
700 /// # Parameters
701 /// - `path`: Logical file path to open.
702 /// - `resolved`: Validated read options, including any internal hint.
703 ///
704 /// # Returns
705 /// A reader bound to the validated provider handle.
706 ///
707 /// # Errors
708 /// Returns a path, option, capability, provider, or provider-contract
709 /// error when the reader cannot be opened safely.
710 pub(crate) fn open_reader_resolved(&self, path: &Path, resolved: ResolvedReadOptions) -> FsResult<FileReader> {
711 let options = resolved.options().clone();
712 self.validate_path(path, FsOperation::OpenReader)?;
713 options
714 .validate_against(self.properties().capabilities())
715 .map_err(|error| self.enrich(error, path, FsOperation::OpenReader))?;
716 self.properties()
717 .limits()
718 .validate_read_range(path, options.length())
719 .map_err(|error| self.enrich(error, path, FsOperation::OpenReader))?;
720 self.require(FileSystemCapability::Read, FsOperation::OpenReader, path)?;
721 let opened = self
722 .spi
723 .open_reader(OpenReaderRequest::new(path, resolved))
724 .map_err(|error| self.enrich(error, path, FsOperation::OpenReader))?;
725 let (info, reader) = opened.into_parts();
726 self.validate_opened_info(&info, path)?;
727 Ok(FileReader::new(info, reader))
728 }
729
730 /// Validates a temporary-resource persistence request before provider
731 /// effects.
732 ///
733 /// This crate-visible preflight preserves source and target context before
734 /// a temporary resource is handed to its provider.
735 ///
736 /// # Parameters
737 /// - `source`: Temporary resource path.
738 /// - `target`: Requested persistence destination.
739 /// - `options`: Persistence behavior to validate.
740 ///
741 /// # Returns
742 /// `Ok(())` when the paths and options pass local validation.
743 ///
744 /// # Errors
745 /// Returns a path or option validation error with source and target
746 /// context.
747 pub(crate) fn preflight_temp_persist(
748 &self,
749 source: &Path,
750 target: &Path,
751 options: &PersistOptions,
752 ) -> FsResult<()> {
753 self.validate_path(source, FsOperation::PersistTemp).map_err(|error| {
754 self.enrich(error, source, FsOperation::PersistTemp)
755 .with_failure_path(source.clone())
756 .with_path(source.clone())
757 .with_target(target.clone())
758 })?;
759 self.validate_path(target, FsOperation::PersistTemp).map_err(|error| {
760 self.enrich(error, source, FsOperation::PersistTemp)
761 .with_failure_target(target.clone())
762 .with_path(source.clone())
763 .with_target(target.clone())
764 })?;
765 options
766 .validate_against(self.properties().capabilities())
767 .map_err(|error| {
768 self.enrich(error, source, FsOperation::PersistTemp)
769 .with_target(target.clone())
770 })?;
771 Ok(())
772 }
773
774 /// Validates a provider-generated target reported by temporary keep.
775 ///
776 /// # Parameters
777 /// - `source`: Temporary resource path used for error context.
778 /// - `target`: Provider-reported destination path.
779 ///
780 /// # Returns
781 /// `Ok(())` when the provider-reported target is a valid logical path.
782 ///
783 /// # Errors
784 /// Returns a provider-contract error when the target path is invalid.
785 pub(crate) fn validate_temp_keep_target(&self, source: &Path, target: &Path) -> FsResult<()> {
786 self.validate_path(target, FsOperation::KeepTemp).map_err(|_| {
787 self.contract_error(
788 source,
789 FsOperation::ValidateProviderOutcome,
790 "provider returned a temporary keep target with an invalid logical path",
791 )
792 .with_target(target.clone())
793 })
794 }
795
796 /// Validates and dispatches one deletion primitive.
797 ///
798 /// # Parameters
799 /// - `path`: Logical target path.
800 /// - `options`: Deletion policy.
801 /// - `directory`: Whether to invoke the directory deletion primitive.
802 ///
803 /// # Returns
804 /// The provider-confirmed deletion outcome.
805 ///
806 /// # Errors
807 /// Returns validation, capability, provider, or provider-contract errors.
808 fn delete(&self, path: &Path, options: DeleteOptions, directory: bool) -> FsResult<DeleteOutcome> {
809 self.validate_path(path, FsOperation::Delete)?;
810 options
811 .validate_against(self.properties().capabilities())
812 .map_err(|error| self.enrich(error, path, FsOperation::Delete))?;
813 self.require(FileSystemCapability::Delete, FsOperation::Delete, path)?;
814 let missing_ok = options.missing_ok();
815 let outcome = if directory {
816 self.spi
817 .delete_directory(DeleteDirectoryRequest::new(path, ResolvedDeleteOptions::new(options)))
818 } else {
819 self.spi
820 .delete_file(DeleteFileRequest::new(path, ResolvedDeleteOptions::new(options)))
821 }
822 .map_err(|error| self.enrich(error, path, FsOperation::Delete))?;
823 if outcome.already_missing() && !missing_ok {
824 return Err(self.contract_error(
825 path,
826 FsOperation::Delete,
827 "provider accepted a missing target without missing_ok",
828 ));
829 }
830 Ok(outcome)
831 }
832
833 /// Performs validation before the single rename provider call.
834 ///
835 /// # Parameters
836 /// - `source`: Existing logical resource path.
837 /// - `target`: Requested destination path.
838 /// - `options`: Rename policy.
839 ///
840 /// # Returns
841 /// `Ok(())` when the request passes local validation.
842 ///
843 /// # Errors
844 /// Returns a path, option, capability, or same-path validation error.
845 fn rename_preflight(&self, source: &Path, target: &Path, options: &RenameOptions) -> FsResult<()> {
846 self.validate_path(source, FsOperation::Rename)?;
847 self.validate_path(target, FsOperation::Rename)?;
848 options
849 .validate_against(self.properties().capabilities())
850 .map_err(|error| {
851 self.enrich(error, source, FsOperation::Rename)
852 .with_target(target.clone())
853 })?;
854 self.require(FileSystemCapability::Rename, FsOperation::Rename, source)?;
855 if source == target {
856 return Err(FsError::new(
857 FsErrorKind::InvalidOptions,
858 FsOperation::Rename,
859 "rename source and target must differ",
860 )
861 .with_path(source.clone())
862 .with_target(target.clone()));
863 }
864 Ok(())
865 }
866
867 /// Adds source, target, and provider facts required by public rename
868 /// failures.
869 ///
870 /// # Parameters
871 /// - `failure`: Rename failure to enrich.
872 /// - `source`: Original source path.
873 /// - `target`: Requested destination path.
874 ///
875 /// # Returns
876 /// The failure with missing source, target, and provider context filled.
877 fn contextualize_rename_failure(&self, failure: RenameFailure, source: &Path, target: &Path) -> RenameFailure {
878 let (error, state) = failure.into_parts();
879 RenameFailure::new(
880 error.with_missing_context(source, Some(target), self.properties().info().provider_id()),
881 state,
882 )
883 }
884
885 /// Validates a path against the cached provider snapshot before I/O.
886 ///
887 /// # Parameters
888 /// - `path`: Logical resource path to validate.
889 /// - `operation`: Operation associated with validation errors.
890 ///
891 /// # Returns
892 /// `Ok(())` when the path is valid for this provider.
893 ///
894 /// # Errors
895 /// Returns the path validation error.
896 fn validate_path(&self, path: &Path, operation: FsOperation) -> FsResult<()> {
897 self.core.validate_path(path, operation)
898 }
899
900 /// Requires an advertised capability before I/O.
901 ///
902 /// # Parameters
903 /// - `capability`: Capability required by the operation.
904 /// - `operation`: Operation associated with a missing-capability error.
905 /// - `path`: Logical resource path included in error context.
906 ///
907 /// # Returns
908 /// `Ok(())` when the provider advertises the capability.
909 ///
910 /// # Errors
911 /// Returns a missing-capability error when the provider lacks it.
912 fn require(&self, capability: FileSystemCapability, operation: FsOperation, path: &Path) -> FsResult<()> {
913 self.core.require(capability, operation, Some(path))
914 }
915
916 /// Adds missing public error context to a provider error.
917 ///
918 /// # Parameters
919 /// - `error`: Provider error to enrich.
920 /// - `path`: Logical resource path associated with the error.
921 /// - `operation`: Operation associated with the error.
922 ///
923 /// # Returns
924 /// The error with missing path, operation, and provider context filled.
925 fn enrich(&self, error: FsError, path: &Path, operation: FsOperation) -> FsError {
926 self.core.enrich(error, Some(path), operation)
927 }
928
929 /// Builds a provider-contract error for an invalid outcome.
930 ///
931 /// # Parameters
932 /// - `path`: Path associated with the invalid outcome.
933 /// - `operation`: Operation that produced the outcome.
934 /// - `message`: Description of the provider contract violation.
935 ///
936 /// # Returns
937 /// A provider-contract error containing the supplied context.
938 fn contract_error(&self, path: &Path, operation: FsOperation, message: &str) -> FsError {
939 self.core.contract_error(path, operation, message)
940 }
941
942 /// Validates the identity the provider attached to an opened file handle.
943 ///
944 /// # Parameters
945 /// - `info`: Provider-reported opened-file identity.
946 /// - `path`: Requested logical resource path.
947 ///
948 /// # Returns
949 /// `Ok(())` when filesystem and path identities match.
950 ///
951 /// # Errors
952 /// Returns a provider-contract error when either identity differs.
953 fn validate_opened_info(&self, info: &OpenedFileInfo, path: &Path) -> FsResult<()> {
954 self.core.validate_opened_info(info, path)
955 }
956
957 /// Validates the filesystem identity captured for a newly-created temporary
958 /// resource.
959 ///
960 /// # Parameters
961 /// - `info`: Provider-reported temporary-resource identity.
962 /// - `expected_kind`: Resource kind requested from the provider.
963 ///
964 /// # Returns
965 /// `Ok(())` when filesystem, path, and resource kind are valid.
966 ///
967 /// # Errors
968 /// Returns a provider-contract error when any identity is inconsistent.
969 fn validate_temp_info(
970 &self,
971 info: &OpenedFileInfo,
972 expected_kind: FileKind,
973 requested_parent: Option<&Path>,
974 ) -> FsResult<()> {
975 self.core.validate_temp_info(info, expected_kind, requested_parent)
976 }
977}