qubit-fs 0.2.0

Provider-neutral synchronous and asynchronous filesystem abstraction for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
// =============================================================================
//    Copyright (c) 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Asynchronous filesystem facade construction boundary.

use std::sync::Arc;

use crate::copy::AsyncCopyFailure;
use crate::copy::AsyncCopyOperation;
use crate::copy::CopyAssessment;
use crate::copy::CopyFailureState;
use crate::copy::CopyOptions;
use crate::copy::CopyOutcome;
use crate::copy::CopyStats;
use crate::directory::AsyncDirectoryOperation;
use crate::directory::AsyncDirectoryStream;
use crate::directory::CreateDirectoryOptions;
use crate::directory::CreateDirectoryOutcome;
use crate::directory::DeleteOptions;
use crate::directory::DeleteOutcome;
use crate::directory::ListOptions;
use crate::directory::ListScope;
use crate::error::FsError;
use crate::error::FsErrorKind;
use crate::error::FsOperation;
use crate::error::FsResult;
use crate::error::OpenFailure;
use crate::error::OpenFailureStage;
use crate::facade::facade_core::FacadeCore;
use crate::metadata::FileMetadata;
use crate::metadata::FileSystemCapability;
use crate::metadata::FileSystemProperties;
use crate::path::Path;
use crate::read::AsyncFileReader;
use crate::read::AsyncReadOperation;
use crate::read::ReadOptions;
use crate::rename::RenameFailure;
use crate::rename::RenameFailureState;
use crate::rename::RenameOptions;
use crate::rename::RenameOutcome;
use crate::rename::validate_rename_outcome;
use crate::spi::AsyncFileSystemSpi;
use crate::spi::CreateDirectoryRequest;
use crate::spi::DeleteDirectoryRequest;
use crate::spi::DeleteFileRequest;
use crate::spi::OpenReaderRequest;
use crate::spi::OpenWriterRequest;
use crate::spi::RenameRequest;
use crate::spi::ResolvedCreateDirectoryOptions;
use crate::spi::ResolvedDeleteOptions;
use crate::spi::ResolvedReadOptions;
use crate::spi::ResolvedRenameOptions;
use crate::spi::ResolvedWriteOptions;
use crate::spi::StatRequest;
use crate::temp::AsyncTempDirectory;
use crate::temp::AsyncTempFile;
use crate::temp::PersistOptions;
use crate::temp::RejectedAsyncTempResource;
use crate::temp::TempOptions;
use crate::write::AsyncFileWriter;
use crate::write::AsyncWriteAllOperation;
use crate::write::AsyncWriteAllOperationFailure;
use crate::write::RejectedAsyncWriter;
use crate::write::WriteOptions;

/// Application-facing asynchronous filesystem facade.
///
/// It validates provider boundaries, exposes asynchronous operations, and owns
/// the cancellation-safe copy operation entry point.
///
/// # Examples
///
/// The example runs against an isolated in-memory fixture. Applications obtain
/// their configured facade from a provider or registry integration.
///
/// ```rust
/// # mod support { include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/common/rustdoc_support.rs")); }
/// # use support::*;
/// # let (filesystem, _) = async_recording_spi::async_recording_file_system(Default::default());
/// # poll_support::ready(async {
/// use qubit_fs::Path;
/// use qubit_fs::read::ReadOptions;
///
/// let bytes = filesystem.read_prefix(&Path::parse("/report")?, ReadOptions::default(), 3).await?;
/// assert_eq!(b"byt", bytes.bytes());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// # }).unwrap();
/// ```
#[derive(Clone)]
pub struct AsyncFileSystem {
    /// Provider implementation receiving validated asynchronous requests.
    spi: Arc<dyn AsyncFileSystemSpi>,
    /// Shared immutable state and deterministic preflight policy.
    core: Arc<FacadeCore>,
}

impl AsyncFileSystem {
    /// Constructs a facade and caches one validated provider snapshot.
    #[inline]
    pub fn from_spi<S>(spi: S) -> FsResult<Self>
    where
        S: AsyncFileSystemSpi + 'static,
    {
        Self::from_shared_spi(Arc::new(spi))
    }

