from mdrsclient.api.users import UsersApi from mdrsclient.connection import MDRSConnection from mdrsclient.exceptions import UnauthorizedException def token_check(connection: MDRSConnection) -> None: """ Bring the access token up to date before a request goes out. Refreshing is a read-modify-write over a cache shared with every other client process on this machine, and a rotating provider stops honouring the refresh token it replaces. Two processes reaching this at once would otherwise both send the same token, and the loser would be left holding one the server no longer accepts, so the whole sequence runs under a lock that spans processes and the cache is re-read inside it. """ with connection.lock: token = connection.token if token is None or not (token.is_refresh_required or token.is_expired): # Nothing to do, which is the answer for almost every request. The lock below # reaches across processes and is held for a round trip, so it is worth # knowing that before taking it. return with connection.cache_lock(): connection.reload_cache() token = connection.token if token is None: return if token.is_expired: connection.logout() return if not token.is_refresh_required: return user_api = UsersApi(connection) try: connection.token = user_api.tokenRefresh(token) except UnauthorizedException: connection.logout()