Skip to main content

aws_smithy_observability/unit_of_work/
checksums.rs

1/*
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6//! Records whether a call's response body was validated against its checksum.
7//!
8//! The SDK reports to a [`ChecksumCapture`] through
9//! [`aws_smithy_runtime_api::client::unit_of_work::checksums`], whose types are stable, so a
10//! capture and a client built against different releases of this crate still find each other.
11
12use super::{sealed, AsHandle, Capture};
13use aws_smithy_runtime_api::client::unit_of_work::checksums::{
14    ChecksumEvent, ChecksumEventKind, ChecksumSkip, ObserveResponseChecksum,
15    SharedResponseChecksumObserver,
16};
17use aws_smithy_types::config_bag::{ConfigBag, Storable, StoreAppend};
18use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
19
20/// Records whether one call's response body was validated against its checksum.
21///
22/// Create one for each call and attach it with [`Capture::with`]. Clones share one record.
23#[derive(Clone, Debug, Default)]
24pub struct ChecksumCapture {
25    slot: Arc<Mutex<ChecksumSlot>>,
26}
27
28impl ChecksumCapture {
29    /// Creates a handle that is not attached to any call.
30    pub fn new() -> Self {
31        Self::default()
32    }
33
34    /// Where the record stands now. Never waits.
35    pub fn state(&self) -> ChecksumState {
36        self.lock().state()
37    }
38
39    /// The outcome, once it is complete. Never waits.
40    ///
41    /// The outcome is complete once the call has ended and, if the response body is validated,
42    /// once that body has ended too. For a validated streaming response, that is after the body
43    /// is read to its end or dropped.
44    pub fn try_outcome(&self) -> Option<ChecksumOutcome> {
45        match self.state() {
46            ChecksumState::Complete(outcome) => Some(outcome),
47            _ => None,
48        }
49    }
50
51    pub(super) fn bind(&self, cfg: &mut ConfigBag) {
52        // The same handle can reach one call twice, through one `Capture` or two. It records
53        // that call once.
54        let already_bound = cfg
55            .load::<CompleteOnDrop>()
56            .any(|guard| Arc::ptr_eq(&guard.0, &self.slot));
57        if !already_bound && self.lock().bind() {
58            cfg.interceptor_state()
59                .store_append(SharedResponseChecksumObserver::new(SlotObserver(
60                    self.slot.clone(),
61                )))
62                .store_append(CompleteOnDrop(self.slot.clone()));
63        }
64    }
65
66    pub(super) fn attempt_started(&self) {
67        self.lock().attempt_started();
68    }
69
70    pub(super) fn call_ended(&self, succeeded: bool) {
71        self.lock().call_ended(succeeded);
72    }
73
74    pub(super) fn capture_dropped(&self) {
75        self.lock().capture_dropped();
76    }
77
78    fn lock(&self) -> MutexGuard<'_, ChecksumSlot> {
79        lock(&self.slot)
80    }
81}
82
83impl AsHandle for ChecksumCapture {}
84
85impl sealed::Sealed for ChecksumCapture {
86    fn add_to(&self, capture: &mut Capture) {
87        capture.checksums.push(self.clone());
88    }
89}
90
91/// Where a [`ChecksumCapture`]'s record stands.
92#[derive(Clone, Debug, PartialEq, Eq)]
93#[non_exhaustive]
94pub enum ChecksumState {
95    /// The handle has not been attached to a call that ran.
96    NotInstalled,
97    /// The call is running, and no response body is being validated.
98    AwaitingResponse,
99    /// A response body is being validated.
100    Validating {
101        /// The algorithm the body is validated with.
102        algorithm: ResponseChecksumAlgorithm,
103    },
104    /// The outcome is final.
105    Complete(ChecksumOutcome),
106}
107
108/// Whether a call's response body was validated against its checksum.
109#[derive(Clone, Debug, PartialEq, Eq)]
110#[non_exhaustive]
111pub enum ChecksumOutcome {
112    /// The body was read to its end, and its checksum matched.
113    Validated {
114        /// The algorithm the body was validated with.
115        algorithm: ResponseChecksumAlgorithm,
116        /// The checksum computed from the body, in base64.
117        computed: String,
118    },
119    /// The body was read to its end, and its checksum did not match.
120    Mismatch {
121        /// The algorithm the body was validated with.
122        algorithm: ResponseChecksumAlgorithm,
123        /// The checksum from the response header, in base64.
124        expected: String,
125        /// The checksum computed from the body, in base64.
126        computed: String,
127    },
128    /// The body was not validated.
129    NotValidated {
130        /// Why the body was not validated.
131        reason: NotValidatedReason,
132    },
133    /// Validation started, but the body did not reach its end.
134    Incomplete {
135        /// The algorithm the body was being validated with.
136        algorithm: ResponseChecksumAlgorithm,
137        /// Why the body did not reach its end.
138        cause: IncompleteCause,
139    },
140}
141
142/// Why a response body was not validated.
143#[derive(Clone, Copy, Debug, PartialEq, Eq)]
144#[non_exhaustive]
145pub enum NotValidatedReason {
146    /// The request did not enable checksum mode, and the client's `response_checksum_validation`
147    /// is `WhenRequired`.
148    Disabled,
149    /// The response has no checksum header for an algorithm the operation lists.
150    NoChecksum,
151    /// The checksum header holds a part-level value, which ends in `-N`.
152    PartLevelChecksum,
153    /// The checksum header is present but is not valid base64.
154    InvalidChecksumHeader,
155    /// The response's only checksum headers are for algorithms the client does not compute.
156    UnsupportedAlgorithm,
157    /// The response's status is not 2xx, such as a 404 or a 503. Its body is never validated.
158    ErrorResponse,
159    /// The call succeeded, but nothing decided whether to validate its response, for example
160    /// because the operation does not validate response checksums.
161    NotApplicable,
162    /// The call failed or was cancelled before a response was validated.
163    NoResponse,
164    /// The handle was not attached to a call that ran.
165    NotInstalled,
166    /// The handle was attached to more than one call.
167    Reused,
168    /// A reason this release does not know, reported by a newer `aws-smithy-runtime-api`.
169    Other,
170}
171
172/// Why validation did not reach the end of the body.
173#[derive(Clone, Copy, Debug, PartialEq, Eq)]
174#[non_exhaustive]
175pub enum IncompleteCause {
176    /// The body was dropped before its end.
177    BodyDropped,
178    /// Reading the body failed before its end.
179    BodyError,
180}
181
182/// A response checksum algorithm.
183#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
184#[non_exhaustive]
185pub enum ResponseChecksumAlgorithm {
186    /// CRC32.
187    Crc32,
188    /// CRC32C.
189    Crc32c,
190    /// CRC64NVME.
191    Crc64Nvme,
192    /// SHA-1.
193    Sha1,
194    /// SHA-256.
195    Sha256,
196    /// An algorithm this release does not know. Read its name with
197    /// [`as_str`](ResponseChecksumAlgorithm::as_str).
198    Unknown(UnknownAlgorithm),
199}
200
201/// The name of an algorithm that this release does not know.
202#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
203pub struct UnknownAlgorithm(&'static str);
204
205impl ResponseChecksumAlgorithm {
206    /// The algorithm's lowercase name, such as `"crc32"`.
207    pub fn as_str(&self) -> &'static str {
208        match self {
209            Self::Crc32 => "crc32",
210            Self::Crc32c => "crc32c",
211            Self::Crc64Nvme => "crc64nvme",
212            Self::Sha1 => "sha1",
213            Self::Sha256 => "sha256",
214            Self::Unknown(UnknownAlgorithm(name)) => name,
215        }
216    }
217
218    fn from_name(name: &'static str) -> Self {
219        match name {
220            "crc32" => Self::Crc32,
221            "crc32c" => Self::Crc32c,
222            "crc64nvme" => Self::Crc64Nvme,
223            "sha1" => Self::Sha1,
224            "sha256" => Self::Sha256,
225            other => Self::Unknown(UnknownAlgorithm(other)),
226        }
227    }
228}
229
230/// A handle's record. It changes only through these methods, under the handle's lock.
231#[derive(Debug, Default)]
232struct ChecksumSlot {
233    status: Status,
234}
235
236#[derive(Debug, Default)]
237enum Status {
238    /// Not attached to a call that ran.
239    #[default]
240    NotInstalled,
241    /// Attached to a call whose outcome is not final yet.
242    Running(Run),
243    Complete(ChecksumOutcome),
244}
245
246#[derive(Debug, Default)]
247struct Run {
248    /// What the producer decided for the latest attempt. Each attempt clears it, so the latest
249    /// attempt wins even when it never reaches the checksum decision.
250    decision: Option<Decision>,
251    /// Whether the call succeeded, once it has ended.
252    call_succeeded: Option<bool>,
253}
254
255#[derive(Debug)]
256enum Decision {
257    NotValidated(NotValidatedReason),
258    Validating {
259        algorithm: ResponseChecksumAlgorithm,
260        ending: Option<Ending>,
261    },
262}
263
264/// How a validated body ended.
265#[derive(Debug)]
266enum Ending {
267    Dropped,
268    Errored,
269    Matched { computed: String },
270    Mismatched { expected: String, computed: String },
271}
272
273impl Ending {
274    /// `SdkBody::map` wraps each rebuilt body, so one attempt's body can end more than once. The
275    /// strongest ending is kept, so a late drop never hides a mismatch.
276    fn strength(&self) -> u8 {
277        match self {
278            Self::Dropped => 0,
279            Self::Errored => 1,
280            Self::Matched { .. } => 2,
281            Self::Mismatched { .. } => 3,
282        }
283    }
284
285    fn outcome(&self, algorithm: ResponseChecksumAlgorithm) -> ChecksumOutcome {
286        match self {
287            Self::Dropped => ChecksumOutcome::Incomplete {
288                algorithm,
289                cause: IncompleteCause::BodyDropped,
290            },
291            Self::Errored => ChecksumOutcome::Incomplete {
292                algorithm,
293                cause: IncompleteCause::BodyError,
294            },
295            Self::Matched { computed } => ChecksumOutcome::Validated {
296                algorithm,
297                computed: computed.clone(),
298            },
299            Self::Mismatched { expected, computed } => ChecksumOutcome::Mismatch {
300                algorithm,
301                expected: expected.clone(),
302                computed: computed.clone(),
303            },
304        }
305    }
306}
307
308impl ChecksumSlot {
309    fn state(&self) -> ChecksumState {
310        match &self.status {
311            Status::NotInstalled => ChecksumState::NotInstalled,
312            Status::Running(Run {
313                decision: Some(Decision::Validating { algorithm, .. }),
314                ..
315            }) => ChecksumState::Validating {
316                algorithm: *algorithm,
317            },
318            Status::Running(_) => ChecksumState::AwaitingResponse,
319            Status::Complete(outcome) => ChecksumState::Complete(outcome.clone()),
320        }
321    }
322
323    /// Attaches the handle to a call that is starting. Returns `false` if the handle already
324    /// recorded another call.
325    fn bind(&mut self) -> bool {
326        match &self.status {
327            Status::NotInstalled
328            | Status::Complete(ChecksumOutcome::NotValidated {
329                reason: NotValidatedReason::NotInstalled,
330            }) => {
331                self.status = Status::Running(Run::default());
332                true
333            }
334            Status::Complete(ChecksumOutcome::NotValidated {
335                reason: NotValidatedReason::Reused,
336            }) => false,
337            _ => {
338                tracing::warn!(
339                    "a ChecksumCapture was attached to a second call, so it now reads \
340                     NotValidated {{ reason: Reused }}; attach a new ChecksumCapture to each call"
341                );
342                self.status = Status::Complete(ChecksumOutcome::NotValidated {
343                    reason: NotValidatedReason::Reused,
344                });
345                false
346            }
347        }
348    }
349
350    fn capture_dropped(&mut self) {
351        if matches!(self.status, Status::NotInstalled) {
352            self.status = Status::Complete(ChecksumOutcome::NotValidated {
353                reason: NotValidatedReason::NotInstalled,
354            });
355        }
356    }
357
358    fn attempt_started(&mut self) {
359        if let Status::Running(run) = &mut self.status {
360            run.decision = None;
361        }
362    }
363
364    fn validating(&mut self, algorithm: ResponseChecksumAlgorithm) {
365        if let Status::Running(run) = &mut self.status {
366            run.decision = Some(Decision::Validating {
367                algorithm,
368                ending: None,
369            });
370        }
371    }
372
373    fn not_validated(&mut self, reason: NotValidatedReason) {
374        if let Status::Running(run) = &mut self.status {
375            run.decision = Some(Decision::NotValidated(reason));
376        }
377    }
378
379    fn ended(&mut self, new: Ending) {
380        if let Status::Running(Run {
381            decision: Some(Decision::Validating { ending, .. }),
382            ..
383        }) = &mut self.status
384        {
385            if ending
386                .as_ref()
387                .is_none_or(|old| new.strength() > old.strength())
388            {
389                *ending = Some(new);
390            }
391            self.complete_if_final();
392        }
393    }
394
395    fn call_ended(&mut self, succeeded: bool) {
396        if let Status::Running(run) = &mut self.status {
397            // The finalizers report first, and the config bag's guard reports again when it drops.
398            run.call_succeeded.get_or_insert(succeeded);
399        }
400        self.complete_if_final();
401    }
402
403    /// The outcome is final once the call has ended and, if the latest attempt's body is being
404    /// validated, once that body has ended too.
405    fn complete_if_final(&mut self) {
406        let Status::Running(Run {
407            decision,
408            call_succeeded: Some(succeeded),
409        }) = &self.status
410        else {
411            return;
412        };
413        let outcome = match decision {
414            None if *succeeded => ChecksumOutcome::NotValidated {
415                reason: NotValidatedReason::NotApplicable,
416            },
417            None => ChecksumOutcome::NotValidated {
418                reason: NotValidatedReason::NoResponse,
419            },
420            Some(Decision::NotValidated(reason)) => {
421                ChecksumOutcome::NotValidated { reason: *reason }
422            }
423            Some(Decision::Validating { ending: None, .. }) => return,
424            Some(Decision::Validating {
425                algorithm,
426                ending: Some(ending),
427            }) => ending.outcome(*algorithm),
428        };
429        self.status = Status::Complete(outcome);
430    }
431}
432
433/// Locks a record. A record is never left half-updated, so a poisoned lock is still usable.
434fn lock(slot: &Mutex<ChecksumSlot>) -> MutexGuard<'_, ChecksumSlot> {
435    slot.lock().unwrap_or_else(PoisonError::into_inner)
436}
437
438/// Feeds the producer's events into one handle's record.
439#[derive(Debug)]
440struct SlotObserver(Arc<Mutex<ChecksumSlot>>);
441
442impl ObserveResponseChecksum for SlotObserver {
443    fn on_event(&self, event: &ChecksumEvent<'_>) {
444        let mut slot = lock(&self.0);
445        match event.kind() {
446            ChecksumEventKind::Validating(data) => {
447                slot.validating(ResponseChecksumAlgorithm::from_name(data.algorithm()))
448            }
449            ChecksumEventKind::NotValidated(data) => {
450                slot.not_validated(not_validated_reason(data.reason()))
451            }
452            ChecksumEventKind::Matched(data) => slot.ended(Ending::Matched {
453                computed: data.computed().to_owned(),
454            }),
455            ChecksumEventKind::Mismatched(data) => slot.ended(Ending::Mismatched {
456                expected: data.expected().to_owned(),
457                computed: data.computed().to_owned(),
458            }),
459            ChecksumEventKind::Errored => slot.ended(Ending::Errored),
460            ChecksumEventKind::Dropped => slot.ended(Ending::Dropped),
461            // A kind added by a later aws-smithy-runtime-api. Only `Matched` makes the record
462            // read `Validated`, so ignoring it never reports a match.
463            _ => {}
464        }
465    }
466}
467
468fn not_validated_reason(skip: ChecksumSkip) -> NotValidatedReason {
469    match skip {
470        ChecksumSkip::Disabled => NotValidatedReason::Disabled,
471        ChecksumSkip::NoChecksum => NotValidatedReason::NoChecksum,
472        ChecksumSkip::PartLevelChecksum => NotValidatedReason::PartLevelChecksum,
473        ChecksumSkip::InvalidChecksumHeader => NotValidatedReason::InvalidChecksumHeader,
474        ChecksumSkip::UnsupportedAlgorithm => NotValidatedReason::UnsupportedAlgorithm,
475        ChecksumSkip::ErrorResponse => NotValidatedReason::ErrorResponse,
476        // A reason added by a later aws-smithy-runtime-api.
477        _ => NotValidatedReason::Other,
478    }
479}
480
481/// Ends a handle's call when the call's config bag is dropped, which covers a call that is
482/// cancelled before its finalizers run.
483#[derive(Debug)]
484struct CompleteOnDrop(Arc<Mutex<ChecksumSlot>>);
485
486impl Drop for CompleteOnDrop {
487    fn drop(&mut self) {
488        lock(&self.0).call_ended(false);
489    }
490}
491
492impl Storable for CompleteOnDrop {
493    type Storer = StoreAppend<Self>;
494}
495
496#[cfg(test)]
497mod tests {
498    use super::*;
499    use aws_smithy_runtime_api::client::interceptors::context::{
500        Input, InterceptorContext, Output,
501    };
502    use aws_smithy_runtime_api::client::interceptors::Intercept;
503    use aws_smithy_runtime_api::client::orchestrator::OrchestratorError;
504    use aws_smithy_runtime_api::client::runtime_components::RuntimeComponentsBuilder;
505    use aws_smithy_runtime_api::client::unit_of_work::checksums::{
506        Match, Mismatch, NotValidated, Validating,
507    };
508    use ResponseChecksumAlgorithm::Crc32;
509
510    /// One call to a generated client, with its hooks run the way the orchestrator runs them.
511    struct Call {
512        context: InterceptorContext,
513        cfg: ConfigBag,
514    }
515
516    impl Call {
517        fn start(captures: &[&Capture]) -> Self {
518            let mut call = Self {
519                context: InterceptorContext::new(Input::doesnt_matter()),
520                cfg: ConfigBag::base(),
521            };
522            for capture in captures {
523                capture
524                    .read_before_execution(&(&call.context).into(), &mut call.cfg)
525                    .unwrap();
526            }
527            call
528        }
529
530        fn attempt(&mut self, captures: &[&Capture]) {
531            let components = RuntimeComponentsBuilder::for_tests().build().unwrap();
532            for capture in captures {
533                capture
534                    .read_before_attempt(&(&self.context).into(), &components, &mut self.cfg)
535                    .unwrap();
536            }
537        }
538
539        /// The observers the SDK's response-checksum producer finds in this call's config bag.
540        fn observers(&self) -> Vec<SharedResponseChecksumObserver> {
541            self.cfg
542                .load::<SharedResponseChecksumObserver>()
543                .cloned()
544                .collect()
545        }
546
547        /// Reports a validator, as the producer does, and returns the observers that the
548        /// body's completion callback holds.
549        fn validating(&self, algorithm: &'static str) -> Vec<SharedResponseChecksumObserver> {
550            let observers = self.observers();
551            send(
552                &observers,
553                ChecksumEventKind::Validating(Validating::new(algorithm)),
554            );
555            observers
556        }
557
558        fn not_validated(&self, skip: ChecksumSkip) {
559            send(
560                &self.observers(),
561                ChecksumEventKind::NotValidated(NotValidated::new(skip)),
562            );
563        }
564
565        fn end(&mut self, captures: &[&Capture], succeeded: bool) {
566            let components = RuntimeComponentsBuilder::for_tests().build().unwrap();
567            self.context.set_output_or_error(if succeeded {
568                Ok(Output::doesnt_matter())
569            } else {
570                Err(OrchestratorError::other("the call failed"))
571            });
572            for capture in captures {
573                capture
574                    .read_after_execution(&(&self.context).into(), &components, &mut self.cfg)
575                    .unwrap();
576            }
577        }
578    }
579
580    /// How a test body ends.
581    #[derive(Clone, Copy, Debug)]
582    enum End {
583        Drop,
584        Error,
585        Match,
586        Mismatch,
587    }
588
589    impl End {
590        fn report(self, body: &[SharedResponseChecksumObserver]) {
591            let kind = match self {
592                End::Drop => ChecksumEventKind::Dropped,
593                End::Error => ChecksumEventKind::Errored,
594                End::Match => ChecksumEventKind::Matched(Match::new("computed==")),
595                End::Mismatch => {
596                    ChecksumEventKind::Mismatched(Mismatch::new("expected==", "computed=="))
597                }
598            };
599            send(body, kind);
600        }
601    }
602
603    /// Sends one event to every observer, as the SDK's response-checksum producer does.
604    fn send(observers: &[SharedResponseChecksumObserver], kind: ChecksumEventKind<'_>) {
605        let event = ChecksumEvent::new(1, kind);
606        observers.iter().for_each(|o| o.on_event(&event));
607    }
608
609    fn handle_and_capture() -> (ChecksumCapture, Capture) {
610        let checksum = ChecksumCapture::new();
611        let capture = Capture::new().with(&checksum);
612        (checksum, capture)
613    }
614
615    fn not_validated(reason: NotValidatedReason) -> Option<ChecksumOutcome> {
616        Some(ChecksumOutcome::NotValidated { reason })
617    }
618
619    fn validated() -> Option<ChecksumOutcome> {
620        Some(ChecksumOutcome::Validated {
621            algorithm: Crc32,
622            computed: "computed==".into(),
623        })
624    }
625
626    fn mismatch() -> Option<ChecksumOutcome> {
627        Some(ChecksumOutcome::Mismatch {
628            algorithm: Crc32,
629            expected: "expected==".into(),
630            computed: "computed==".into(),
631        })
632    }
633
634    #[test]
635    fn a_handle_reads_not_installed_until_its_call_starts() {
636        let (checksum, capture) = handle_and_capture();
637        assert_eq!(checksum.state(), ChecksumState::NotInstalled);
638        assert_eq!(checksum.try_outcome(), None);
639
640        let _call = Call::start(&[&capture]);
641        assert_eq!(checksum.state(), ChecksumState::AwaitingResponse);
642    }
643
644    #[test]
645    fn a_capture_dropped_before_its_call_runs_reads_not_installed() {
646        let (checksum, capture) = handle_and_capture();
647        drop(capture);
648        assert_eq!(
649            checksum.try_outcome(),
650            not_validated(NotValidatedReason::NotInstalled)
651        );
652
653        // The handle never recorded a call, so a later call can still use it.
654        let capture = Capture::new().with(&checksum);
655        let mut call = Call::start(&[&capture]);
656        call.end(&[&capture], true);
657        assert_eq!(
658            checksum.try_outcome(),
659            not_validated(NotValidatedReason::NotApplicable)
660        );
661    }
662
663    #[test]
664    fn a_streamed_body_completes_the_outcome_after_the_call_returns() {
665        let (checksum, capture) = handle_and_capture();
666        let mut call = Call::start(&[&capture]);
667        call.attempt(&[&capture]);
668        let body = call.validating("crc32");
669        assert_eq!(
670            checksum.state(),
671            ChecksumState::Validating { algorithm: Crc32 }
672        );
673
674        // The call returns, and its config bag drops, before the body is read.
675        call.end(&[&capture], true);
676        drop(call);
677        assert_eq!(checksum.try_outcome(), None);
678
679        End::Match.report(&body);
680        assert_eq!(checksum.try_outcome(), validated());
681    }
682
683    #[test]
684    fn a_body_read_inside_the_call_completes_the_outcome_when_the_call_ends() {
685        let (checksum, capture) = handle_and_capture();
686        let mut call = Call::start(&[&capture]);
687        call.attempt(&[&capture]);
688        End::Match.report(&call.validating("crc32"));
689        // Another attempt could still replace this one.
690        assert_eq!(checksum.try_outcome(), None);
691
692        call.end(&[&capture], true);
693        assert_eq!(checksum.try_outcome(), validated());
694    }
695
696    #[test]
697    fn a_mismatch_is_recorded_as_soon_as_the_body_reports_it() {
698        let (checksum, capture) = handle_and_capture();
699        let mut call = Call::start(&[&capture]);
700        call.attempt(&[&capture]);
701        let body = call.validating("crc32");
702        call.end(&[&capture], true);
703
704        // The body reports the mismatch just before it yields its error.
705        End::Mismatch.report(&body);
706        assert_eq!(checksum.try_outcome(), mismatch());
707    }
708
709    #[test]
710    fn a_body_that_stops_short_reads_incomplete() {
711        for (end, cause) in [
712            (End::Error, IncompleteCause::BodyError),
713            (End::Drop, IncompleteCause::BodyDropped),
714        ] {
715            let (checksum, capture) = handle_and_capture();
716            let mut call = Call::start(&[&capture]);
717            call.attempt(&[&capture]);
718            let body = call.validating("crc32");
719            call.end(&[&capture], true);
720
721            end.report(&body);
722            assert_eq!(
723                checksum.try_outcome(),
724                Some(ChecksumOutcome::Incomplete {
725                    algorithm: Crc32,
726                    cause
727                }),
728                "{end:?}"
729            );
730        }
731    }
732
733    #[test]
734    fn the_strongest_ending_of_an_attempt_wins() {
735        let body_error = Some(ChecksumOutcome::Incomplete {
736            algorithm: Crc32,
737            cause: IncompleteCause::BodyError,
738        });
739        for (ends, expected) in [
740            ([End::Match, End::Drop], validated()),
741            ([End::Drop, End::Match], validated()),
742            ([End::Error, End::Match], validated()),
743            ([End::Match, End::Mismatch], mismatch()),
744            ([End::Mismatch, End::Match], mismatch()),
745            ([End::Drop, End::Error], body_error),
746        ] {
747            let (checksum, capture) = handle_and_capture();
748            let mut call = Call::start(&[&capture]);
749            call.attempt(&[&capture]);
750            let body = call.validating("crc32");
751            ends.iter().for_each(|end| end.report(&body));
752
753            call.end(&[&capture], true);
754            assert_eq!(checksum.try_outcome(), expected, "{ends:?}");
755        }
756    }
757
758    #[test]
759    fn each_skip_reason_reads_as_its_not_validated_reason() {
760        for (skip, reason) in [
761            (ChecksumSkip::Disabled, NotValidatedReason::Disabled),
762            (ChecksumSkip::NoChecksum, NotValidatedReason::NoChecksum),
763            (
764                ChecksumSkip::PartLevelChecksum,
765                NotValidatedReason::PartLevelChecksum,
766            ),
767            (
768                ChecksumSkip::InvalidChecksumHeader,
769                NotValidatedReason::InvalidChecksumHeader,
770            ),
771            (
772                ChecksumSkip::UnsupportedAlgorithm,
773                NotValidatedReason::UnsupportedAlgorithm,
774            ),
775            (
776                ChecksumSkip::ErrorResponse,
777                NotValidatedReason::ErrorResponse,
778            ),
779        ] {
780            let (checksum, capture) = handle_and_capture();
781            let mut call = Call::start(&[&capture]);
782            call.attempt(&[&capture]);
783            call.not_validated(skip);
784
785            call.end(&[&capture], true);
786            assert_eq!(checksum.try_outcome(), not_validated(reason), "{skip:?}");
787        }
788    }
789
790    #[test]
791    fn a_call_without_a_checksum_decision_reads_not_applicable_or_no_response() {
792        for (succeeded, reason) in [
793            (true, NotValidatedReason::NotApplicable),
794            (false, NotValidatedReason::NoResponse),
795        ] {
796            let (checksum, capture) = handle_and_capture();
797            let mut call = Call::start(&[&capture]);
798            call.attempt(&[&capture]);
799
800            call.end(&[&capture], succeeded);
801            assert_eq!(checksum.try_outcome(), not_validated(reason));
802        }
803    }
804
805    #[test]
806    fn the_latest_attempt_wins() {
807        // A mismatched attempt, then an attempt that never connects.
808        let (checksum, capture) = handle_and_capture();
809        let mut call = Call::start(&[&capture]);
810        call.attempt(&[&capture]);
811        End::Mismatch.report(&call.validating("crc32"));
812        call.attempt(&[&capture]);
813        call.end(&[&capture], false);
814        assert_eq!(
815            checksum.try_outcome(),
816            not_validated(NotValidatedReason::NoResponse)
817        );
818
819        // A mismatched attempt, then one that validates.
820        let (checksum, capture) = handle_and_capture();
821        let mut call = Call::start(&[&capture]);
822        call.attempt(&[&capture]);
823        End::Mismatch.report(&call.validating("crc32"));
824        call.attempt(&[&capture]);
825        End::Match.report(&call.validating("crc32"));
826        call.end(&[&capture], true);
827        assert_eq!(checksum.try_outcome(), validated());
828    }
829
830    #[test]
831    fn a_dropped_call_reads_no_response_right_away() {
832        let (checksum, capture) = handle_and_capture();
833        let mut call = Call::start(&[&capture]);
834        call.attempt(&[&capture]);
835
836        drop(call);
837        assert_eq!(
838            checksum.try_outcome(),
839            not_validated(NotValidatedReason::NoResponse)
840        );
841    }
842
843    #[test]
844    fn two_captures_on_one_call_each_record_it() {
845        let (first, first_capture) = handle_and_capture();
846        let (second, second_capture) = handle_and_capture();
847        let captures = [&first_capture, &second_capture];
848        let mut call = Call::start(&captures);
849        call.attempt(&captures);
850        let body = call.validating("crc32");
851        assert_eq!(body.len(), 2, "each capture appends its own observer");
852
853        // Dropping the bag drops both guards; neither may end its handle's call again.
854        call.end(&captures, true);
855        drop(call);
856        End::Match.report(&body);
857        for checksum in [first, second] {
858            assert_eq!(checksum.try_outcome(), validated());
859        }
860    }
861
862    #[test]
863    fn one_capture_with_two_handles_records_the_call_in_each() {
864        let (first, second) = (ChecksumCapture::new(), ChecksumCapture::new());
865        let capture = Capture::new().with(&first).with(&second);
866        let mut call = Call::start(&[&capture]);
867        call.attempt(&[&capture]);
868        let body = call.validating("crc32");
869        assert_eq!(body.len(), 2, "each handle appends its own observer");
870
871        call.end(&[&capture], true);
872        End::Match.report(&body);
873        for checksum in [first, second] {
874            assert_eq!(checksum.try_outcome(), validated());
875        }
876    }
877
878    #[test]
879    fn a_handle_carried_twice_into_one_call_records_it_once() {
880        let setups: [fn(&ChecksumCapture) -> Vec<Capture>; 2] = [
881            |c| vec![Capture::new().with(c).with(c)],
882            |c| vec![Capture::new().with(c), Capture::new().with(c)],
883        ];
884        for setup in setups {
885            let checksum = ChecksumCapture::new();
886            let captures = setup(&checksum);
887            let captures: Vec<&Capture> = captures.iter().collect();
888            let mut call = Call::start(&captures);
889            call.attempt(&captures);
890            let body = call.validating("crc32");
891            assert_eq!(body.len(), 1, "the handle registers one observer");
892
893            call.end(&captures, true);
894            End::Match.report(&body);
895            assert_eq!(checksum.try_outcome(), validated());
896        }
897    }
898
899    #[test]
900    fn a_handle_attached_to_a_second_call_reads_reused() {
901        // A capture installed on the client runs for every call.
902        let (checksum, capture) = handle_and_capture();
903        let mut first = Call::start(&[&capture]);
904        first.attempt(&[&capture]);
905        let body = first.validating("crc32");
906
907        let second = Call::start(&[&capture]);
908        assert!(second.observers().is_empty());
909        assert_eq!(
910            checksum.try_outcome(),
911            not_validated(NotValidatedReason::Reused)
912        );
913
914        // The first call's result never becomes the handle's outcome.
915        first.end(&[&capture], true);
916        End::Match.report(&body);
917        assert_eq!(
918            checksum.try_outcome(),
919            not_validated(NotValidatedReason::Reused)
920        );
921    }
922
923    #[test]
924    fn every_algorithm_the_sdk_validates_has_a_variant() {
925        for name in aws_smithy_checksums::http::CHECKSUM_ALGORITHMS_IN_PRIORITY_ORDER {
926            let sdk_name = name
927                .parse::<aws_smithy_checksums::ChecksumAlgorithm>()
928                .unwrap()
929                .as_str();
930            let algorithm = ResponseChecksumAlgorithm::from_name(sdk_name);
931            assert!(
932                !matches!(algorithm, ResponseChecksumAlgorithm::Unknown(_)),
933                "{sdk_name} has no variant"
934            );
935            assert_eq!(algorithm.as_str(), sdk_name);
936        }
937    }
938
939    #[test]
940    fn an_algorithm_this_release_does_not_know_keeps_its_name() {
941        let algorithm = ResponseChecksumAlgorithm::from_name("xxhash64");
942        assert!(matches!(algorithm, ResponseChecksumAlgorithm::Unknown(_)));
943        assert_eq!(algorithm.as_str(), "xxhash64");
944    }
945}