    /// Constructs a facade from a shared provider implementation.
    #[inline]
    pub fn from_shared_spi(spi: Arc<dyn AsyncFileSystemSpi>) -> FsResult<Self> {
        let core = FacadeCore::new(spi.properties())?;
        Ok(Self {
            spi,
            core: Arc::new(core),
        })
    }

    /// Returns the immutable property snapshot without provider I/O.
    #[inline]
    #[must_use]
    pub fn properties(&self) -> &FileSystemProperties {
        self.core.properties()
    }

    /// Validates a write request without opening a provider session.
    pub fn validate_write(&self, path: &Path, options: &WriteOptions) -> FsResult<()> {
        self.core.validate_write_request(path, options)
    }

    /// Assesses copy routes without performing provider I/O.
    ///
    /// # Errors
    /// Returns an invalid-options or requirement error when no provider or
    /// stream execution route can satisfy the request.
    pub fn assess_copy(&self, source: &Path, target: &Path, options: &CopyOptions) -> FsResult<CopyAssessment> {
        self.core.assess_copy(source, target, options)
    }

    /// Returns shared deterministic facade policy to operation objects.
    #[inline]
    pub(crate) fn core(&self) -> &FacadeCore {
        &self.core
    }

    /// Returns the asynchronous provider implementation to operation objects.
    #[inline]
    pub(crate) fn spi(&self) -> &dyn AsyncFileSystemSpi {
        self.spi.as_ref()
    }

    /// Asynchronously reads metadata after local validation completes.
    ///
    /// Local validation happens before this future reaches the provider. A
    /// provider response is checked again after awaiting to bind the returned
    /// metadata to the requested logical path.
    ///
    /// # Errors
    /// Returns a validation, provider, or provider-contract error when the
    /// path cannot be read or the response identifies another path.
    pub async fn stat(&self, path: &Path) -> FsResult<FileMetadata> {
        self.validate_path(path, FsOperation::Stat)?;
        let response = self
            .spi
            .stat(StatRequest::new(path, ()))
            .await
            .map_err(|error| self.enrich(error, path, FsOperation::Stat))?;
        if response.path() != path {
            return Err(self.contract_error(path, "provider returned metadata for a different path"));
        }
        Ok(response.into_metadata())
    }

    /// Asynchronously reports whether the path exists.
    ///
    /// # Errors
    /// Returns the original filesystem error for failures other than an
    /// explicit `NotFound` response.
    pub async fn exists(&self, path: &Path) -> FsResult<bool> {
        match self.stat(path).await {
            Ok(_) => Ok(true),
            Err(error) if error.kind() == FsErrorKind::NotFound => Ok(false),
            Err(error) => Err(error.with_operation(FsOperation::Exists)),
        }
    }

    /// Asynchronously opens a validated directory stream.
    ///
    /// # Errors
    /// Returns an invalid-options, missing-capability, or provider error when
    /// the scope or options cannot be served.
    pub async fn list(&self, scope: &ListScope, options: ListOptions) -> FsResult<AsyncDirectoryStream> {
        AsyncDirectoryOperation::new(self).list(scope, options).await
    }

    /// Asynchronously opens a validated reader and verifies its identity.
    ///
    /// # Errors
    /// Returns a validation, capability, provider, or provider-contract error
    /// when the reader cannot be opened safely.
    pub async fn open_reader(&self, path: &Path, options: ReadOptions) -> FsResult<AsyncFileReader> {
        self.open_reader_resolved(path, ResolvedReadOptions::new(options)).await
    }

