Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,11 @@ private ResponseEntity<String> rateLimited(HttpServletRequest request) {
return null;
}
LOGGER.warn("rate limit hit by {} ({} writes/hour)", client, rateLimiter.maxWritesPerHour());
// Retry-After is when this client's window really ends, not a flat hour: a visitor who
// hit the limit 50 minutes into their window only has 10 minutes to wait.
long retryAfter = Math.max(1, rateLimiter.resetInSeconds(client));
return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS)
.header("Retry-After", "3600")
.header("Retry-After", String.valueOf(retryAfter))
.body("write limit reached: " + rateLimiter.maxWritesPerHour()
+ " writes per hour. This is a shared demo.");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,6 @@

import com.memcache.gateway.kv.WriteRateLimiter;

/**
* How many writes this client has left this hour, so the page shows the server's real count
* instead of guessing
*/
@RestController
@RequestMapping("/api")
public class QuotaController {
Expand All @@ -25,9 +21,10 @@ public QuotaController(WriteRateLimiter rateLimiter) {
}

@GetMapping("/quota")
public Map<String, Integer> quota(HttpServletRequest request) {
public Map<String, Long> quota(HttpServletRequest request) {
String client = request.getRemoteAddr();
return Map.of("remaining", rateLimiter.remaining(client),
"limit", rateLimiter.maxWritesPerHour());
return Map.of("remaining", (long) rateLimiter.remaining(client),
"limit", (long) rateLimiter.maxWritesPerHour(),
"resetInSeconds", rateLimiter.resetInSeconds(client));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,14 @@ public int remaining(String clientId) {
return Math.max(0, maxWritesPerHour - used);
}

public long resetInSeconds(String clientId) {
return writesPerClient.policy().expireAfterWrite()
.flatMap(window -> window.ageOf(clientId)
.map(age -> window.getExpiresAfter().minus(age)))
.map(left -> Math.max(0L, (left.toMillis() + 999) / 1000))
.orElse(0L);
}

public int maxWritesPerHour() {
return maxWritesPerHour;
}
Expand Down
Loading