-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathlib.rs
2413 lines (2144 loc) · 74.9 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! A metric instrumentation wrapper over [`ObjectStore`] implementations.
#![allow(clippy::clone_on_ref_ptr)]
use multipart_upload_metrics::MultipartUploadWrapper;
use object_store::{
GetOptions, GetResultPayload, MultipartUpload, PutMultipartOpts, PutOptions, PutPayload,
PutResult,
};
// Workaround for "unused crate" lint false positives.
use workspace_hack as _;
use std::sync::Arc;
use std::{borrow::Cow, ops::Range};
use std::{
marker::PhantomData,
pin::Pin,
task::{Context, Poll},
};
use async_trait::async_trait;
use bytes::Bytes;
use futures::{stream::BoxStream, Stream, StreamExt};
use iox_time::{Time, TimeProvider};
use metric::{DurationHistogram, Metric, U64Counter};
use pin_project::{pin_project, pinned_drop};
use object_store::{path::Path, GetResult, ListResult, ObjectMeta, ObjectStore, Result};
use tokio::{sync::Mutex, task::JoinSet};
#[cfg(test)]
mod dummy;
mod multipart_upload_metrics;
/// A typed name of a scope / type to report the metrics under.
#[derive(Debug, Clone)]
pub struct StoreType(Cow<'static, str>);
impl<T> From<T> for StoreType
where
T: Into<Cow<'static, str>>,
{
fn from(v: T) -> Self {
Self(v.into())
}
}
#[derive(Debug, Clone)]
struct Metrics {
success_duration: DurationHistogram,
error_duration: DurationHistogram,
}
impl Metrics {
fn new(registry: &metric::Registry, store_type: &StoreType, op: &'static str) -> Self {
// Call durations broken down by op & result
let duration: Metric<DurationHistogram> = registry.register_metric(
"object_store_op_duration",
"object store operation duration",
);
Self {
success_duration: duration.recorder([
("store_type", store_type.0.clone()),
("op", Cow::Borrowed(op)),
("result", Cow::Borrowed("success")),
]),
error_duration: duration.recorder([
("store_type", store_type.0.clone()),
("op", Cow::Borrowed(op)),
("result", Cow::Borrowed("error")),
]),
}
}
fn record(&self, t_begin: Time, t_end: Time, success: bool) {
// Avoid exploding if time goes backwards - simply drop the measurement
// if it happens.
let Some(delta) = t_end.checked_duration_since(t_begin) else {
return;
};
if success {
self.success_duration.record(delta);
} else {
self.error_duration.record(delta);
}
}
}
#[derive(Debug, Clone)]
struct MetricsWithBytes {
inner: Metrics,
success_bytes: U64Counter,
error_bytes: U64Counter,
}
impl MetricsWithBytes {
fn new(registry: &metric::Registry, store_type: &StoreType, op: &'static str) -> Self {
// Byte counts up/down
let bytes = registry.register_metric::<U64Counter>(
"object_store_transfer_bytes",
"cumulative count of file content bytes transferred to/from the object store",
);
Self {
inner: Metrics::new(registry, store_type, op),
success_bytes: bytes.recorder([
("store_type", store_type.0.clone()),
("op", Cow::Borrowed(op)),
("result", Cow::Borrowed("success")),
]),
error_bytes: bytes.recorder([
("store_type", store_type.0.clone()),
("op", Cow::Borrowed(op)),
("result", Cow::Borrowed("error")),
]),
}
}
fn record_bytes_only(&self, success: bool, bytes: u64) {
if success {
self.success_bytes.inc(bytes);
} else {
self.error_bytes.inc(bytes);
}
}
fn record(&self, t_begin: Time, t_end: Time, success: bool, bytes: Option<u64>) {
if let Some(bytes) = bytes {
self.record_bytes_only(success, bytes);
}
self.inner.record(t_begin, t_end, success);
}
}
#[derive(Debug, Clone)]
struct MetricsWithBytesAndTtfb {
inner: MetricsWithBytes,
success_duration: DurationHistogram,
error_duration: DurationHistogram,
}
impl MetricsWithBytesAndTtfb {
fn new(registry: &metric::Registry, store_type: &StoreType, op: &'static str) -> Self {
// Call durations broken down by op & result
let duration: Metric<DurationHistogram> = registry.register_metric(
"object_store_op_ttfb",
"Time to first byte for object store operation",
);
Self {
inner: MetricsWithBytes::new(registry, store_type, op),
success_duration: duration.recorder([
("store_type", store_type.0.clone()),
("op", Cow::Borrowed(op)),
("result", Cow::Borrowed("success")),
]),
error_duration: duration.recorder([
("store_type", store_type.0.clone()),
("op", Cow::Borrowed(op)),
("result", Cow::Borrowed("error")),
]),
}
}
fn record_bytes_only(&self, success: bool, bytes: u64) {
self.inner.record_bytes_only(success, bytes);
}
fn record(
&self,
t_begin: Time,
t_first_byte: Time,
t_end: Time,
success: bool,
bytes: Option<u64>,
) {
if let Some(delta) = t_first_byte.checked_duration_since(t_begin) {
if success {
self.success_duration.record(delta);
} else {
self.error_duration.record(delta);
}
}
self.inner.record(t_begin, t_end, success, bytes);
}
}
#[derive(Debug, Clone)]
struct MetricsWithCount {
inner: Metrics,
success_count: U64Counter,
error_count: U64Counter,
}
impl MetricsWithCount {
fn new(registry: &metric::Registry, store_type: &StoreType, op: &'static str) -> Self {
let count = registry.register_metric::<U64Counter>(
"object_store_transfer_objects",
"cumulative count of objects transferred to/from the object store",
);
Self {
inner: Metrics::new(registry, store_type, op),
success_count: count.recorder([
("store_type", store_type.0.clone()),
("op", Cow::Borrowed(op)),
("result", Cow::Borrowed("success")),
]),
error_count: count.recorder([
("store_type", store_type.0.clone()),
("op", Cow::Borrowed(op)),
("result", Cow::Borrowed("error")),
]),
}
}
fn record_count_only(&self, success: bool, count: u64) {
if success {
self.success_count.inc(count);
} else {
self.error_count.inc(count);
}
}
fn record(&self, t_begin: Time, t_end: Time, success: bool, count: Option<u64>) {
if let Some(count) = count {
self.record_count_only(success, count);
}
self.inner.record(t_begin, t_end, success);
}
}
/// An instrumentation decorator, wrapping an underlying [`ObjectStore`]
/// implementation and recording bytes transferred and call latency.
///
/// # Stream Duration
///
/// The [`ObjectStore::get()`] call can return a [`Stream`] which is polled
/// by the caller and may yield chunks of a file over a series of polls (as
/// opposed to all of the file data in one go). Because the caller drives the
/// polling and therefore fetching of data from the object store over the
/// lifetime of the [`Stream`], the duration of a [`ObjectStore::get()`]
/// request is measured to be the wall clock difference between the moment the
/// caller executes the [`ObjectStore::get()`] call, up until the last chunk
/// of data is yielded to the caller.
///
/// This means the duration metrics measuring consumption of returned streams
/// are recording the rate at which the application reads the data, as opposed
/// to the duration of time taken to fetch that data.
///
/// # Stream Errors
///
/// The [`ObjectStore::get()`] method can return a [`Stream`] of [`Result`]
/// instances, and returning an error when polled is not necessarily a terminal
/// state. The metric recorder allows for a caller to observe a transient error
/// and subsequently go on to complete reading the stream, recording this read
/// in the "success" histogram.
///
/// If a stream is not polled again after observing an error, the operation is
/// recorded in the "error" histogram.
///
/// A stream can return an arbitrary sequence of success and error states before
/// terminating, with the last observed poll result that yields a [`Result`]
/// dictating which histogram the operation is recorded in.
///
/// # Bytes Transferred
///
/// The metric recording bytes transferred accounts for only object data, and
/// not object metadata (such as that returned by list methods).
///
/// The total data transferred will be greater than the metric value due to
/// metadata queries, read errors, etc. The metric tracks the amount of object
/// data successfully yielded to the caller.
///
/// # Backwards Clocks
///
/// If the system clock is observed as moving backwards in time, call durations
/// are not recorded. The bytes transferred metric is not affected.
#[derive(Debug)]
pub struct ObjectStoreMetrics {
inner: Arc<dyn ObjectStore>,
time_provider: Arc<dyn TimeProvider>,
put: MetricsWithBytes,
put_multipart: Arc<MetricsWithBytes>,
inprogress_multipart: Mutex<JoinSet<()>>,
get: MetricsWithBytesAndTtfb,
get_range: MetricsWithBytes,
get_ranges: MetricsWithBytes,
head: Metrics,
delete: Metrics,
delete_stream: MetricsWithCount,
list: MetricsWithCount,
list_with_offset: MetricsWithCount,
list_with_delimiter: MetricsWithCount,
copy: Metrics,
rename: Metrics,
copy_if_not_exists: Metrics,
rename_if_not_exists: Metrics,
}
impl ObjectStoreMetrics {
/// Instrument `T`, pushing to `registry`.
pub fn new(
inner: Arc<dyn ObjectStore>,
time_provider: Arc<dyn TimeProvider>,
store_type: impl Into<StoreType>,
registry: &metric::Registry,
) -> Self {
let store_type = store_type.into();
Self {
inner,
time_provider,
put: MetricsWithBytes::new(registry, &store_type, "put"),
put_multipart: Arc::new(MetricsWithBytes::new(
registry,
&store_type,
"put_multipart",
)),
inprogress_multipart: Default::default(),
get: MetricsWithBytesAndTtfb::new(registry, &store_type, "get"),
get_range: MetricsWithBytes::new(registry, &store_type, "get_range"),
get_ranges: MetricsWithBytes::new(registry, &store_type, "get_ranges"),
head: Metrics::new(registry, &store_type, "head"),
delete: Metrics::new(registry, &store_type, "delete"),
delete_stream: MetricsWithCount::new(registry, &store_type, "delete_stream"),
list: MetricsWithCount::new(registry, &store_type, "list"),
list_with_offset: MetricsWithCount::new(registry, &store_type, "list_with_offset"),
list_with_delimiter: MetricsWithCount::new(
registry,
&store_type,
"list_with_delimiter",
),
copy: Metrics::new(registry, &store_type, "copy"),
rename: Metrics::new(registry, &store_type, "rename"),
copy_if_not_exists: Metrics::new(registry, &store_type, "copy_if_not_exists"),
rename_if_not_exists: Metrics::new(registry, &store_type, "rename_if_not_exists"),
}
}
#[cfg(test)]
async fn close(&self) {
let _ = self.inprogress_multipart.lock().await.join_next().await;
}
}
impl std::fmt::Display for ObjectStoreMetrics {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "ObjectStoreMetrics({})", self.inner)
}
}
#[async_trait]
impl ObjectStore for ObjectStoreMetrics {
async fn put_opts(
&self,
location: &Path,
bytes: PutPayload,
opts: PutOptions,
) -> Result<PutResult> {
let t = self.time_provider.now();
let size = bytes.content_length();
let res = self.inner.put_opts(location, bytes, opts).await;
self.put
.record(t, self.time_provider.now(), res.is_ok(), Some(size as _));
res
}
async fn put_multipart_opts(
&self,
location: &Path,
_opts: PutMultipartOpts,
) -> Result<Box<dyn MultipartUpload>> {
let t = self.time_provider.now();
let inner = self.inner.put_multipart(location).await?;
let (tx, rx) = futures::channel::oneshot::channel();
let reporter = Arc::clone(&self.put_multipart);
self.inprogress_multipart.lock().await.spawn(async move {
if let Ok((res, bytes, t_end)) = rx.await {
reporter.record(t, t_end, res, bytes);
}
});
let multipart_upload =
MultipartUploadWrapper::new(inner, Arc::clone(&self.time_provider), tx);
Ok(Box::new(multipart_upload))
}
async fn get_opts(&self, location: &Path, options: GetOptions) -> Result<GetResult> {
let started_at = self.time_provider.now();
let res = self.inner.get_opts(location, options).await;
match res {
Ok(mut res) => {
res.payload = match res.payload {
GetResultPayload::File(file, path) => {
let file = tokio::fs::File::from_std(file);
let size = file.metadata().await.ok().map(|m| m.len());
let file = file.into_std().await;
let end = self.time_provider.now();
self.get.record(
started_at,
// first byte wasn't really measured, so take "end" instead
end, end, true, size,
);
GetResultPayload::File(file, path)
}
GetResultPayload::Stream(s) => {
// Wrap the object store data stream in a decorator to track the
// yielded data / wall clock, inclusive of the inner call above.
GetResultPayload::Stream(Box::pin(Box::new(
StreamMetricRecorder::new(
s,
started_at,
BytesStreamDelegate::new(self.get.clone()),
Arc::clone(&self.time_provider),
)
.fuse(),
)))
}
};
Ok(res)
}
Err(e) => {
let end = self.time_provider.now();
self.get.record(started_at, end, end, false, None);
Err(e)
}
}
}
async fn get_range(&self, location: &Path, range: Range<usize>) -> Result<Bytes> {
let t = self.time_provider.now();
let res = self.inner.get_range(location, range).await;
self.get_range.record(
t,
self.time_provider.now(),
res.is_ok(),
res.as_ref().ok().map(|b| b.len() as _),
);
res
}
async fn get_ranges(&self, location: &Path, ranges: &[Range<usize>]) -> Result<Vec<Bytes>> {
let t = self.time_provider.now();
let res = self.inner.get_ranges(location, ranges).await;
self.get_ranges.record(
t,
self.time_provider.now(),
res.is_ok(),
res.as_ref()
.ok()
.map(|b| b.iter().map(|b| b.len() as u64).sum()),
);
res
}
async fn head(&self, location: &Path) -> Result<ObjectMeta> {
let t = self.time_provider.now();
let res = self.inner.head(location).await;
self.head.record(t, self.time_provider.now(), res.is_ok());
res
}
async fn delete(&self, location: &Path) -> Result<()> {
let t = self.time_provider.now();
let res = self.inner.delete(location).await;
self.delete.record(t, self.time_provider.now(), res.is_ok());
res
}
fn delete_stream<'a>(
&'a self,
locations: BoxStream<'a, Result<Path>>,
) -> BoxStream<'a, Result<Path>> {
let started_at = self.time_provider.now();
let s = self.inner.delete_stream(locations);
// Wrap the object store data stream in a decorator to track the
// yielded data / wall clock, inclusive of the inner call above.
StreamMetricRecorder::new(
s,
started_at,
CountStreamDelegate::new(self.delete_stream.clone()),
Arc::clone(&self.time_provider),
)
.fuse()
.boxed()
}
fn list(&self, prefix: Option<&Path>) -> BoxStream<'_, Result<ObjectMeta>> {
let started_at = self.time_provider.now();
let s = self.inner.list(prefix);
// Wrap the object store data stream in a decorator to track the
// yielded data / wall clock, inclusive of the inner call above.
StreamMetricRecorder::new(
s,
started_at,
CountStreamDelegate::new(self.list.clone()),
Arc::clone(&self.time_provider),
)
.fuse()
.boxed()
}
fn list_with_offset(
&self,
prefix: Option<&Path>,
offset: &Path,
) -> BoxStream<'_, Result<ObjectMeta>> {
let started_at = self.time_provider.now();
let s = self.inner.list_with_offset(prefix, offset);
// Wrap the object store data stream in a decorator to track the
// yielded data / wall clock, inclusive of the inner call above.
StreamMetricRecorder::new(
s,
started_at,
CountStreamDelegate::new(self.list_with_offset.clone()),
Arc::clone(&self.time_provider),
)
.fuse()
.boxed()
}
async fn list_with_delimiter(&self, prefix: Option<&Path>) -> Result<ListResult> {
let t = self.time_provider.now();
let res = self.inner.list_with_delimiter(prefix).await;
self.list_with_delimiter.record(
t,
self.time_provider.now(),
res.is_ok(),
res.as_ref().ok().map(|res| res.objects.len() as _),
);
res
}
async fn copy(&self, from: &Path, to: &Path) -> Result<()> {
let t = self.time_provider.now();
let res = self.inner.copy(from, to).await;
self.copy.record(t, self.time_provider.now(), res.is_ok());
res
}
async fn rename(&self, from: &Path, to: &Path) -> Result<()> {
let t = self.time_provider.now();
let res = self.inner.rename(from, to).await;
self.rename.record(t, self.time_provider.now(), res.is_ok());
res
}
async fn copy_if_not_exists(&self, from: &Path, to: &Path) -> Result<()> {
let t = self.time_provider.now();
let res = self.inner.copy_if_not_exists(from, to).await;
self.copy_if_not_exists
.record(t, self.time_provider.now(), res.is_ok());
res
}
async fn rename_if_not_exists(&self, from: &Path, to: &Path) -> Result<()> {
let t = self.time_provider.now();
let res = self.inner.rename_if_not_exists(from, to).await;
self.rename_if_not_exists
.record(t, self.time_provider.now(), res.is_ok());
res
}
}
/// A [`MetricDelegate`] is called whenever the [`StreamMetricRecorder`]
/// observes an `Ok(Item)` in the stream.
trait MetricDelegate {
/// The type this delegate observes.
type Item;
/// Invoked when the stream yields an `Ok(Item)`.
fn observe_ok(&mut self, value: &Self::Item, t: Time);
/// Finish stream.
fn finish(&mut self, t_begin: Time, t_end: Time, success: bool);
}
/// A [`MetricDelegate`] for instrumented streams of [`Bytes`].
///
/// This impl is used to record the number of bytes yielded for
/// [`ObjectStore::get()`] calls.
#[derive(Debug)]
struct BytesStreamDelegate {
metrics: MetricsWithBytesAndTtfb,
first_byte: Option<Time>,
}
impl BytesStreamDelegate {
fn new(metrics: MetricsWithBytesAndTtfb) -> Self {
Self {
metrics,
first_byte: None,
}
}
}
impl MetricDelegate for BytesStreamDelegate {
type Item = Bytes;
fn observe_ok(&mut self, bytes: &Self::Item, t: Time) {
if self.first_byte.is_none() {
self.first_byte = Some(t);
}
self.metrics.record_bytes_only(true, bytes.len() as _);
}
fn finish(&mut self, t_begin: Time, t_end: Time, success: bool) {
self.metrics.record(
t_begin,
self.first_byte.unwrap_or(t_end),
t_end,
success,
None,
);
}
}
#[derive(Debug)]
struct CountStreamDelegate<T>(MetricsWithCount, PhantomData<T>);
impl<T> CountStreamDelegate<T> {
fn new(metrics: MetricsWithCount) -> Self {
Self(metrics, Default::default())
}
}
impl<T> MetricDelegate for CountStreamDelegate<T> {
type Item = T;
fn observe_ok(&mut self, _value: &Self::Item, _t: Time) {
self.0.record_count_only(true, 1);
}
fn finish(&mut self, t_begin: Time, t_end: Time, success: bool) {
self.0.record(t_begin, t_end, success, None);
}
}
/// [`StreamMetricRecorder`] decorates an underlying [`Stream`] for "get" /
/// "list" catalog operations, recording the wall clock duration and invoking
/// the metric delegate with the `Ok(T)` values.
///
/// For "gets" using the [`BytesStreamDelegate`], the bytes read counter is
/// incremented each time [`Self::poll_next()`] yields a buffer, and once the
/// [`StreamMetricRecorder`] is read to completion (specifically, until it
/// yields `Poll::Ready(None)`), or when it is dropped (whichever is sooner) the
/// decorator emits the wall clock measurement into the relevant histogram,
/// bucketed by operation result.
///
/// A stream may return a transient error when polled, and later successfully
/// emit all data in subsequent polls - therefore the duration is logged as an
/// error only if the last poll performed by the caller returned an error.
#[derive(Debug)]
#[pin_project(PinnedDrop)]
struct StreamMetricRecorder<S, D>
where
D: MetricDelegate,
{
#[pin]
inner: S,
time_provider: Arc<dyn TimeProvider>,
// The timestamp at which the read request began, inclusive of the work
// required to acquire the inner stream (which may involve fetching all the
// data if the result is only pretending to be a stream).
started_at: Time,
// The time at which the last part of the data stream (or error) was
// returned to the caller.
//
// The total get operation duration is calculated as this timestamp minus
// the started_at timestamp.
//
// This field is always Some, until the end of the stream is observed at
// which point the metrics are emitted and this field is set to None,
// preventing the drop impl duplicating them.
last_yielded_at: Option<Time>,
// The error state of the last poll - true if OK, false if an error
// occurred.
//
// This is used to select the correct success/error histogram which records
// the operation duration.
last_call_ok: bool,
// Called when the stream yields an `Ok(T)` to allow the delegate to inspect
// the `T`.
metric_delegate: D,
}
impl<S, D> StreamMetricRecorder<S, D>
where
S: Stream,
D: MetricDelegate,
{
fn new(
stream: S,
started_at: Time,
metric_delegate: D,
time_provider: Arc<dyn TimeProvider>,
) -> Self {
Self {
inner: stream,
// Set the last_yielded_at to now, ensuring the duration of work
// already completed acquiring the steam is correctly recorded even
// if the stream is never polled / data never read.
last_yielded_at: Some(time_provider.now()),
// Acquiring the stream was successful, even if the data was never
// read.
last_call_ok: true,
started_at,
time_provider,
metric_delegate,
}
}
}
impl<S, T, D, E> Stream for StreamMetricRecorder<S, D>
where
S: Stream<Item = Result<T, E>>,
D: MetricDelegate<Item = T>,
{
type Item = S::Item;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.project();
let res = this.inner.poll_next(cx);
match res {
Poll::Ready(Some(Ok(value))) => {
let now = this.time_provider.now();
*this.last_call_ok = true;
*this.last_yielded_at.as_mut().unwrap() = now;
// Allow the pluggable metric delegate to record the value of T
this.metric_delegate.observe_ok(&value, now);
Poll::Ready(Some(Ok(value)))
}
Poll::Ready(Some(Err(e))) => {
*this.last_call_ok = false;
*this.last_yielded_at.as_mut().unwrap() = this.time_provider.now();
Poll::Ready(Some(Err(e)))
}
Poll::Ready(None) => {
// The stream has terminated - record the wall clock duration
// immediately.
this.metric_delegate.finish(
*this.started_at,
this.last_yielded_at
.take()
.expect("no last_yielded_at value for fused stream"),
*this.last_call_ok,
);
Poll::Ready(None)
}
v => v,
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
// Impl the default size_hint() so this wrapper doesn't mask the size
// hint from the inner stream, if any.
self.inner.size_hint()
}
}
#[pinned_drop]
impl<S, D> PinnedDrop for StreamMetricRecorder<S, D>
where
D: MetricDelegate,
{
fn drop(self: Pin<&mut Self>) {
let this = self.project();
// Only emit metrics if the end of the stream was not observed (and
// therefore last_yielded_at is still Some).
if let Some(last) = this.last_yielded_at {
this.metric_delegate
.finish(*this.started_at, *last, *this.last_call_ok);
}
}
}
#[cfg(test)]
mod tests {
use std::future::ready;
use std::{
io::{Error, ErrorKind},
sync::Arc,
time::Duration,
};
use futures::{stream, FutureExt, TryStreamExt};
use iox_time::{MockProvider, SystemProvider};
use metric::Attributes;
use std::io::Read;
use std::sync::atomic::{AtomicBool, Ordering};
use dummy::DummyObjectStore;
use object_store::{local::LocalFileSystem, memory::InMemory, UploadPart};
use super::*;
#[track_caller]
fn assert_histogram_hit<const N: usize>(
metrics: &metric::Registry,
name: &'static str,
attr: [(&'static str, &'static str); N],
) {
let histogram = metrics
.get_instrument::<Metric<DurationHistogram>>(name)
.expect("failed to read histogram")
.get_observer(&Attributes::from(&attr))
.expect("failed to get observer")
.fetch();
let hit_count = histogram.sample_count();
assert!(hit_count > 0, "metric {name} did not record any calls");
}
#[track_caller]
fn assert_histogram_not_hit<const N: usize>(
metrics: &metric::Registry,
name: &'static str,
attr: [(&'static str, &'static str); N],
) {
let histogram = metrics
.get_instrument::<Metric<DurationHistogram>>(name)
.expect("failed to read histogram")
.get_observer(&Attributes::from(&attr))
.expect("failed to get observer")
.fetch();
let hit_count = histogram.sample_count();
assert!(hit_count == 0, "metric {name} did record {hit_count} calls");
}
#[track_caller]
fn assert_counter_value<const N: usize>(
metrics: &metric::Registry,
name: &'static str,
attr: [(&'static str, &'static str); N],
value: u64,
) {
let count = metrics
.get_instrument::<Metric<U64Counter>>(name)
.expect("failed to read counter")
.get_observer(&Attributes::from(&attr))
.expect("failed to get observer")
.fetch();
assert_eq!(count, value);
}
#[tokio::test]
async fn test_put() {
let metrics = Arc::new(metric::Registry::default());
let store = Arc::new(InMemory::new());
let time = Arc::new(SystemProvider::new());
let store = ObjectStoreMetrics::new(store, time, "bananas", &metrics);
store
.put(
&Path::from("test"),
PutPayload::from([42_u8, 42, 42, 42, 42].as_slice()),
)
.await
.expect("put should succeed");
assert_counter_value(
&metrics,
"object_store_transfer_bytes",
[
("store_type", "bananas"),
("op", "put"),
("result", "success"),
],
5,
);
assert_histogram_hit(
&metrics,
"object_store_op_duration",
[
("store_type", "bananas"),
("op", "put"),
("result", "success"),
],
);
}
#[tokio::test]
async fn test_put_fails() {
let metrics = Arc::new(metric::Registry::default());
let store = Arc::new(DummyObjectStore::new("s3"));
let time = Arc::new(SystemProvider::new());
let store = ObjectStoreMetrics::new(store, time, "bananas", &metrics);
store
.put(
&Path::from("test"),
PutPayload::from([42_u8, 42, 42, 42, 42].as_slice()),
)
.await
.expect_err("put should error");
assert_counter_value(
&metrics,
"object_store_transfer_bytes",
[
("store_type", "bananas"),
("op", "put"),
("result", "error"),
],
5,
);
assert_histogram_hit(
&metrics,
"object_store_op_duration",
[
("store_type", "bananas"),
("op", "put"),
("result", "error"),
],
);
}
#[tokio::test]
async fn test_put_multipart() {
let metrics = Arc::new(metric::Registry::default());
let store = Arc::new(InMemory::new());
let time = Arc::new(SystemProvider::new());
let store = ObjectStoreMetrics::new(store, time, "bananas", &metrics);
let mut multipart_upload = store
.put_multipart(&Path::from("test"))
.await
.expect("should get multipart upload");
assert!(multipart_upload
.put_part(PutPayload::from_static(&[42_u8, 42, 42, 42, 42]))
.await
.is_ok());
// demonstrate that it sums across bytes
assert!(multipart_upload
.put_part(PutPayload::from_static(&[42_u8, 42, 42]))
.await
.is_ok());
drop(multipart_upload);
store.close().await;
assert_counter_value(
&metrics,
"object_store_transfer_bytes",
[
("store_type", "bananas"),
("op", "put_multipart"),
("result", "success"),
],
8,
);
assert_histogram_hit(
&metrics,
"object_store_op_duration",
[
("store_type", "bananas"),
("op", "put_multipart"),
("result", "success"),
],
);
}
#[derive(Debug)]
struct NopeMultipartUpload;
#[async_trait]
impl MultipartUpload for NopeMultipartUpload {
fn put_part(&mut self, _data: PutPayload) -> UploadPart {