1use std::fmt::{Display, Formatter};
12use std::ops::Range;
13#[cfg(feature = "test-util")]
14use std::sync::atomic::AtomicU16;
15use std::sync::{Arc, Mutex};
16#[cfg(feature = "metrics")]
17use std::time::Instant;
18
19use bytes::Bytes;
20use futures::StreamExt;
21use futures::TryStreamExt;
22use futures::stream::BoxStream;
23use object_store::path::Path;
24use object_store::{
25 CopyOptions, GetOptions, GetRange, GetResult, ListResult, MultipartUpload, ObjectMeta,
26 ObjectStore, PutMultipartOptions, PutOptions, PutPayload, PutResult, RenameOptions,
27 Result as OSResult, UploadPart,
28};
29
30use crate::object_store::WrappingObjectStore;
31#[cfg(feature = "metrics")]
32use crate::object_store::metrics::{InFlightGuard, record_outcome};
33use object_store::list::PaginatedListStore;
34
35#[derive(Debug, Default, Clone)]
36pub struct IOTracker {
37 stats: Arc<Mutex<IoStats>>,
38 #[cfg(feature = "metrics")]
43 metrics_base: Option<Arc<str>>,
44}
45
46impl IOTracker {
47 pub fn incremental_stats(&self) -> IoStats {
52 std::mem::take(&mut *self.stats.lock().unwrap())
53 }
54
55 pub fn stats(&self) -> IoStats {
60 self.stats.lock().unwrap().clone()
61 }
62
63 pub fn record_read(
68 &self,
69 #[allow(unused_variables)] method: &'static str,
70 #[allow(unused_variables)] path: Path,
71 num_bytes: u64,
72 #[allow(unused_variables)] range: Option<Range<u64>>,
73 ) {
74 let mut stats = self.stats.lock().unwrap();
75 stats.read_iops += 1;
76 stats.read_bytes += num_bytes;
77 #[cfg(feature = "test-util")]
78 stats.requests.push(IoRequestRecord {
79 method,
80 path,
81 range,
82 });
83 }
84
85 pub fn record_write(
90 &self,
91 #[allow(unused_variables)] method: &'static str,
92 #[allow(unused_variables)] path: Path,
93 num_bytes: u64,
94 ) {
95 let mut stats = self.stats.lock().unwrap();
96 stats.write_iops += 1;
97 stats.written_bytes += num_bytes;
98 #[cfg(feature = "test-util")]
99 stats.requests.push(IoRequestRecord {
100 method,
101 path,
102 range: None,
103 });
104 }
105
106 #[cfg(feature = "metrics")]
113 pub(crate) fn set_metrics_base(&mut self, base: &str) {
114 self.metrics_base = Some(base.into());
115 }
116
117 #[cfg(feature = "metrics")]
125 pub fn begin_io(&self, operation: &'static str) -> IoMetricsGuard {
126 IoMetricsGuard {
127 state: self.metrics_base.as_ref().map(|base| IoMetricsState {
128 _in_flight: InFlightGuard::new(base, operation),
129 base: base.clone(),
130 operation,
131 start: Instant::now(),
132 }),
133 }
134 }
135
136 #[cfg(not(feature = "metrics"))]
138 pub fn begin_io(&self, _operation: &'static str) -> IoMetricsGuard {
139 IoMetricsGuard {}
140 }
141}
142
143#[must_use = "the operation is not recorded until `record` is called"]
150pub struct IoMetricsGuard {
151 #[cfg(feature = "metrics")]
152 state: Option<IoMetricsState>,
153}
154
155#[cfg(feature = "metrics")]
156struct IoMetricsState {
157 base: Arc<str>,
158 operation: &'static str,
159 start: Instant,
160 _in_flight: InFlightGuard,
162}
163
164impl IoMetricsGuard {
165 pub fn record<T, E>(self, result: &std::result::Result<T, E>, num_bytes: u64) {
168 #[cfg(feature = "metrics")]
169 if let Some(state) = self.state {
170 record_outcome(
171 &state.base,
172 state.operation,
173 state.start,
174 num_bytes,
175 result.is_err(),
176 );
177 }
178 #[cfg(not(feature = "metrics"))]
179 let _ = (result, num_bytes);
180 }
181}
182
183impl WrappingObjectStore for IOTracker {
184 fn wrap(&self, _store_prefix: &str, target: Arc<dyn ObjectStore>) -> Arc<dyn ObjectStore> {
185 Arc::new(IoTrackingStore::new(target, self.stats.clone()))
186 }
187
188 fn wrap_paginated(
191 &self,
192 _store_prefix: &str,
193 original: Arc<dyn PaginatedListStore>,
194 ) -> Option<Arc<dyn PaginatedListStore>> {
195 Some(original)
196 }
197}
198
199#[derive(Debug, Default, Clone)]
200pub struct IoStats {
201 pub read_iops: u64,
202 pub read_bytes: u64,
203 pub write_iops: u64,
204 pub written_bytes: u64,
205 #[cfg(feature = "test-util")]
207 pub num_stages: u64,
209 #[cfg(feature = "test-util")]
210 pub requests: Vec<IoRequestRecord>,
211}
212
213#[cfg(feature = "test-util")]
218#[macro_export]
219macro_rules! assert_io_eq {
220 ($io_stats:expr, $field:ident, $expected:expr) => {
221 assert_eq!(
222 $io_stats.$field, $expected,
223 "Expected {} to be {}, got {}. Requests: {:#?}",
224 stringify!($field),
225 $expected,
226 $io_stats.$field,
227 $io_stats.requests
228 );
229 };
230 ($io_stats:expr, $field:ident, $expected:expr, $($arg:tt)+) => {
231 assert_eq!(
232 $io_stats.$field, $expected,
233 "Expected {} to be {}, got {}. Requests: {:#?} {}",
234 stringify!($field),
235 $expected,
236 $io_stats.$field,
237 $io_stats.requests,
238 format_args!($($arg)+)
239 );
240 };
241}
242
243#[cfg(feature = "test-util")]
244#[macro_export]
245macro_rules! assert_io_gt {
246 ($io_stats:expr, $field:ident, $expected:expr) => {
247 assert!(
248 $io_stats.$field > $expected,
249 "Expected {} to be > {}, got {}. Requests: {:#?}",
250 stringify!($field),
251 $expected,
252 $io_stats.$field,
253 $io_stats.requests
254 );
255 };
256 ($io_stats:expr, $field:ident, $expected:expr, $($arg:tt)+) => {
257 assert!(
258 $io_stats.$field > $expected,
259 "Expected {} to be > {}, got {}. Requests: {:#?} {}",
260 stringify!($field),
261 $expected,
262 $io_stats.$field,
263 $io_stats.requests,
264 format_args!($($arg)+)
265 );
266 };
267}
268
269#[cfg(feature = "test-util")]
270#[macro_export]
271macro_rules! assert_io_lt {
272 ($io_stats:expr, $field:ident, $expected:expr) => {
273 assert!(
274 $io_stats.$field < $expected,
275 "Expected {} to be < {}, got {}. Requests: {:#?}",
276 stringify!($field),
277 $expected,
278 $io_stats.$field,
279 $io_stats.requests
280 );
281 };
282 ($io_stats:expr, $field:ident, $expected:expr, $($arg:tt)+) => {
283 assert!(
284 $io_stats.$field < $expected,
285 "Expected {} to be < {}, got {}. Requests: {:#?} {}",
286 stringify!($field),
287 $expected,
288 $io_stats.$field,
289 $io_stats.requests,
290 format_args!($($arg)+)
291 );
292 };
293}
294
295#[cfg(feature = "test-util")]
297#[derive(Clone)]
298pub struct IoRequestRecord {
299 pub method: &'static str,
300 pub path: Path,
301 pub range: Option<Range<u64>>,
302}
303
304#[cfg(feature = "test-util")]
305impl std::fmt::Debug for IoRequestRecord {
306 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
307 write!(
309 f,
310 "IORequest(method={}, path=\"{}\"",
311 self.method, self.path
312 )?;
313 if let Some(range) = &self.range {
314 write!(f, ", range={:?}", range)?;
315 }
316 write!(f, ")")?;
317 Ok(())
318 }
319}
320
321impl Display for IoStats {
322 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
323 write!(f, "{:#?}", self)
324 }
325}
326
327#[derive(Debug)]
328pub struct IoTrackingStore {
329 target: Arc<dyn ObjectStore>,
330 stats: Arc<Mutex<IoStats>>,
331 #[cfg(feature = "test-util")]
332 active_requests: Arc<AtomicU16>,
333}
334
335impl Display for IoTrackingStore {
336 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
337 write!(f, "{:#?}", self)
338 }
339}
340
341impl IoTrackingStore {
342 pub fn new(target: Arc<dyn ObjectStore>, stats: Arc<Mutex<IoStats>>) -> Self {
343 Self {
344 target,
345 stats,
346 #[cfg(feature = "test-util")]
347 active_requests: Arc::new(AtomicU16::new(0)),
348 }
349 }
350
351 fn record_read(
352 &self,
353 method: &'static str,
354 path: Path,
355 num_bytes: u64,
356 range: Option<Range<u64>>,
357 ) {
358 let mut stats = self.stats.lock().unwrap();
359 stats.read_iops += 1;
360 stats.read_bytes += num_bytes;
361 #[cfg(feature = "test-util")]
362 stats.requests.push(IoRequestRecord {
363 method,
364 path,
365 range,
366 });
367 #[cfg(not(feature = "test-util"))]
368 let _ = (method, path, range); }
370
371 fn record_write(&self, method: &'static str, path: Path, num_bytes: u64) {
372 let mut stats = self.stats.lock().unwrap();
373 stats.write_iops += 1;
374 stats.written_bytes += num_bytes;
375 #[cfg(feature = "test-util")]
376 stats.requests.push(IoRequestRecord {
377 method,
378 path,
379 range: None,
380 });
381 #[cfg(not(feature = "test-util"))]
382 let _ = (method, path); }
384
385 #[cfg(feature = "test-util")]
386 fn stage_guard(&self) -> StageGuard {
387 StageGuard::new(self.active_requests.clone(), self.stats.clone())
388 }
389
390 #[cfg(not(feature = "test-util"))]
391 fn stage_guard(&self) -> StageGuard {
392 StageGuard
393 }
394}
395
396#[async_trait::async_trait]
397#[deny(clippy::missing_trait_methods)]
398impl ObjectStore for IoTrackingStore {
399 async fn put_opts(
400 &self,
401 location: &Path,
402 bytes: PutPayload,
403 opts: PutOptions,
404 ) -> OSResult<PutResult> {
405 let _guard = self.stage_guard();
406 self.record_write(
407 "put_opts",
408 location.to_owned(),
409 bytes.content_length() as u64,
410 );
411 self.target.put_opts(location, bytes, opts).await
412 }
413
414 async fn put_multipart_opts(
415 &self,
416 location: &Path,
417 opts: PutMultipartOptions,
418 ) -> OSResult<Box<dyn MultipartUpload>> {
419 let _guard = self.stage_guard();
420 let target = self.target.put_multipart_opts(location, opts).await?;
421 Ok(Box::new(IoTrackingMultipartUpload {
422 target,
423 stats: self.stats.clone(),
424 #[cfg(feature = "test-util")]
425 path: location.to_owned(),
426 #[cfg(feature = "test-util")]
427 _guard,
428 }))
429 }
430
431 async fn get_opts(&self, location: &Path, options: GetOptions) -> OSResult<GetResult> {
432 let _guard = self.stage_guard();
433 let range = match &options.range {
434 Some(GetRange::Bounded(range)) => Some(range.clone()),
435 _ => None, };
437 let result = self.target.get_opts(location, options).await;
438 if let Ok(result) = &result {
439 let num_bytes = result.range.end - result.range.start;
440
441 self.record_read("get_opts", location.to_owned(), num_bytes, range);
442 }
443 result
444 }
445
446 async fn get_ranges(&self, location: &Path, ranges: &[Range<u64>]) -> OSResult<Vec<Bytes>> {
447 let _guard = self.stage_guard();
448 let result = self.target.get_ranges(location, ranges).await;
449 if let Ok(result) = &result {
450 self.record_read(
451 "get_ranges",
452 location.to_owned(),
453 result.iter().map(|b| b.len() as u64).sum(),
454 None,
455 );
456 }
457 result
458 }
459
460 fn delete_stream(
461 &self,
462 locations: BoxStream<'static, OSResult<Path>>,
463 ) -> BoxStream<'static, OSResult<Path>> {
464 let stats = Arc::clone(&self.stats);
465 let tracked = locations
466 .map_ok(move |path| {
467 let mut stats = stats.lock().unwrap();
468 stats.write_iops += 1;
469 #[cfg(feature = "test-util")]
470 stats.requests.push(IoRequestRecord {
471 method: "delete",
472 path: path.clone(),
473 range: None,
474 });
475 path
476 })
477 .boxed();
478 self.target.delete_stream(tracked)
479 }
480
481 fn list(&self, prefix: Option<&Path>) -> BoxStream<'static, OSResult<ObjectMeta>> {
482 let _guard = self.stage_guard();
483 self.record_read("list", prefix.cloned().unwrap_or_default(), 0, None);
484 self.target.list(prefix)
485 }
486
487 fn list_with_offset(
488 &self,
489 prefix: Option<&Path>,
490 offset: &Path,
491 ) -> BoxStream<'static, OSResult<ObjectMeta>> {
492 self.record_read(
493 "list_with_offset",
494 prefix.cloned().unwrap_or_default(),
495 0,
496 None,
497 );
498 self.target.list_with_offset(prefix, offset)
499 }
500
501 async fn list_with_delimiter(&self, prefix: Option<&Path>) -> OSResult<ListResult> {
502 let _guard = self.stage_guard();
503 self.record_read(
504 "list_with_delimiter",
505 prefix.cloned().unwrap_or_default(),
506 0,
507 None,
508 );
509 self.target.list_with_delimiter(prefix).await
510 }
511
512 async fn copy_opts(&self, from: &Path, to: &Path, opts: CopyOptions) -> OSResult<()> {
513 let _guard = self.stage_guard();
514 self.record_write("copy", from.to_owned(), 0);
515 self.target.copy_opts(from, to, opts).await
516 }
517
518 async fn rename_opts(&self, from: &Path, to: &Path, opts: RenameOptions) -> OSResult<()> {
519 let _guard = self.stage_guard();
520 self.record_write("rename", from.to_owned(), 0);
521 self.target.rename_opts(from, to, opts).await
522 }
523}
524
525#[derive(Debug)]
526struct IoTrackingMultipartUpload {
527 target: Box<dyn MultipartUpload>,
528 #[cfg(feature = "test-util")]
529 path: Path,
530 stats: Arc<Mutex<IoStats>>,
531 #[cfg(feature = "test-util")]
532 _guard: StageGuard,
533}
534
535#[async_trait::async_trait]
536impl MultipartUpload for IoTrackingMultipartUpload {
537 async fn abort(&mut self) -> OSResult<()> {
538 self.target.abort().await
539 }
540
541 async fn complete(&mut self) -> OSResult<PutResult> {
542 self.target.complete().await
543 }
544
545 fn put_part(&mut self, payload: PutPayload) -> UploadPart {
546 {
547 let mut stats = self.stats.lock().unwrap();
548 stats.write_iops += 1;
549 stats.written_bytes += payload.content_length() as u64;
550 #[cfg(feature = "test-util")]
551 stats.requests.push(IoRequestRecord {
552 method: "put_part",
553 path: self.path.to_owned(),
554 range: None,
555 });
556 }
557 self.target.put_part(payload)
558 }
559}
560
561#[cfg(feature = "test-util")]
562#[derive(Debug)]
563struct StageGuard {
564 active_requests: Arc<AtomicU16>,
565 stats: Arc<Mutex<IoStats>>,
566}
567
568#[cfg(not(feature = "test-util"))]
569struct StageGuard;
570
571#[cfg(feature = "test-util")]
572impl StageGuard {
573 fn new(active_requests: Arc<AtomicU16>, stats: Arc<Mutex<IoStats>>) -> Self {
574 active_requests.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
575 Self {
576 active_requests,
577 stats,
578 }
579 }
580}
581
582#[cfg(feature = "test-util")]
583impl Drop for StageGuard {
584 fn drop(&mut self) {
585 if self
586 .active_requests
587 .fetch_sub(1, std::sync::atomic::Ordering::SeqCst)
588 == 1
589 {
590 let mut stats = self.stats.lock().unwrap();
591 stats.num_stages += 1;
592 }
593 }
594}