    /// Opens a facade-validated asynchronous reader with an internal hint.
    pub(crate) async fn open_reader_resolved(
        &self,
        path: &Path,
        resolved: ResolvedReadOptions,
    ) -> FsResult<AsyncFileReader> {
        let options = resolved.options().clone();
        self.validate_path(path, FsOperation::OpenReader)?;
        options
            .validate_against(self.properties().capabilities())
            .map_err(|error| self.enrich(error, path, FsOperation::OpenReader))?;
        self.properties()
            .limits()
            .validate_read_range(path, options.length())
            .map_err(|error| self.enrich(error, path, FsOperation::OpenReader))?;
        self.require(FileSystemCapability::Read, FsOperation::OpenReader, path)?;
        let opened = self
            .spi
            .open_reader(OpenReaderRequest::new(path, resolved))
            .await
            .map_err(|error| self.enrich(error, path, FsOperation::OpenReader))?;
        self.validate_opened_info(opened.info(), path)?;
        Ok(opened.into_reader())
    }

    /// Asynchronously reads an entire file while enforcing a strict byte cap.
    ///
    /// The cap applies to bytes actually read, even when opened metadata
    /// overestimates the resource length.
    ///
    /// # Errors
    /// Returns the reader or read error when validation, opening, or bounded
    /// reading fails.
    pub async fn read_all(&self, path: &Path, options: ReadOptions, max_bytes: usize) -> FsResult<Vec<u8>> {
        AsyncReadOperation::new(self).read_all(path, options, max_bytes).await
    }

    /// Asynchronously reads at most max_bytes from a file.
    ///
    /// # Errors
    /// Returns the reader or read error when validation, opening, or bounded
    /// reading fails.
    pub async fn read_prefix(
        &self,
        path: &Path,
        options: ReadOptions,
        max_bytes: usize,
    ) -> FsResult<crate::read::PrefixReadOutcome> {
        AsyncReadOperation::new(self)
            .read_prefix(path, options, max_bytes)
            .await
    }

    /// Asynchronously opens a validated writer and verifies its identity.
    pub async fn open_writer(
        &self,
        path: &Path,
        options: WriteOptions,
    ) -> Result<AsyncFileWriter, OpenFailure<RejectedAsyncWriter>> {
        self.core
            .validate_write_request(path, &options)
            .map_err(|error| OpenFailure::new(error, OpenFailureStage::Preflight, None))?;
        let atomicity = options.atomicity();
        let durability = options.durability();
        let opened = self
            .spi
            .open_writer(OpenWriterRequest::new(path, ResolvedWriteOptions::new(options)))
            .await
            .map_err(|error| {
                OpenFailure::new(
                    self.enrich(error, path, FsOperation::OpenWriter),
                    OpenFailureStage::ProviderOpen,
                    None,
                )
            })?;
        let (info, session) = opened.into_parts();
        if let Err(error) = self.validate_opened_info(&info, path) {
            return Err(OpenFailure::new(
                error,
                OpenFailureStage::OutcomeValidation,
                Some(RejectedAsyncWriter::new(
                    session,
                    self.properties().info().provider_id(),
                    Some(path.clone()),
                )),
            ));
        }
        Ok(AsyncFileWriter::new(
            info,
            session,
            atomicity,
            durability,
            self.properties().info().provider_id(),
            self.properties().limits().max_write_bytes().maximum(),
        ))
    }

    /// Begins an owning asynchronous whole-file write operation.
    ///
    /// Moves `path`, `bytes`, and `options` into the request and retains a
    /// clone of this filesystem. Construction performs no provider I/O.
    /// Keep the operation outside the cancellation scope and cancel only
    /// its `execute` future so publication facts and recovery
    /// responsibility remain available.
    ///
    /// # Returns
    ///
    /// A ready operation that no longer borrows the caller's filesystem or
    /// payload. The payload is released after execution ends or is cancelled.
    ///
    /// # Errors
    ///
    /// Returns a `NotPublished` failure with zero confirmed bytes if the path,
    /// capabilities, options, or payload size fail local validation. Rejected
    /// construction consumes and releases the payload.
    pub fn begin_write_all(
        &self,
        path: Path,
        bytes: Vec<u8>,
        options: WriteOptions,
    ) -> Result<AsyncWriteAllOperation, AsyncWriteAllOperationFailure> {
        self.core.validate_write_request(&path, &options).map_err(|error| {
            AsyncWriteAllOperationFailure::new(error, crate::write::WriteFailureState::NotPublished, 0)
        })?;
        self.properties()
            .limits()
            .validate_write_size(&path, bytes.len())
            .map_err(|error| {
                AsyncWriteAllOperationFailure::new(
                    self.core.enrich(error, Some(&path), FsOperation::Write),
                    crate::write::WriteFailureState::NotPublished,
                    0,
                )
            })?;
        Ok(AsyncWriteAllOperation::new(self.clone(), path, bytes, options))
    }

