Skip to main content

toasty_driver_integration_suite/
instrumented_driver.rs

1use async_trait::async_trait;
2use std::{
3    borrow::Cow,
4    collections::VecDeque,
5    fmt,
6    sync::{
7        Arc, Mutex,
8        atomic::{AtomicBool, Ordering},
9    },
10};
11use toasty_core::{
12    Result, Schema,
13    driver::{Capability, ConnectContext, Connection, Driver, ExecResponse, Operation, Rows},
14    schema::db::{AppliedMigration, Migration},
15};
16
17/// A fault that can be injected into the next operation routed through
18/// the driver. Faults are consumed in FIFO order: each `exec` call pops
19/// at most one fault off the queue before delegating (or short-circuiting
20/// past) the underlying driver.
21#[derive(Debug, Clone)]
22pub enum Fault {
23    /// Causes the next `exec` to return `Error::driver_operation_failed`
24    /// without touching the underlying connection or marking it invalid.
25    OperationFailed,
26
27    /// Causes the next `exec` to return `Error::connection_lost` without
28    /// touching the underlying connection. The wrapping
29    /// `InstrumentedConnection`'s `is_valid` flips to `false`, mirroring
30    /// what a real connection-lost error would do and prompting the pool
31    /// to evict the connection.
32    ConnectionLost,
33}
34
35#[derive(Debug)]
36pub struct DriverOp {
37    pub operation: Operation,
38    pub response: ExecResponse,
39}
40
41/// Single control handle for the [`InstrumentedDriver`] test middleware.
42/// Exposes both the operation log (for assertions) and the fault queue
43/// (for injecting failures). Cheaply cloneable; every clone refers to
44/// the same shared state.
45#[derive(Clone, Default)]
46pub struct InstrumentedHandle {
47    inner: Arc<InstrumentedState>,
48}
49
50#[derive(Default)]
51struct InstrumentedState {
52    ops_log: Mutex<Vec<DriverOp>>,
53    faults: Mutex<VecDeque<Fault>>,
54}
55
56impl InstrumentedHandle {
57    /// Get the number of logged operations
58    pub fn len(&self) -> usize {
59        self.inner.ops_log.lock().unwrap().len()
60    }
61
62    /// Check if the log is empty
63    pub fn is_empty(&self) -> bool {
64        self.inner.ops_log.lock().unwrap().is_empty()
65    }
66
67    /// Clear the log
68    pub fn clear(&self) {
69        self.inner.ops_log.lock().unwrap().clear();
70    }
71
72    /// Remove and return the first operation from the log
73    #[track_caller]
74    pub fn pop(&self) -> (Operation, ExecResponse) {
75        let mut ops = self.inner.ops_log.lock().unwrap();
76        if ops.is_empty() {
77            panic!("no operations in log");
78        }
79        let driver_op = ops.remove(0);
80        (driver_op.operation, driver_op.response)
81    }
82
83    #[track_caller]
84    pub fn pop_op(&self) -> Operation {
85        self.pop().0
86    }
87
88    /// Remove and return the last operation from the log
89    #[track_caller]
90    pub fn pop_last(&self) -> (Operation, ExecResponse) {
91        let mut ops = self.inner.ops_log.lock().unwrap();
92        let Some(driver_op) = ops.pop() else {
93            panic!("no operations in log");
94        };
95        (driver_op.operation, driver_op.response)
96    }
97
98    #[track_caller]
99    pub fn pop_last_op(&self) -> Operation {
100        self.pop_last().0
101    }
102
103    /// Queue a fault to fire on the next driver `exec` call. Faults fire
104    /// in FIFO order across all connections produced by the driver.
105    pub fn inject_fault(&self, fault: Fault) {
106        self.inner
107            .faults
108            .lock()
109            .expect("Failed to acquire faults lock")
110            .push_back(fault);
111    }
112}
113
114impl fmt::Debug for InstrumentedHandle {
115    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116        let ops = self.inner.ops_log.lock().unwrap();
117        f.debug_struct("InstrumentedHandle")
118            .field("ops", &*ops)
119            .finish()
120    }
121}
122
123/// Test-only driver wrapper that instruments an underlying driver: it
124/// records every operation for later assertion and can inject faults
125/// (connection loss, etc.) to exercise error-handling paths.
126#[derive(Debug)]
127pub struct InstrumentedDriver {
128    inner: Box<dyn Driver>,
129    handle: InstrumentedHandle,
130    /// Reported in place of the inner driver's capability when set.
131    capability: Option<&'static Capability>,
132}
133
134impl InstrumentedDriver {
135    pub fn new(driver: Box<dyn Driver>) -> Self {
136        Self {
137            inner: driver,
138            handle: InstrumentedHandle::default(),
139            capability: None,
140        }
141    }
142
143    /// Report `capability` to the engine instead of the inner driver's own,
144    /// so a test can watch how the engine plans for a backend it does not
145    /// have. The inner driver still executes whatever the engine asks of it.
146    pub fn with_capability(mut self, capability: &'static Capability) -> Self {
147        self.capability = Some(capability);
148        self
149    }
150
151    /// Get the single control handle for this driver. The handle exposes
152    /// both the operations log and the fault-injection queue.
153    pub fn handle(&self) -> InstrumentedHandle {
154        self.handle.clone()
155    }
156}
157
158#[async_trait]
159impl Driver for InstrumentedDriver {
160    fn url(&self) -> Cow<'_, str> {
161        self.inner.url()
162    }
163
164    fn capability(&self) -> &'static Capability {
165        self.capability.unwrap_or_else(|| self.inner.capability())
166    }
167
168    async fn connect(&self, cx: &ConnectContext) -> Result<Box<dyn Connection>> {
169        Ok(Box::new(InstrumentedConnection {
170            inner: self.inner.connect(cx).await?,
171            handle: self.handle.clone(),
172            valid: AtomicBool::new(true),
173        }))
174    }
175
176    async fn reset_db(&self) -> Result<()> {
177        self.inner.reset_db().await
178    }
179}
180
181/// Per-connection counterpart of [`InstrumentedDriver`]: records each
182/// `exec` and consults the shared fault queue before delegating.
183#[derive(Debug)]
184pub struct InstrumentedConnection {
185    /// The underlying driver that actually executes operations
186    inner: Box<dyn Connection>,
187
188    /// Shared handle: ops log + fault queue.
189    handle: InstrumentedHandle,
190
191    /// Set to `false` once an injected `ConnectionLost` fault has fired
192    /// against this connection. Surfaced through [`Connection::is_valid`]
193    /// so the pool evicts it the same way it would after a real
194    /// connection-lost error.
195    valid: AtomicBool,
196}
197
198#[async_trait]
199impl Connection for InstrumentedConnection {
200    async fn exec(&mut self, schema: &Arc<Schema>, operation: Operation) -> Result<ExecResponse> {
201        // Pop a queued fault, if any, and short-circuit before reaching
202        // the underlying driver.
203        let fault = self
204            .handle
205            .inner
206            .faults
207            .lock()
208            .expect("Failed to acquire faults lock")
209            .pop_front();
210        if let Some(fault) = fault {
211            match fault {
212                Fault::OperationFailed => {
213                    return Err(toasty_core::Error::driver_operation_failed(
214                        std::io::Error::other("injected operation failure"),
215                    ));
216                }
217                Fault::ConnectionLost => {
218                    self.valid.store(false, Ordering::Release);
219                    return Err(toasty_core::Error::connection_lost(std::io::Error::other(
220                        "injected connection-lost fault",
221                    )));
222                }
223            }
224        }
225
226        // Clone the operation for logging
227        let operation_clone = operation.clone();
228
229        // Execute the operation on the underlying driver
230        let mut response = self.inner.exec(schema, operation).await?;
231
232        // Duplicate the response for logging
233        let duplicated_response = duplicate_response_mut(&mut response).await?;
234
235        // Log the operation and response
236        let driver_op = DriverOp {
237            operation: operation_clone,
238            response: duplicated_response,
239        };
240
241        self.handle
242            .inner
243            .ops_log
244            .lock()
245            .expect("Failed to acquire ops log lock")
246            .push(driver_op);
247
248        Ok(response)
249    }
250
251    async fn push_schema(&mut self, schema: &Schema) -> Result<()> {
252        self.inner.push_schema(schema).await
253    }
254
255    async fn applied_migrations(&mut self) -> Result<Vec<AppliedMigration>> {
256        self.inner.applied_migrations().await
257    }
258
259    async fn apply_migration(&mut self, id: u64, name: &str, migration: &Migration) -> Result<()> {
260        self.inner.apply_migration(id, name, migration).await
261    }
262
263    fn is_valid(&self) -> bool {
264        self.valid.load(Ordering::Acquire) && self.inner.is_valid()
265    }
266
267    async fn ping(&mut self) -> Result<()> {
268        // Consume a queued fault before delegating, mirroring `exec`.
269        // A `ConnectionLost` fault here lets tests target the sweep's
270        // ping path the same way they target user query paths.
271        let fault = self
272            .handle
273            .inner
274            .faults
275            .lock()
276            .expect("Failed to acquire faults lock")
277            .pop_front();
278        if let Some(fault) = fault {
279            match fault {
280                Fault::OperationFailed => {
281                    return Err(toasty_core::Error::driver_operation_failed(
282                        std::io::Error::other("injected operation failure"),
283                    ));
284                }
285                Fault::ConnectionLost => {
286                    self.valid.store(false, Ordering::Release);
287                    return Err(toasty_core::Error::connection_lost(std::io::Error::other(
288                        "injected connection-lost fault",
289                    )));
290                }
291            }
292        }
293        self.inner.ping().await
294    }
295}
296
297/// Duplicate an ExecResponse, using ValueStream::dup() for value streams
298/// This version takes a mutable reference so we can call dup() on the ValueStream
299async fn duplicate_response_mut(response: &mut ExecResponse) -> Result<ExecResponse> {
300    let values = match &mut response.values {
301        Rows::Count(count) => Rows::Count(*count),
302        Rows::Value(_) => todo!(),
303        Rows::Stream(stream) => {
304            // Duplicate the value stream
305            let duplicated_stream = stream.dup().await?;
306            Rows::Stream(duplicated_stream)
307        }
308    };
309
310    Ok(ExecResponse::from_rows(values))
311}