Skip to content

Commit

Permalink
Keep auth session alive when inactive
Browse files Browse the repository at this point in the history
  • Loading branch information
fqqb committed May 10, 2024
1 parent f62b6ee commit 5f9fef3
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 4 deletions.
9 changes: 9 additions & 0 deletions yamcs-client/src/yamcs/client/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@ def __init__(
tls_verify: Union[bool, str] = True,
credentials: Optional[Credentials] = None,
user_agent: Optional[str] = None,
keep_alive: bool = True,
on_token_update: Optional[Callable[[Credentials], None]] = None,
):
"""
Expand All @@ -172,6 +173,13 @@ def __init__(
Credentials for when the server is secured
:param user_agent:
Optionally override the default user agent
:param keep_alive:
Automatically renew the client session. If disabled,
the session will terminate after about 30 minutes of
inactivity.
This property is only considered when accessing a
server that requires authentication.
"""

# Allow server URLs.
Expand All @@ -190,6 +198,7 @@ def __init__(
user_agent=user_agent,
on_token_update=on_token_update,
tls_verify=tls_verify,
keep_alive=keep_alive,
)

@staticmethod
Expand Down
26 changes: 23 additions & 3 deletions yamcs-client/src/yamcs/core/context.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from datetime import datetime, timezone
from typing import Callable, Optional, Union

import requests
Expand All @@ -7,11 +8,11 @@
from yamcs.api import exception_pb2
from yamcs.core.auth import Credentials
from yamcs.core.exceptions import NotFound, Unauthorized, YamcsError
from yamcs.core.helpers import do_request
from yamcs.core.helpers import FixedDelay, do_request


class Context:
credentials = None
credentials: Optional[Credentials] = None

def __init__(
self,
Expand All @@ -21,6 +22,7 @@ def __init__(
user_agent: Optional[str] = None,
on_token_update: Optional[Callable[[Credentials], None]] = None,
tls_verify: Union[bool, str] = True,
keep_alive: bool = True,
):
if address.endswith("/"):
self.address = address[:-1]
Expand Down Expand Up @@ -51,9 +53,23 @@ def __init__(
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

if credentials:
self.credentials = credentials.login(
converted_creds = credentials.login(
self.session, self.auth_root, on_token_update
)
self.credentials = converted_creds

# An assigned refresh token lives only for about 30 minutes. We actively
# extend it, so that the session survives when idle.
if converted_creds.expiry and keep_alive:

def renew_session():
expiry = converted_creds.expiry
if expiry:
remaining = expiry - datetime.now(tz=timezone.utc)
if 0 < remaining.total_seconds() < 60:
converted_creds.refresh(self.session, self.auth_root)

self._session_renewer = FixedDelay(renew_session, 10)

if not user_agent:
user_agent = "python-yamcs-client v" + clientversion.__version__
Expand Down Expand Up @@ -121,4 +137,8 @@ def request(self, method: str, path: str, **kwargs) -> requests.Response:

def close(self):
"""Close this context"""

if self._session_renewer:
self._session_renewer.stop()

self.session.close()
34 changes: 33 additions & 1 deletion yamcs-client/src/yamcs/core/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
import logging
import os
from datetime import datetime, timezone
from typing import Any, Iterator, List, Union
from threading import Timer
from typing import Any, Callable, Iterator, List, Union
from urllib.parse import urlparse

import requests
Expand Down Expand Up @@ -359,3 +360,34 @@ def clear(self):
copy = list(repeatable)
for item in copy:
repeatable.remove(item)


class FixedDelay:
"""
Helper class to run a periodic action, with a fixed delay between
the termination of one execution, and the commencement of the next.
"""

def __init__(self, action: Callable[[], None], period: float):
self._timer = None
self.action = action
self.period = period
self.is_running = False
self.start()

def start(self):
if not self.is_running:
self._timer = Timer(self.period, self._run)
self._timer.daemon = True
self._timer.start()
self.is_running = True

def stop(self):
if self._timer:
self._timer.cancel()
self.is_running = False

def _run(self):
self.is_running = False
self.start()
self.action()

0 comments on commit 5f9fef3

Please sign in to comment.