aws-smithy-runtime 1.16.0

The new smithy runtime crate
Documentation
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
/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

use aws_smithy_async::time::{SharedTimeSource, TimeSource};
use aws_smithy_observability::{
    global::get_telemetry_provider, instruments::Histogram, AttributeValue, Attributes,
    ObservabilityError,
};
use aws_smithy_runtime_api::client::http::telemetry::{
    CaptureHttpAttemptTelemetry, ConnectionAcquisitionTelemetry, HttpAttemptTelemetry,
};
use aws_smithy_runtime_api::client::{
    interceptors::{
        context::BeforeTransmitInterceptorContextMut, dyn_dispatch_hint, Intercept,
        SharedInterceptor,
    },
    orchestrator::Metadata,
    runtime_components::RuntimeComponentsBuilder,
    runtime_plugin::RuntimePlugin,
};
use aws_smithy_types::config_bag::{FrozenLayer, Layer, Storable, StoreReplace};
use aws_smithy_types::telemetry::{CapturedTelemetryAttributes, RequestedTelemetryAttributes};
use std::{borrow::Cow, sync::Arc, time::SystemTime};

/// Sets the outcome attributes (`error.type` and `http.status_code`) on `attrs` from a
/// finalizer-phase context.
fn add_outcome_attrs(
    attrs: &mut Attributes,
    context: &aws_smithy_runtime_api::client::interceptors::context::FinalizerInterceptorContextRef<
        '_,
    >,
) {
    // Coarse category only; the error is type-erased here, so the modeled name isn't reachable.
    // Absent on success, per OTel convention.
    if let Some(Err(err)) = context.output_or_error() {
        let category = if err.is_timeout_error() {
            "timeout"
        } else if err.is_connector_error() {
            "connector"
        } else if err.is_response_error() {
            "response"
        } else if err.is_operation_error() {
            "operation"
        } else {
            "other"
        };
        attrs.set("error.type", AttributeValue::String(category.into()));
    }

    // Raw HTTP status code, whenever a response reached us.
    if let Some(response) = context.response() {
        attrs.set(
            "http.status_code",
            AttributeValue::I64(i64::from(response.status().as_u16())),
        );
    }
}

/// Struct to hold metric data in the ConfigBag
#[derive(Debug, Clone)]
pub(crate) struct MeasurementsContainer {
    call_start: SystemTime,
    attempts: u32,
    attempt_start: SystemTime,
    attempt_capture: Option<CaptureHttpAttemptTelemetry>,
}

impl Storable for MeasurementsContainer {
    type Storer = StoreReplace<Self>;
}

/// Instruments for recording a single operation
#[derive(Debug, Clone)]
pub(crate) struct OperationTelemetry {
    pub(crate) operation_duration: Arc<dyn Histogram>,
    pub(crate) attempt_duration: Arc<dyn Histogram>,
    pub(crate) connection_acquisition_duration: Arc<dyn Histogram>,
    // Body sizes are their own instruments rather than attributes on the duration histogram: body
    // size is near-unique per call, so attaching it as a label would fragment the duration metric
    // into one time series per byte count.
    pub(crate) request_body_size: Arc<dyn Histogram>,
    pub(crate) response_body_size: Arc<dyn Histogram>,
}

impl OperationTelemetry {
    pub(crate) fn new(scope: &'static str) -> Result<Self, ObservabilityError> {
        let meter = get_telemetry_provider()?
            .meter_provider()
            .get_meter(scope, None);

        Ok(Self{
            operation_duration: meter
                .create_histogram("smithy.client.call.duration")
                .set_units("s")
                .set_description("Overall call duration (including retries and time to send or receive request and response body)")
                .build(),
            attempt_duration: meter
                .create_histogram("smithy.client.call.attempt.duration")
                .set_units("s")
                .set_description("The time it takes to connect to the service, send the request, and get back HTTP status code and headers (including time queued waiting to be sent)")
                .build(),
            connection_acquisition_duration: meter
                .create_histogram("smithy.client.http.connections.acquire_duration")
                .set_units("s")
                .set_description("Time spent acquiring the connection that accepted the request")
                .build(),
            request_body_size: meter
                .create_histogram("smithy.client.call.request.size")
                .set_units("By")
                .set_description("Size of the transferred request body, in bytes")
                .build(),
            response_body_size: meter
                .create_histogram("smithy.client.call.response.size")
                .set_units("By")
                .set_description("Size of the transferred response body, in bytes")
                .build(),
        })
    }