    /// Asynchronously creates a directory after local validation.
    ///
    /// # Errors
    /// Returns a validation, capability, provider, or provider-contract error
    /// when the directory cannot be created as requested.
    pub async fn create_directory(
        &self,
        path: &Path,
        options: CreateDirectoryOptions,
    ) -> FsResult<CreateDirectoryOutcome> {
        self.validate_path(path, FsOperation::CreateDir)?;
        self.require(FileSystemCapability::CreateDirectory, FsOperation::CreateDir, path)?;
        let exists_ok = options.exists_ok();
        let outcome = self
            .spi
            .create_directory(CreateDirectoryRequest::new(
                path,
                ResolvedCreateDirectoryOptions::new(options),
            ))
            .await
            .map_err(|error| self.enrich(error, path, FsOperation::CreateDir))?;
        if outcome.already_existed() && !exists_ok {
            return Err(self.contract_error(path, "provider accepted an existing directory without exists_ok"));
        }
        Ok(outcome)
    }

    /// Asynchronously deletes a file after local validation.
    ///
    /// # Errors
    /// Returns a validation, capability, provider, or provider-contract error
    /// when deletion cannot be confirmed.
    #[inline]
    pub async fn delete_file(&self, path: &Path, options: DeleteOptions) -> FsResult<DeleteOutcome> {
        self.delete(path, options, false).await
    }

    /// Asynchronously deletes a directory after local validation.
    ///
    /// # Errors
    /// Returns a validation, capability, provider, or provider-contract error
    /// when deletion cannot be confirmed.
    #[inline]
    pub async fn delete_directory(&self, path: &Path, options: DeleteOptions) -> FsResult<DeleteOutcome> {
        self.delete(path, options, true).await
    }

    /// Renames one resource through the single asynchronous provider primitive.
    ///
    /// # Errors
    /// Returns [`RenameFailure`] with the confirmed transition state when
    /// validation, provider execution, or outcome validation fails.
    pub async fn rename(
        &self,
        source: &Path,
        target: &Path,
        options: RenameOptions,
    ) -> Result<RenameOutcome, RenameFailure> {
        if let Err(error) = self.rename_preflight(source, target, &options) {
            return Err(self.contextual_rename_failure(error, RenameFailureState::Unchanged, source, target));
        }
        match self
            .spi
            .rename(RenameRequest::new(
                source,
                target,
                ResolvedRenameOptions::new(options.clone()),
            ))
            .await
        {
            Ok(outcome) => match validate_rename_outcome(&outcome, &options, source, target) {
                Some(violation) => Err(self.contextual_rename_failure(
                    self.contract_error(source, violation.message),
                    violation.state,
                    source,
                    target,
                )),
                None => Ok(outcome),
            },
            Err(failure) => {
                let (error, state) = failure.into_parts();
                Err(self.contextual_rename_failure(error, state, source, target))
            }
        }
    }

