1+ from datetime import datetime , timezone
12from typing import Callable , Optional , Union
23
34import requests
78from yamcs .api import exception_pb2
89from yamcs .core .auth import Credentials
910from yamcs .core .exceptions import NotFound , Unauthorized , YamcsError
10- from yamcs .core .helpers import do_request
11+ from yamcs .core .helpers import FixedDelay , do_request
1112
1213
1314class Context :
14- credentials = None
15+ credentials : Optional [ Credentials ] = None
1516
1617 def __init__ (
1718 self ,
@@ -21,6 +22,7 @@ def __init__(
2122 user_agent : Optional [str ] = None ,
2223 on_token_update : Optional [Callable [[Credentials ], None ]] = None ,
2324 tls_verify : Union [bool , str ] = True ,
25+ keep_alive : bool = True ,
2426 ):
2527 if address .endswith ("/" ):
2628 self .address = address [:- 1 ]
@@ -51,9 +53,23 @@ def __init__(
5153 urllib3 .disable_warnings (urllib3 .exceptions .InsecureRequestWarning )
5254
5355 if credentials :
54- self . credentials = credentials .login (
56+ converted_creds = credentials .login (
5557 self .session , self .auth_root , on_token_update
5658 )
59+ self .credentials = converted_creds
60+
61+ # An assigned refresh token lives only for about 30 minutes. We actively
62+ # extend it, so that the session survives when idle.
63+ if converted_creds .expiry and keep_alive :
64+
65+ def renew_session ():
66+ expiry = converted_creds .expiry
67+ if expiry :
68+ remaining = expiry - datetime .now (tz = timezone .utc )
69+ if 0 < remaining .total_seconds () < 60 :
70+ converted_creds .refresh (self .session , self .auth_root )
71+
72+ self ._session_renewer = FixedDelay (renew_session , 10 )
5773
5874 if not user_agent :
5975 user_agent = "python-yamcs-client v" + clientversion .__version__
@@ -121,4 +137,8 @@ def request(self, method: str, path: str, **kwargs) -> requests.Response:
121137
122138 def close (self ):
123139 """Close this context"""
140+
141+ if self ._session_renewer :
142+ self ._session_renewer .stop ()
143+
124144 self .session .close ()
0 commit comments