kivra / oauth2_client

Erlang OAuth2 Client
MIT License
73 stars 38 forks source link

token-cache-PLT-19 #19

Closed jakobsvenning closed 4 years ago

jakobsvenning commented 4 years ago

I have added a GenServer which is responsible for managing cached tokens. The API of oauth2_client has not changed, it is identical to what it was before. Whenever an application invokes retrieve_access_token, the function first checks whether the caching GenServer (oauth2c_token_cache_gen_server) is running and if this is the case it will first check in the cache before trying to fetch a new token. There should be no breaking changes since if the caching GenServer is not running, retrieve_access_token should work exactly as before. However, applications that want to utilize the caching mechanism needs to start the GenServer responsible for the caching. By default, a cached token is saved for 1 hour before being discarded. However, it is possible to specify the expiration time when starting the caching GenServer.

UPDATE:

The cached tokens are stored in a ETS-table which can be concurrently read by multiple processes and thus avoiding the "single process botlleneck" which existed in the previous implementation that only allowed the GenServer process to read and write the cache. The new implementation also handles "bursts" better than the previous implementation. If multiple concurrent requests for the same key to an empty cache would be performed in the old implementation, it is possible that several processes would have asked the remote provider for a token that would later be cached. In the new implementation, only a single process would ask the remote provider for a token and all other concurrent request would use the token returned to the single requesting process from the remote token provider.

For instance, if multiple token requests are made concurrently for the same key to an empty cache; only a single of those requests will ask the remote provider for a token and the rest will use the cached one.