Skip to content

Commit 0d00b78

Browse files
committed
chore: remove magic numbers
1 parent d82769a commit 0d00b78

1 file changed

Lines changed: 10 additions & 7 deletions

File tree

app/src/main/java/to/bitkit/repositories/LightningRepo.kt

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -60,13 +60,16 @@ import javax.inject.Inject
6060
import javax.inject.Singleton
6161
import kotlin.math.min
6262
import kotlin.math.pow
63+
import kotlin.random.Random
6364
import kotlin.time.Duration
6465
import kotlin.time.Duration.Companion.minutes
6566
import kotlin.time.Duration.Companion.seconds
6667

6768
private const val SYNC_TIMEOUT_MS = 10_000L
6869
private const val MAX_RETRY_ATTEMPTS = 5
6970
private const val INITIAL_RETRY_DELAY_MS = 1000L
71+
private const val MAX_DELAY_MS = 30_000L
72+
private const val JITTER_PERCENTAGE = 0.25
7073

7174
@Singleton
7275
@Suppress("LongParameterList", "LargeClass", "TooManyFunctions")
@@ -204,7 +207,7 @@ class LightningRepo @Inject constructor(
204207
context = TAG
205208
)
206209

207-
val retryDelay = calculateRetryDelay(retryAttempt)
210+
val retryDelay = calculateRetryDelayWithJitter(retryAttempt)
208211
delay(retryDelay)
209212

210213
return@withContext start(
@@ -271,7 +274,7 @@ class LightningRepo @Inject constructor(
271274

272275
_lightningState.update { it.copy(nodeLifecycleState = initialLifecycleState) }
273276

274-
val retryDelay = calculateRetryDelay(retryAttempt)
277+
val retryDelay = calculateRetryDelayWithJitter(retryAttempt)
275278
delay(retryDelay)
276279

277280
return@withContext start(
@@ -313,14 +316,14 @@ class LightningRepo @Inject constructor(
313316
/**
314317
* Calculates retry delay with exponential backoff and jitter
315318
*/
316-
private fun calculateRetryDelay(retryAttempt: Int): Long {
319+
private fun calculateRetryDelayWithJitter(retryAttempt: Int): Long {
317320
val baseDelay = INITIAL_RETRY_DELAY_MS
318321
val exponentialDelay = baseDelay * 2.0.pow(retryAttempt.toDouble()).toLong()
319-
val maxDelay = 30_000L // 30 seconds max
320-
val delayWithCap = min(exponentialDelay, maxDelay)
322+
val delayWithCap = min(exponentialDelay, MAX_DELAY_MS)
323+
324+
val maxJitter = (delayWithCap * JITTER_PERCENTAGE).toLong()
325+
val jitter = Random.nextLong(-maxJitter, maxJitter + 1)
321326

322-
// Add jitter (±25% of the delay)
323-
val jitter = (delayWithCap * 0.25 * (Math.random() - 0.5)).toLong()
324327
return delayWithCap + jitter
325328
}
326329

0 commit comments

Comments
 (0)