Skip to content

Session and Token Storage

SDK API reference for tlm_cloud_sdk.CloudSession and the token storages.

Every client of the SDK is built from a CloudSession. The session reads no configuration file and no default path: pass the instance, the credentials and a TokenStorage that keeps the token — FileTokenStorage at a path you choose, MemoryTokenStorage, or your own subclass.

from tlm_cloud_sdk import CloudSession, MemoryTokenStorage
from tlm_cloud_sdk.manufacturing import PMSClient

session = CloudSession.login("tolomeo.io", username, password, token_storage=MemoryTokenStorage())
pms = PMSClient(session)

Runtime Behavior

Behavior Description
Request timeout 10 seconds; override with the REQUEST_TIMEOUT environment variable, read when the SDK is imported
Session binding PMSClient(session) binds the session to every PMS model in the process; FMClient and EMClient do the same for the /resources models, so a process talks to one instance at a time
Thread safety A CloudSession can be shared between threads; concurrent requests trigger at most one login at a time
Token file FileTokenStorage writes its file atomically with owner-only (0600) permissions
Concurrency Synchronous; call it from a worker thread in an async application

CloudSession

tlm_cloud_sdk.session.CloudSession

Where to reach a ToloMEO instance, and how to get a valid token for it.

Every client of the SDK is built from a session: PMSClient(session), IoTClient(session) and so on. The session reads no file and no environment of its own: the caller passes the instance, the credentials and a :class:~tlm_cloud_sdk.auth.TokenStorage that keeps the token between calls.

It is safe to share one session between threads: a token is fetched at most once at a time.

Parameters:

Name Type Description Default
instance InstanceConfig | str

The instance hostname (e.g. "tolomeo.io") or its :class:InstanceConfig.

required
token_provider TokenProvider

Supplies a valid token for each request.

required

Examples:

