noderings 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
noderings/__init__.py ADDED
@@ -0,0 +1,66 @@
1
+ """The Python SDK for the NodeRings API.
2
+
3
+ from noderings import NodeRings
4
+
5
+ client = NodeRings() # reads NODERINGS_TOKEN
6
+ for vm in client.virtual_machine.list_virtual_machines_all():
7
+ print(vm.name, vm.ipv4)
8
+
9
+ Every model is available as ``noderings.models.<Name>`` and, for convenience,
10
+ as ``noderings.<Name>``.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from typing import Any
16
+
17
+ from . import models
18
+ from ._base import DEFAULT_BASE_URL, NOT_GIVEN, NotGiven
19
+ from ._client import AsyncNodeRings, NodeRings, WaitTimeoutError
20
+ from ._errors import (
21
+ APIConnectionError,
22
+ APIError,
23
+ APITimeoutError,
24
+ AuthenticationError,
25
+ BadRequestError,
26
+ Code,
27
+ ConflictError,
28
+ InternalServerError,
29
+ NodeRingsError,
30
+ NotFoundError,
31
+ PermissionDeniedError,
32
+ QuotaExceededError,
33
+ RateLimitError,
34
+ )
35
+ from ._version import __version__
36
+
37
+ __all__ = [
38
+ "DEFAULT_BASE_URL",
39
+ "NOT_GIVEN",
40
+ "APIConnectionError",
41
+ "APIError",
42
+ "APITimeoutError",
43
+ "AsyncNodeRings",
44
+ "AuthenticationError",
45
+ "BadRequestError",
46
+ "Code",
47
+ "ConflictError",
48
+ "InternalServerError",
49
+ "NodeRings",
50
+ "NodeRingsError",
51
+ "NotFoundError",
52
+ "NotGiven",
53
+ "PermissionDeniedError",
54
+ "QuotaExceededError",
55
+ "RateLimitError",
56
+ "WaitTimeoutError",
57
+ "__version__",
58
+ "models",
59
+ ]
60
+
61
+
62
+ def __getattr__(name: str) -> Any:
63
+ # noderings.VirtualMachine is noderings.models.VirtualMachine.
64
+ if name in models.__all__:
65
+ return getattr(models, name)
66
+ raise AttributeError(f"module 'noderings' has no attribute {name!r}")
noderings/_base.py ADDED
@@ -0,0 +1,418 @@
1
+ """The HTTP core shared by NodeRings and AsyncNodeRings."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import email.utils
7
+ import logging
8
+ import os
9
+ import random
10
+ import time
11
+ import uuid
12
+ from datetime import datetime, timezone
13
+ from enum import Enum
14
+ from typing import TYPE_CHECKING, Any, TypeVar, Union
15
+ from urllib.parse import quote
16
+
17
+ import httpx
18
+
19
+ from ._errors import APIConnectionError, APIError, APITimeoutError, error_from_response
20
+ from ._types import Model
21
+ from ._version import __version__
22
+
23
+ if TYPE_CHECKING:
24
+ from typing import TypeAlias
25
+
26
+ __all__ = ["DEFAULT_BASE_URL", "NOT_GIVEN", "NotGiven", "Timeout"]
27
+
28
+ DEFAULT_BASE_URL = "https://api.noderings.com"
29
+ DEFAULT_TIMEOUT = 60.0
30
+ DEFAULT_MAX_RETRIES = 3
31
+
32
+ logger = logging.getLogger("noderings")
33
+
34
+ M = TypeVar("M", bound=Model)
35
+
36
+
37
+ class NotGiven:
38
+ """The default of ``timeout``: use the client's own setting."""
39
+
40
+ _instance: NotGiven | None = None
41
+
42
+ def __new__(cls) -> NotGiven:
43
+ if cls._instance is None:
44
+ cls._instance = super().__new__(cls)
45
+ return cls._instance
46
+
47
+ def __bool__(self) -> bool:
48
+ return False
49
+
50
+ def __repr__(self) -> str:
51
+ return "NOT_GIVEN"
52
+
53
+
54
+ NOT_GIVEN = NotGiven()
55
+
56
+ Timeout: TypeAlias = Union[float, httpx.Timeout, NotGiven, None]
57
+
58
+
59
+ # ---------------------------------------------------------------- request building
60
+
61
+
62
+ def _path(v: Any) -> str:
63
+ """One path segment, percent-escaped."""
64
+ if isinstance(v, Enum):
65
+ v = v.value
66
+ return quote(str(v), safe="")
67
+
68
+
69
+ def _scalar(v: Any) -> str:
70
+ if isinstance(v, bool):
71
+ return "true" if v else "false"
72
+ if isinstance(v, Enum):
73
+ return str(v.value)
74
+ if isinstance(v, datetime):
75
+ if v.tzinfo is None:
76
+ v = v.replace(tzinfo=timezone.utc)
77
+ return str(v.astimezone(timezone.utc).isoformat()).replace("+00:00", "Z")
78
+ return str(v)
79
+
80
+
81
+ def _query(extra: dict[str, Any] | None, *pairs: tuple[str, Any]) -> list[tuple[str, Any]]:
82
+ """Query parameters, leaving out the ones that are None."""
83
+ out: list[tuple[str, Any]] = []
84
+ items = list(pairs) + list((extra or {}).items())
85
+ for name, v in items:
86
+ if v is None:
87
+ continue
88
+ if isinstance(v, (list, tuple, set)):
89
+ out.extend((name, _scalar(x)) for x in v)
90
+ else:
91
+ out.append((name, _scalar(v)))
92
+ return out
93
+
94
+
95
+ def _body(model: type[M], extra: dict[str, Any] | None, idempotent: bool, *pairs: tuple[str, Any]) -> dict[str, Any]:
96
+ """A request body from keyword arguments, validated by its model.
97
+
98
+ Only arguments that are not None are sent. Nested objects may be models or
99
+ dicts (with snake_case or camelCase keys).
100
+ """
101
+ given = {name: v for name, v in pairs if v is not None}
102
+ if idempotent and not given.get("idempotency_key"):
103
+ given["idempotency_key"] = str(uuid.uuid4())
104
+ obj = model.model_validate(given)
105
+ body = obj.model_dump(mode="json", by_alias=True, exclude_unset=True)
106
+ if extra:
107
+ body.update(extra)
108
+ return body
109
+
110
+
111
+ # ---------------------------------------------------------------- client core
112
+
113
+
114
+ class _BaseClient:
115
+ def __init__(
116
+ self,
117
+ token: str | None,
118
+ *,
119
+ organization_id: str | None,
120
+ base_url: str | None,
121
+ timeout: float | httpx.Timeout | None,
122
+ max_retries: int,
123
+ min_backoff: float,
124
+ max_backoff: float,
125
+ user_agent: str | None,
126
+ ) -> None:
127
+ token = (token if token is not None else os.environ.get("NODERINGS_TOKEN", "")).strip()
128
+ if not token:
129
+ raise ValueError("a token is required: pass token=... or set NODERINGS_TOKEN")
130
+ if max_retries < 0 or min_backoff < 0 or max_backoff < min_backoff:
131
+ raise ValueError("invalid retry settings")
132
+ base = (base_url or os.environ.get("NODERINGS_BASE_URL") or DEFAULT_BASE_URL).strip().rstrip("/")
133
+ parsed = httpx.URL(base)
134
+ if parsed.scheme not in ("http", "https") or not parsed.host:
135
+ raise ValueError(f"invalid base URL {base!r}")
136
+ self._token = token
137
+ self.organization_id = (organization_id or os.environ.get("NODERINGS_ORGANIZATION_ID") or "").strip() or None
138
+ self.base_url = base
139
+ self.timeout = timeout
140
+ self.max_retries = max_retries
141
+ self.min_backoff = min_backoff
142
+ self.max_backoff = max_backoff
143
+ ua = f"noderings-python/{__version__}"
144
+ if user_agent and user_agent.strip():
145
+ ua = user_agent.strip() + " " + ua
146
+ self.user_agent = ua
147
+
148
+ def __repr__(self) -> str:
149
+ return f"{type(self).__name__}(base_url={self.base_url!r}, organization_id={self.organization_id!r})"
150
+
151
+ def _headers(self, has_body: bool) -> dict[str, str]:
152
+ h = {
153
+ "Authorization": f"Bearer {self._token}",
154
+ "Accept": "application/json",
155
+ "User-Agent": self.user_agent,
156
+ }
157
+ if has_body:
158
+ h["Content-Type"] = "application/json"
159
+ if self.organization_id:
160
+ h["X-Organization-ID"] = self.organization_id
161
+ return h
162
+
163
+ @staticmethod
164
+ def _safe(method: str, idempotent: bool) -> bool:
165
+ return method in ("GET", "HEAD", "PUT", "DELETE") or idempotent
166
+
167
+ @staticmethod
168
+ def _retryable(err: APIError, safe: bool) -> bool:
169
+ if err.status_code == 429:
170
+ return not err.is_quota_exceeded
171
+ if err.status_code in (502, 503, 504):
172
+ return safe
173
+ return False
174
+
175
+ def _backoff(self, attempt: int, hint: float) -> float:
176
+ d = min(self.min_backoff * (2 ** min(attempt, 16)), self.max_backoff)
177
+ d = d / 2 + random.uniform(0, d / 2) # jitter
178
+ if hint > d:
179
+ d = min(hint, self.max_backoff)
180
+ return float(d)
181
+
182
+ @staticmethod
183
+ def _retry_after(resp: httpx.Response) -> float:
184
+ v = resp.headers.get("Retry-After", "").strip()
185
+ if not v:
186
+ return 0.0
187
+ if v.isdigit():
188
+ return float(v)
189
+ try:
190
+ t = email.utils.parsedate_to_datetime(v)
191
+ except (TypeError, ValueError):
192
+ return 0.0
193
+ return max(0.0, t.timestamp() - time.time())
194
+
195
+ def _timeout(self, timeout: Timeout) -> float | httpx.Timeout | None:
196
+ return self.timeout if isinstance(timeout, NotGiven) else timeout
197
+
198
+ @staticmethod
199
+ def _decode(resp: httpx.Response, cls: type[M], method: str, path: str) -> M:
200
+ if not resp.content.strip():
201
+ return cls()
202
+ try:
203
+ data = resp.json()
204
+ except ValueError as e:
205
+ raise APIError(
206
+ resp.status_code,
207
+ error_from_response(resp, method, path).code,
208
+ f"invalid JSON in response: {e}",
209
+ [],
210
+ method,
211
+ path,
212
+ resp.headers,
213
+ ) from e
214
+ return cls.model_validate(data)
215
+
216
+
217
+ class SyncAPIClient(_BaseClient):
218
+ def __init__(self, token: str | None, *, http_client: httpx.Client | None, **kw: Any) -> None:
219
+ super().__init__(token, **kw)
220
+ self._owns_http = http_client is None
221
+ self._http = http_client or httpx.Client(timeout=self.timeout)
222
+
223
+ def close(self) -> None:
224
+ """Close the HTTP connections (only those the client opened itself)."""
225
+ if self._owns_http:
226
+ self._http.close()
227
+
228
+ def __enter__(self) -> Any:
229
+ return self
230
+
231
+ def __exit__(self, *exc: object) -> None:
232
+ self.close()
233
+
234
+ def request(
235
+ self,
236
+ method: str,
237
+ path: str,
238
+ *,
239
+ query: dict[str, Any] | None = None,
240
+ body: Any = None,
241
+ timeout: Timeout = NOT_GIVEN,
242
+ ) -> Any:
243
+ """Call any API path, for operations the SDK does not cover yet.
244
+
245
+ ``body`` is sent as JSON when not None. Returns the decoded JSON (or
246
+ None for an empty response).
247
+ """
248
+ resp = self._send(method.upper(), path, _query(query), body, False, timeout)
249
+ return resp.json() if resp.content.strip() else None
250
+
251
+ def _call(
252
+ self,
253
+ method: str,
254
+ path: str,
255
+ cls: type[M],
256
+ *,
257
+ query: list[tuple[str, Any]],
258
+ body: Any,
259
+ idempotent: bool,
260
+ timeout: Timeout,
261
+ ) -> M:
262
+ resp = self._send(method, path, query, body, idempotent, timeout)
263
+ return self._decode(resp, cls, method, path)
264
+
265
+ def _send(
266
+ self,
267
+ method: str,
268
+ path: str,
269
+ query: list[tuple[str, Any]],
270
+ body: Any,
271
+ idempotent: bool,
272
+ timeout: Timeout,
273
+ ) -> httpx.Response:
274
+ safe = self._safe(method, idempotent)
275
+ url = self.base_url + path
276
+ attempt = 0
277
+ while True:
278
+ start = time.monotonic()
279
+ try:
280
+ resp = self._http.request(
281
+ method,
282
+ url,
283
+ params=query or None,
284
+ json=body,
285
+ headers=self._headers(body is not None),
286
+ timeout=self._timeout(timeout),
287
+ )
288
+ except httpx.TimeoutException as e:
289
+ logger.debug("noderings request failed: %s %s: %s", method, path, e)
290
+ if not safe or attempt >= self.max_retries:
291
+ raise APITimeoutError(f"{method} {path}: {e}") from e
292
+ time.sleep(self._backoff(attempt, 0))
293
+ attempt += 1
294
+ continue
295
+ except httpx.TransportError as e:
296
+ logger.debug("noderings request failed: %s %s: %s", method, path, e)
297
+ if not safe or attempt >= self.max_retries:
298
+ raise APIConnectionError(f"{method} {path}: {e}") from e
299
+ time.sleep(self._backoff(attempt, 0))
300
+ attempt += 1
301
+ continue
302
+ logger.debug(
303
+ "noderings request: %s %s -> %d in %.3fs", method, path, resp.status_code, time.monotonic() - start
304
+ )
305
+ if resp.is_success:
306
+ return resp
307
+ err = error_from_response(resp, method, path)
308
+ if attempt >= self.max_retries or not self._retryable(err, safe):
309
+ raise err
310
+ time.sleep(self._backoff(attempt, self._retry_after(resp)))
311
+ attempt += 1
312
+
313
+
314
+ class AsyncAPIClient(_BaseClient):
315
+ def __init__(self, token: str | None, *, http_client: httpx.AsyncClient | None, **kw: Any) -> None:
316
+ super().__init__(token, **kw)
317
+ self._owns_http = http_client is None
318
+ self._http = http_client or httpx.AsyncClient(timeout=self.timeout)
319
+
320
+ async def close(self) -> None:
321
+ """Close the HTTP connections (only those the client opened itself)."""
322
+ if self._owns_http:
323
+ await self._http.aclose()
324
+
325
+ async def __aenter__(self) -> Any:
326
+ return self
327
+
328
+ async def __aexit__(self, *exc: object) -> None:
329
+ await self.close()
330
+
331
+ async def request(
332
+ self,
333
+ method: str,
334
+ path: str,
335
+ *,
336
+ query: dict[str, Any] | None = None,
337
+ body: Any = None,
338
+ timeout: Timeout = NOT_GIVEN,
339
+ ) -> Any:
340
+ """Call any API path, for operations the SDK does not cover yet.
341
+
342
+ ``body`` is sent as JSON when not None. Returns the decoded JSON (or
343
+ None for an empty response).
344
+ """
345
+ resp = await self._send(method.upper(), path, _query(query), body, False, timeout)
346
+ return resp.json() if resp.content.strip() else None
347
+
348
+ async def _call(
349
+ self,
350
+ method: str,
351
+ path: str,
352
+ cls: type[M],
353
+ *,
354
+ query: list[tuple[str, Any]],
355
+ body: Any,
356
+ idempotent: bool,
357
+ timeout: Timeout,
358
+ ) -> M:
359
+ resp = await self._send(method, path, query, body, idempotent, timeout)
360
+ return self._decode(resp, cls, method, path)
361
+
362
+ async def _send(
363
+ self,
364
+ method: str,
365
+ path: str,
366
+ query: list[tuple[str, Any]],
367
+ body: Any,
368
+ idempotent: bool,
369
+ timeout: Timeout,
370
+ ) -> httpx.Response:
371
+ safe = self._safe(method, idempotent)
372
+ url = self.base_url + path
373
+ attempt = 0
374
+ while True:
375
+ start = time.monotonic()
376
+ try:
377
+ resp = await self._http.request(
378
+ method,
379
+ url,
380
+ params=query or None,
381
+ json=body,
382
+ headers=self._headers(body is not None),
383
+ timeout=self._timeout(timeout),
384
+ )
385
+ except httpx.TimeoutException as e:
386
+ logger.debug("noderings request failed: %s %s: %s", method, path, e)
387
+ if not safe or attempt >= self.max_retries:
388
+ raise APITimeoutError(f"{method} {path}: {e}") from e
389
+ await asyncio.sleep(self._backoff(attempt, 0))
390
+ attempt += 1
391
+ continue
392
+ except httpx.TransportError as e:
393
+ logger.debug("noderings request failed: %s %s: %s", method, path, e)
394
+ if not safe or attempt >= self.max_retries:
395
+ raise APIConnectionError(f"{method} {path}: {e}") from e
396
+ await asyncio.sleep(self._backoff(attempt, 0))
397
+ attempt += 1
398
+ continue
399
+ logger.debug(
400
+ "noderings request: %s %s -> %d in %.3fs", method, path, resp.status_code, time.monotonic() - start
401
+ )
402
+ if resp.is_success:
403
+ return resp
404
+ err = error_from_response(resp, method, path)
405
+ if attempt >= self.max_retries or not self._retryable(err, safe):
406
+ raise err
407
+ await asyncio.sleep(self._backoff(attempt, self._retry_after(resp)))
408
+ attempt += 1
409
+
410
+
411
+ class _Service:
412
+ def __init__(self, client: SyncAPIClient) -> None:
413
+ self._client = client
414
+
415
+
416
+ class _ServiceAsync:
417
+ def __init__(self, client: AsyncAPIClient) -> None:
418
+ self._client = client
noderings/_client.py ADDED
@@ -0,0 +1,217 @@
1
+ """The NodeRings clients."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import time
7
+ from collections.abc import Awaitable, Callable
8
+ from typing import Any
9
+
10
+ import httpx
11
+
12
+ from . import models as m
13
+ from ._base import DEFAULT_MAX_RETRIES, DEFAULT_TIMEOUT, AsyncAPIClient, SyncAPIClient
14
+ from ._errors import NotFoundError
15
+ from ._services import _AsyncServices, _Services
16
+
17
+ __all__ = ["AsyncNodeRings", "NodeRings", "WaitTimeoutError"]
18
+
19
+
20
+ class WaitTimeoutError(TimeoutError):
21
+ """A wait helper gave up. ``last`` is the last state read, if any."""
22
+
23
+ def __init__(self, message: str, last: Any = None) -> None:
24
+ super().__init__(message)
25
+ self.last = last
26
+
27
+
28
+ def _status(vm: m.VirtualMachine | None) -> str:
29
+ return str(vm.operation_status) if vm is not None and vm.operation_status is not None else "unknown"
30
+
31
+
32
+ class NodeRings(SyncAPIClient, _Services):
33
+ """A client for the NodeRings API.
34
+
35
+ Every API area is an attribute (``virtual_machine``, ``dns_zone``,
36
+ ``dns_record``, ``firewall``, ``marketplace``, and so on). Each method
37
+ calls one API operation; paged lists also have an ``..._all`` method
38
+ that yields every result.
39
+
40
+ Args:
41
+ token: A NodeRings service account token. Defaults to the
42
+ ``NODERINGS_TOKEN`` environment variable.
43
+ organization_id: Send every request in this organization (the
44
+ ``X-Organization-ID`` header). Defaults to ``NODERINGS_ORGANIZATION_ID``,
45
+ else the token's own organization.
46
+ base_url: Another API endpoint, for example a test environment.
47
+ Defaults to ``NODERINGS_BASE_URL``, else https://api.noderings.com.
48
+ timeout: Seconds per request (or an ``httpx.Timeout``). Default 60.
49
+ max_retries: How often a failed request is retried. Default 3; 0 turns
50
+ retrying off. Retried: rate limits (HTTP 429, unless a plan quota is
51
+ used up), and connection errors and HTTP 502, 503 and 504 when the
52
+ request is safe to repeat (reads, PUT, DELETE, and creates that
53
+ carry an idempotency key). ``Retry-After`` is honoured.
54
+ min_backoff, max_backoff: The first and largest wait between attempts,
55
+ in seconds. Default 0.5 and 10.
56
+ user_agent: A product token such as ``"my-app/1.2"``, sent in front of
57
+ the SDK's own User-Agent.
58
+ http_client: Your own ``httpx.Client``, for proxies or custom TLS.
59
+
60
+ Use it as a context manager, or call :meth:`close` when done::
61
+
62
+ with NodeRings() as client:
63
+ for vm in client.virtual_machine.list_virtual_machines_all():
64
+ print(vm.name, vm.operation_status)
65
+ """
66
+
67
+ def __init__(
68
+ self,
69
+ token: str | None = None,
70
+ *,
71
+ organization_id: str | None = None,
72
+ base_url: str | None = None,
73
+ timeout: float | httpx.Timeout | None = DEFAULT_TIMEOUT,
74
+ max_retries: int = DEFAULT_MAX_RETRIES,
75
+ min_backoff: float = 0.5,
76
+ max_backoff: float = 10.0,
77
+ user_agent: str | None = None,
78
+ http_client: httpx.Client | None = None,
79
+ ) -> None:
80
+ super().__init__(
81
+ token,
82
+ organization_id=organization_id,
83
+ base_url=base_url,
84
+ timeout=timeout,
85
+ max_retries=max_retries,
86
+ min_backoff=min_backoff,
87
+ max_backoff=max_backoff,
88
+ user_agent=user_agent,
89
+ http_client=http_client,
90
+ )
91
+ self._init_services()
92
+
93
+ def __enter__(self) -> NodeRings:
94
+ return self
95
+
96
+ def wait_for_virtual_machine(
97
+ self,
98
+ id: str,
99
+ until: Callable[[m.VirtualMachine], bool],
100
+ *,
101
+ interval: float = 5.0,
102
+ timeout: float = 900.0,
103
+ ) -> m.VirtualMachine:
104
+ """Poll a virtual machine until ``until(vm)`` is true and return it.
105
+
106
+ Raises :class:`WaitTimeoutError` after ``timeout`` seconds (default 15
107
+ minutes), and :class:`NotFoundError` if the machine does not exist.
108
+ """
109
+ deadline = time.monotonic() + timeout
110
+ last: m.VirtualMachine | None = None
111
+ while True:
112
+ last = self.virtual_machine.get_virtual_machine(id)
113
+ if until(last):
114
+ return last
115
+ if time.monotonic() + interval > deadline:
116
+ raise WaitTimeoutError(
117
+ f"waiting for virtual machine {id}: timed out (last status {_status(last)})", last
118
+ )
119
+ time.sleep(interval)
120
+
121
+ def wait_for_virtual_machine_status(
122
+ self, id: str, *statuses: m.OperationStatus | str, interval: float = 5.0, timeout: float = 900.0
123
+ ) -> m.VirtualMachine:
124
+ """Wait until the virtual machine is in one of ``statuses``, for example ``OperationStatus.STARTED``."""
125
+ want = {str(s) for s in statuses}
126
+ return self.wait_for_virtual_machine(
127
+ id, lambda vm: str(vm.operation_status) in want, interval=interval, timeout=timeout
128
+ )
129
+
130
+ def wait_for_virtual_machine_deleted(self, id: str, *, interval: float = 5.0, timeout: float = 900.0) -> None:
131
+ """Wait until the virtual machine is gone."""
132
+ try:
133
+ self.wait_for_virtual_machine(
134
+ id, lambda vm: vm.operation_status == m.OperationStatus.DELETED, interval=interval, timeout=timeout
135
+ )
136
+ except NotFoundError:
137
+ return
138
+
139
+
140
+ class AsyncNodeRings(AsyncAPIClient, _AsyncServices):
141
+ """The asyncio version of :class:`NodeRings`, with the same arguments and API areas::
142
+
143
+ async with AsyncNodeRings() as client:
144
+ async for vm in client.virtual_machine.list_virtual_machines_all():
145
+ print(vm.name)
146
+ """
147
+
148
+ def __init__(
149
+ self,
150
+ token: str | None = None,
151
+ *,
152
+ organization_id: str | None = None,
153
+ base_url: str | None = None,
154
+ timeout: float | httpx.Timeout | None = DEFAULT_TIMEOUT,
155
+ max_retries: int = DEFAULT_MAX_RETRIES,
156
+ min_backoff: float = 0.5,
157
+ max_backoff: float = 10.0,
158
+ user_agent: str | None = None,
159
+ http_client: httpx.AsyncClient | None = None,
160
+ ) -> None:
161
+ super().__init__(
162
+ token,
163
+ organization_id=organization_id,
164
+ base_url=base_url,
165
+ timeout=timeout,
166
+ max_retries=max_retries,
167
+ min_backoff=min_backoff,
168
+ max_backoff=max_backoff,
169
+ user_agent=user_agent,
170
+ http_client=http_client,
171
+ )
172
+ self._init_services()
173
+
174
+ async def __aenter__(self) -> AsyncNodeRings:
175
+ return self
176
+
177
+ async def wait_for_virtual_machine(
178
+ self,
179
+ id: str,
180
+ until: Callable[[m.VirtualMachine], bool | Awaitable[bool]],
181
+ *,
182
+ interval: float = 5.0,
183
+ timeout: float = 900.0,
184
+ ) -> m.VirtualMachine:
185
+ """Poll a virtual machine until ``until(vm)`` is true and return it. See :meth:`NodeRings.wait_for_virtual_machine`."""
186
+ loop = asyncio.get_running_loop()
187
+ deadline = loop.time() + timeout
188
+ while True:
189
+ last = await self.virtual_machine.get_virtual_machine(id)
190
+ done = until(last)
191
+ if not isinstance(done, bool):
192
+ done = await done
193
+ if done:
194
+ return last
195
+ if loop.time() + interval > deadline:
196
+ raise WaitTimeoutError(
197
+ f"waiting for virtual machine {id}: timed out (last status {_status(last)})", last
198
+ )
199
+ await asyncio.sleep(interval)
200
+
201
+ async def wait_for_virtual_machine_status(
202
+ self, id: str, *statuses: m.OperationStatus | str, interval: float = 5.0, timeout: float = 900.0
203
+ ) -> m.VirtualMachine:
204
+ """Wait until the virtual machine is in one of ``statuses``."""
205
+ want = {str(s) for s in statuses}
206
+ return await self.wait_for_virtual_machine(
207
+ id, lambda vm: str(vm.operation_status) in want, interval=interval, timeout=timeout
208
+ )
209
+
210
+ async def wait_for_virtual_machine_deleted(self, id: str, *, interval: float = 5.0, timeout: float = 900.0) -> None:
211
+ """Wait until the virtual machine is gone."""
212
+ try:
213
+ await self.wait_for_virtual_machine(
214
+ id, lambda vm: vm.operation_status == m.OperationStatus.DELETED, interval=interval, timeout=timeout
215
+ )
216
+ except NotFoundError:
217
+ return