    fn record_connection_acquisition(&self, telemetry: &HttpAttemptTelemetry) {
        if let Some(duration) = telemetry
            .acquisition()
            .and_then(ConnectionAcquisitionTelemetry::duration)
        {
            self.connection_acquisition_duration
                .record(duration.as_secs_f64(), None, None);
        }
    }
}

impl Storable for OperationTelemetry {
    type Storer = StoreReplace<Self>;
}

#[derive(Debug)]
pub(crate) struct MetricsInterceptor {
    // Holding a TimeSource here isn't ideal, but RuntimeComponents aren't available in
    // the read_before_execution hook and that is when we need to start the timer for
    // the operation.
    time_source: SharedTimeSource,
}

impl MetricsInterceptor {
    pub(crate) fn new(time_source: SharedTimeSource) -> Result<Self, ObservabilityError> {
        Ok(MetricsInterceptor { time_source })
    }

    pub(crate) fn get_attrs_from_cfg(
        &self,
        cfg: &aws_smithy_types::config_bag::ConfigBag,
    ) -> Option<Attributes> {
        let operation_metadata = cfg.load::<Metadata>();

        if let Some(md) = operation_metadata {
            let mut attributes = Attributes::new();
            attributes.set("rpc.service", AttributeValue::String(md.service().into()));
            attributes.set("rpc.method", AttributeValue::String(md.name().into()));

            // Merge captured input members that the customer opted in to *emit*. Capture-only
            // members are present in the bag for in-process reads but are deliberately excluded
            // from the metric label set.
            if let (Some(captured), Some(requested)) = (
                cfg.load::<CapturedTelemetryAttributes>(),
                cfg.load::<RequestedTelemetryAttributes>(),
            ) {
                for (name, value) in captured.iter() {
                    if requested.should_emit(name) {
                        attributes.set(name, AttributeValue::String(value.into()));
                    }
                }
            }

            Some(attributes)
        } else {
            None
        }
    }

    pub(crate) fn get_measurements_and_instruments<'a>(
        &self,
        cfg: &'a aws_smithy_types::config_bag::ConfigBag,
    ) -> (&'a MeasurementsContainer, &'a OperationTelemetry) {
        let measurements = cfg
            .load::<MeasurementsContainer>()
            .expect("set in `read_before_execution`");

        let instruments = cfg
            .load::<OperationTelemetry>()
            .expect("set in RuntimePlugin");

        (measurements, instruments)
    }
}