>>> session = CloudSession.login(
...     "tolomeo.io", "operator@example.com", "secret", token_storage=MemoryTokenStorage()
... )
>>> pms = PMSClient(session)
Source code in packages/tlm-cloud-sdk/tlm_cloud_sdk/session.py
class CloudSession:
    """Where to reach a ToloMEO instance, and how to get a valid token for it.

    Every client of the SDK is built from a session: ``PMSClient(session)``, ``IoTClient(session)`` and so on.
    The session reads no file and no environment of its own: the caller passes the instance, the credentials and
    a :class:`~tlm_cloud_sdk.auth.TokenStorage` that keeps the token between calls.

    It is safe to share one session between threads: a token is fetched at most once at a time.

    Args:
        instance: The instance hostname (e.g. ``"tolomeo.io"``) or its :class:`InstanceConfig`.
        token_provider: Supplies a valid token for each request.

    Examples:
        >>> session = CloudSession.login(
        ...     "tolomeo.io", "operator@example.com", "secret", token_storage=MemoryTokenStorage()
        ... )
        >>> pms = PMSClient(session)
    """

    def __init__(self, instance: InstanceConfig | str, token_provider: TokenProvider) -> None:
        self._instance = InstanceConfig(instance=instance) if isinstance(instance, str) else instance
        self._token_provider = token_provider

    @classmethod
    def login(
        cls,
        instance: InstanceConfig | str,
        username: str,
        password: str,
        *,
        token_storage: TokenStorage,
        log: logging.Logger | None = None,
    ) -> CloudSession:
        """Log in to the instance's Kratos with a username and password, and return the session.

        A valid token already in ``token_storage`` for this instance and user is reused; otherwise the Kratos
        login flow runs now and the new token is stored there, so a wrong password fails here and not on the
        first API call. Later expiries are handled by logging in again on demand.

        Args:
            instance: The instance hostname (e.g. ``"tolomeo.io"``) or its :class:`InstanceConfig`.
            username: The Kratos identifier, an email address.
            password: The password.
            token_storage: Where the token is kept, e.g. ``FileTokenStorage(path)`` or ``MemoryTokenStorage()``.
            log: Optional logger for the authentication flow.

        Returns:
            CloudSession: An authenticated session.

        Raises:
            httpx2.HTTPStatusError: If Kratos rejects the login.
            ValueError: If Kratos answers in an unexpected format.
        """
        session = cls.from_credentials(
            instance,
            AuthCredentials(username=username, password=password),  # type: ignore[arg-type]
            token_storage=token_storage,
            log=log,
        )
        session.token_provider.get_valid_token()
        return session

    @classmethod
    def from_credentials(
        cls,
        instance: InstanceConfig | str,
        credentials: AuthCredentials,
        *,
        token_storage: TokenStorage,
        log: logging.Logger | None = None,
    ) -> CloudSession:
        """Return a session that logs in lazily, on the first request that needs a token.

        Args:
            instance: The instance hostname or its :class:`InstanceConfig`.
            credentials: Username and password.
            token_storage: Where the token is kept. Its key is set to ``"<instance>:<username>"`` when unset,
                so one storage can hold the tokens of several instances and users.
            log: Optional logger for the authentication flow.
        """
        instance_config = InstanceConfig(instance=instance) if isinstance(instance, str) else instance
        token_storage.bind_key(
            KratosTokenProvider.create_storage_key(instance_config.instance, str(credentials.username))
        )
        provider = KratosTokenProvider(
            storage=token_storage,
            auth_base_url=instance_config.auth_base_url,
            credentials=credentials,
            logger=log,
        )
        return cls(instance_config, provider)

    @classmethod
    def from_config(
        cls, config: AppConfig, *, token_storage: TokenStorage, log: logging.Logger | None = None
    ) -> CloudSession:
        """Return a lazily authenticated session from an :class:`AppConfig` the caller loaded."""
        return cls.from_credentials(config.application, config.auth, token_storage=token_storage, log=log)

    @property
    def instance(self) -> InstanceConfig:
        """The target instance, with its derived API and auth URLs."""
        return self._instance

    @property
    def token_provider(self) -> TokenProvider:
        """The provider every client of this session takes its tokens from."""
        return self._token_provider

    def url(self, path: str) -> str:
        """Return the API URL of ``path``, e.g. ``https://apis.tolomeo.io/manufacturing``."""
        return f"{self._instance.api_base_url}/{path.strip('/')}".rstrip("/")

    def jsonapi(self, path: str) -> orm.OrmApi:
        """Return a jsonapi-requests ORM session for ``{api_base_url}/{path}``.

        Each request carries a token that is valid at the time it is sent.
        """
        return build_jsonapi_orm(base_url=self.url(path), token=self._token_provider)

instance property

The target instance, with its derived API and auth URLs.

token_provider property

The provider every client of this session takes its tokens from.

from_config(config, *, token_storage, log=None) classmethod

Return a lazily authenticated session from an :class:AppConfig the caller loaded.

Source code in packages/tlm-cloud-sdk/tlm_cloud_sdk/session.py
@classmethod
def from_config(
    cls, config: AppConfig, *, token_storage: TokenStorage, log: logging.Logger | None = None
) -> CloudSession:
    """Return a lazily authenticated session from an :class:`AppConfig` the caller loaded."""
    return cls.from_credentials(config.application, config.auth, token_storage=token_storage, log=log)

from_credentials(instance, credentials, *, token_storage, log=None) classmethod

Return a session that logs in lazily, on the first request that needs a token.

Parameters:

Name Type Description Default
instance InstanceConfig | str

The instance hostname or its :class:InstanceConfig.

required
credentials AuthCredentials

Username and password.

required
token_storage TokenStorage

Where the token is kept. Its key is set to "<instance>:<username>" when unset, so one storage can hold the tokens of several instances and users.

required
log Logger | None

Optional logger for the authentication flow.

None
Source code in packages/tlm-cloud-sdk/tlm_cloud_sdk/session.py
@classmethod
def from_credentials(
    cls,
    instance: InstanceConfig | str,
    credentials: AuthCredentials,
    *,
    token_storage: TokenStorage,
    log: logging.Logger | None = None,
) -> CloudSession:
    """Return a session that logs in lazily, on the first request that needs a token.

    Args:
        instance: The instance hostname or its :class:`InstanceConfig`.
        credentials: Username and password.
        token_storage: Where the token is kept. Its key is set to ``"<instance>:<username>"`` when unset,
            so one storage can hold the tokens of several instances and users.
        log: Optional logger for the authentication flow.
    """
    instance_config = InstanceConfig(instance=instance) if isinstance(instance, str) else instance
    token_storage.bind_key(
        KratosTokenProvider.create_storage_key(instance_config.instance, str(credentials.username))
    )
    provider = KratosTokenProvider(
        storage=token_storage,
        auth_base_url=instance_config.auth_base_url,
        credentials=credentials,
        logger=log,
    )
    return cls(instance_config, provider)

