1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: Apache-2.0
4 """Thread-safe wrapper for an Arvados API client
6 This module provides `ThreadSafeApiCache`, a thread-safe, API-compatible
23 api = sys.modules['arvados.api']
25 class ThreadSafeApiCache(object):
26 """Thread-safe wrapper for an Arvados API client
28 This class takes all the arguments necessary to build a lower-level
29 Arvados API client `googleapiclient.discovery.Resource`, then
30 transparently builds and wraps a unique object per thread. This works
31 around the fact that the client's underlying HTTP client object is not
36 * apiconfig: Mapping[str, str] | None --- A mapping with entries for
37 `ARVADOS_API_HOST`, `ARVADOS_API_TOKEN`, and optionally
38 `ARVADOS_API_HOST_INSECURE`. If not provided, uses
39 `arvados.config.settings` to get these parameters from user
40 configuration. You can pass an empty mapping to build the client
41 solely from `api_params`.
43 * keep_params: Mapping[str, Any] --- Keyword arguments used to construct
44 an associated `arvados.keep.KeepClient`.
46 * api_params: Mapping[str, Any] --- Keyword arguments used to construct
47 each thread's API client. These have the same meaning as in the
48 `arvados.api.api` function.
50 * version: str | None --- A string naming the version of the Arvados API
51 to use. If not specified, the code will log a warning and fall back to
56 apiconfig: Optional[Mapping[str, str]]=None,
57 keep_params: Optional[Mapping[str, Any]]={},
58 api_params: Optional[Mapping[str, Any]]={},
59 version: Optional[str]=None,
61 if apiconfig or apiconfig is None:
62 self._api_kwargs = api.api_kwargs_from_config(version, apiconfig, **api_params)
64 self._api_kwargs = api.normalize_api_kwargs(version, **api_params)
65 self.api_token = self._api_kwargs['token']
66 self.request_id = self._api_kwargs.get('request_id')
67 self.local = threading.local()
68 self.keep = keep.KeepClient(api_client=self, **keep_params)
70 def localapi(self) -> 'googleapiclient.discovery.Resource':
72 client = self.local.api
73 except AttributeError:
74 client = api.api_client(**self._api_kwargs)
75 client._http._request_id = lambda: self.request_id or util.new_request_id()
76 self.local.api = client
79 def __getattr__(self, name: str) -> Any:
80 # Proxy nonexistent attributes to the thread-local API client.
81 return getattr(self.localapi(), name)