Skip to content

Commit 85bf5a9

Browse files
committed
Add tolerance in token refresh
1 parent 87e982d commit 85bf5a9

File tree

2 files changed

+32
-6
lines changed

2 files changed

+32
-6
lines changed

graphdatascience/session/aura_api.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -262,13 +262,15 @@ class Token:
262262

263263
def __init__(self, json: Dict[str, Any]) -> None:
264264
self.access_token = json["access_token"]
265-
expires_in: int = json["expires_in"]
266-
self.expires_at = int(time.time()) + expires_in
267265
self.token_type = json["token_type"]
268266

269-
# TODO add a buffer of 10s to avoid nearly expiring tokens
270-
def is_expired(self) -> bool:
271-
return self.expires_at >= int(time.time())
267+
expires_in: int = json["expires_in"]
268+
refresh_in: int = expires_in if expires_in <= 10 else expires_in - 10
269+
# avoid token expiry during request send by refreshing 10 seconds earlier
270+
self.refresh_at = int(time.time()) + refresh_in
271+
272+
def should_refresh(self) -> bool:
273+
return self.refresh_at >= int(time.time())
272274

273275
def __init__(self, oauth_url: str, credentials: Tuple[str, str]) -> None:
274276
self._token: Optional[AuraApi.Auth.Token] = None
@@ -281,7 +283,7 @@ def __call__(self, r: requests.PreparedRequest) -> requests.PreparedRequest:
281283
return r
282284

283285
def _auth_token(self) -> str:
284-
if self._token is None or self._token.is_expired():
286+
if self._token is None or self._token.should_refresh():
285287
self._token = self._update_token()
286288
return self._token.access_token
287289

graphdatascience/tests/unit/test_aura_api.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -365,6 +365,30 @@ def test_auth_token(requests_mock: Mocker) -> None:
365365
assert api._auth._auth_token() == "longer_token"
366366

367367

368+
def test_auth_token_reused(requests_mock: Mocker) -> None:
369+
api = AuraApi(client_id="", client_secret="", tenant_id="some-tenant")
370+
371+
requests_mock.post(
372+
"https://api.neo4j.io/oauth/token",
373+
json={"access_token": "one_token", "expires_in": 3600, "token_type": "Bearer"},
374+
)
375+
376+
assert api._auth._auth_token() == "one_token"
377+
assert api._auth._auth_token() == "one_token"
378+
379+
380+
def test_auth_token_use_short_token(requests_mock: Mocker) -> None:
381+
api = AuraApi(client_id="", client_secret="", tenant_id="some-tenant")
382+
383+
requests_mock.post(
384+
"https://api.neo4j.io/oauth/token",
385+
json={"access_token": "one_token", "expires_in": 10, "token_type": "Bearer"},
386+
)
387+
388+
assert api._auth._auth_token() == "one_token"
389+
assert api._auth._auth_token() == "one_token"
390+
391+
368392
def test_derive_tenant(requests_mock: Mocker) -> None:
369393
mock_auth_token(requests_mock)
370394

0 commit comments

Comments
 (0)