#[dyn_dispatch_hint]
impl Intercept for MetricsInterceptor {
    fn name(&self) -> &'static str {
        "MetricsInterceptor"
    }

    fn read_before_execution(
        &self,
        _context: &aws_smithy_runtime_api::client::interceptors::context::BeforeSerializationInterceptorContextRef<'_>,
        cfg: &mut aws_smithy_types::config_bag::ConfigBag,
    ) -> Result<(), aws_smithy_runtime_api::box_error::BoxError> {
        cfg.interceptor_state().store_put(MeasurementsContainer {
            call_start: self.time_source.now(),
            attempts: 0,
            attempt_start: SystemTime::UNIX_EPOCH,
            attempt_capture: None,
        });

        Ok(())
    }

    fn read_after_execution(
        &self,
        context: &aws_smithy_runtime_api::client::interceptors::context::FinalizerInterceptorContextRef<'_>,
        _runtime_components: &aws_smithy_runtime_api::client::runtime_components::RuntimeComponents,
        cfg: &mut aws_smithy_types::config_bag::ConfigBag,
    ) -> Result<(), aws_smithy_runtime_api::box_error::BoxError> {
        let (measurements, instruments) = self.get_measurements_and_instruments(cfg);

        let attributes = self.get_attrs_from_cfg(cfg);

        if let Some(mut attrs) = attributes {
            // The outcome is only known at the finalizer, so it is set here rather than in
            // `get_attrs_from_cfg` (which also serves the per-attempt path).
            add_outcome_attrs(&mut attrs, context);

            // Transferred byte sizes are recorded on their own instruments by the byte
            // interceptor (see `telemetry_bytes`), not as attributes on the duration histogram.

            let call_end = self.time_source.now();
            let call_duration = call_end.duration_since(measurements.call_start);
            if let Ok(elapsed) = call_duration {
                instruments
                    .operation_duration
                    .record(elapsed.as_secs_f64(), Some(&attrs), None);
            }
        }

        Ok(())
    }

    fn read_before_attempt(
        &self,
        _context: &aws_smithy_runtime_api::client::interceptors::context::BeforeTransmitInterceptorContextRef<'_>,
        _runtime_components: &aws_smithy_runtime_api::client::runtime_components::RuntimeComponents,
        cfg: &mut aws_smithy_types::config_bag::ConfigBag,
    ) -> Result<(), aws_smithy_runtime_api::box_error::BoxError> {
        let measurements = cfg
            .get_mut::<MeasurementsContainer>()
            .expect("set in `read_before_execution`");

        measurements.attempts += 1;
        measurements.attempt_start = self.time_source.now();
        measurements.attempt_capture = None;

        Ok(())
    }

    fn modify_before_transmit(
        &self,
        context: &mut BeforeTransmitInterceptorContextMut<'_>,
        _runtime_components: &aws_smithy_runtime_api::client::runtime_components::RuntimeComponents,
        _cfg: &mut aws_smithy_types::config_bag::ConfigBag,
    ) -> Result<(), aws_smithy_runtime_api::box_error::BoxError> {
        if context
            .request()
            .extension::<CaptureHttpAttemptTelemetry>()
            .is_none()
        {
            context
                .request_mut()
                .add_extension(CaptureHttpAttemptTelemetry::new());
        }
        Ok(())
    }

    fn read_before_transmit(
        &self,
        context: &aws_smithy_runtime_api::client::interceptors::context::BeforeTransmitInterceptorContextRef<'_>,
        _runtime_components: &aws_smithy_runtime_api::client::runtime_components::RuntimeComponents,
        cfg: &mut aws_smithy_types::config_bag::ConfigBag,
    ) -> Result<(), aws_smithy_runtime_api::box_error::BoxError> {
        let capture = context
            .request()
            .extension::<CaptureHttpAttemptTelemetry>()
            .cloned();
        cfg.get_mut::<MeasurementsContainer>()
            .expect("set in `read_before_execution`")
            .attempt_capture = capture;
        Ok(())
    }

    fn read_after_attempt(
        &self,
        _context: &aws_smithy_runtime_api::client::interceptors::context::FinalizerInterceptorContextRef<'_>,
        _runtime_components: &aws_smithy_runtime_api::client::runtime_components::RuntimeComponents,
        cfg: &mut aws_smithy_types::config_bag::ConfigBag,
    ) -> Result<(), aws_smithy_runtime_api::box_error::BoxError> {
        let (attempts, attempt_start, http_telemetry) = {
            let measurements = cfg
                .get_mut::<MeasurementsContainer>()
                .expect("set in `read_before_execution`");
            (
                measurements.attempts,
                measurements.attempt_start,
                measurements
                    .attempt_capture
                    .take()
                    .map(|capture| capture.get()),
            )
        };
        let instruments = cfg
            .load::<OperationTelemetry>()
            .expect("set in RuntimePlugin");

        let attempt_end = self.time_source.now();
        let attempt_duration = attempt_end.duration_since(attempt_start);
        let attributes = self.get_attrs_from_cfg(cfg);

        if let Some(http_telemetry) = http_telemetry {
            instruments.record_connection_acquisition(&http_telemetry);
        }

        if let (Ok(elapsed), Some(mut attrs)) = (attempt_duration, attributes) {
            attrs.set("attempt", AttributeValue::I64(attempts.into()));

            instruments
                .attempt_duration
                .record(elapsed.as_secs_f64(), Some(&attrs), None);
        }
        Ok(())
    }
}

