Skip to content

Commit

Permalink
refactor: extract jitter to separate variable and fix test case naming
Browse files Browse the repository at this point in the history
  • Loading branch information
ewanharris committed Apr 26, 2024
1 parent c34968c commit f98569c
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 11 deletions.
5 changes: 4 additions & 1 deletion src/main/java/dev/openfga/sdk/api/auth/AccessToken.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@

class AccessToken {
private static final int TOKEN_EXPIRY_BUFFER_THRESHOLD_IN_SEC = 300;
private static final int TOKEN_EXPIRY_JITTER_IN_SEC =
300; // We add some jitter so that token refreshes are less likely to collide

private Instant expiresAt;

private final Random random = new Random();
Expand All @@ -39,7 +42,7 @@ public boolean isValid() {
// to account for multiple calls to `isValid` at the same time and prevent multiple refresh calls
Instant expiresWithLeeway = expiresAt
.minusSeconds(TOKEN_EXPIRY_BUFFER_THRESHOLD_IN_SEC)
.minusSeconds(random.nextInt(TOKEN_EXPIRY_BUFFER_THRESHOLD_IN_SEC))
.minusSeconds(random.nextInt(TOKEN_EXPIRY_JITTER_IN_SEC))
.truncatedTo(ChronoUnit.SECONDS);

return Instant.now().truncatedTo(ChronoUnit.SECONDS).isBefore(expiresWithLeeway);
Expand Down
16 changes: 6 additions & 10 deletions src/test/java/dev/openfga/sdk/api/auth/AccessTokenTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,26 +30,22 @@ private static Stream<Arguments> expTimeAndResults() {
"Expires in 15 minutes should be valid", Instant.now().plus(15, ChronoUnit.MINUTES), true),
Arguments.of("No expiry value should be valid", null, true),
Arguments.of(
"Expired 1 hour ago should not not be valid",
Instant.now().minus(1, ChronoUnit.HOURS),
false),
"Expired 1 hour ago should not be valid", Instant.now().minus(1, ChronoUnit.HOURS), false),
Arguments.of(
"Expired 10 minutes ago should not not be valid",
"Expired 10 minutes ago should not be valid",
Instant.now().minus(10, ChronoUnit.MINUTES),
false),
Arguments.of(
"Expired 5 minutes ago should not not be valid",
"Expired 5 minutes ago should not be valid",
Instant.now().minus(5, ChronoUnit.MINUTES),
false),
Arguments.of(
"Expires in 5 minutes should not not be valid",
"Expires in 5 minutes should not be valid",
Instant.now().plus(5, ChronoUnit.MINUTES),
false),
Arguments.of(
"Expires in 1 minute should not not be valid",
Instant.now().plus(1, ChronoUnit.MINUTES),
false),
Arguments.of("Expires now should not not be valid", Instant.now(), false));
"Expires in 1 minute should not be valid", Instant.now().plus(1, ChronoUnit.MINUTES), false),
Arguments.of("Expires now should not be valid", Instant.now(), false));
}

@MethodSource("expTimeAndResults")
Expand Down

0 comments on commit f98569c

Please sign in to comment.