    /// Asynchronously creates a temporary file and validates its provider
    /// identity.
    ///
    /// # Errors
    /// Returns [`OpenFailure`] when preflight, provider creation, or temporary
    /// identity validation fails.
    pub async fn create_temp_file(
        &self,
        options: TempOptions,
    ) -> Result<AsyncTempFile, OpenFailure<RejectedAsyncTempResource>> {
        let parent = options.parent().cloned();
        self.core
            .validate_temp_parent(parent.as_ref())
            .map_err(|error| OpenFailure::new(error, OpenFailureStage::Preflight, None))?;
        self.core
            .require(FileSystemCapability::TempFile, FsOperation::CreateTemp, parent.as_ref())
            .map_err(|error| OpenFailure::new(error, OpenFailureStage::Preflight, None))?;
        let opened = self
            .spi
            .create_temp_file(crate::spi::CreateTempFileRequest::new(options))
            .await
            .map_err(|error| {
                OpenFailure::new(
                    self.core.enrich(error, parent.as_ref(), FsOperation::CreateTemp),
                    OpenFailureStage::ProviderOpen,
                    None,
                )
            })?;
        let (info, session) = opened.into_parts();
        if let Err(cause) = self.validate_temp_info(&info, crate::metadata::FileKind::File) {
            let error = FsError::with_source(
                FsErrorKind::ProviderContractViolation,
                FsOperation::ValidateProviderOutcome,
                "provider returned an invalid temporary identity",
                cause,
            )
            .with_provider(self.properties().info().provider_id());
            let error = match parent.as_ref() {
                Some(path) => error.with_path(path.clone()),
                None => error,
            };
            return Err(OpenFailure::new(
                error,
                OpenFailureStage::OutcomeValidation,
                Some(RejectedAsyncTempResource::new(
                    session,
                    self.properties().info().provider_id(),
                    parent,
                )),
            ));
        }
        Ok(AsyncTempFile::new(
            self.clone(),
            info.path().clone(),
            session,
            "temporary file",
        ))
    }

    /// Asynchronously creates a temporary directory and validates its identity.
    ///
    /// # Errors
    /// Returns [`OpenFailure`] when preflight, provider creation, or temporary
    /// identity validation fails.
    pub async fn create_temp_directory(
        &self,
        options: TempOptions,
    ) -> Result<AsyncTempDirectory, OpenFailure<RejectedAsyncTempResource>> {
        let parent = options.parent().cloned();
        self.core
            .validate_temp_parent(parent.as_ref())
            .map_err(|error| OpenFailure::new(error, OpenFailureStage::Preflight, None))?;
        self.core
            .require(
                FileSystemCapability::TempDirectory,
                FsOperation::CreateTemp,
                parent.as_ref(),
            )
            .map_err(|error| OpenFailure::new(error, OpenFailureStage::Preflight, None))?;
        let opened = self
            .spi
            .create_temp_directory(crate::spi::CreateTempDirectoryRequest::new(options))
            .await
            .map_err(|error| {
                OpenFailure::new(
                    self.core.enrich(error, parent.as_ref(), FsOperation::CreateTemp),
                    OpenFailureStage::ProviderOpen,
                    None,
                )
            })?;
        let (info, session) = opened.into_parts();
        if let Err(cause) = self.validate_temp_info(&info, crate::metadata::FileKind::Directory) {
            let error = FsError::with_source(
                FsErrorKind::ProviderContractViolation,
                FsOperation::ValidateProviderOutcome,
                "provider returned an invalid temporary identity",
                cause,
            )
            .with_provider(self.properties().info().provider_id());
            let error = match parent.as_ref() {
                Some(path) => error.with_path(path.clone()),
                None => error,
            };
            return Err(OpenFailure::new(
                error,
                OpenFailureStage::OutcomeValidation,
                Some(RejectedAsyncTempResource::new(
                    session,
                    self.properties().info().provider_id(),
                    parent,
                )),
            ));
        }
        Ok(AsyncTempDirectory::new(self.clone(), info.path().clone(), session))
    }