/// Runtime plugin that adds an interceptor for collecting metrics
#[derive(Debug, Default)]
pub struct MetricsRuntimePlugin {
    scope: &'static str,
    time_source: SharedTimeSource,
    metadata: Option<Metadata>,
}

impl MetricsRuntimePlugin {
    /// Create a [MetricsRuntimePluginBuilder]
    pub fn builder() -> MetricsRuntimePluginBuilder {
        MetricsRuntimePluginBuilder::default()
    }
}

impl RuntimePlugin for MetricsRuntimePlugin {
    fn runtime_components(
        &self,
        _current_components: &RuntimeComponentsBuilder,
    ) -> Cow<'_, RuntimeComponentsBuilder> {
        let interceptor = MetricsInterceptor::new(self.time_source.clone());
        if let Ok(interceptor) = interceptor {
            Cow::Owned(
                RuntimeComponentsBuilder::new("Metrics")
                    .with_interceptor(SharedInterceptor::permanent(interceptor))
                    // Counts transferred bytes into the bag for the metrics interceptor to read.
                    .with_interceptor(SharedInterceptor::permanent(
                        crate::client::telemetry_bytes::TelemetryBytesInterceptor,
                    )),
            )
        } else {
            Cow::Owned(RuntimeComponentsBuilder::new("Metrics"))
        }
    }

    fn config(&self) -> Option<FrozenLayer> {
        let instruments = OperationTelemetry::new(self.scope);

        if let Ok(instruments) = instruments {
            let mut cfg = Layer::new("Metrics");
            cfg.store_put(instruments);

            if let Some(metadata) = &self.metadata {
                cfg.store_put(metadata.clone());
            }

            Some(cfg.freeze())
        } else {
            None
        }
    }
}

/// Builder for [MetricsRuntimePlugin]
#[derive(Debug, Default)]
pub struct MetricsRuntimePluginBuilder {
    scope: Option<&'static str>,
    time_source: Option<SharedTimeSource>,
    metadata: Option<Metadata>,
}

impl MetricsRuntimePluginBuilder {
    /// Set the scope for the metrics
    pub fn with_scope(mut self, scope: &'static str) -> Self {
        self.scope = Some(scope);
        self
    }

    /// Set the [TimeSource] for the metrics
    pub fn with_time_source(mut self, time_source: impl TimeSource + 'static) -> Self {
        self.time_source = Some(SharedTimeSource::new(time_source));
        self
    }

    /// Set the [Metadata] for the metrics.
    ///
    /// Note: the Metadata is optional, most operations set it themselves, but this is useful
    /// for operations that do not, like some of the credential providers.
    pub fn with_metadata(mut self, metadata: Metadata) -> Self {
        self.metadata = Some(metadata);
        self
    }

    /// Build a [MetricsRuntimePlugin]
    pub fn build(
        self,
    ) -> Result<MetricsRuntimePlugin, aws_smithy_runtime_api::box_error::BoxError> {
        if let Some(scope) = self.scope {
            Ok(MetricsRuntimePlugin {
                scope,
                time_source: self.time_source.unwrap_or_default(),
                metadata: self.metadata,
            })
        } else {
            Err("Scope is required for MetricsRuntimePlugin.".into())
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use aws_smithy_async::time::SystemTimeSource;
    use aws_smithy_runtime_api::client::connection::ConnectionMetadata;
    use aws_smithy_runtime_api::client::http::telemetry::{
        ConnectionAcquisitionTelemetry, ConnectionUsage,
    };
    use aws_smithy_runtime_api::client::interceptors::context::{Input, InterceptorContext};
    use aws_smithy_runtime_api::client::orchestrator::HttpRequest;
    use aws_smithy_types::config_bag::ConfigBag;
    use std::sync::Mutex;

    #[derive(Debug, Default)]
    struct RecordingHistogram {
        records: Mutex<Vec<(f64, Option<Attributes>)>>,
    }

    impl RecordingHistogram {
        fn only_record(&self) -> (f64, Option<Attributes>) {
            let records = self.records.lock().unwrap();
            assert_eq!(records.len(), 1);
            records[0].clone()
        }

        fn record_count(&self) -> usize {
            self.records.lock().unwrap().len()
        }
    }

    impl Histogram for RecordingHistogram {
        fn record(
            &self,
            value: f64,
            attributes: Option<&Attributes>,
            _context: Option<&dyn aws_smithy_observability::Context>,
        ) {
            self.records
                .lock()
                .unwrap()
                .push((value, attributes.cloned()));
        }
    }

    fn interceptor() -> MetricsInterceptor {
        MetricsInterceptor::new(SharedTimeSource::new(SystemTimeSource::new())).unwrap()
    }

    fn cfg_with(layer: Layer) -> ConfigBag {
        ConfigBag::of_layers(vec![layer])
    }

    fn string_attr<'a>(attrs: &'a Attributes, key: &str) -> Option<&'a str> {
        match attrs.get(key) {
            Some(AttributeValue::String(s)) => Some(s.as_str()),
            _ => None,
        }
    }

