From 42c2d2f3872323f2435891ea88612740627b73c2 Mon Sep 17 00:00:00 2001 From: Graham Christensen Date: Thu, 26 Aug 2021 12:54:38 -0400 Subject: [PATCH] Hydra::Math: add an exponential_backoff function --- src/lib/Hydra/Math.pm | 30 ++++++++++++++++++++++++++++++ t/Math.t | 19 +++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 src/lib/Hydra/Math.pm create mode 100644 t/Math.t diff --git a/src/lib/Hydra/Math.pm b/src/lib/Hydra/Math.pm new file mode 100644 index 00000000..40c7f335 --- /dev/null +++ b/src/lib/Hydra/Math.pm @@ -0,0 +1,30 @@ +package Hydra::Math; + +use strict; +use warnings; +use List::Util qw(min); +use Exporter 'import'; +our @EXPORT_OK = qw(exponential_backoff); + +=head2 exponential_backoff + +Calculates a number of seconds to wait before reattempting something. + +Arguments: + +=over 1 + +=item C<$attempts> + +Integer number of attempts made. + +=back + +=cut +sub exponential_backoff { + my ($attempt) = @_; + my $clamp = min(10, $attempt); + return 2 ** $clamp; +} + +1; diff --git a/t/Math.t b/t/Math.t new file mode 100644 index 00000000..a9a49b6f --- /dev/null +++ b/t/Math.t @@ -0,0 +1,19 @@ +use strict; +use warnings; +use Setup; + +use Hydra::Math qw(exponential_backoff); + +use Test2::V0; + +subtest "exponential_backoff" => sub { + is(exponential_backoff(0), 1); + is(exponential_backoff(1), 2); + is(exponential_backoff(2), 4); + is(exponential_backoff(9), 512); + is(exponential_backoff(10), 1024); + is(exponential_backoff(11), 1024, "we're clamped to 1024 seconds"); + is(exponential_backoff(11000), 1024, "we're clamped to 1024 seconds"); +}; + +done_testing;