jsonapi(path)

Return a jsonapi-requests ORM session for {api_base_url}/{path}.

Each request carries a token that is valid at the time it is sent.

Source code in packages/tlm-cloud-sdk/tlm_cloud_sdk/session.py
def jsonapi(self, path: str) -> orm.OrmApi:
    """Return a jsonapi-requests ORM session for ``{api_base_url}/{path}``.

    Each request carries a token that is valid at the time it is sent.
    """
    return build_jsonapi_orm(base_url=self.url(path), token=self._token_provider)

login(instance, username, password, *, token_storage, log=None) classmethod

Log in to the instance's Kratos with a username and password, and return the session.

A valid token already in token_storage for this instance and user is reused; otherwise the Kratos login flow runs now and the new token is stored there, so a wrong password fails here and not on the first API call. Later expiries are handled by logging in again on demand.

Parameters:

Name Type Description Default
instance InstanceConfig | str

The instance hostname (e.g. "tolomeo.io") or its :class:InstanceConfig.

required
username str

The Kratos identifier, an email address.

required
password str

The password.

required
token_storage TokenStorage

Where the token is kept, e.g. FileTokenStorage(path) or MemoryTokenStorage().

required
log Logger | None

Optional logger for the authentication flow.

None

Returns:

Name Type Description
CloudSession CloudSession

An authenticated session.

Raises:

Type Description
HTTPStatusError

If Kratos rejects the login.

ValueError

If Kratos answers in an unexpected format.

Source code in packages/tlm-cloud-sdk/tlm_cloud_sdk/session.py
@classmethod
def login(
    cls,
    instance: InstanceConfig | str,
    username: str,
    password: str,
    *,
    token_storage: TokenStorage,
    log: logging.Logger | None = None,
) -> CloudSession:
    """Log in to the instance's Kratos with a username and password, and return the session.

    A valid token already in ``token_storage`` for this instance and user is reused; otherwise the Kratos
    login flow runs now and the new token is stored there, so a wrong password fails here and not on the
    first API call. Later expiries are handled by logging in again on demand.

    Args:
        instance: The instance hostname (e.g. ``"tolomeo.io"``) or its :class:`InstanceConfig`.
        username: The Kratos identifier, an email address.
        password: The password.
        token_storage: Where the token is kept, e.g. ``FileTokenStorage(path)`` or ``MemoryTokenStorage()``.
        log: Optional logger for the authentication flow.

    Returns:
        CloudSession: An authenticated session.

    Raises:
        httpx2.HTTPStatusError: If Kratos rejects the login.
        ValueError: If Kratos answers in an unexpected format.
    """
    session = cls.from_credentials(
        instance,
        AuthCredentials(username=username, password=password),  # type: ignore[arg-type]
        token_storage=token_storage,
        log=log,
    )
    session.token_provider.get_valid_token()
    return session

url(path)

Return the API URL of path, e.g. https://apis.tolomeo.io/manufacturing.

Source code in packages/tlm-cloud-sdk/tlm_cloud_sdk/session.py
def url(self, path: str) -> str:
    """Return the API URL of ``path``, e.g. ``https://apis.tolomeo.io/manufacturing``."""
    return f"{self._instance.api_base_url}/{path.strip('/')}".rstrip("/")

Token Storage

tlm_cloud_sdk.auth.storage.TokenStorage

Bases: ABC

Where a token provider keeps its token between calls (and between runs, for a persistent storage).

Implement this to keep tokens somewhere else (a database, a secret store). A storage holds the token of one storage_key at a time, typically "<instance>:<username>"; :class:~tlm_cloud_sdk.CloudSession sets it through :meth:bind_key when the caller did not.