    #[test]
    fn base_attrs_are_service_and_method() {
        let mut layer = Layer::new("test");
        layer.store_put(Metadata::new("GetObject", "S3"));

        let attrs = interceptor()
            .get_attrs_from_cfg(&cfg_with(layer))
            .expect("metadata present");

        assert_eq!(Some("S3"), string_attr(&attrs, "rpc.service"));
        assert_eq!(Some("GetObject"), string_attr(&attrs, "rpc.method"));
    }

    #[test]
    fn no_attrs_without_metadata() {
        // Nothing to key the metric on, so no attributes are produced.
        assert!(interceptor()
            .get_attrs_from_cfg(&cfg_with(Layer::new("test")))
            .is_none());
    }

    fn test_instruments(acquisition: Arc<RecordingHistogram>) -> OperationTelemetry {
        let ignored: Arc<dyn Histogram> = Arc::new(RecordingHistogram::default());
        OperationTelemetry {
            operation_duration: ignored.clone(),
            attempt_duration: ignored.clone(),
            connection_acquisition_duration: acquisition,
            request_body_size: ignored.clone(),
            response_body_size: ignored,
        }
    }

    fn install_measurements(cfg: &mut ConfigBag) {
        cfg.interceptor_state().store_put(MeasurementsContainer {
            call_start: SystemTime::UNIX_EPOCH,
            attempts: 0,
            attempt_start: SystemTime::UNIX_EPOCH,
            attempt_capture: None,
        });
    }

    #[test]
    fn before_transmit_adopts_an_existing_attempt_capture() {
        let runtime_components = RuntimeComponentsBuilder::for_tests().build().unwrap();
        let mut context = InterceptorContext::new(Input::doesnt_matter());
        context.set_request(HttpRequest::empty());
        let mut cfg = cfg_with(Layer::new("test"));
        install_measurements(&mut cfg);
        let caller_capture = CaptureHttpAttemptTelemetry::new();
        context
            .request_mut()
            .unwrap()
            .add_extension(caller_capture.clone());

        interceptor()
            .modify_before_transmit(&mut (&mut context).into(), &runtime_components, &mut cfg)
            .unwrap();
        interceptor()
            .read_before_transmit(&(&context).into(), &runtime_components, &mut cfg)
            .unwrap();

        let request_capture = context
            .request()
            .unwrap()
            .extension::<CaptureHttpAttemptTelemetry>()
            .expect("request capture");
        request_capture.record_connector_call_duration(std::time::Duration::from_millis(4));
        assert_eq!(
            cfg.load::<MeasurementsContainer>()
                .and_then(|measurements| measurements.attempt_capture.as_ref())
                .expect("attempt capture")
                .get()
                .connector_call_duration(),
            Some(std::time::Duration::from_millis(4))
        );
        assert_eq!(
            caller_capture.get().connector_call_duration(),
            Some(std::time::Duration::from_millis(4))
        );
    }

