Skip to content

Commit 128454e

Browse files
committed
refactor: helper and magic numbers
moves numbers used for backing off hours to constants and adds a helper to calculate backing off hours duration
1 parent 83fbf83 commit 128454e

1 file changed

Lines changed: 13 additions & 5 deletions

File tree

application/src/main/java/org/togetherjava/tjbot/features/rss/RSSHandlerRoutine.java

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,9 @@ private record FailureState(int count, ZonedDateTime lastFailure) {
9393
Caffeine.newBuilder().expireAfterWrite(7, TimeUnit.DAYS).maximumSize(500).build();
9494

9595
private static final int DEAD_RSS_FEED_FAILURE_THRESHOLD = 15;
96+
private static final double BACKOFF_BASE = 2.0;
97+
private static final double BACKOFF_EXPONENT_OFFSET = 1.0;
98+
private static final double MAX_BACKOFF_HOURS = 24.0;
9699

97100
/**
98101
* Constructs an RSSHandlerRoutine with the provided configuration and database.
@@ -430,11 +433,11 @@ private List<Item> fetchRSSItemsFromURL(String rssUrl) {
430433
}
431434
circuitBreaker.put(rssUrl, new FailureState(newCount, ZonedDateTime.now()));
432435

433-
long nextWait = (long) Math.min(Math.pow(2.0, newCount - 1.0), 24.0);
436+
long blacklistedHours = calculateWaitHours(newCount);
434437

435438
logger.warn(
436439
"RSS fetch failed for {} (Attempt #{}). Backing off for {} hours. Reason: {}",
437-
rssUrl, newCount, nextWait, e.getMessage(), e);
440+
rssUrl, newCount, blacklistedHours, e.getMessage(), e);
438441

439442
return List.of();
440443
}
@@ -458,12 +461,17 @@ private static ZonedDateTime getZonedDateTime(@Nullable String date, String form
458461
return ZonedDateTime.parse(date, DateTimeFormatter.ofPattern(format));
459462
}
460463

464+
private long calculateWaitHours(int failureCount) {
465+
return (long) Math.min(Math.pow(BACKOFF_BASE, failureCount - BACKOFF_EXPONENT_OFFSET),
466+
MAX_BACKOFF_HOURS);
467+
}
468+
461469
private boolean isBackingOff(String url) {
462470
FailureState state = circuitBreaker.getIfPresent(url);
463-
if (state == null) {
471+
if (state == null)
464472
return false;
465-
}
466-
long waitHours = (long) Math.min(Math.pow(2.0, state.count() - 1.0), 24.0);
473+
474+
long waitHours = calculateWaitHours(state.count());
467475
ZonedDateTime retryAt = state.lastFailure().plusHours(waitHours);
468476

469477
return ZonedDateTime.now().isBefore(retryAt);

0 commit comments

Comments
 (0)