    /// Begins a copy after synchronous path, option, and capability preflight.
    ///
    /// This method performs no provider I/O. Provider work begins only when
    /// [`AsyncCopyOperation::execute`] is polled.
    ///
    /// # Errors
    /// Returns [`AsyncCopyFailure`] when local preflight rejects the request.
    #[allow(clippy::result_large_err)]
    pub fn begin_copy(
        &self,
        source: Path,
        target: Path,
        options: CopyOptions,
    ) -> Result<AsyncCopyOperation, AsyncCopyFailure> {
        self.copy_preflight(&source, &target, &options).map_err(|error| {
            self.contextual_copy_failure(
                error,
                CopyFailureState::Unchanged,
                CopyStats::default(),
                &source,
                &target,
            )
        })?;
        let symlink_policy = options
            .symlink_policy_override()
            .unwrap_or(self.properties().symlink_policy());
        Ok(AsyncCopyOperation::new(
            self.clone(),
            source,
            target,
            options,
            symlink_policy,
        ))
    }

    /// Rechecks provider-reported success against requested copy guarantees.
    #[allow(clippy::result_large_err)]
    pub(crate) fn verify_completed_copy(
        &self,
        outcome: CopyOutcome,
        options: &CopyOptions,
        source: &Path,
        target: &Path,
    ) -> Result<CopyOutcome, AsyncCopyFailure> {
        if let Some(message) = outcome.contract_violation(options) {
            return Err(self.contextual_copy_failure(
                FsError::new(FsErrorKind::ProviderContractViolation, FsOperation::Copy, message),
                CopyFailureState::Published,
                *outcome.stats(),
                source,
                target,
            ));
        }
        Ok(outcome)
    }

    /// Performs all no-I/O copy validation required before an operation exists.
    fn copy_preflight(&self, source: &Path, target: &Path, options: &CopyOptions) -> FsResult<()> {
        self.validate_path(source, FsOperation::Copy)?;
        self.validate_path(target, FsOperation::Copy)?;
        options
            .validate_against(self.properties().capabilities())
            .map_err(|error| {
                self.enrich(error, source, FsOperation::Copy)
                    .with_target(target.clone())
            })?;
        if source == target {
            return Err(FsError::new(
                crate::error::FsErrorKind::InvalidOptions,
                FsOperation::Copy,
                "copy source and target must differ",
            )
            .with_path(source.clone())
            .with_target(target.clone()));
        }
        Ok(())
    }

    /// Performs no-I/O validation for the single rename primitive.
    fn rename_preflight(&self, source: &Path, target: &Path, options: &RenameOptions) -> FsResult<()> {
        self.validate_path(source, FsOperation::Rename)?;
        self.validate_path(target, FsOperation::Rename)?;
        options
            .validate_against(self.properties().capabilities())
            .map_err(|error| {
                self.enrich(error, source, FsOperation::Rename)
                    .with_target(target.clone())
            })?;
        self.require(FileSystemCapability::Rename, FsOperation::Rename, source)?;
        if source == target {
            return Err(FsError::new(
                FsErrorKind::InvalidOptions,
                FsOperation::Rename,
                "rename source and target must differ",
            )
            .with_path(source.clone())
            .with_target(target.clone()));
        }
        Ok(())
    }

    /// Dispatches the selected deletion primitive after local validation.
    async fn delete(&self, path: &Path, options: DeleteOptions, directory: bool) -> FsResult<DeleteOutcome> {
        self.validate_path(path, FsOperation::Delete)?;
        options
            .validate_against(self.properties().capabilities())
            .map_err(|error| self.enrich(error, path, FsOperation::Delete))?;
        self.require(FileSystemCapability::Delete, FsOperation::Delete, path)?;
        let missing_ok = options.missing_ok();
        let request_options = ResolvedDeleteOptions::new(options);
        let outcome = if directory {
            self.spi
                .delete_directory(DeleteDirectoryRequest::new(path, request_options))
                .await
        } else {
            self.spi
                .delete_file(DeleteFileRequest::new(path, request_options))
                .await
        }
        .map_err(|error| self.enrich(error, path, FsOperation::Delete))?;
        if outcome.already_missing() && !missing_ok {
            return Err(self.contract_error(path, "provider accepted a missing target without missing_ok"));
        }
        Ok(outcome)
    }

    /// Validates a logical path against the cached provider snapshot.
    fn validate_path(&self, path: &Path, operation: FsOperation) -> FsResult<()> {
        self.core.validate_path(path, operation)
    }