    #[test]
    fn before_transmit_adopts_the_final_replacement_capture() {
        let runtime_components = RuntimeComponentsBuilder::for_tests().build().unwrap();
        let mut context = InterceptorContext::new(Input::doesnt_matter());
        context.set_request(HttpRequest::empty());
        let mut cfg = cfg_with(Layer::new("test"));
        install_measurements(&mut cfg);

        interceptor()
            .modify_before_transmit(&mut (&mut context).into(), &runtime_components, &mut cfg)
            .unwrap();
        let replacement = CaptureHttpAttemptTelemetry::new();
        context
            .request_mut()
            .unwrap()
            .add_extension(replacement.clone());
        interceptor()
            .read_before_transmit(&(&context).into(), &runtime_components, &mut cfg)
            .unwrap();

        replacement.record_connector_call_duration(std::time::Duration::from_millis(6));
        assert_eq!(
            cfg.load::<MeasurementsContainer>()
                .and_then(|measurements| measurements.attempt_capture.as_ref())
                .expect("attempt capture")
                .get()
                .connector_call_duration(),
            Some(std::time::Duration::from_millis(6))
        );
    }

    #[test]
    fn attempt_capture_is_consumed_once_and_cleared_before_retry() {
        let runtime_components = RuntimeComponentsBuilder::for_tests().build().unwrap();
        let acquisition = Arc::new(RecordingHistogram::default());
        let mut layer = Layer::new("test");
        layer.store_put(Metadata::new("GetObject", "S3"));
        layer.store_put(test_instruments(acquisition.clone()));
        let mut cfg = cfg_with(layer);
        install_measurements(&mut cfg);
        let mut context = InterceptorContext::new(Input::doesnt_matter());
        context.set_request(HttpRequest::empty());
        let metrics = interceptor();

        metrics
            .read_before_attempt(&(&context).into(), &runtime_components, &mut cfg)
            .unwrap();
        metrics
            .modify_before_transmit(&mut (&mut context).into(), &runtime_components, &mut cfg)
            .unwrap();
        metrics
            .read_before_transmit(&(&context).into(), &runtime_components, &mut cfg)
            .unwrap();
        context
            .request()
            .unwrap()
            .extension::<CaptureHttpAttemptTelemetry>()
            .expect("request capture")
            .record_connection_selection(
                ConnectionAcquisitionTelemetry::new(
                    std::time::Duration::from_millis(3),
                    ConnectionUsage::Fresh,
                ),
                ConnectionMetadata::builder()
                    .proxied(false)
                    .poison_fn(|| {})
                    .build(),
            );
        metrics
            .read_after_attempt(&(&context).into(), &runtime_components, &mut cfg)
            .unwrap();
        assert_eq!(acquisition.record_count(), 1);

        metrics
            .read_before_attempt(&(&context).into(), &runtime_components, &mut cfg)
            .unwrap();
        metrics
            .read_after_attempt(&(&context).into(), &runtime_components, &mut cfg)
            .unwrap();
        assert_eq!(
            acquisition.record_count(),
            1,
            "a pre-transmit retry halt must not repeat the prior acquisition"
        );
    }

    #[test]
    fn records_connection_acquisition_without_attributes() {
        let acquisition = Arc::new(RecordingHistogram::default());
        let instruments = test_instruments(acquisition.clone());
        let capture = CaptureHttpAttemptTelemetry::new();
        capture.record_connector_call_duration(std::time::Duration::from_millis(7));
        capture.record_connection_selection(
            ConnectionAcquisitionTelemetry::new(
                std::time::Duration::from_millis(3),
                ConnectionUsage::Reused,
            ),
            ConnectionMetadata::builder()
                .proxied(false)
                .poison_fn(|| {})
                .build(),
        );
        instruments.record_connection_acquisition(&capture.get());

        let (acquisition_value, acquisition_attrs) = acquisition.only_record();
        assert_eq!(
            acquisition_value,
            std::time::Duration::from_millis(3).as_secs_f64()
        );
        assert!(acquisition_attrs.is_none());
    }

    #[test]
    fn emitted_members_are_merged_onto_attrs() {
        let mut captured = CapturedTelemetryAttributes::new();
        captured.insert("Bucket", "my-bucket");

        let mut layer = Layer::new("test");
        layer.store_put(Metadata::new("GetObject", "S3"));
        layer.store_put(captured);
        layer.store_put(RequestedTelemetryAttributes::new(["Bucket"]));

        let attrs = interceptor()
            .get_attrs_from_cfg(&cfg_with(layer))
            .expect("metadata present");

        // The emitted input member rides alongside the built-in rpc.* attributes.
        assert_eq!(Some("my-bucket"), string_attr(&attrs, "Bucket"));
        assert_eq!(Some("S3"), string_attr(&attrs, "rpc.service"));
    }

