1use 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#[derive(Clone, Debug, Default)]
24pub struct ChecksumCapture {
25 slot: Arc<Mutex<ChecksumSlot>>,
26}
27
28impl ChecksumCapture {
29 pub fn new() -> Self {
31 Self::default()
32 }
33
34 pub fn state(&self) -> ChecksumState {
36 self.lock().state()
37 }
38
39 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 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#[derive(Clone, Debug, PartialEq, Eq)]
93#[non_exhaustive]
94pub enum ChecksumState {
95 NotInstalled,
97 AwaitingResponse,
99 Validating {
101 algorithm: ResponseChecksumAlgorithm,
103 },
104 Complete(ChecksumOutcome),
106}
107
108#[derive(Clone, Debug, PartialEq, Eq)]
110#[non_exhaustive]
111pub enum ChecksumOutcome {
112 Validated {
114 algorithm: ResponseChecksumAlgorithm,
116 computed: String,
118 },
119 Mismatch {
121 algorithm: ResponseChecksumAlgorithm,
123 expected: String,
125 computed: String,
127 },
128 NotValidated {
130 reason: NotValidatedReason,
132 },
133 Incomplete {
135 algorithm: ResponseChecksumAlgorithm,
137 cause: IncompleteCause,
139 },
140}
141
142#[derive(Clone, Copy, Debug, PartialEq, Eq)]
144#[non_exhaustive]
145pub enum NotValidatedReason {
146 Disabled,
149 NoChecksum,
151 PartLevelChecksum,
153 InvalidChecksumHeader,
155 UnsupportedAlgorithm,
157 ErrorResponse,
159 NotApplicable,
162 NoResponse,
164 NotInstalled,
166 Reused,
168 Other,
170}
171
172#[derive(Clone, Copy, Debug, PartialEq, Eq)]
174#[non_exhaustive]
175pub enum IncompleteCause {
176 BodyDropped,
178 BodyError,
180}
181
182#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
184#[non_exhaustive]
185pub enum ResponseChecksumAlgorithm {
186 Crc32,
188 Crc32c,
190 Crc64Nvme,
192 Sha1,
194 Sha256,
196 Unknown(UnknownAlgorithm),
199}
200
201#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
203pub struct UnknownAlgorithm(&'static str);
204
205impl ResponseChecksumAlgorithm {
206 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#[derive(Debug, Default)]
232struct ChecksumSlot {
233 status: Status,
234}
235
236#[derive(Debug, Default)]
237enum Status {
238 #[default]
240 NotInstalled,
241 Running(Run),
243 Complete(ChecksumOutcome),
244}
245
246#[derive(Debug, Default)]
247struct Run {
248 decision: Option<Decision>,
251 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#[derive(Debug)]
266enum Ending {
267 Dropped,
268 Errored,
269 Matched { computed: String },
270 Mismatched { expected: String, computed: String },
271}
272
273impl Ending {
274 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 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 run.call_succeeded.get_or_insert(succeeded);
399 }
400 self.complete_if_final();
401 }
402
403 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
433fn lock(slot: &Mutex<ChecksumSlot>) -> MutexGuard<'_, ChecksumSlot> {
435 slot.lock().unwrap_or_else(PoisonError::into_inner)
436}
437
438#[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 _ => {}
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 _ => NotValidatedReason::Other,
478 }
479}
480
481#[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 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 fn observers(&self) -> Vec<SharedResponseChecksumObserver> {
541 self.cfg
542 .load::<SharedResponseChecksumObserver>()
543 .cloned()
544 .collect()
545 }
546
547 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 #[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 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 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 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 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 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 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 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 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 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 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}