Parameters:

Name Type Description Default
storage_key str | None

Key of the token this storage reads and writes.

None
Source code in packages/tlm-cloud-sdk/tlm_cloud_sdk/auth/storage.py
class TokenStorage(ABC):
    """Where a token provider keeps its token between calls (and between runs, for a persistent storage).

    Implement this to keep tokens somewhere else (a database, a secret store). A storage holds the token of one
    ``storage_key`` at a time, typically ``"<instance>:<username>"``; :class:`~tlm_cloud_sdk.CloudSession` sets it
    through :meth:`bind_key` when the caller did not.

    Args:
        storage_key: Key of the token this storage reads and writes.
    """

    def __init__(self, storage_key: str | None = None) -> None:
        self._storage_key = storage_key
        self._explicit_key = storage_key is not None

    @property
    def storage_key(self) -> str | None:
        """Key of the token this storage reads and writes."""
        return self._storage_key

    def bind_key(self, storage_key: str) -> None:
        """Set the storage key, unless one was given at construction.

        Raises:
            ValueError: If an earlier session already bound another key: the two sessions would read each
                other's token. Give each session its own storage, or a key at construction.
        """
        if self._explicit_key or self._storage_key == storage_key:
            return
        if self._storage_key is not None:
            raise ValueError(
                f"This token storage is already bound to {self._storage_key!r}, not {storage_key!r}: "
                "give each session its own storage, or pass storage_key explicitly."
            )
        self._storage_key = storage_key

    @abstractmethod
    def store_token(self, token_info: ApiTokenInfo) -> None: ...

    @abstractmethod
    def get_token(self) -> ApiTokenInfo | None:
        """Return the stored token, or None when there is none or it has expired."""

    @abstractmethod
    def clear_token(self) -> None: ...

storage_key property

Key of the token this storage reads and writes.

bind_key(storage_key)

Set the storage key, unless one was given at construction.

Raises:

Type Description
ValueError

If an earlier session already bound another key: the two sessions would read each other's token. Give each session its own storage, or a key at construction.

Source code in packages/tlm-cloud-sdk/tlm_cloud_sdk/auth/storage.py
def bind_key(self, storage_key: str) -> None:
    """Set the storage key, unless one was given at construction.

    Raises:
        ValueError: If an earlier session already bound another key: the two sessions would read each
            other's token. Give each session its own storage, or a key at construction.
    """
    if self._explicit_key or self._storage_key == storage_key:
        return
    if self._storage_key is not None:
        raise ValueError(
            f"This token storage is already bound to {self._storage_key!r}, not {storage_key!r}: "
            "give each session its own storage, or pass storage_key explicitly."
        )
    self._storage_key = storage_key

get_token() abstractmethod

Return the stored token, or None when there is none or it has expired.

Source code in packages/tlm-cloud-sdk/tlm_cloud_sdk/auth/storage.py
@abstractmethod
def get_token(self) -> ApiTokenInfo | None:
    """Return the stored token, or None when there is none or it has expired."""

tlm_cloud_sdk.auth.storage.FileTokenStorage

Bases: TokenStorage

Stores tokens in a JSON file, keyed by instance:username.

Supports multiple accounts in a single file and auto-cleans expired tokens. Nothing touches the filesystem until the first token is stored: the directory is created then, and the file is written atomically with owner-only permissions.

Parameters:

Name Type Description Default
file_path str | Path

Path to the token storage JSON file, chosen by the caller.

required
storage_key str | None

Unique key for this token, e.g. "instance:username".

