Skip to main content

datafusion_cli/object_storage/
instrumented.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use std::{
6    cmp, fmt,
7    ops::AddAssign,
8    str::FromStr,
9    sync::{
10        Arc,
11        atomic::{AtomicU8, AtomicU64, Ordering},
12    },
13    time::Duration,
14};
15
16use arrow::array::{ArrayRef, RecordBatch, StringArray};
17use arrow::util::pretty::pretty_format_batches;
18use async_trait::async_trait;
19use chrono::Utc;
20use datafusion::{
21    common::{HashMap, instant::Instant},
22    error::DataFusionError,
23    execution::object_store::{DefaultObjectStoreRegistry, ObjectStoreRegistry},
24};
25use futures::stream::{BoxStream, Stream};
26use futures::{StreamExt, TryStreamExt};
27use object_store::{
28    CopyOptions, GetOptions, GetRange, GetResult, ListResult, MultipartUpload,
29    ObjectMeta, ObjectStore, ObjectStoreExt, PutMultipartOptions, PutOptions, PutPayload,
30    PutResult, Result, path::Path,
31};
32use parking_lot::{Mutex, RwLock};
33use url::Url;
34
35/// A stream wrapper that measures the time until the first response(item or end of stream) is yielded.
36///
37/// The timer starts on the first `poll_next` call (not at stream creation) to avoid
38/// measuring unrelated work between stream creation and first poll.
39/// Duration is stored as nanoseconds in an `AtomicU64` (0 = not yet set).
40struct TimeToFirstItemStream<S> {
41    inner: S,
42    start: Option<Instant>,
43    request_duration: Arc<AtomicU64>,
44    duration_recorded: bool,
45}
46
47impl<S> TimeToFirstItemStream<S> {
48    fn new(inner: S, request_duration: Arc<AtomicU64>) -> Self {
49        Self {
50            inner,
51            start: None,
52            request_duration,
53            duration_recorded: false,
54        }
55    }
56}
57
58impl<S> Stream for TimeToFirstItemStream<S>
59where
60    S: Stream<Item = Result<ObjectMeta>> + Unpin,
61{
62    type Item = Result<ObjectMeta>;
63
64    fn poll_next(
65        mut self: std::pin::Pin<&mut Self>,
66        cx: &mut std::task::Context<'_>,
67    ) -> std::task::Poll<Option<Self::Item>> {
68        let start = *self.start.get_or_insert_with(Instant::now);
69
70        let poll_result = std::pin::Pin::new(&mut self.inner).poll_next(cx);
71
72        if !self.duration_recorded && poll_result.is_ready() {
73            self.duration_recorded = true;
74            let nanos = start.elapsed().as_nanos() as u64;
75            self.request_duration.store(nanos, Ordering::Release);
76        }
77
78        poll_result
79    }
80}
81
82/// The profiling mode to use for an [`InstrumentedObjectStore`] instance. Collecting profiling
83/// data will have a small negative impact on both CPU and memory usage. Default is `Disabled`
84#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
85pub enum InstrumentedObjectStoreMode {
86    /// Disable collection of profiling data
87    #[default]
88    Disabled,
89    /// Enable collection of profiling data and output a summary
90    Summary,
91    /// Enable collection of profiling data and output a summary and all details
92    Trace,
93}
94
95impl fmt::Display for InstrumentedObjectStoreMode {
96    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97        write!(f, "{self:?}")
98    }
99}
100
101impl FromStr for InstrumentedObjectStoreMode {
102    type Err = DataFusionError;
103
104    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
105        match s.to_lowercase().as_str() {
106            "disabled" => Ok(Self::Disabled),
107            "summary" => Ok(Self::Summary),
108            "trace" => Ok(Self::Trace),
109            _ => Err(DataFusionError::Execution(format!("Unrecognized mode {s}"))),
110        }
111    }
112}
113
114impl From<u8> for InstrumentedObjectStoreMode {
115    fn from(value: u8) -> Self {
116        match value {
117            1 => InstrumentedObjectStoreMode::Summary,
118            2 => InstrumentedObjectStoreMode::Trace,
119            _ => InstrumentedObjectStoreMode::Disabled,
120        }
121    }
122}
123
124/// Wrapped [`ObjectStore`] instances that record information for reporting on the usage of the
125/// inner [`ObjectStore`]
126#[derive(Debug)]
127pub struct InstrumentedObjectStore {
128    inner: Arc<dyn ObjectStore>,
129    instrument_mode: AtomicU8,
130    requests: Arc<Mutex<Vec<RequestDetails>>>,
131}
132
133#[expect(
134    clippy::result_large_err,
135    reason = "error type is dictated by the object_store API"
136)]
137impl InstrumentedObjectStore {
138    /// Returns a new [`InstrumentedObjectStore`] that wraps the provided [`ObjectStore`]
139    fn new(object_store: Arc<dyn ObjectStore>, instrument_mode: AtomicU8) -> Self {
140        Self {
141            inner: object_store,
142            instrument_mode,
143            requests: Arc::new(Mutex::new(Vec::new())),
144        }
145    }
146
147    fn set_instrument_mode(&self, mode: InstrumentedObjectStoreMode) {
148        self.instrument_mode.store(mode as u8, Ordering::Relaxed)
149    }
150
151    /// Returns all [`RequestDetails`] accumulated in this [`InstrumentedObjectStore`] and clears
152    /// the stored requests
153    pub fn take_requests(&self) -> Vec<RequestDetails> {
154        let mut req = self.requests.lock();
155
156        req.drain(..).collect()
157    }
158
159    fn enabled(&self) -> bool {
160        self.instrument_mode.load(Ordering::Relaxed)
161            != InstrumentedObjectStoreMode::Disabled as u8
162    }
163
164    async fn instrumented_put_opts(
165        &self,
166        location: &Path,
167        payload: PutPayload,
168        opts: PutOptions,
169    ) -> Result<PutResult> {
170        let timestamp = Utc::now();
171        let start = Instant::now();
172        let size = payload.content_length();
173        let ret = self.inner.put_opts(location, payload, opts).await?;
174        let elapsed = start.elapsed();
175
176        self.requests.lock().push(RequestDetails {
177            op: Operation::Put,
178            path: location.clone(),
179            timestamp,
180            duration_nanos: Arc::new(AtomicU64::new(elapsed.as_nanos() as u64)),
181            size: Some(size),
182            range: None,
183            extra_display: None,
184        });
185
186        Ok(ret)
187    }
188
189    async fn instrumented_put_multipart(
190        &self,
191        location: &Path,
192        opts: PutMultipartOptions,
193    ) -> Result<Box<dyn MultipartUpload>> {
194        let timestamp = Utc::now();
195        let start = Instant::now();
196        let ret = self.inner.put_multipart_opts(location, opts).await?;
197        let elapsed = start.elapsed();
198
199        self.requests.lock().push(RequestDetails {
200            op: Operation::Put,
201            path: location.clone(),
202            timestamp,
203            duration_nanos: Arc::new(AtomicU64::new(elapsed.as_nanos() as u64)),
204            size: None,
205            range: None,
206            extra_display: None,
207        });
208
209        Ok(ret)
210    }
211
212    async fn instrumented_get_opts(
213        &self,
214        location: &Path,
215        options: GetOptions,
216    ) -> Result<GetResult> {
217        let timestamp = Utc::now();
218        let range = options.range.clone();
219
220        let head = options.head;
221        let start = Instant::now();
222        let ret = self.inner.get_opts(location, options).await?;
223        let elapsed = start.elapsed();
224
225        let (op, size) = if head {
226            (Operation::Head, None)
227        } else {
228            (
229                Operation::Get,
230                Some((ret.range.end - ret.range.start) as usize),
231            )
232        };
233
234        self.requests.lock().push(RequestDetails {
235            op,
236            path: location.clone(),
237            timestamp,
238            duration_nanos: Arc::new(AtomicU64::new(elapsed.as_nanos() as u64)),
239            size,
240            range,
241            extra_display: None,
242        });
243
244        Ok(ret)
245    }
246
247    fn instrumented_delete_stream(
248        &self,
249        locations: BoxStream<'static, Result<Path>>,
250    ) -> BoxStream<'static, Result<Path>> {
251        let requests_captured = Arc::clone(&self.requests);
252
253        let timestamp = Utc::now();
254        let start = Instant::now();
255        self.inner
256            .delete_stream(locations)
257            .and_then(move |location| {
258                let elapsed = start.elapsed();
259                requests_captured.lock().push(RequestDetails {
260                    op: Operation::Delete,
261                    path: location.clone(),
262                    timestamp,
263                    duration_nanos: Arc::new(AtomicU64::new(elapsed.as_nanos() as u64)),
264                    size: None,
265                    range: None,
266                    extra_display: None,
267                });
268                futures::future::ok(location)
269            })
270            .boxed()
271    }
272
273    fn instrumented_list(
274        &self,
275        prefix: Option<&Path>,
276    ) -> BoxStream<'static, Result<ObjectMeta>> {
277        let timestamp = Utc::now();
278        let inner_stream = self.inner.list(prefix);
279
280        let duration_nanos = Arc::new(AtomicU64::new(0));
281        self.requests.lock().push(RequestDetails {
282            op: Operation::List,
283            path: prefix.cloned().unwrap_or_else(|| Path::from("")),
284            timestamp,
285            duration_nanos: Arc::clone(&duration_nanos),
286            size: None,
287            range: None,
288            extra_display: None,
289        });
290
291        Box::pin(TimeToFirstItemStream::new(inner_stream, duration_nanos))
292    }
293
294    async fn instrumented_list_with_delimiter(
295        &self,
296        prefix: Option<&Path>,
297    ) -> Result<ListResult> {
298        let timestamp = Utc::now();
299        let start = Instant::now();
300        let ret = self.inner.list_with_delimiter(prefix).await?;
301        let elapsed = start.elapsed();
302
303        self.requests.lock().push(RequestDetails {
304            op: Operation::List,
305            path: prefix.cloned().unwrap_or_else(|| Path::from("")),
306            timestamp,
307            duration_nanos: Arc::new(AtomicU64::new(elapsed.as_nanos() as u64)),
308            size: None,
309            range: None,
310            extra_display: None,
311        });
312
313        Ok(ret)
314    }
315
316    async fn instrumented_copy(&self, from: &Path, to: &Path) -> Result<()> {
317        let timestamp = Utc::now();
318        let start = Instant::now();
319        self.inner.copy(from, to).await?;
320        let elapsed = start.elapsed();
321
322        self.requests.lock().push(RequestDetails {
323            op: Operation::Copy,
324            path: from.clone(),
325            timestamp,
326            duration_nanos: Arc::new(AtomicU64::new(elapsed.as_nanos() as u64)),
327            size: None,
328            range: None,
329            extra_display: Some(format!("copy_to: {to}")),
330        });
331
332        Ok(())
333    }
334
335    async fn instrumented_copy_if_not_exists(
336        &self,
337        from: &Path,
338        to: &Path,
339    ) -> Result<()> {
340        let timestamp = Utc::now();
341        let start = Instant::now();
342        self.inner.copy_if_not_exists(from, to).await?;
343        let elapsed = start.elapsed();
344
345        self.requests.lock().push(RequestDetails {
346            op: Operation::Copy,
347            path: from.clone(),
348            timestamp,
349            duration_nanos: Arc::new(AtomicU64::new(elapsed.as_nanos() as u64)),
350            size: None,
351            range: None,
352            extra_display: Some(format!("copy_to: {to}")),
353        });
354
355        Ok(())
356    }
357}
358
359impl fmt::Display for InstrumentedObjectStore {
360    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
361        let mode: InstrumentedObjectStoreMode =
362            self.instrument_mode.load(Ordering::Relaxed).into();
363        write!(
364            f,
365            "Instrumented Object Store: instrument_mode: {mode}, inner: {}",
366            self.inner
367        )
368    }
369}
370
371#[async_trait]
372impl ObjectStore for InstrumentedObjectStore {
373    async fn put_opts(
374        &self,
375        location: &Path,
376        payload: PutPayload,
377        opts: PutOptions,
378    ) -> Result<PutResult> {
379        if self.enabled() {
380            return self.instrumented_put_opts(location, payload, opts).await;
381        }
382
383        self.inner.put_opts(location, payload, opts).await
384    }
385
386    async fn put_multipart_opts(
387        &self,
388        location: &Path,
389        opts: PutMultipartOptions,
390    ) -> Result<Box<dyn MultipartUpload>> {
391        if self.enabled() {
392            return self.instrumented_put_multipart(location, opts).await;
393        }
394
395        self.inner.put_multipart_opts(location, opts).await
396    }
397
398    async fn get_opts(&self, location: &Path, options: GetOptions) -> Result<GetResult> {
399        if self.enabled() {
400            return self.instrumented_get_opts(location, options).await;
401        }
402
403        self.inner.get_opts(location, options).await
404    }
405
406    fn delete_stream(
407        &self,
408        locations: BoxStream<'static, Result<Path>>,
409    ) -> BoxStream<'static, Result<Path>> {
410        if self.enabled() {
411            return self.instrumented_delete_stream(locations);
412        }
413
414        self.inner.delete_stream(locations)
415    }
416
417    fn list(&self, prefix: Option<&Path>) -> BoxStream<'static, Result<ObjectMeta>> {
418        if self.enabled() {
419            return self.instrumented_list(prefix);
420        }
421
422        self.inner.list(prefix)
423    }
424
425    async fn list_with_delimiter(&self, prefix: Option<&Path>) -> Result<ListResult> {
426        if self.enabled() {
427            return self.instrumented_list_with_delimiter(prefix).await;
428        }
429
430        self.inner.list_with_delimiter(prefix).await
431    }
432
433    async fn copy_opts(
434        &self,
435        from: &Path,
436        to: &Path,
437        options: CopyOptions,
438    ) -> Result<()> {
439        if self.enabled() {
440            return match options.mode {
441                object_store::CopyMode::Create => {
442                    self.instrumented_copy_if_not_exists(from, to).await
443                }
444                object_store::CopyMode::Overwrite => {
445                    self.instrumented_copy(from, to).await
446                }
447            };
448        }
449
450        self.inner.copy_opts(from, to, options).await
451    }
452}
453
454/// Object store operation types tracked by [`InstrumentedObjectStore`]
455#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
456pub enum Operation {
457    Copy,
458    Delete,
459    Get,
460    Head,
461    List,
462    Put,
463}
464
465impl fmt::Display for Operation {
466    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
467        write!(f, "{self:?}")
468    }
469}
470
471/// Holds profiling details about individual requests made through an [`InstrumentedObjectStore`]
472pub struct RequestDetails {
473    op: Operation,
474    path: Path,
475    timestamp: chrono::DateTime<Utc>,
476    /// Duration stored as nanoseconds in an AtomicU64. 0 means not yet set.
477    duration_nanos: Arc<AtomicU64>,
478    size: Option<usize>,
479    range: Option<GetRange>,
480    extra_display: Option<String>,
481}
482
483impl fmt::Debug for RequestDetails {
484    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
485        f.debug_struct("RequestDetails")
486            .field("op", &self.op)
487            .field("path", &self.path)
488            .field("timestamp", &self.timestamp)
489            .field("duration", &self.duration())
490            .field("size", &self.size)
491            .field("range", &self.range)
492            .field("extra_display", &self.extra_display)
493            .finish()
494    }
495}
496
497impl RequestDetails {
498    fn duration(&self) -> Option<Duration> {
499        let nanos = self.duration_nanos.load(Ordering::Acquire);
500        if nanos == 0 {
501            None
502        } else {
503            Some(Duration::from_nanos(nanos))
504        }
505    }
506}
507
508impl fmt::Display for RequestDetails {
509    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
510        let mut output_parts = vec![format!(
511            "{} operation={:?}",
512            self.timestamp.to_rfc3339(),
513            self.op
514        )];
515
516        if let Some(d) = self.duration() {
517            output_parts.push(format!("duration={:.6}s", d.as_secs_f32()));
518        }
519        if let Some(s) = self.size {
520            output_parts.push(format!("size={s}"));
521        }
522        if let Some(r) = &self.range {
523            output_parts.push(format!("range: {r}"));
524        }
525        output_parts.push(format!("path={}", self.path));
526
527        if let Some(ed) = &self.extra_display {
528            output_parts.push(ed.clone());
529        }
530
531        write!(f, "{}", output_parts.join(" "))
532    }
533}
534
535/// Summary statistics for all requests recorded in an [`InstrumentedObjectStore`]
536#[derive(Default)]
537pub struct RequestSummaries {
538    summaries: Vec<RequestSummary>,
539}
540
541/// Display the summary as a table
542impl fmt::Display for RequestSummaries {
543    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
544        // Don't expect an error, but avoid panicking if it happens
545        match pretty_format_batches(&[self.to_batch()]) {
546            Err(e) => {
547                write!(f, "Error formatting summary: {e}")
548            }
549            Ok(displayable) => {
550                write!(f, "{displayable}")
551            }
552        }
553    }
554}
555
556impl RequestSummaries {
557    /// Summarizes input [`RequestDetails`]
558    pub fn new(requests: &[RequestDetails]) -> Self {
559        let mut summaries: HashMap<Operation, RequestSummary> = HashMap::new();
560        for rd in requests {
561            match summaries.get_mut(&rd.op) {
562                Some(rs) => rs.push(rd),
563                None => {
564                    let mut rs = RequestSummary::new(rd.op);
565                    rs.push(rd);
566                    summaries.insert(rd.op, rs);
567                }
568            }
569        }
570        // Convert to a Vec with consistent ordering
571        let mut summaries: Vec<RequestSummary> = summaries.into_values().collect();
572        summaries.sort_by_key(|s| s.operation);
573        Self { summaries }
574    }
575
576    /// Convert the summaries into a `RecordBatch` for display
577    ///
578    /// Results in a table like:
579    /// ```text
580    /// +-----------+----------+-----------+-----------+-----------+-----------+-----------+
581    /// | Operation | Metric   | min       | max       | avg       | sum       | count     |
582    /// +-----------+----------+-----------+-----------+-----------+-----------+-----------+
583    /// | Get       | duration | 5.000000s | 5.000000s | 5.000000s |           | 1         |
584    /// | Get       | size     | 100 B     | 100 B     | 100 B     | 100 B     | 1         |
585    /// +-----------+----------+-----------+-----------+-----------+-----------+-----------+
586    /// ```
587    pub fn to_batch(&self) -> RecordBatch {
588        let operations: StringArray = self
589            .iter()
590            .flat_map(|s| std::iter::repeat_n(Some(s.operation.to_string()), 2))
591            .collect();
592        let metrics: StringArray = self
593            .iter()
594            .flat_map(|_s| [Some("duration"), Some("size")])
595            .collect();
596        let mins: StringArray = self
597            .stats_iter()
598            .flat_map(|(duration_stats, size_stats)| {
599                let dur_min =
600                    duration_stats.map(|d| format!("{:.6}s", d.min.as_secs_f32()));
601                let size_min = size_stats.map(|s| format!("{} B", s.min));
602                [dur_min, size_min]
603            })
604            .collect();
605        let maxs: StringArray = self
606            .stats_iter()
607            .flat_map(|(duration_stats, size_stats)| {
608                let dur_max =
609                    duration_stats.map(|d| format!("{:.6}s", d.max.as_secs_f32()));
610                let size_max = size_stats.map(|s| format!("{} B", s.max));
611                [dur_max, size_max]
612            })
613            .collect();
614        let avgs: StringArray = self
615            .iter()
616            .flat_map(|s| {
617                let count = s.count as f32;
618                let duration_stats = s.duration_stats.as_ref();
619                let size_stats = s.size_stats.as_ref();
620                let dur_avg = duration_stats.map(|d| {
621                    let avg = d.sum.as_secs_f32() / count;
622                    format!("{avg:.6}s")
623                });
624                let size_avg = size_stats.map(|s| {
625                    let avg = s.sum as f32 / count;
626                    format!("{avg} B")
627                });
628                [dur_avg, size_avg]
629            })
630            .collect();
631        let sums: StringArray = self
632            .stats_iter()
633            .flat_map(|(duration_stats, size_stats)| {
634                // Omit a sum stat for duration in the initial
635                // implementation because it can be a bit misleading (at least
636                // at first glance). For example, particularly large queries the
637                // sum of the durations was often larger than the total time of
638                // the query itself, can be confusing without additional
639                // explanation (e.g. that the sum is of individual requests,
640                // which may be concurrent).
641                let dur_sum =
642                    duration_stats.map(|d| format!("{:.6}s", d.sum.as_secs_f32()));
643                let size_sum = size_stats.map(|s| format!("{} B", s.sum));
644                [dur_sum, size_sum]
645            })
646            .collect();
647        let counts: StringArray = self
648            .iter()
649            .flat_map(|s| {
650                let count = s.count.to_string();
651                [Some(count.clone()), Some(count)]
652            })
653            .collect();
654
655        RecordBatch::try_from_iter(vec![
656            ("Operation", Arc::new(operations) as ArrayRef),
657            ("Metric", Arc::new(metrics) as ArrayRef),
658            ("min", Arc::new(mins) as ArrayRef),
659            ("max", Arc::new(maxs) as ArrayRef),
660            ("avg", Arc::new(avgs) as ArrayRef),
661            ("sum", Arc::new(sums) as ArrayRef),
662            ("count", Arc::new(counts) as ArrayRef),
663        ])
664        .expect("Created the batch correctly")
665    }
666
667    /// Return an iterator over the summaries
668    fn iter(&self) -> impl Iterator<Item = &RequestSummary> {
669        self.summaries.iter()
670    }
671
672    /// Return an iterator over (duration_stats, size_stats) tuples
673    /// for each summary
674    fn stats_iter(
675        &self,
676    ) -> impl Iterator<Item = (Option<&Stats<Duration>>, Option<&Stats<usize>>)> {
677        self.summaries
678            .iter()
679            .map(|s| (s.duration_stats.as_ref(), s.size_stats.as_ref()))
680    }
681}
682
683/// Summary statistics for a particular type of [`Operation`] (e.g. `GET` or `PUT`)
684/// in an [`InstrumentedObjectStore`]'s [`RequestDetails`]
685pub struct RequestSummary {
686    operation: Operation,
687    count: usize,
688    duration_stats: Option<Stats<Duration>>,
689    size_stats: Option<Stats<usize>>,
690}
691
692impl RequestSummary {
693    fn new(operation: Operation) -> Self {
694        Self {
695            operation,
696            count: 0,
697            duration_stats: None,
698            size_stats: None,
699        }
700    }
701    fn push(&mut self, request: &RequestDetails) {
702        self.count += 1;
703        if let Some(dur) = request.duration() {
704            self.duration_stats.get_or_insert_default().push(dur)
705        }
706        if let Some(size) = request.size {
707            self.size_stats.get_or_insert_default().push(size)
708        }
709    }
710}
711
712struct Stats<T: Copy + Ord + AddAssign<T>> {
713    min: T,
714    max: T,
715    sum: T,
716}
717
718impl<T: Copy + Ord + AddAssign<T>> Stats<T> {
719    fn push(&mut self, val: T) {
720        self.min = cmp::min(val, self.min);
721        self.max = cmp::max(val, self.max);
722        self.sum += val;
723    }
724}
725
726impl Default for Stats<Duration> {
727    fn default() -> Self {
728        Self {
729            min: Duration::MAX,
730            max: Duration::ZERO,
731            sum: Duration::ZERO,
732        }
733    }
734}
735
736impl Default for Stats<usize> {
737    fn default() -> Self {
738        Self {
739            min: usize::MAX,
740            max: usize::MIN,
741            sum: 0,
742        }
743    }
744}
745
746/// Provides access to [`InstrumentedObjectStore`] instances that record requests for reporting
747#[derive(Debug)]
748pub struct InstrumentedObjectStoreRegistry {
749    inner: Arc<dyn ObjectStoreRegistry>,
750    instrument_mode: AtomicU8,
751    stores: RwLock<Vec<Arc<InstrumentedObjectStore>>>,
752}
753
754impl Default for InstrumentedObjectStoreRegistry {
755    fn default() -> Self {
756        Self::new()
757    }
758}
759
760impl InstrumentedObjectStoreRegistry {
761    /// Returns a new [`InstrumentedObjectStoreRegistry`] that wraps the provided
762    /// [`ObjectStoreRegistry`]
763    pub fn new() -> Self {
764        Self {
765            inner: Arc::new(DefaultObjectStoreRegistry::new()),
766            instrument_mode: AtomicU8::new(InstrumentedObjectStoreMode::default() as u8),
767            stores: RwLock::new(Vec::new()),
768        }
769    }
770
771    pub fn with_profile_mode(self, mode: InstrumentedObjectStoreMode) -> Self {
772        self.instrument_mode.store(mode as u8, Ordering::Relaxed);
773        self
774    }
775
776    /// Provides access to all of the [`InstrumentedObjectStore`]s managed by this
777    /// [`InstrumentedObjectStoreRegistry`]
778    pub fn stores(&self) -> Vec<Arc<InstrumentedObjectStore>> {
779        self.stores.read().clone()
780    }
781
782    /// Returns the current [`InstrumentedObjectStoreMode`] for this
783    /// [`InstrumentedObjectStoreRegistry`]
784    pub fn instrument_mode(&self) -> InstrumentedObjectStoreMode {
785        self.instrument_mode.load(Ordering::Relaxed).into()
786    }
787
788    /// Sets the [`InstrumentedObjectStoreMode`] for this [`InstrumentedObjectStoreRegistry`]
789    pub fn set_instrument_mode(&self, mode: InstrumentedObjectStoreMode) {
790        self.instrument_mode.store(mode as u8, Ordering::Relaxed);
791        for s in self.stores.read().iter() {
792            s.set_instrument_mode(mode)
793        }
794    }
795}
796
797impl ObjectStoreRegistry for InstrumentedObjectStoreRegistry {
798    fn register_store(
799        &self,
800        url: &Url,
801        store: Arc<dyn ObjectStore>,
802    ) -> Option<Arc<dyn ObjectStore>> {
803        let mode = self.instrument_mode.load(Ordering::Relaxed);
804        let instrumented =
805            Arc::new(InstrumentedObjectStore::new(store, AtomicU8::new(mode)));
806        self.stores.write().push(Arc::clone(&instrumented));
807        self.inner.register_store(url, instrumented)
808    }
809
810    fn deregister_store(
811        &self,
812        url: &Url,
813    ) -> datafusion::common::Result<Arc<dyn ObjectStore>> {
814        self.inner.deregister_store(url)
815    }
816
817    fn get_store(&self, url: &Url) -> datafusion::common::Result<Arc<dyn ObjectStore>> {
818        self.inner.get_store(url)
819    }
820}
821
822#[cfg(test)]
823mod tests {
824    use futures::StreamExt;
825    use object_store::WriteMultipart;
826
827    use super::*;
828    use insta::assert_snapshot;
829
830    #[test]
831    fn instrumented_mode() {
832        assert!(matches!(
833            InstrumentedObjectStoreMode::default(),
834            InstrumentedObjectStoreMode::Disabled
835        ));
836
837        assert!(matches!(
838            "dIsABleD".parse().unwrap(),
839            InstrumentedObjectStoreMode::Disabled
840        ));
841        assert!(matches!(
842            "SUmMaRy".parse().unwrap(),
843            InstrumentedObjectStoreMode::Summary
844        ));
845        assert!(matches!(
846            "TRaCe".parse().unwrap(),
847            InstrumentedObjectStoreMode::Trace
848        ));
849        assert!(
850            "does_not_exist"
851                .parse::<InstrumentedObjectStoreMode>()
852                .is_err()
853        );
854
855        assert!(matches!(0.into(), InstrumentedObjectStoreMode::Disabled));
856        assert!(matches!(1.into(), InstrumentedObjectStoreMode::Summary));
857        assert!(matches!(2.into(), InstrumentedObjectStoreMode::Trace));
858        assert!(matches!(3.into(), InstrumentedObjectStoreMode::Disabled));
859    }
860
861    #[test]
862    fn instrumented_registry() {
863        let mut reg = InstrumentedObjectStoreRegistry::new();
864        assert!(reg.stores().is_empty());
865        assert_eq!(
866            reg.instrument_mode(),
867            InstrumentedObjectStoreMode::default()
868        );
869
870        reg = reg.with_profile_mode(InstrumentedObjectStoreMode::Trace);
871        assert_eq!(reg.instrument_mode(), InstrumentedObjectStoreMode::Trace);
872
873        let store = object_store::memory::InMemory::new();
874        let url = "mem://test".parse().unwrap();
875        let registered = reg.register_store(&url, Arc::new(store));
876        assert!(registered.is_none());
877
878        let fetched = reg.get_store(&url);
879        assert!(fetched.is_ok());
880        assert_eq!(reg.stores().len(), 1);
881    }
882
883    // Returns an `InstrumentedObjectStore` with some data loaded for testing and the path to
884    // access the data
885    async fn setup_test_store() -> (InstrumentedObjectStore, Path) {
886        let store = Arc::new(object_store::memory::InMemory::new());
887        let mode = AtomicU8::new(InstrumentedObjectStoreMode::default() as u8);
888        let instrumented = InstrumentedObjectStore::new(store, mode);
889
890        // Load the test store with some data we can read
891        let path = Path::from("test/data");
892        let payload = PutPayload::from_static(b"test_data");
893        instrumented.put(&path, payload).await.unwrap();
894
895        (instrumented, path)
896    }
897
898    #[tokio::test]
899    async fn instrumented_store_get() {
900        let (instrumented, path) = setup_test_store().await;
901
902        // By default no requests should be instrumented/stored
903        assert!(instrumented.requests.lock().is_empty());
904        let _ = instrumented.get(&path).await.unwrap();
905        assert!(instrumented.requests.lock().is_empty());
906
907        instrumented.set_instrument_mode(InstrumentedObjectStoreMode::Trace);
908        assert!(instrumented.requests.lock().is_empty());
909        let _ = instrumented.get(&path).await.unwrap();
910        assert_eq!(instrumented.requests.lock().len(), 1);
911
912        let mut requests = instrumented.take_requests();
913        assert_eq!(requests.len(), 1);
914        assert!(instrumented.requests.lock().is_empty());
915
916        let request = requests.pop().unwrap();
917        assert_eq!(request.op, Operation::Get);
918        assert_eq!(request.path, path);
919        assert!(request.duration().is_some());
920        assert_eq!(request.size, Some(9));
921        assert_eq!(request.range, None);
922        assert!(request.extra_display.is_none());
923    }
924
925    #[tokio::test]
926    async fn instrumented_store_delete() {
927        let (instrumented, path) = setup_test_store().await;
928
929        // By default no requests should be instrumented/stored
930        assert!(instrumented.requests.lock().is_empty());
931        instrumented.delete(&path).await.unwrap();
932        assert!(instrumented.requests.lock().is_empty());
933
934        // We need a new store so we have data to delete again
935        let (instrumented, path) = setup_test_store().await;
936        instrumented.set_instrument_mode(InstrumentedObjectStoreMode::Trace);
937        assert!(instrumented.requests.lock().is_empty());
938        instrumented.delete(&path).await.unwrap();
939        assert_eq!(instrumented.requests.lock().len(), 1);
940
941        let mut requests = instrumented.take_requests();
942        assert_eq!(requests.len(), 1);
943        assert!(instrumented.requests.lock().is_empty());
944
945        let request = requests.pop().unwrap();
946        assert_eq!(request.op, Operation::Delete);
947        assert_eq!(request.path, path);
948        assert!(request.duration().is_some());
949        assert!(request.size.is_none());
950        assert!(request.range.is_none());
951        assert!(request.extra_display.is_none());
952    }
953
954    #[tokio::test]
955    async fn instrumented_store_list() {
956        let (instrumented, path) = setup_test_store().await;
957
958        // By default no requests should be instrumented/stored
959        assert!(instrumented.requests.lock().is_empty());
960        let _ = instrumented.list(Some(&path));
961        assert!(instrumented.requests.lock().is_empty());
962
963        instrumented.set_instrument_mode(InstrumentedObjectStoreMode::Trace);
964        assert!(instrumented.requests.lock().is_empty());
965        let mut stream = instrumented.list(Some(&path));
966        // Sleep between stream creation and first poll to verify the timer
967        // starts on first poll, not at stream creation.
968        let delay = Duration::from_millis(50);
969        tokio::time::sleep(delay).await;
970        let _ = stream.next().await;
971        assert_eq!(instrumented.requests.lock().len(), 1);
972
973        let request = instrumented.take_requests().pop().unwrap();
974        assert_eq!(request.op, Operation::List);
975        assert_eq!(request.path, path);
976        let duration = request
977            .duration()
978            .expect("duration should be set after consuming stream");
979        assert!(
980            duration < delay,
981            "duration {duration:?} should exclude the {delay:?} sleep before first poll"
982        );
983        assert!(request.size.is_none());
984        assert!(request.range.is_none());
985        assert!(request.extra_display.is_none());
986    }
987
988    #[tokio::test]
989    async fn time_to_first_item_stream_captures_inner_latency() {
990        let inner_delay = Duration::from_millis(50);
991        let inner_stream = futures::stream::once(async move {
992            tokio::time::sleep(inner_delay).await;
993            Ok(ObjectMeta {
994                location: Path::from("test"),
995                last_modified: Utc::now(),
996                size: 0,
997                e_tag: None,
998                version: None,
999            })
1000        })
1001        .boxed();
1002
1003        let duration_nanos = Arc::new(AtomicU64::new(0));
1004        let mut stream = Box::pin(TimeToFirstItemStream::new(
1005            inner_stream,
1006            Arc::clone(&duration_nanos),
1007        ));
1008        let _ = stream.next().await;
1009
1010        let recorded = Duration::from_nanos(duration_nanos.load(Ordering::Acquire));
1011        assert!(
1012            recorded >= inner_delay,
1013            "recorded duration {recorded:?} should be >= inner stream delay {inner_delay:?}"
1014        );
1015    }
1016
1017    #[tokio::test]
1018    async fn instrumented_store_list_with_delimiter() {
1019        let (instrumented, path) = setup_test_store().await;
1020
1021        // By default no requests should be instrumented/stored
1022        assert!(instrumented.requests.lock().is_empty());
1023        let _ = instrumented.list_with_delimiter(Some(&path)).await.unwrap();
1024        assert!(instrumented.requests.lock().is_empty());
1025
1026        instrumented.set_instrument_mode(InstrumentedObjectStoreMode::Trace);
1027        assert!(instrumented.requests.lock().is_empty());
1028        let _ = instrumented.list_with_delimiter(Some(&path)).await.unwrap();
1029        assert_eq!(instrumented.requests.lock().len(), 1);
1030
1031        let request = instrumented.take_requests().pop().unwrap();
1032        assert_eq!(request.op, Operation::List);
1033        assert_eq!(request.path, path);
1034        assert!(request.duration().is_some());
1035        assert!(request.size.is_none());
1036        assert!(request.range.is_none());
1037        assert!(request.extra_display.is_none());
1038    }
1039
1040    #[tokio::test]
1041    async fn instrumented_store_put_opts() {
1042        // The `setup_test_store()` method comes with data already `put` into it, so we'll setup
1043        // manually for this test
1044        let store = Arc::new(object_store::memory::InMemory::new());
1045        let mode = AtomicU8::new(InstrumentedObjectStoreMode::default() as u8);
1046        let instrumented = InstrumentedObjectStore::new(store, mode);
1047
1048        let path = Path::from("test/data");
1049        let payload = PutPayload::from_static(b"test_data");
1050        let size = payload.content_length();
1051
1052        // By default no requests should be instrumented/stored
1053        assert!(instrumented.requests.lock().is_empty());
1054        instrumented.put(&path, payload.clone()).await.unwrap();
1055        assert!(instrumented.requests.lock().is_empty());
1056
1057        instrumented.set_instrument_mode(InstrumentedObjectStoreMode::Trace);
1058        assert!(instrumented.requests.lock().is_empty());
1059        instrumented.put(&path, payload).await.unwrap();
1060        assert_eq!(instrumented.requests.lock().len(), 1);
1061
1062        let request = instrumented.take_requests().pop().unwrap();
1063        assert_eq!(request.op, Operation::Put);
1064        assert_eq!(request.path, path);
1065        assert!(request.duration().is_some());
1066        assert_eq!(request.size.unwrap(), size);
1067        assert!(request.range.is_none());
1068        assert!(request.extra_display.is_none());
1069    }
1070
1071    #[tokio::test]
1072    async fn instrumented_store_put_multipart() {
1073        // The `setup_test_store()` method comes with data already `put` into it, so we'll setup
1074        // manually for this test
1075        let store = Arc::new(object_store::memory::InMemory::new());
1076        let mode = AtomicU8::new(InstrumentedObjectStoreMode::default() as u8);
1077        let instrumented = InstrumentedObjectStore::new(store, mode);
1078
1079        let path = Path::from("test/data");
1080
1081        // By default no requests should be instrumented/stored
1082        assert!(instrumented.requests.lock().is_empty());
1083        let mp = instrumented.put_multipart(&path).await.unwrap();
1084        let mut write = WriteMultipart::new(mp);
1085        write.write(b"test_data");
1086        write.finish().await.unwrap();
1087        assert!(instrumented.requests.lock().is_empty());
1088
1089        instrumented.set_instrument_mode(InstrumentedObjectStoreMode::Trace);
1090        assert!(instrumented.requests.lock().is_empty());
1091        let mp = instrumented.put_multipart(&path).await.unwrap();
1092        let mut write = WriteMultipart::new(mp);
1093        write.write(b"test_data");
1094        write.finish().await.unwrap();
1095        assert_eq!(instrumented.requests.lock().len(), 1);
1096
1097        let request = instrumented.take_requests().pop().unwrap();
1098        assert_eq!(request.op, Operation::Put);
1099        assert_eq!(request.path, path);
1100        assert!(request.duration().is_some());
1101        assert!(request.size.is_none());
1102        assert!(request.range.is_none());
1103        assert!(request.extra_display.is_none());
1104    }
1105
1106    #[tokio::test]
1107    async fn instrumented_store_copy() {
1108        let (instrumented, path) = setup_test_store().await;
1109        let copy_to = Path::from("test/copied");
1110
1111        // By default no requests should be instrumented/stored
1112        assert!(instrumented.requests.lock().is_empty());
1113        instrumented.copy(&path, &copy_to).await.unwrap();
1114        assert!(instrumented.requests.lock().is_empty());
1115
1116        instrumented.set_instrument_mode(InstrumentedObjectStoreMode::Trace);
1117        assert!(instrumented.requests.lock().is_empty());
1118        instrumented.copy(&path, &copy_to).await.unwrap();
1119        assert_eq!(instrumented.requests.lock().len(), 1);
1120
1121        let mut requests = instrumented.take_requests();
1122        assert_eq!(requests.len(), 1);
1123        assert!(instrumented.requests.lock().is_empty());
1124
1125        let request = requests.pop().unwrap();
1126        assert_eq!(request.op, Operation::Copy);
1127        assert_eq!(request.path, path);
1128        assert!(request.duration().is_some());
1129        assert!(request.size.is_none());
1130        assert!(request.range.is_none());
1131        assert_eq!(
1132            request.extra_display.unwrap(),
1133            format!("copy_to: {copy_to}")
1134        );
1135    }
1136
1137    #[tokio::test]
1138    async fn instrumented_store_copy_if_not_exists() {
1139        let (instrumented, path) = setup_test_store().await;
1140        let mut copy_to = Path::from("test/copied");
1141
1142        // By default no requests should be instrumented/stored
1143        assert!(instrumented.requests.lock().is_empty());
1144        instrumented
1145            .copy_if_not_exists(&path, &copy_to)
1146            .await
1147            .unwrap();
1148        assert!(instrumented.requests.lock().is_empty());
1149
1150        // Use a new destination since the previous one already exists
1151        copy_to = Path::from("test/copied_again");
1152        instrumented.set_instrument_mode(InstrumentedObjectStoreMode::Trace);
1153        assert!(instrumented.requests.lock().is_empty());
1154        instrumented
1155            .copy_if_not_exists(&path, &copy_to)
1156            .await
1157            .unwrap();
1158        assert_eq!(instrumented.requests.lock().len(), 1);
1159
1160        let mut requests = instrumented.take_requests();
1161        assert_eq!(requests.len(), 1);
1162        assert!(instrumented.requests.lock().is_empty());
1163
1164        let request = requests.pop().unwrap();
1165        assert_eq!(request.op, Operation::Copy);
1166        assert_eq!(request.path, path);
1167        assert!(request.duration().is_some());
1168        assert!(request.size.is_none());
1169        assert!(request.range.is_none());
1170        assert_eq!(
1171            request.extra_display.unwrap(),
1172            format!("copy_to: {copy_to}")
1173        );
1174    }
1175
1176    #[tokio::test]
1177    async fn instrumented_store_head() {
1178        let (instrumented, path) = setup_test_store().await;
1179
1180        // By default no requests should be instrumented/stored
1181        assert!(instrumented.requests.lock().is_empty());
1182        let _ = instrumented.head(&path).await.unwrap();
1183        assert!(instrumented.requests.lock().is_empty());
1184
1185        instrumented.set_instrument_mode(InstrumentedObjectStoreMode::Trace);
1186        assert!(instrumented.requests.lock().is_empty());
1187        let _ = instrumented.head(&path).await.unwrap();
1188        assert_eq!(instrumented.requests.lock().len(), 1);
1189
1190        let mut requests = instrumented.take_requests();
1191        assert_eq!(requests.len(), 1);
1192        assert!(instrumented.requests.lock().is_empty());
1193
1194        let request = requests.pop().unwrap();
1195        assert_eq!(request.op, Operation::Head);
1196        assert_eq!(request.path, path);
1197        assert!(request.duration().is_some());
1198        assert!(request.size.is_none());
1199        assert!(request.range.is_none());
1200        assert!(request.extra_display.is_none());
1201    }
1202
1203    #[test]
1204    fn request_details() {
1205        let rd = RequestDetails {
1206            op: Operation::Get,
1207            path: Path::from("test"),
1208            timestamp: chrono::DateTime::from_timestamp(0, 0).unwrap(),
1209            duration_nanos: Arc::new(AtomicU64::new(
1210                Duration::new(5, 0).as_nanos() as u64
1211            )),
1212            size: Some(10),
1213            range: Some((..10).into()),
1214            extra_display: Some(String::from("extra info")),
1215        };
1216
1217        assert_eq!(
1218            format!("{rd}"),
1219            "1970-01-01T00:00:00+00:00 operation=Get duration=5.000000s size=10 range: bytes=0-9 path=test extra info"
1220        );
1221    }
1222
1223    #[test]
1224    fn request_summary() {
1225        // Test empty request list
1226        let mut requests = Vec::new();
1227        assert_snapshot!(RequestSummaries::new(&requests), @r"
1228        +-----------+--------+-----+-----+-----+-----+-------+
1229        | Operation | Metric | min | max | avg | sum | count |
1230        +-----------+--------+-----+-----+-----+-----+-------+
1231        +-----------+--------+-----+-----+-----+-----+-------+
1232        ");
1233
1234        requests.push(RequestDetails {
1235            op: Operation::Get,
1236            path: Path::from("test1"),
1237            timestamp: chrono::DateTime::from_timestamp(0, 0).unwrap(),
1238            duration_nanos: Arc::new(AtomicU64::new(
1239                Duration::from_secs(5).as_nanos() as u64
1240            )),
1241            size: Some(100),
1242            range: None,
1243            extra_display: None,
1244        });
1245
1246        assert_snapshot!(RequestSummaries::new(&requests), @r"
1247        +-----------+----------+-----------+-----------+-----------+-----------+-------+
1248        | Operation | Metric   | min       | max       | avg       | sum       | count |
1249        +-----------+----------+-----------+-----------+-----------+-----------+-------+
1250        | Get       | duration | 5.000000s | 5.000000s | 5.000000s | 5.000000s | 1     |
1251        | Get       | size     | 100 B     | 100 B     | 100 B     | 100 B     | 1     |
1252        +-----------+----------+-----------+-----------+-----------+-----------+-------+
1253        ");
1254
1255        // Add more Get requests to test aggregation
1256        requests.push(RequestDetails {
1257            op: Operation::Get,
1258            path: Path::from("test2"),
1259            timestamp: chrono::DateTime::from_timestamp(1, 0).unwrap(),
1260            duration_nanos: Arc::new(AtomicU64::new(
1261                Duration::from_secs(8).as_nanos() as u64
1262            )),
1263            size: Some(150),
1264            range: None,
1265            extra_display: None,
1266        });
1267        requests.push(RequestDetails {
1268            op: Operation::Get,
1269            path: Path::from("test3"),
1270            timestamp: chrono::DateTime::from_timestamp(2, 0).unwrap(),
1271            duration_nanos: Arc::new(AtomicU64::new(
1272                Duration::from_secs(2).as_nanos() as u64
1273            )),
1274            size: Some(50),
1275            range: None,
1276            extra_display: None,
1277        });
1278        assert_snapshot!(RequestSummaries::new(&requests), @r"
1279        +-----------+----------+-----------+-----------+-----------+------------+-------+
1280        | Operation | Metric   | min       | max       | avg       | sum        | count |
1281        +-----------+----------+-----------+-----------+-----------+------------+-------+
1282        | Get       | duration | 2.000000s | 8.000000s | 5.000000s | 15.000000s | 3     |
1283        | Get       | size     | 50 B      | 150 B     | 100 B     | 300 B      | 3     |
1284        +-----------+----------+-----------+-----------+-----------+------------+-------+
1285        ");
1286
1287        // Add Put requests to test grouping
1288        requests.push(RequestDetails {
1289            op: Operation::Put,
1290            path: Path::from("test4"),
1291            timestamp: chrono::DateTime::from_timestamp(3, 0).unwrap(),
1292            duration_nanos: Arc::new(AtomicU64::new(
1293                Duration::from_millis(200).as_nanos() as u64,
1294            )),
1295            size: Some(75),
1296            range: None,
1297            extra_display: None,
1298        });
1299
1300        assert_snapshot!(RequestSummaries::new(&requests), @r"
1301        +-----------+----------+-----------+-----------+-----------+------------+-------+
1302        | Operation | Metric   | min       | max       | avg       | sum        | count |
1303        +-----------+----------+-----------+-----------+-----------+------------+-------+
1304        | Get       | duration | 2.000000s | 8.000000s | 5.000000s | 15.000000s | 3     |
1305        | Get       | size     | 50 B      | 150 B     | 100 B     | 300 B      | 3     |
1306        | Put       | duration | 0.200000s | 0.200000s | 0.200000s | 0.200000s  | 1     |
1307        | Put       | size     | 75 B      | 75 B      | 75 B      | 75 B       | 1     |
1308        +-----------+----------+-----------+-----------+-----------+------------+-------+
1309        ");
1310    }
1311
1312    #[test]
1313    fn request_summary_only_duration() {
1314        // Test request with only duration (no size)
1315        let only_duration = vec![RequestDetails {
1316            op: Operation::Get,
1317            path: Path::from("test1"),
1318            timestamp: chrono::DateTime::from_timestamp(0, 0).unwrap(),
1319            duration_nanos: Arc::new(AtomicU64::new(
1320                Duration::from_secs(3).as_nanos() as u64
1321            )),
1322            size: None,
1323            range: None,
1324            extra_display: None,
1325        }];
1326        assert_snapshot!(RequestSummaries::new(&only_duration), @r"
1327        +-----------+----------+-----------+-----------+-----------+-----------+-------+
1328        | Operation | Metric   | min       | max       | avg       | sum       | count |
1329        +-----------+----------+-----------+-----------+-----------+-----------+-------+
1330        | Get       | duration | 3.000000s | 3.000000s | 3.000000s | 3.000000s | 1     |
1331        | Get       | size     |           |           |           |           | 1     |
1332        +-----------+----------+-----------+-----------+-----------+-----------+-------+
1333        ");
1334    }
1335
1336    #[test]
1337    fn request_summary_only_size() {
1338        // Test request with only size (no duration)
1339        let only_size = vec![RequestDetails {
1340            op: Operation::Get,
1341            path: Path::from("test1"),
1342            timestamp: chrono::DateTime::from_timestamp(0, 0).unwrap(),
1343            duration_nanos: Arc::new(AtomicU64::new(0)),
1344            size: Some(200),
1345            range: None,
1346            extra_display: None,
1347        }];
1348        assert_snapshot!(RequestSummaries::new(&only_size), @r"
1349        +-----------+----------+-------+-------+-------+-------+-------+
1350        | Operation | Metric   | min   | max   | avg   | sum   | count |
1351        +-----------+----------+-------+-------+-------+-------+-------+
1352        | Get       | duration |       |       |       |       | 1     |
1353        | Get       | size     | 200 B | 200 B | 200 B | 200 B | 1     |
1354        +-----------+----------+-------+-------+-------+-------+-------+
1355        ");
1356    }
1357
1358    #[test]
1359    fn request_summary_neither_duration_or_size() {
1360        // Test request with neither duration nor size
1361        let no_stats = vec![RequestDetails {
1362            op: Operation::Get,
1363            path: Path::from("test1"),
1364            timestamp: chrono::DateTime::from_timestamp(0, 0).unwrap(),
1365            duration_nanos: Arc::new(AtomicU64::new(0)),
1366            size: None,
1367            range: None,
1368            extra_display: None,
1369        }];
1370        assert_snapshot!(RequestSummaries::new(&no_stats), @r"
1371        +-----------+----------+-----+-----+-----+-----+-------+
1372        | Operation | Metric   | min | max | avg | sum | count |
1373        +-----------+----------+-----+-----+-----+-----+-------+
1374        | Get       | duration |     |     |     |     | 1     |
1375        | Get       | size     |     |     |     |     | 1     |
1376        +-----------+----------+-----+-----+-----+-----+-------+
1377        ");
1378    }
1379}