Skip to main content

qubit_fs_testkit/
async_file_system_fixture.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//! Typed asynchronous fixtures for filesystem contract suites.
9
10use std::future::Future;
11use std::pin::Pin;
12
13use qubit_fs as qfs;
14use qubit_fs::AsyncFileSystem;
15use qubit_fs::copy::CopyMethod;
16use qubit_fs::metadata::ResourceVersion;
17use qubit_fs::path::Path;
18
19use crate::AsyncCopyCancellationStage;
20use crate::AsyncWriteCancellationStage;
21use crate::CopyCancellationProbe;
22use crate::CopyFixtureCase;
23use crate::FixtureResult;
24use crate::FixtureSupport;
25use crate::WriteCancellationProbe;
26
27/// Runtime-neutral future returned by asynchronous fixture observations.
28///
29/// # Type Parameters
30///
31/// * `'a` - Lifetime shared by the fixture and borrowed request data.
32/// * `T` - Successful value produced by the asynchronous hook.
33///
34/// # Examples
35///
36/// ```
37/// use qubit_fs_testkit::FixtureFuture;
38///
39/// let future: FixtureFuture<'_, i32> = Box::pin(async { Ok(42) });
40/// let _ = future;
41/// ```
42pub type FixtureFuture<'a, T> = Pin<Box<dyn Future<Output = FixtureResult<T>> + Send + 'a>>;
43
44/// Supplies an isolated asynchronous facade and optional provider observations.
45///
46/// # Examples
47///
48/// ```
49/// # mod support { include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/common/rustdoc_support.rs")); }
50/// # use support::RustdocAsyncFixture;
51/// use qubit_fs_testkit::{AsyncFileSystemContractSuite, AsyncFileSystemFixture};
52///
53/// let fixture = RustdocAsyncFixture::new();
54/// let suite = AsyncFileSystemContractSuite::new(&fixture);
55/// assert!(suite.run().report().checks().is_empty());
56/// ```
57pub trait AsyncFileSystemFixture: Sync {
58    /// Independently reports whether the provider implements random-access
59    /// sessions. This must reflect provider SPI configuration rather than
60    /// range-read support.
61    ///
62    /// # Returns
63    /// `Supported(true)` or `Supported(false)` with the independent SPI
64    /// declaration, or `Unsupported` when the fixture cannot observe it.
65    #[inline]
66    fn random_access_operation(&self) -> FixtureSupport<bool> {
67        FixtureSupport::Unsupported
68    }
69
70    /// Replaces a path while preserving any object already opened by a reader.
71    /// The fixture must use an independent setup path rather than the facade
72    /// under test.
73    ///
74    /// # Parameters
75    /// * `path` - Seeded path to replace.
76    /// * `bytes` - Replacement object content.
77    ///
78    /// # Returns
79    /// A future resolving to `Supported(())` when replacement is available,
80    /// or `Unsupported` when it cannot be performed independently.
81    ///
82    /// # Errors
83    /// The future returns [`FixtureError`](crate::FixtureError) when fixture
84    /// replacement fails.
85    #[inline]
86    fn replace_random_access_path<'a>(
87        &'a self,
88        path: &'a Path,
89        bytes: &'a [u8],
90    ) -> FixtureFuture<'a, FixtureSupport<()>> {
91        let _ = (path, bytes);
92        Box::pin(async { Ok(FixtureSupport::Unsupported) })
93    }
94
95    /// Arms a deterministic pending read for the next random-access read.
96    /// The hook changes fixture state only; it must not start an async runtime.
97    ///
98    /// # Parameters
99    /// * `path` - Seed path whose next random-access read will be gated.
100    ///
101    /// # Returns
102    /// `Supported(())` when the gate was armed, or `Unsupported` when this
103    /// fixture cannot inject a pending read.
104    ///
105    /// # Errors
106    /// Returns [`FixtureError`](crate::FixtureError) when arming fails.
107    #[inline]
108    fn arm_random_access_pending_read(&self, path: &Path) -> FixtureResult<FixtureSupport<()>> {
109        let _ = path;
110        Ok(FixtureSupport::Unsupported)
111    }
112
113    /// Idempotently releases a previously armed pending-read probe.
114    /// This hook is synchronous so guards can release the gate during future
115    /// cancellation without a runtime.
116    ///
117    /// # Parameters
118    /// * `path` - Seed path associated with the gate.
119    ///
120    /// # Returns
121    /// `Ok(())` once the gate has been released.
122    ///
123    /// # Errors
124    /// Returns [`FixtureError`](crate::FixtureError) when release fails.
125    #[inline]
126    fn disarm_random_access_pending_read(&self, path: &Path) -> FixtureResult<()> {
127        let _ = path;
128        Ok(())
129    }
130
131    /// Independently reports whether a random-access read reached the injected
132    /// pending gate. This must inspect fixture instrumentation only and
133    /// must not perform I/O. The cancellation check passes only for
134    /// `Supported(true)` after observing the read future return `Pending`;
135    /// `Supported(false)` and `Unsupported` leave the check unverified. The
136    /// runner drops the future before querying this hook, then disarms the
137    /// gate. The fixture must allow the reader to be used again after
138    /// disarming.
139    ///
140    /// # Parameters
141    /// * `path` - Seed path associated with the pending-read probe.
142    ///
143    /// # Returns
144    /// `Supported(true)` when the read reached the gate, `Supported(false)`
145    /// when it did not, or `Unsupported` when this fixture cannot observe
146    /// gate entry.
147    ///
148    /// # Errors
149    /// Returns [`FixtureError`](crate::FixtureError) when reading the
150    /// independent instrumentation fails.
151    #[inline]
152    fn random_access_pending_read_reached(&self, path: &Path) -> FixtureResult<FixtureSupport<bool>> {
153        let _ = path;
154        Ok(FixtureSupport::Unsupported)
155    }
156
157    /// Snapshots every logical path in the isolated configured namespace.
158    ///
159    /// Use the underlying SDK or fixture model, never the facade list method.
160    /// Include resources created by earlier checks, not only the current seed.
161    /// Returns unsupported when independent completeness cannot be established.
162    ///
163    /// # Returns
164    ///
165    /// A future resolving to every path in the isolated namespace, or
166    /// `Unsupported` when the fixture cannot establish a complete snapshot.
167    ///
168    /// # Errors
169    ///
170    /// The future returns [`FixtureError`](crate::FixtureError) when the
171    /// independent snapshot operation fails.
172    fn snapshot_namespace_paths(&self) -> FixtureFuture<'_, FixtureSupport<Vec<Path>>> {
173        Box::pin(async { Ok(FixtureSupport::Unsupported) })
174    }
175
176    /// Independently prepares a copy source and a scenario-specific target.
177    ///
178    /// File scenarios contain the supplied bytes and use file options, with
179    /// Required atomicity or durability for the respective strong scenario.
180    /// `Native` cases provide an independently seeded source containing
181    /// 1..=64 KiB; missing independent source evidence is reported as
182    /// unverified. `ServerSide` cases use provider-selected bytes that are
183    /// independently seeded and readable, contain 1..=64 KiB, and require
184    /// server-side copy. The suite independently checks source contents and
185    /// target absence before execution, then source and target contents after
186    /// execution; unavailable preparation or observation evidence is
187    /// reported as unverified. Ready cases have distinct paths, and Conflict
188    /// targets contain `b"existing"`.
189    /// Teardown must clean partial setup even when preparation fails.
190    ///
191    /// # Parameters
192    ///
193    /// * `scenario` - Copy behavior and guarantees to prepare.
194    /// * `source_relative` - Testkit-relative source name.
195    /// * `target_relative` - Testkit-relative destination name.
196    /// * `bytes` - Source content for file-copy scenarios and the child file
197    ///   for tree-copy scenarios.
198    ///
199    /// # Returns
200    ///
201    /// A future resolving to `Ready(case)` when setup succeeds, or
202    /// `Unavailable` when required fixture setup is unsupported.
203    ///
204    /// # Errors
205    ///
206    /// The future returns [`FixtureError`](crate::FixtureError) when path
207    /// mapping or an out-of-band preparation operation fails.
208    fn prepare_copy<'a>(
209        &'a self,
210        scenario: crate::CopyScenario,
211        source_relative: &'a str,
212        target_relative: &'a str,
213        bytes: &'a [u8],
214    ) -> FixtureFuture<'a, crate::FixturePreparation<crate::CopyFixtureCase>> {
215        Box::pin(async move {
216            if scenario == crate::CopyScenario::ServerSide {
217                return Ok(match self.copy_fast_path_case(CopyMethod::ServerSide).await? {
218                    FixtureSupport::Supported(case) => crate::FixturePreparation::Ready(case),
219                    FixtureSupport::Unsupported => crate::FixturePreparation::Unavailable {
220                        reason: "fixture has no server-side copy case".to_owned(),
221                    },
222                });
223            }
224            if matches!(
225                scenario,
226                crate::CopyScenario::AtomicTree | crate::CopyScenario::DurableTree
227            ) {
228                let FixtureSupport::Supported(source) = self.seed_empty_directory(source_relative).await? else {
229                    return Ok(crate::FixturePreparation::Unavailable {
230                        reason: "tree root setup unavailable".to_owned(),
231                    });
232                };
233                let sub_relative = format!("{source_relative}/sub");
234                if matches!(
235                    self.seed_empty_directory(&sub_relative).await?,
236                    FixtureSupport::Unsupported
237                ) {
238                    return Ok(crate::FixturePreparation::Unavailable {
239                        reason: "tree subdirectory setup unavailable".to_owned(),
240                    });
241                }
242                let child_relative = format!("{source_relative}/sub/child");
243                if matches!(
244                    self.seed_file(&child_relative, bytes).await?,
245                    FixtureSupport::Unsupported
246                ) {
247                    return Ok(crate::FixturePreparation::Unavailable {
248                        reason: "tree child setup unavailable".to_owned(),
249                    });
250                }
251                let target = self.path(target_relative)?;
252                let options = if scenario == crate::CopyScenario::AtomicTree {
253                    qfs::copy::CopyOptions::tree().with_atomicity(qfs::metadata::AtomicityRequirement::Required)
254                } else {
255                    qfs::copy::CopyOptions::tree().with_durability(qfs::metadata::DurabilityRequirement::Required)
256                };
257                return Ok(crate::FixturePreparation::Ready(crate::CopyFixtureCase::new(
258                    source, target, options,
259                )));
260            }
261            let FixtureSupport::Supported(source) = self.seed_file(source_relative, bytes).await? else {
262                return Ok(crate::FixturePreparation::Unavailable {
263                    reason: "copy source seed unavailable".to_owned(),
264                });
265            };
266            let target = if scenario == crate::CopyScenario::Conflict {
267                let FixtureSupport::Supported(target) = self.seed_file(target_relative, b"existing").await? else {
268                    return Ok(crate::FixturePreparation::Unavailable {
269                        reason: "copy conflict target seed unavailable".to_owned(),
270                    });
271                };
272                target
273            } else {
274                self.path(target_relative)?
275            };
276            let options = match scenario {
277                crate::CopyScenario::AtomicFile => {
278                    qfs::copy::CopyOptions::file().with_atomicity(qfs::metadata::AtomicityRequirement::Required)
279                }
280                crate::CopyScenario::DurableFile => {
281                    qfs::copy::CopyOptions::file().with_durability(qfs::metadata::DurabilityRequirement::Required)
282                }
283                _ => qfs::copy::CopyOptions::file(),
284            };
285            Ok(crate::FixturePreparation::Ready(crate::CopyFixtureCase::new(
286                source, target, options,
287            )))
288        })
289    }
290
291    /// Independently prepares an existing file for a selected deletion
292    /// scenario. Version hooks must provide evidence for
293    /// `DeleteScenario::IfMatch`.
294    ///
295    /// # Parameters
296    ///
297    /// * `scenario` - Deletion behavior to prepare.
298    /// * `relative` - Testkit-relative name of the file to seed.
299    /// * `bytes` - Exact initial file content.
300    ///
301    /// # Returns
302    ///
303    /// A future resolving to the prepared path, or `Unavailable` when the
304    /// fixture cannot seed the file.
305    ///
306    /// # Errors
307    ///
308    /// The future returns [`FixtureError`](crate::FixtureError) when seeding
309    /// fails.
310    fn prepare_delete<'a>(
311        &'a self,
312        _scenario: crate::DeleteScenario,
313        relative: &'a str,
314        bytes: &'a [u8],
315    ) -> FixtureFuture<'a, crate::FixturePreparation<Path>> {
316        Box::pin(async move {
317            Ok(match self.seed_file(relative, bytes).await? {
318                FixtureSupport::Supported(path) => crate::FixturePreparation::Ready(path),
319                FixtureSupport::Unsupported => crate::FixturePreparation::Unavailable {
320                    reason: "fixture cannot seed deletion scenario".to_owned(),
321                },
322            })
323        })
324    }
325
326    /// Independently prepares one read scenario and its initial content.
327    ///
328    /// A Ready path must contain the supplied bytes, except for the explicit
329    /// corruption scenario. Version observations remain independent fixture
330    /// hooks. Preparation errors must not become inapplicability declarations.
331    ///
332    /// # Parameters
333    ///
334    /// * `scenario` - Read behavior to prepare.
335    /// * `relative` - Testkit-relative name of the resource.
336    /// * `bytes` - Exact initial content, except for checksum corruption.
337    ///
338    /// # Returns
339    ///
340    /// A future resolving to the prepared path, or `Unavailable` when the
341    /// fixture cannot independently prepare the selected scenario.
342    ///
343    /// # Errors
344    ///
345    /// The future returns [`FixtureError`](crate::FixtureError) when setup or
346    /// checksum-case preparation fails.
347    fn prepare_read<'a>(
348        &'a self,
349        scenario: crate::ReadScenario,
350        relative: &'a str,
351        bytes: &'a [u8],
352    ) -> FixtureFuture<'a, crate::FixturePreparation<Path>> {
353        Box::pin(async move {
354            let prepared = if scenario == crate::ReadScenario::ChecksumCorruption {
355                self.checksum_failure_case(relative).await?
356            } else {
357                self.seed_file(relative, bytes).await?
358            };
359            Ok(match prepared {
360                FixtureSupport::Supported(path) => crate::FixturePreparation::Ready(path),
361                FixtureSupport::Unsupported => crate::FixturePreparation::Unavailable {
362                    reason: "fixture cannot independently prepare this read scenario".to_owned(),
363                },
364            })
365        })
366    }
367
368    /// Independently prepares the selected write request and initial state.
369    ///
370    /// The default prepares CreateNew and durable creation requests, and seeds
371    /// targets for atomic replacement, creation conflicts and append
372    /// independently. Missing setup remains explicit and is never counted
373    /// as successful testing.
374    ///
375    /// # Parameters
376    ///
377    /// * `scenario` - Write behavior and guarantees to prepare.
378    /// * `relative` - Testkit-relative target name.
379    /// * `bytes` - Payload submitted by the write operation.
380    ///
381    /// # Returns
382    ///
383    /// A future resolving to the prepared write request, or `Unavailable`
384    /// when required setup is unsupported.
385    ///
386    /// # Errors
387    ///
388    /// The future returns [`FixtureError`](crate::FixtureError) when path
389    /// mapping or out-of-band seeding fails.
390    fn prepare_write<'a>(
391        &'a self,
392        scenario: crate::WriteScenario,
393        relative: &'a str,
394        bytes: &'a [u8],
395    ) -> FixtureFuture<'a, crate::FixturePreparation<crate::WriteFixtureCase>> {
396        Box::pin(async move {
397            if scenario == crate::WriteScenario::Replace {
398                let FixtureSupport::Supported(path) = self.seed_file(relative, b"previous contents").await? else {
399                    return Ok(crate::FixturePreparation::Unavailable {
400                        reason: "replacement seed unavailable".to_owned(),
401                    });
402                };
403                return Ok(crate::FixturePreparation::Ready(crate::WriteFixtureCase::new(
404                    path,
405                    bytes.to_vec(),
406                    qfs::write::WriteOptions::default(),
407                )));
408            }
409            if scenario == crate::WriteScenario::CreateConflict {
410                let FixtureSupport::Supported(path) = self.seed_file(relative, b"a").await? else {
411                    return Ok(crate::FixturePreparation::Unavailable {
412                        reason: "creation conflict seed unavailable".to_owned(),
413                    });
414                };
415                return Ok(crate::FixturePreparation::Ready(crate::WriteFixtureCase::new(
416                    path,
417                    bytes.to_vec(),
418                    qfs::write::WriteOptions::default().with_disposition(qfs::write::WriteDisposition::CreateNew),
419                )));
420            }
421            if scenario == crate::WriteScenario::Append {
422                let FixtureSupport::Supported(path) = self.seed_file(relative, b"before").await? else {
423                    return Ok(crate::FixturePreparation::Unavailable {
424                        reason: "append seed unavailable".to_owned(),
425                    });
426                };
427                return Ok(crate::FixturePreparation::Ready(crate::WriteFixtureCase::new(
428                    path,
429                    bytes.to_vec(),
430                    qfs::write::WriteOptions::default().with_disposition(qfs::write::WriteDisposition::Append),
431                )));
432            }
433            if scenario == crate::WriteScenario::AtomicReplace {
434                let FixtureSupport::Supported(path) = self.seed_file(relative, b"a").await? else {
435                    return Ok(crate::FixturePreparation::Unavailable {
436                        reason: "atomic replacement seed unavailable".to_owned(),
437                    });
438                };
439                return Ok(crate::FixturePreparation::Ready(crate::WriteFixtureCase::new(
440                    path,
441                    bytes.to_vec(),
442                    qfs::write::WriteOptions::default().with_atomicity(qfs::metadata::AtomicityRequirement::Required),
443                )));
444            }
445            if scenario == crate::WriteScenario::Durable {
446                return Ok(crate::FixturePreparation::Ready(crate::WriteFixtureCase::new(
447                    self.path(relative)?,
448                    bytes.to_vec(),
449                    qfs::write::WriteOptions::default()
450                        .with_disposition(qfs::write::WriteDisposition::CreateNew)
451                        .with_durability(qfs::metadata::DurabilityRequirement::Required),
452                )));
453            }
454            if !matches!(scenario, crate::WriteScenario::Create | crate::WriteScenario::Abort) {
455                return Ok(crate::FixturePreparation::Unavailable {
456                    reason: "fixture does not prepare this write scenario".to_owned(),
457                });
458            }
459            Ok(crate::FixturePreparation::Ready(crate::WriteFixtureCase::new(
460                self.path(relative)?,
461                bytes.to_vec(),
462                qfs::write::WriteOptions::default().with_disposition(qfs::write::WriteDisposition::CreateNew),
463            )))
464        })
465    }
466
467    /// Returns the concrete asynchronous filesystem facade under test.
468    ///
469    /// # Returns
470    ///
471    /// The isolated asynchronous facade owned by this fixture.
472    fn file_system(&self) -> &AsyncFileSystem;
473
474    /// Maps a testkit-relative name to an isolated logical path.
475    ///
476    /// # Parameters
477    ///
478    /// * `relative` - Suite-generated name relative to the fixture namespace.
479    ///
480    /// # Returns
481    ///
482    /// The corresponding logical path within the isolated namespace.
483    ///
484    /// # Errors
485    ///
486    /// Returns [`FixtureError`](crate::FixtureError) when the name cannot be
487    /// represented by the provider's path model.
488    fn path(&self, relative: &str) -> FixtureResult<Path>;
489
490    /// Reports whether copy is intentionally limited to the stream fallback.
491    ///
492    /// # Returns
493    ///
494    /// `true` when copy contract checks must use the stream fallback.
495    #[inline]
496    #[must_use]
497    fn copy_fallback_only(&self) -> bool {
498        false
499    }
500
501    /// Maps a relative list prefix for the supplied root.
502    ///
503    /// # Parameters
504    ///
505    /// * `root` - Logical directory passed to the list operation.
506    /// * `relative` - Testkit-relative descendant selected by the contract.
507    ///
508    /// # Returns
509    ///
510    /// The provider-specific prefix expected by its list implementation.
511    ///
512    /// # Errors
513    ///
514    /// Returns [`FixtureError`](crate::FixtureError) when the prefix cannot be
515    /// represented for the supplied root.
516    #[inline]
517    fn list_prefix(&self, root: &Path, relative: &str) -> FixtureResult<String> {
518        let _ = root;
519        Ok(relative.to_owned())
520    }
521
522    /// Asynchronously seeds a complete file outside the operation under test.
523    ///
524    /// # Parameters
525    ///
526    /// * `relative` - Testkit-relative path for the seeded file.
527    /// * `bytes` - Exact content to publish.
528    ///
529    /// # Returns
530    ///
531    /// A future resolving to `Supported(path)` when seeding succeeds, or
532    /// `Unsupported` when the fixture cannot prepare files out of band.
533    ///
534    /// # Errors
535    ///
536    /// The future returns [`FixtureError`](crate::FixtureError) when
537    /// provider-specific setup fails.
538    #[inline]
539    fn seed_file<'a>(&'a self, relative: &'a str, bytes: &'a [u8]) -> FixtureFuture<'a, FixtureSupport<Path>> {
540        let _ = (relative, bytes);
541        Box::pin(async { Ok(FixtureSupport::Unsupported) })
542    }
543
544    /// Asynchronously observes a complete file outside the operation under
545    /// test.
546    ///
547    /// # Parameters
548    ///
549    /// * `path` - Logical path to observe.
550    ///
551    /// # Returns
552    ///
553    /// A future resolving to `Supported(bytes)` with complete content, or
554    /// `Unsupported` when the fixture cannot observe files out of band.
555    ///
556    /// # Errors
557    ///
558    /// The future returns [`FixtureError`](crate::FixtureError) when
559    /// provider-specific observation fails.
560    #[inline]
561    fn read_file<'a>(&'a self, path: &'a Path) -> FixtureFuture<'a, FixtureSupport<Vec<u8>>> {
562        let _ = path;
563        Box::pin(async { Ok(FixtureSupport::Unsupported) })
564    }
565
566    /// Asynchronously observes whether a resource exists out of band.
567    ///
568    /// # Parameters
569    ///
570    /// * `path` - Resource to observe independently of the facade under test.
571    ///
572    /// # Returns
573    ///
574    /// A future resolving to `Supported(true/false)` when observable, or
575    /// `Unsupported` when independent observation is unavailable.
576    ///
577    /// # Errors
578    ///
579    /// The future returns [`FixtureError`](crate::FixtureError) when
580    /// observation fails.
581    #[inline]
582    fn exists_out_of_band<'a>(&'a self, path: &'a Path) -> FixtureFuture<'a, FixtureSupport<bool>> {
583        let _ = path;
584        Box::pin(async { Ok(FixtureSupport::Unsupported) })
585    }
586
587    /// Asynchronously writes a complete resource through fixture setup.
588    ///
589    /// # Parameters
590    ///
591    /// * `path` - Resource to seed independently of the facade under test.
592    /// * `bytes` - Complete content to write.
593    ///
594    /// # Returns
595    ///
596    /// A future resolving to `Supported(())` when setup succeeds, or
597    /// `Unsupported` when out-of-band writing is unavailable.
598    ///
599    /// # Errors
600    ///
601    /// The future returns [`FixtureError`](crate::FixtureError) when setup
602    /// fails.
603    #[inline]
604    fn write_file_out_of_band<'a>(&'a self, path: &'a Path, bytes: &'a [u8]) -> FixtureFuture<'a, FixtureSupport<()>> {
605        let _ = (path, bytes);
606        Box::pin(async { Ok(FixtureSupport::Unsupported) })
607    }
608
609    /// Asynchronously observes the current provider resource version.
610    ///
611    /// # Parameters
612    ///
613    /// * `path` - Resource whose provider version is observed.
614    ///
615    /// # Returns
616    ///
617    /// A future resolving to the current version, or `Unsupported` when the
618    /// fixture cannot independently obtain it.
619    ///
620    /// # Errors
621    ///
622    /// The future returns [`FixtureError`](crate::FixtureError) when version
623    /// observation fails.
624    #[inline]
625    fn resource_version<'a>(&'a self, path: &'a Path) -> FixtureFuture<'a, FixtureSupport<ResourceVersion>> {
626        let _ = path;
627        Box::pin(async { Ok(FixtureSupport::Unsupported) })
628    }
629
630    /// Asynchronously returns a valid version that cannot match the resource.
631    ///
632    /// # Parameters
633    ///
634    /// * `path` - Resource whose current version the supplied token must not
635    ///   match.
636    ///
637    /// # Returns
638    ///
639    /// A future resolving to a valid stale version, or `Unsupported` when the
640    /// fixture cannot produce one.
641    ///
642    /// # Errors
643    ///
644    /// The future returns [`FixtureError`](crate::FixtureError) when producing
645    /// or validating the version fails.
646    #[inline]
647    fn stale_resource_version<'a>(&'a self, path: &'a Path) -> FixtureFuture<'a, FixtureSupport<ResourceVersion>> {
648        let _ = path;
649        Box::pin(async { Ok(FixtureSupport::Unsupported) })
650    }
651
652    /// Asynchronously supplies a resource whose checksum is invalid.
653    ///
654    /// # Parameters
655    ///
656    /// * `relative` - Testkit-relative name for the corrupted resource.
657    ///
658    /// # Returns
659    ///
660    /// A future resolving to the prepared path, or `Unsupported` when the
661    /// fixture cannot create a checksum-corrupt resource.
662    ///
663    /// # Errors
664    ///
665    /// The future returns [`FixtureError`](crate::FixtureError) when
666    /// preparation fails.
667    #[inline]
668    fn checksum_failure_case<'a>(&'a self, relative: &'a str) -> FixtureFuture<'a, FixtureSupport<Path>> {
669        let _ = relative;
670        Box::pin(async { Ok(FixtureSupport::Unsupported) })
671    }
672
673    /// Independently releases every resource owned by this fixture.
674    ///
675    /// This mandatory operation must be idempotent and must reclaim partially
676    /// prepared resources and staging state, including resources unknown to
677    /// the suite. Use a native or out-of-band channel independent of the
678    /// facade under test. Return an error if cleanup could not be confirmed.
679    /// A cancelled asynchronous attempt must remain safe to retry.
680    ///
681    /// # Returns
682    ///
683    /// A future completing after fixture-owned resources and staging state
684    /// have been independently reclaimed.
685    ///
686    /// # Errors
687    ///
688    /// The future returns [`FixtureError`](crate::FixtureError) when cleanup
689    /// cannot be confirmed.
690    fn teardown(&self) -> FixtureFuture<'_, ()>;
691
692    /// Asynchronously seeds an empty directory or prefix.
693    ///
694    /// # Parameters
695    ///
696    /// * `relative` - Testkit-relative name of the directory or prefix.
697    ///
698    /// # Returns
699    ///
700    /// A future resolving to its path, or `Unsupported` when independent
701    /// seeding is unavailable.
702    ///
703    /// # Errors
704    ///
705    /// The future returns [`FixtureError`](crate::FixtureError) when seeding
706    /// fails.
707    #[inline]
708    fn seed_empty_directory<'a>(&'a self, relative: &'a str) -> FixtureFuture<'a, FixtureSupport<Path>> {
709        let _ = relative;
710        Box::pin(async { Ok(FixtureSupport::Unsupported) })
711    }
712
713    /// Asynchronously seeds a symbolic link.
714    ///
715    /// # Parameters
716    ///
717    /// * `relative` - Testkit-relative name for the symbolic link.
718    ///
719    /// # Returns
720    ///
721    /// A future resolving to the link path, or `Unsupported` when the fixture
722    /// cannot seed symbolic links.
723    ///
724    /// # Errors
725    ///
726    /// The future returns [`FixtureError`](crate::FixtureError) when seeding
727    /// fails.
728    #[inline]
729    fn seed_symlink<'a>(&'a self, relative: &'a str) -> FixtureFuture<'a, FixtureSupport<Path>> {
730        let _ = relative;
731        Box::pin(async { Ok(FixtureSupport::Unsupported) })
732    }
733
734    /// Supplies an asynchronously prepared native copy fast-path case.
735    ///
736    /// # Parameters
737    ///
738    /// * `method` - Provider-native copy method the case must exercise.
739    ///
740    /// # Returns
741    ///
742    /// A future resolving to a case for that method, or `Unsupported` when
743    /// the fixture cannot provide the native path. For `Native`, the case
744    /// must be a single file with a distinct, independently confirmed absent
745    /// target and an independently seeded source containing 1..=64 KiB.
746    /// Return `Unsupported` when those premises cannot be guaranteed; a
747    /// streamed result does not satisfy this request. Returned source and
748    /// target paths are registered for cleanup immediately.
749    ///
750    /// # Errors
751    ///
752    /// The future returns [`FixtureError`](crate::FixtureError) when case
753    /// preparation fails.
754    #[inline]
755    fn copy_fast_path_case<'a>(&'a self, method: CopyMethod) -> FixtureFuture<'a, FixtureSupport<CopyFixtureCase>> {
756        let _ = method;
757        Box::pin(async { Ok(FixtureSupport::Unsupported) })
758    }
759
760    /// Asynchronously prepares a stage-aware single-file cancellation probe.
761    ///
762    /// A supported probe must also support independent `read_file` and
763    /// `exists_out_of_band` observations for its source and destination.
764    /// The source must contain a complete file and the destination must have
765    /// a known initial state; otherwise return `Unsupported`.
766    ///
767    /// # Parameters
768    ///
769    /// * `stage` - Provider-owned copy stage that must be held pending.
770    /// * `relative` - Testkit-relative name used to isolate probe resources.
771    ///
772    /// # Returns
773    ///
774    /// A future resolving to a probe for the requested stage, or
775    /// `Unsupported` when stage control or independent observations are
776    /// unavailable.
777    ///
778    /// # Errors
779    ///
780    /// The future returns [`FixtureError`](crate::FixtureError) when probe
781    /// setup fails; setup errors must not be reported as `Unsupported`.
782    #[inline]
783    fn prepare_copy_cancellation<'a>(
784        &'a self,
785        stage: AsyncCopyCancellationStage,
786        relative: &'a str,
787    ) -> FixtureFuture<'a, FixtureSupport<Box<dyn CopyCancellationProbe>>> {
788        let _ = (stage, relative);
789        Box::pin(async { Ok(FixtureSupport::Unsupported) })
790    }
791
792    /// Prepares a stage-aware whole-file write cancellation probe. A supported
793    /// probe independently observes the target and reports bytes accepted by
794    /// the provider writer. Return `Unsupported` when reliable stage
795    /// acknowledgement or evidence is unavailable.
796    ///
797    /// # Parameters
798    ///
799    /// * `stage` - Provider-owned write stage that must be held pending.
800    /// * `relative` - Testkit-relative target name used to isolate the probe.
801    ///
802    /// # Returns
803    ///
804    /// A future resolving to a probe for the requested stage, or
805    /// `Unsupported` when reliable stage control or independent evidence is
806    /// unavailable.
807    ///
808    /// # Errors
809    ///
810    /// The future returns [`FixtureError`](crate::FixtureError) when probe
811    /// setup fails; setup errors must not be reported as `Unsupported`.
812    #[inline]
813    fn prepare_write_cancellation<'a>(
814        &'a self,
815        stage: AsyncWriteCancellationStage,
816        relative: &'a str,
817    ) -> FixtureFuture<'a, FixtureSupport<Box<dyn WriteCancellationProbe>>> {
818        let _ = (stage, relative);
819        Box::pin(async { Ok(FixtureSupport::Unsupported) })
820    }
821}
822
823#[cfg(all(test, feature = "async"))]
824mod tests {
825    use std::future::Future;
826    use std::sync::atomic::AtomicUsize;
827    use std::sync::atomic::Ordering;
828
829    use qubit_fs::AsyncFileSystem;
830    use qubit_fs::path::Path;
831
832    use super::AsyncFileSystemFixture;
833    use super::FixtureFuture;
834    use crate::CopyScenario;
835    use crate::FixtureError;
836    use crate::FixturePreparation;
837    use crate::FixtureResult;
838    use crate::FixtureSupport;
839    use crate::tests::common::AsyncMemoryFixture;
840    use crate::tests::common::async_memory_file_system::run_controlled;
841
842    struct DefaultFixture<'a> {
843        file_system: &'a AsyncFileSystem,
844        directory_calls: AtomicUsize,
845        supported_directory_calls: usize,
846        file_calls: AtomicUsize,
847        supported_file_calls: usize,
848    }
849
850    impl DefaultFixture<'_> {
851        fn path_for(relative: &str) -> FixtureResult<Path> {
852            Path::parse(&format!("/default-fixture/{relative}")).map_err(|error| FixtureError::new(error.to_string()))
853        }
854    }
855
856    impl AsyncFileSystemFixture for DefaultFixture<'_> {
857        fn file_system(&self) -> &AsyncFileSystem {
858            self.file_system
859        }
860
861        fn path(&self, relative: &str) -> FixtureResult<Path> {
862            Self::path_for(relative)
863        }
864
865        fn seed_empty_directory<'a>(&'a self, relative: &'a str) -> FixtureFuture<'a, FixtureSupport<Path>> {
866            let call = self.directory_calls.fetch_add(1, Ordering::SeqCst) + 1;
867            let result = if call <= self.supported_directory_calls {
868                Self::path_for(relative).map(FixtureSupport::Supported)
869            } else {
870                Ok(FixtureSupport::Unsupported)
871            };
872            Box::pin(async move { result })
873        }
874
875        fn seed_file<'a>(&'a self, relative: &'a str, _bytes: &'a [u8]) -> FixtureFuture<'a, FixtureSupport<Path>> {
876            let call = self.file_calls.fetch_add(1, Ordering::SeqCst) + 1;
877            let result = if call <= self.supported_file_calls {
878                Self::path_for(relative).map(FixtureSupport::Supported)
879            } else {
880                Ok(FixtureSupport::Unsupported)
881            };
882            Box::pin(async move { result })
883        }
884
885        fn teardown(&self) -> FixtureFuture<'_, ()> {
886            Box::pin(async { Ok(()) })
887        }
888    }
889
890    fn fixture<'a>(
891        memory: &'a AsyncMemoryFixture,
892        supported_directory_calls: usize,
893        seed_file_supported: bool,
894    ) -> DefaultFixture<'a> {
895        fixture_with_file_limit(
896            memory,
897            supported_directory_calls,
898            if seed_file_supported { usize::MAX } else { 0 },
899        )
900    }
901
902    fn fixture_with_file_limit<'a>(
903        memory: &'a AsyncMemoryFixture,
904        supported_directory_calls: usize,
905        supported_file_calls: usize,
906    ) -> DefaultFixture<'a> {
907        DefaultFixture {
908            file_system: memory.file_system(),
909            directory_calls: AtomicUsize::new(0),
910            supported_directory_calls,
911            file_calls: AtomicUsize::new(0),
912            supported_file_calls,
913        }
914    }
915
916    fn block_on<T>(future: impl Future<Output = T>) -> T {
917        run_controlled(future)
918    }
919
920    #[test]
921    fn test_default_random_access_fixture_hooks_report_unsupported() {
922        let memory = AsyncMemoryFixture::new();
923        let fixture = fixture(&memory, 0, false);
924        let path = DefaultFixture::path_for("random-access").expect("build fixture path");
925        assert!(DefaultFixture::path_for("\0").is_err());
926
927        assert!(matches!(
928            block_on(fixture.replace_random_access_path(&path, b"replacement")),
929            Ok(FixtureSupport::Unsupported)
930        ));
931        assert!(matches!(
932            fixture.arm_random_access_pending_read(&path),
933            Ok(FixtureSupport::Unsupported)
934        ));
935        assert!(matches!(fixture.disarm_random_access_pending_read(&path), Ok(())));
936        assert!(matches!(
937            fixture.random_access_pending_read_reached(&path),
938            Ok(FixtureSupport::Unsupported)
939        ));
940    }
941
942    #[test]
943    fn test_tree_copy_preparation_reports_missing_subdirectory_support() {
944        let memory = AsyncMemoryFixture::new();
945        let fixture = fixture(&memory, 1, false);
946
947        let prepared = block_on(fixture.prepare_copy(CopyScenario::AtomicTree, "source", "target", b"child"))
948            .expect("prepare tree copy");
949        assert!(matches!(
950            prepared,
951            FixturePreparation::Unavailable { ref reason } if reason == "tree subdirectory setup unavailable"
952        ));
953    }
954
955    #[test]
956    fn test_tree_copy_preparation_reports_missing_child_support() {
957        let memory = AsyncMemoryFixture::new();
958        let fixture = fixture(&memory, 2, false);
959
960        let prepared = block_on(fixture.prepare_copy(CopyScenario::DurableTree, "source", "target", b"child"))
961            .expect("prepare tree copy");
962        assert!(matches!(
963            prepared,
964            FixturePreparation::Unavailable { ref reason } if reason == "tree child setup unavailable"
965        ));
966    }
967
968    #[test]
969    fn test_file_copy_preparation_reports_missing_conflict_target_support() {
970        let memory = AsyncMemoryFixture::new();
971        let fixture = fixture_with_file_limit(&memory, 0, 1);
972
973        let prepared = block_on(fixture.prepare_copy(CopyScenario::Conflict, "source", "target", b"payload"))
974            .expect("prepare conflict copy");
975        assert!(matches!(
976            prepared,
977            FixturePreparation::Unavailable { ref reason } if reason == "copy conflict target seed unavailable"
978        ));
979    }
980
981    #[test]
982    fn test_supported_copy_preparation_uses_fixture_path_and_cleanup_hooks() {
983        let memory = AsyncMemoryFixture::new();
984        let fixture = fixture_with_file_limit(&memory, 2, 1);
985
986        assert!(std::ptr::eq(fixture.file_system(), memory.file_system()));
987        assert_eq!(
988            fixture.path("explicit").expect("map fixture path").as_str(),
989            "/default-fixture/explicit"
990        );
991        let prepared = block_on(fixture.prepare_copy(CopyScenario::DurableTree, "source", "target", b"child"))
992            .expect("prepare supported tree copy");
993        assert!(matches!(prepared, FixturePreparation::Ready(_)));
994        block_on(fixture.teardown()).expect("tear down fixture");
995    }
996}