Backoff.kt (1298B)
1 /* 2 * This file is part of LibEuFin. 3 * Copyright (C) 2023-2024 Taler Systems S.A. 4 5 * LibEuFin is free software; you can redistribute it and/or modify 6 * it under the terms of the GNU Affero General Public License as 7 * published by the Free Software Foundation; either version 3, or 8 * (at your option) any later version. 9 10 * LibEuFin is distributed in the hope that it will be useful, but 11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General 13 * Public License for more details. 14 15 * You should have received a copy of the GNU Affero General Public 16 * License along with LibEuFin; see the file COPYING. If not, see 17 * <http://www.gnu.org/licenses/> 18 */ 19 20 package tech.libeufin.common 21 22 import kotlin.random.Random 23 24 /** Infinite exponential backoff with decorrelated jitter */ 25 class ExpoBackoffDecorr( 26 private val base: Long = 100, // 0.1 second 27 private val max: Long = 60000, // 60 seconds 28 private val factor: Double = 2.0, 29 ) { 30 private var sleep: Long = base 31 32 fun next() : Long { 33 sleep = Random.nextDouble(base.toDouble(), sleep.toDouble() * factor) 34 .toLong().coerceAtMost(max) 35 return sleep 36 } 37 38 fun reset() { 39 sleep = base 40 } 41 }