None
Source code in packages/tlm-cloud-sdk/tlm_cloud_sdk/auth/storage.py
class FileTokenStorage(TokenStorage):
    """Stores tokens in a JSON file, keyed by instance:username.

    Supports multiple accounts in a single file and auto-cleans expired tokens. Nothing touches the filesystem
    until the first token is stored: the directory is created then, and the file is written atomically with
    owner-only permissions.

    Args:
        file_path: Path to the token storage JSON file, chosen by the caller.
        storage_key: Unique key for this token, e.g. "instance:username".
    """

    def __init__(self, file_path: str | Path, storage_key: str | None = None):
        super().__init__(storage_key)
        self._file_path = Path(file_path)
        self._lock = threading.Lock()

    @property
    def file_path(self) -> Path:
        """The token file."""
        return self._file_path

    def store_token(self, token_info: ApiTokenInfo) -> None:
        token_data: Dict = {"token": token_info.token, "expires_at": token_info.expires_at.isoformat()}
        with self._lock:
            all_tokens = self._load_all_tokens()
            all_tokens["tokens"][self._storage_key] = token_data
            self._cleanup_expired_tokens(all_tokens["tokens"])
            self._write(all_tokens)

    def get_token(self) -> ApiTokenInfo | None:
        if not self._file_path.exists():
            return None
        try:
            with self._file_path.open("r") as f:
                data: Dict = json.load(f)
            if "tokens" not in data or self._storage_key not in data["tokens"]:
                return None
            td = data["tokens"][self._storage_key]
            token_info = ApiTokenInfo(token=td["token"], expires_at=datetime.fromisoformat(td["expires_at"]))
            return token_info if not token_info.is_expired else None
        except (json.JSONDecodeError, KeyError, ValueError):
            return None

    def clear_token(self) -> None:
        if not self._file_path.exists():
            return
        with self._lock:
            try:
                all_tokens = self._load_all_tokens()
                if self._storage_key in all_tokens["tokens"]:
                    del all_tokens["tokens"][self._storage_key]
                    if all_tokens["tokens"]:
                        self._write(all_tokens)
                    else:
                        os.remove(self._file_path)
            except (json.JSONDecodeError, KeyError):
                pass

    def _write(self, all_tokens: Dict) -> None:
        """Replace the file in one step, so a concurrent reader never sees half a document."""
        self._file_path.parent.mkdir(parents=True, exist_ok=True)
        fd, tmp = tempfile.mkstemp(dir=self._file_path.parent, prefix=f".{self._file_path.name}.")
        try:
            with os.fdopen(fd, "w") as f:
                json.dump(all_tokens, f, indent=2)
            os.chmod(tmp, 0o600)
            os.replace(tmp, self._file_path)
        except BaseException:
            Path(tmp).unlink(missing_ok=True)
            raise

    def _load_all_tokens(self) -> Dict:
        if not self._file_path.exists():
            return {"tokens": {}}
        try:
            with self._file_path.open("r") as f:
                data: Dict = json.load(f)
            if "token" in data and "expires_at" in data:
                logger.info("Detected legacy token format, will be migrated on next authentication")
                return {"tokens": {}}
            if "tokens" in data:
                return data
            return {"tokens": {}}
        except (json.JSONDecodeError, KeyError):
            return {"tokens": {}}

    def _cleanup_expired_tokens(self, tokens: Dict) -> None:
        expired_keys: List = []
        for key, token_data in tokens.items():
            try:
                expires_at = datetime.fromisoformat(token_data["expires_at"])
                if datetime.now(timezone.utc) > expires_at:
                    expired_keys.append(key)
            except (KeyError, ValueError):
                expired_keys.append(key)
        for key in expired_keys:
            del tokens[key]
            logger.debug("Cleaned up expired token for key: %s", key)  # nosemgrep: python-logger-credential-disclosure

file_path property

The token file.

tlm_cloud_sdk.auth.storage.MemoryTokenStorage

Bases: TokenStorage

Keeps the token in memory only: every new process logs in again.

Source code in packages/tlm-cloud-sdk/tlm_cloud_sdk/auth/storage.py
class MemoryTokenStorage(TokenStorage):
    """Keeps the token in memory only: every new process logs in again."""

    def __init__(self, storage_key: str | None = None) -> None:
        super().__init__(storage_key)
        self._tokens: Dict[str | None, ApiTokenInfo] = {}

    def store_token(self, token_info: ApiTokenInfo) -> None:
        self._tokens[self._storage_key] = token_info

    def get_token(self) -> ApiTokenInfo | None:
        token_info = self._tokens.get(self._storage_key)
        return token_info if token_info is not None and not token_info.is_expired else None

    def clear_token(self) -> None:
        self._tokens.pop(self._storage_key, None)