qubit_fs_testkit/contract_source.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//! Owned provider failures that may retain a non-Sync recovery handle.
9
10use std::error::Error;
11use std::fmt::Debug;
12use std::fmt::Display;
13use std::fmt::Formatter;
14use std::fmt::Result as FmtResult;
15use std::sync::Mutex;
16
17/// Preserves the complete original error while keeping the report Send + Sync.
18///
19/// Some filesystem errors own a recovery writer that is Send but not Sync.
20/// This wrapper serializes explicit inspection and ownership transfer.
21/// Formatting never invokes provider code. Taking the source transfers any
22/// recovery responsibility; otherwise ordinary destruction still drops it.
23///
24/// # Examples
25///
26/// A run returned by `FileSystemContractSuite::run` exposes failures through
27/// `ContractRun::failures`. A failed owned write may retain this wrapper in the
28/// failure's standard error source chain. Taking the source transfers the
29/// provider error and any recovery responsibility:
30///
31/// ```
32/// use std::error::Error;
33///
34/// use qubit_fs_testkit::ContractRun;
35/// use qubit_fs_testkit::ContractSource;
36///
37/// fn take_owned_source(run: &ContractRun) -> Option<Box<dyn Error + Send>> {
38/// let failure = run.failures().first()?;
39/// Error::source(failure)?
40/// .downcast_ref::<ContractSource>()?
41/// .take()
42/// }
43/// ```
44#[must_use]
45pub struct ContractSource {
46 /// Serializes access to the retained error and allows recovery after
47 /// poisoning.
48 error: Mutex<Option<Box<dyn Error + Send>>>,
49}
50
51impl ContractSource {
52 /// Retains an original typed error without formatting provider internals.
53 ///
54 /// # Parameters
55 ///
56 /// - `error`: The owned provider error to retain for later inspection.
57 pub(crate) fn new(error: impl Error + Send + 'static) -> Self {
58 Self {
59 error: Mutex::new(Some(Box::new(error))),
60 }
61 }
62
63 /// Inspects the original concrete error while it remains owned by the run.
64 ///
65 /// The callback runs synchronously while this source's mutex is held. It
66 /// must not directly or indirectly call `inspect` or `take` on the same
67 /// source, or wait for another operation that needs that mutex. Return
68 /// the inspection result first, then call `take` outside the callback.
69 ///
70 /// ```
71 /// use std::error::Error;
72 ///
73 /// use qubit_fs_testkit::ContractSource;
74 ///
75 /// fn take_io_source(source: &ContractSource) -> Option<Box<dyn Error + Send>> {
76 /// let is_io_error = source.inspect(|error| error.is::<std::io::Error>())?;
77 /// if is_io_error { source.take() } else { None }
78 /// }
79 /// ```
80 ///
81 /// Inspection and transfer are not atomic. Another caller may take the
82 /// source between these operations, so callers must handle `take() ==
83 /// None`. Taking the source also transfers explicit recovery
84 /// responsibility to the caller.
85 ///
86 ///
87 /// # Type Parameters
88 ///
89 /// - `T`: The result produced by the caller's inspection callback.
90 ///
91 /// # Parameters
92 ///
93 /// - `inspect`: A synchronous callback that inspects the retained error
94 /// while the source mutex is held.
95 ///
96 /// # Returns
97 ///
98 /// Returns `Some` with the result of `inspect` while the source is
99 /// retained. Returns `None` after a caller has taken ownership of the
100 /// source.
101 pub fn inspect<T>(&self, inspect: impl FnOnce(&(dyn Error + Send + 'static)) -> T) -> Option<T> {
102 let guard = self.error.lock().unwrap_or_else(|poison| poison.into_inner());
103 guard.as_deref().map(inspect)
104 }
105
106 /// Transfers the original error and any recovery handle to the caller.
107 ///
108 /// The caller becomes responsible for its explicit recovery or disposal.
109 ///
110 /// # Returns
111 ///
112 /// The original error if it is still retained, or `None` if another caller
113 /// has already taken it.
114 pub fn take(&self) -> Option<Box<dyn Error + Send>> {
115 self.error.lock().unwrap_or_else(|poison| poison.into_inner()).take()
116 }
117}
118
119impl Debug for ContractSource {
120 /// Formats a stable summary without invoking the retained provider error.
121 ///
122 /// # Parameters
123 ///
124 /// - `formatter`: Destination for the stable source summary.
125 fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
126 formatter.write_str("ContractSource { original_error: retained }")
127 }
128}
129
130impl Display for ContractSource {
131 /// Formats recovery guidance without exposing provider-specific details.
132 ///
133 /// # Parameters
134 ///
135 /// - `formatter`: Destination for the recovery guidance.
136 fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
137 formatter.write_str("original provider failure; inspect the retained source for recovery")
138 }
139}
140
141impl Error for ContractSource {}
142
143#[cfg(test)]
144mod tests {
145 use std::panic::AssertUnwindSafe;
146
147 use super::ContractSource;
148
149 #[test]
150 fn test_poisoned_source_lock_remains_inspectable_and_transferable() {
151 let source = ContractSource::new(std::io::Error::other("poisoned source"));
152 let _ = std::panic::catch_unwind(AssertUnwindSafe(|| {
153 let _guard = source.error.lock().unwrap();
154 panic!("poison source lock");
155 }));
156
157 assert_eq!(
158 source.inspect(|error| error.to_string()),
159 Some("poisoned source".to_owned())
160 );
161 assert_eq!(source.inspect(|error| error.is::<std::io::Error>()), Some(true));
162 assert_eq!(source.take().unwrap().to_string(), "poisoned source");
163 assert!(source.take().is_none());
164 }
165}