    #[test]
    fn capture_only_members_are_not_emitted() {
        // A value captured for in-process reads must not land on the metric.
        let mut captured = CapturedTelemetryAttributes::new();
        captured.insert("Prefix", "logs/");

        let mut requested = RequestedTelemetryAttributes::default();
        requested.capture_only(["Prefix"]);

        let mut layer = Layer::new("test");
        layer.store_put(Metadata::new("GetObject", "S3"));
        layer.store_put(captured);
        layer.store_put(requested);

        let attrs = interceptor()
            .get_attrs_from_cfg(&cfg_with(layer))
            .expect("metadata present");

        assert!(
            attrs.get("Prefix").is_none(),
            "capture-only member must not be emitted on the metric"
        );
    }

    #[test]
    fn nothing_captured_leaves_only_base_attrs() {
        // Opt-in is off by default: an empty capture set adds nothing.
        let mut layer = Layer::new("test");
        layer.store_put(Metadata::new("GetObject", "S3"));
        layer.store_put(CapturedTelemetryAttributes::new());

        let attrs = interceptor()
            .get_attrs_from_cfg(&cfg_with(layer))
            .expect("metadata present");

        assert_eq!(Some("GetObject"), string_attr(&attrs, "rpc.method"));
        assert!(attrs.get("Bucket").is_none());
    }

    // --- add_outcome_attrs (the `status` dimension) ---

    use aws_smithy_runtime_api::client::interceptors::context::{Error, Output};
    use aws_smithy_runtime_api::client::orchestrator::OrchestratorError;
    use aws_smithy_runtime_api::client::result::ConnectorError;
    use aws_smithy_runtime_api::http::{Response, StatusCode};
    use aws_smithy_types::body::SdkBody;

    fn i64_attr(attrs: &Attributes, key: &str) -> Option<i64> {
        match attrs.get(key) {
            Some(AttributeValue::I64(v)) => Some(*v),
            _ => None,
        }
    }

    #[test]
    fn outcome_on_success_has_status_code_and_no_error_type() {
        let mut ctx = InterceptorContext::new(Input::doesnt_matter());
        ctx.set_output_or_error(Ok(Output::doesnt_matter()));
        ctx.set_response(Response::new(
            StatusCode::try_from(200).unwrap(),
            SdkBody::empty(),
        ));

        let mut attrs = Attributes::new();
        add_outcome_attrs(&mut attrs, &(&ctx).into());

        // error.type is absent on success (OTel convention); status code is present.
        assert!(attrs.get("error.type").is_none());
        assert_eq!(Some(200), i64_attr(&attrs, "http.status_code"));
    }

    #[test]
    fn outcome_on_failure_sets_error_type_category() {
        let mut ctx = InterceptorContext::new(Input::doesnt_matter());
        ctx.set_output_or_error(Err(OrchestratorError::connector(ConnectorError::io(
            "boom".into(),
        ))));

        let mut attrs = Attributes::new();
        add_outcome_attrs(&mut attrs, &(&ctx).into());

        // A connector error maps to the `connector` category.
        assert_eq!(Some("connector"), string_attr(&attrs, "error.type"));
    }

    #[test]
    fn outcome_without_response_omits_status_code() {
        let mut ctx: InterceptorContext<Input, Output, Error> =
            InterceptorContext::new(Input::doesnt_matter());
        ctx.set_output_or_error(Err(OrchestratorError::connector(ConnectorError::io(
            "boom".into(),
        ))));

        let mut attrs = Attributes::new();
        add_outcome_attrs(&mut attrs, &(&ctx).into());

        // No response reached us, so there is no HTTP status code to record.
        assert!(attrs.get("http.status_code").is_none());
        assert_eq!(Some("connector"), string_attr(&attrs, "error.type"));
    }
}