Skip to content
Open
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
11 changes: 9 additions & 2 deletions java/src/main/java/org/opensky/api/OpenSkyApi.java
Original file line number Diff line number Diff line change
Expand Up @@ -136,8 +136,15 @@ private OpenSkyStates getResponse(String baseUri, Collection<AbstractMap.Entry<S
private boolean checkRateLimit(REQUEST_TYPE type, long timeDiffAuth, long timeDiffNoAuth) {
Long t = lastRequestTime.get(type);
long now = System.currentTimeMillis();
lastRequestTime.put(type, now);
return (t == null || (authenticated && now - t > timeDiffAuth) || (!authenticated && now - t > timeDiffNoAuth));
boolean mayIssueRequest = t == null
|| (authenticated && now - t > timeDiffAuth)
|| (!authenticated && now - t > timeDiffNoAuth);
if (mayIssueRequest) {
// Optimistically update the last request time if the client can actually issue a request. If the request
// fails, we don't want to immediately retry anyway
lastRequestTime.put(type, now);
}
return mayIssueRequest;
}

/**
Expand Down
27 changes: 27 additions & 0 deletions java/src/test/java/TestOpenSkyApi.java
Original file line number Diff line number Diff line change
Expand Up @@ -153,4 +153,31 @@ public void testAuthGetMyStates() throws IOException {
}
}

@Test
public void testClientSideRateLimitingDoesNotLockClient() throws IOException, InterruptedException {
// If the client is requesting too fast, ensure it doesn't prevent requests from occurring after the
// rate limiting expires
OpenSkyApi api = new OpenSkyApi();
OpenSkyStates os = api.getStates(0, null);
assertTrue("More than 1 state vector", os.getStates().size() > 1);
int initialTime = os.getTime();

// Simulate frequently-requesting client
long startTime = System.currentTimeMillis();
while (startTime + 8000L > System.currentTimeMillis()) {
OpenSkyStates states = api.getStates(0, null);
assertNull("Client-side rate limited, should not receive data", states);
Thread.sleep(100L);
}

// Wait a few more seconds (but less than anon rate limit frequency)
Thread.sleep(5000L);

// It's been ~13s since our initial request, we should be able to request again as an anonymous caller
os = api.getStates(0, null);
assertNotNull(os);
assertTrue("More than 1 state vector for second valid request", os.getStates().size() > 1);
assertNotEquals("Second request should be different", initialTime, os.getTime());
}

}