Class ApiKeyLastUsedService
API key authentication is stateless: it happens on every single request. Writing the
lastUsedAt of the API key each time turns a read-only workload into one UPDATE plus one
commit per request and invalidates the cache regions of UserToken just as often.
The timestamp is therefore only refreshed once per INTERVAL, making it accurate to
within that interval. On top of that, a lease of LEASE_TIMEOUT keeps concurrent requests
sharing an API key from all refreshing it at once.
-
Field Summary
Fields -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionprotected booleanisOutdated(UserToken userToken, LocalDateTime now) Whether thelastUsedAtof the given token is outdated enough to be written again.voidsetLastUsed(UserToken userToken) Refreshes thelastUsedAtof the given token, unless it has been refreshed recently enough.protected booleantryAcquireLease(UserToken userToken) Tries to acquire the lease allowing to refresh thelastUsedAtof the given token.protected voidupdate(UserToken userToken, LocalDateTime lastUsedAt) Writes thelastUsedAtof the given token.
-
Field Details
-
INTERVAL
Duration during whichlastUsedAtis not refreshed again. -
LEASE_TIMEOUT
Duration of the lease acquired to refreshlastUsedAt.
-
-
Constructor Details
-
ApiKeyLastUsedService
public ApiKeyLastUsedService()
-
-
Method Details
-
setLastUsed
Refreshes thelastUsedAtof the given token, unless it has been refreshed recently enough.- Parameters:
userToken- the token being used
-
isOutdated
Whether thelastUsedAtof the given token is outdated enough to be written again.- Parameters:
userToken- the token being usednow- the current time- Returns:
trueiflastUsedAtis older than the interval
-
tryAcquireLease
Tries to acquire the lease allowing to refresh thelastUsedAtof the given token.Once the interval has elapsed, concurrent requests using the same key all see the same outdated value. Only the one acquiring the lease refreshes it, the others move on: they would otherwise queue on the very same row. The lease is not released once the refresh is done, it expires after
LEASE_TIMEOUT, which also covers the requests that readlastUsedAtbefore the refresh but reach this point after it.The lease is always acquired, so that
lastUsedAtis never refreshed more than once perLEASE_TIMEOUT. It is the last guard against a burst of requests hammering the very same row.- Parameters:
userToken- the token being used- Returns:
trueif the lease was acquired
-
update
Writes thelastUsedAtof the given token.This performs a non-versioned update:
version,updatedOnandupdatedByare intentionally left untouched, as using an API key is not a modification of the token. Keepingversionout of it also means concurrent requests sharing a key can no longer make each other fail with an optimistic lock error.- Parameters:
userToken- the token being usedlastUsedAt- the value to write
-