toasty_driver_integration_suite/
instrumented_driver.rs1use 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#[derive(Debug, Clone)]
22pub enum Fault {
23 OperationFailed,
26
27 ConnectionLost,
33}
34
35#[derive(Debug)]
36pub struct DriverOp {
37 pub operation: Operation,
38 pub response: ExecResponse,
39}
40
41#[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 pub fn len(&self) -> usize {
59 self.inner.ops_log.lock().unwrap().len()
60 }
61
62 pub fn is_empty(&self) -> bool {
64 self.inner.ops_log.lock().unwrap().is_empty()
65 }
66
67 pub fn clear(&self) {
69 self.inner.ops_log.lock().unwrap().clear();
70 }
71
72 #[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 #[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 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#[derive(Debug)]
127pub struct InstrumentedDriver {
128 inner: Box<dyn Driver>,
129 handle: InstrumentedHandle,
130 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 pub fn with_capability(mut self, capability: &'static Capability) -> Self {
147 self.capability = Some(capability);
148 self
149 }
150
151 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#[derive(Debug)]
184pub struct InstrumentedConnection {
185 inner: Box<dyn Connection>,
187
188 handle: InstrumentedHandle,
190
191 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 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 let operation_clone = operation.clone();
228
229 let mut response = self.inner.exec(schema, operation).await?;
231
232 let duplicated_response = duplicate_response_mut(&mut response).await?;
234
235 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 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
297async 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 let duplicated_stream = stream.dup().await?;
306 Rows::Stream(duplicated_stream)
307 }
308 };
309
310 Ok(ExecResponse::from_rows(values))
311}