about summary refs log tree commit diff
path: root/fun/clbot/backoffutil
diff options
context:
space:
mode:
Diffstat (limited to 'fun/clbot/backoffutil')
-rw-r--r--fun/clbot/backoffutil/backoffutil.go43
-rw-r--r--fun/clbot/backoffutil/default.nix14
2 files changed, 57 insertions, 0 deletions
diff --git a/fun/clbot/backoffutil/backoffutil.go b/fun/clbot/backoffutil/backoffutil.go
new file mode 100644
index 000000000000..1b1ea5f9d012
--- /dev/null
+++ b/fun/clbot/backoffutil/backoffutil.go
@@ -0,0 +1,43 @@
+// Package backoffutil provides useful utilities for backoff.
+package backoffutil
+
+import (
+	"time"
+
+	backoff "github.com/cenkalti/backoff/v4"
+)
+
+// ZeroStartingBackOff is a backoff.BackOff that returns "0" as the first Duration after a reset.
+// This is useful for constructing loops and just enforcing a backoff duration on every loop, rather than incorporating this logic into the loop directly.
+type ZeroStartingBackOff struct {
+	bo      backoff.BackOff
+	initial bool
+}
+
+// NewZeroStartingBackOff creates a new ZeroStartingBackOff.
+func NewZeroStartingBackOff(bo backoff.BackOff) *ZeroStartingBackOff {
+	return &ZeroStartingBackOff{bo: bo, initial: true}
+}
+
+// NewDefaultBackOff creates a sensibly configured BackOff that starts at zero.
+func NewDefaultBackOff() backoff.BackOff {
+	ebo := backoff.NewExponentialBackOff()
+	ebo.MaxElapsedTime = 0
+	return NewZeroStartingBackOff(ebo)
+}
+
+// NextBackOff returns the next back off duration to use.
+// For the first call after a call to Reset(), this is 0. For each subsequent duration, the underlying BackOff is consulted.
+func (bo *ZeroStartingBackOff) NextBackOff() time.Duration {
+	if bo.initial == true {
+		bo.initial = false
+		return 0
+	}
+	return bo.bo.NextBackOff()
+}
+
+// Reset resets to the initial state, and also passes a Reset through to the underlying BackOff.
+func (bo *ZeroStartingBackOff) Reset() {
+	bo.initial = true
+	bo.bo.Reset()
+}
diff --git a/fun/clbot/backoffutil/default.nix b/fun/clbot/backoffutil/default.nix
new file mode 100644
index 000000000000..78585da236e3
--- /dev/null
+++ b/fun/clbot/backoffutil/default.nix
@@ -0,0 +1,14 @@
+{ depot, ... }:
+
+let
+  inherit (depot.third_party) gopkgs;
+in
+depot.nix.buildGo.package {
+  name = "code.tvl.fyi/fun/clbot/backoffutil";
+  srcs = [
+    ./backoffutil.go
+  ];
+  deps = [
+    gopkgs."github.com".cenkalti.backoff.gopkg
+  ];
+}