    /// Requires a provider-advertised capability before operation creation.
    pub(crate) fn require(
        &self,
        capability: FileSystemCapability,
        operation: FsOperation,
        path: &Path,
    ) -> FsResult<()> {
        self.core.require(capability, operation, Some(path))
    }

    /// Contextualizes a copy failure with its source, target, and provider
    /// facts.
    pub(crate) fn contextual_copy_failure(
        &self,
        error: FsError,
        state: CopyFailureState,
        stats: CopyStats,
        source: &Path,
        target: &Path,
    ) -> AsyncCopyFailure {
        AsyncCopyFailure::new(
            error.with_operation(FsOperation::Copy).with_missing_context(
                source,
                Some(target),
                self.properties().info().provider_id(),
            ),
            state,
            stats,
        )
    }

    /// Adds source, target, and provider facts to an asynchronous rename
    /// failure.
    fn contextual_rename_failure(
        &self,
        error: FsError,
        state: RenameFailureState,
        source: &Path,
        target: &Path,
    ) -> RenameFailure {
        RenameFailure::new(
            error.with_operation(FsOperation::Rename).with_missing_context(
                source,
                Some(target),
                self.properties().info().provider_id(),
            ),
            state,
        )
    }

    /// Adds missing public context to a provider error.
    fn enrich(&self, error: FsError, path: &Path, operation: FsOperation) -> FsError {
        self.core.enrich(error, Some(path), operation)
    }

    /// Creates a provider-contract violation bound to the requested path.
    fn contract_error(&self, path: &Path, message: &'static str) -> FsError {
        self.core
            .contract_error(path, FsOperation::ValidateProviderOutcome, message)
    }

    /// Validates a provider-opened handle identity before exposing it to
    /// callers.
    fn validate_opened_info(&self, info: &crate::metadata::OpenedFileInfo, path: &Path) -> FsResult<()> {
        if info.filesystem_id() != self.properties().info().id() || info.path() != path {
            return Err(self.contract_error(path, "provider returned an opened handle with a different identity"));
        }
        Ok(())
    }

    /// Validates a provider-created temporary resource before exposing it.
    fn validate_temp_info(
        &self,
        info: &crate::metadata::OpenedFileInfo,
        expected_kind: crate::metadata::FileKind,
    ) -> FsResult<()> {
        if info.filesystem_id() != self.properties().info().id() {
            return Err(self.contract_error(
                info.path(),
                "provider returned a temporary handle for a different filesystem",
            ));
        }
        self.validate_path(info.path(), FsOperation::CreateTemp).map_err(|_| {
            self.contract_error(
                info.path(),
                "provider returned a temporary handle with an invalid logical path",
            )
        })?;
        if info.metadata().is_none_or(|metadata| metadata.kind() != &expected_kind) {
            return Err(self.contract_error(
                info.path(),
                "provider returned a temporary handle with an inconsistent resource kind",
            ));
        }
        Ok(())
    }

    /// Performs no-I/O preflight for asynchronous temporary persistence.
    pub(crate) fn preflight_temp_persist(
        &self,
        source: &Path,
        target: &Path,
        options: &PersistOptions,
    ) -> FsResult<()> {
        self.validate_path(source, FsOperation::PersistTemp)?;
        self.validate_path(target, FsOperation::PersistTemp)?;
        options
            .validate_against(self.properties().capabilities())
            .map_err(|error| {
                self.enrich(error, source, FsOperation::PersistTemp)
                    .with_target(target.clone())
            })
    }

    /// Validates a provider-generated target reported by temporary keep.
    pub(crate) fn validate_temp_keep_target(&self, source: &Path, target: &Path) -> FsResult<()> {
        self.validate_path(target, FsOperation::KeepTemp).map_err(|_| {
            self.contract_error(
                source,
                "provider returned a temporary keep target with an invalid logical path",
            )
            .with_target(target.clone())
        })
    }
}