Debian Codegraph @

ansible_collections/hetzner/hcloud/plugins/module_utils/_client.py

raw
1 # Copyright: (c) 2023, Hetzner Cloud GmbH <[email protected]>
2
3 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
4 # Do not use this from other collections or standalone plugins/modules!
5
6 from __future__ import annotations
7
8 from contextlib import contextmanager
9
10 from ansible.module_utils.basic import missing_required_lib
11
12 from ._vendor.hcloud import APIException, Client as ClientBase
13
14 HAS_REQUESTS = True
15 HAS_DATEUTIL = True
16
17 try:
18 import requests # pylint: disable=unused-import
19 except ImportError:
20 HAS_REQUESTS = False
21
22 try:
23 import dateutil # pylint: disable=unused-import
24 except ImportError:
25 HAS_DATEUTIL = False
26
27
28 class ClientException(Exception):
29 """An error related to the client occurred."""
30
31
32 def client_check_required_lib():
33 if not HAS_REQUESTS:
34 raise ClientException(missing_required_lib("requests"))
35 if not HAS_DATEUTIL:
36 raise ClientException(missing_required_lib("python-dateutil"))
37
38
39 def client_resource_not_found(resource: str, param: str | int):
40 return ClientException(f"resource ({resource}) does not exist: {param}")
41
42
43 def client_get_by_name_or_id(client: Client, resource: str, param: str | int):
44 """
45 Get a resource by name, and if not found by its ID.
46
47 :param client: Client to use to make the call
48 :param resource: Name of the resource client that implements both `get_by_name` and `get_by_id` methods
49 :param param: Name or ID of the resource to query
50 """
51 resource_client = getattr(client, resource)
52
53 result = resource_client.get_by_name(param)
54 if result is not None:
55 return result
56
57 # If the param is not a valid ID, prevent an unnecessary call to the API.
58 try:
59 int(param)
60 except ValueError as exception:
61 raise client_resource_not_found(resource.rstrip("s"), param) from exception
62
63 try:
64 return resource_client.get_by_id(param)
65 except APIException as exception:
66 if exception.code == "not_found":
67 raise client_resource_not_found(resource.rstrip("s"), param) from exception
68 raise exception
69
70
71 if HAS_REQUESTS:
72
73 class CachedSession(requests.Session):
74 cache: dict[str, requests.Response]
75
76 def __init__(self) -> None:
77 super().__init__()
78 self.cache = {}
79
80 def send(self, request: requests.PreparedRequest, **kwargs) -> requests.Response: # type: ignore[no-untyped-def]
81 """
82 Send a given PreparedRequest.
83 """
84 if request.method != "GET" or request.url is None:
85 return super().send(request, **kwargs)
86
87 if request.url in self.cache:
88 return self.cache[request.url]
89
90 response = super().send(request, **kwargs)
91 if response.ok:
92 self.cache[request.url] = response
93
94 return response
95
96
97 class Client(ClientBase):
98 @contextmanager
99 def cached_session(self):
100 """
101 Swap the client session during the scope of the context. The session will cache
102 all GET requests.
103
104 Cached response will not expire, therefore the cached client must not be used
105 for long living scopes.
106 """
107 self._client._session = CachedSession()
108 try:
109 yield
110 finally:
111 self._client._session = requests.Session()