dwave-cloud-client 0.12.0.dev0__tar.gz → 0.13.0__tar.gz
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.
- {dwave-cloud-client-0.12.0.dev0/dwave_cloud_client.egg-info → dwave-cloud-client-0.13.0}/PKG-INFO +1 -1
- dwave-cloud-client-0.13.0/dwave/cloud/__init__.py +78 -0
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave/cloud/api/client.py +268 -17
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave/cloud/api/models.py +43 -11
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave/cloud/api/resources.py +70 -41
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave/cloud/auth/flows.py +6 -3
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave/cloud/cli.py +18 -19
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave/cloud/client/base.py +212 -139
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave/cloud/coders.py +61 -6
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave/cloud/computation.py +17 -35
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave/cloud/config/loaders.py +9 -3
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave/cloud/config/models.py +44 -8
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave/cloud/events.py +18 -4
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave/cloud/package_info.py +1 -1
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave/cloud/regions.py +21 -30
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave/cloud/solver.py +52 -25
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave/cloud/testing/mocks.py +91 -15
- dwave-cloud-client-0.13.0/dwave/cloud/utils/__init__.py +26 -0
- dwave-cloud-client-0.13.0/dwave/cloud/utils/cli.py +105 -0
- dwave-cloud-client-0.13.0/dwave/cloud/utils/coders.py +77 -0
- dwave-cloud-client-0.13.0/dwave/cloud/utils/decorators.py +449 -0
- dwave-cloud-client-0.13.0/dwave/cloud/utils/dist.py +94 -0
- dwave-cloud-client-0.13.0/dwave/cloud/utils/exception.py +93 -0
- dwave-cloud-client-0.13.0/dwave/cloud/utils/http.py +160 -0
- dwave-cloud-client-0.13.0/dwave/cloud/utils/logging.py +292 -0
- dwave-cloud-client-0.13.0/dwave/cloud/utils/qubo.py +147 -0
- dwave-cloud-client-0.13.0/dwave/cloud/utils/time.py +72 -0
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0/dwave_cloud_client.egg-info}/PKG-INFO +1 -1
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave_cloud_client.egg-info/SOURCES.txt +11 -1
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave_cloud_client.egg-info/requires.txt +2 -1
- dwave-cloud-client-0.13.0/pyproject.toml +6 -0
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/setup.py +2 -1
- dwave-cloud-client-0.12.0.dev0/dwave/cloud/__init__.py +0 -174
- dwave-cloud-client-0.12.0.dev0/dwave/cloud/utils.py +0 -1069
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/LICENSE +0 -0
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/README.rst +0 -0
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave/__init__.py +0 -0
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave/cloud/api/__init__.py +0 -0
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave/cloud/api/constants.py +0 -0
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave/cloud/api/exceptions.py +0 -0
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave/cloud/auth/__init__.py +0 -0
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave/cloud/auth/_creds.py +0 -0
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave/cloud/auth/config.py +0 -0
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave/cloud/auth/creds.py +0 -0
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave/cloud/auth/server.py +0 -0
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave/cloud/client/__init__.py +0 -0
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave/cloud/client/hybrid.py +0 -0
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave/cloud/client/qpu.py +0 -0
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave/cloud/client/sw.py +0 -0
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave/cloud/concurrency.py +0 -0
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave/cloud/config/__init__.py +0 -0
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave/cloud/exceptions.py +0 -0
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave/cloud/testing/__init__.py +0 -0
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave/cloud/upload.py +0 -0
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave_cloud_client.egg-info/dependency_links.txt +0 -0
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave_cloud_client.egg-info/entry_points.txt +0 -0
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave_cloud_client.egg-info/not-zip-safe +0 -0
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/dwave_cloud_client.egg-info/top_level.txt +0 -0
- {dwave-cloud-client-0.12.0.dev0 → dwave-cloud-client-0.13.0}/setup.cfg +0 -0
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
# Copyright 2017 D-Wave Systems Inc.
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
import sys
|
|
16
|
+
import logging
|
|
17
|
+
import importlib
|
|
18
|
+
import types
|
|
19
|
+
import warnings
|
|
20
|
+
|
|
21
|
+
from dwave.cloud.utils.logging import add_loglevel, configure_logging_from_env
|
|
22
|
+
|
|
23
|
+
__all__ = ['Client', 'Solver', 'Future']
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
# prevent log output (from library) when logging not configured by user/app
|
|
27
|
+
logger = logging.getLogger(__name__)
|
|
28
|
+
logger.addHandler(logging.NullHandler())
|
|
29
|
+
|
|
30
|
+
# make sure TRACE level is available
|
|
31
|
+
add_loglevel('TRACE', 5)
|
|
32
|
+
|
|
33
|
+
# configure logger if DWAVE_LOG_LEVEL present in environment
|
|
34
|
+
configure_logging_from_env(logger)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
# lazily import Client/Solver/Future -- only when actually asked for
|
|
38
|
+
def __getattr__(cls):
|
|
39
|
+
modname = {'Client': 'client', 'Solver': 'solver', 'Future': 'computation'}
|
|
40
|
+
if cls in modname:
|
|
41
|
+
mod = importlib.import_module(f'dwave.cloud.{modname[cls]}')
|
|
42
|
+
return getattr(mod, cls)
|
|
43
|
+
|
|
44
|
+
raise AttributeError(f"module '{__name__}' has no attribute '{cls}'")
|
|
45
|
+
|
|
46
|
+
def __dir__():
|
|
47
|
+
# dev note: make sure __all__ is limited to symbols we import lazily
|
|
48
|
+
yield from __all__
|
|
49
|
+
yield from globals()
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
# lazily alias dwave.cloud.client.{qpu,sw,hybrid} as dwave.cloud.*
|
|
53
|
+
# (i.e. don't preemptively import Client from submodules)
|
|
54
|
+
def _alias_old_client_submodules():
|
|
55
|
+
class _submod(types.ModuleType):
|
|
56
|
+
def __getattr__(self, name):
|
|
57
|
+
modname = self.__name__
|
|
58
|
+
if name == 'Client':
|
|
59
|
+
warnings.warn(
|
|
60
|
+
f"Importing 'Client' from 'dwave.cloud.{modname}' has been "
|
|
61
|
+
f"deprecated and will be removed in dwave-cloud-client 0.14. "
|
|
62
|
+
f"Import 'Client' directly from 'dwave.cloud.client.{modname}'.",
|
|
63
|
+
DeprecationWarning, stacklevel=2)
|
|
64
|
+
|
|
65
|
+
mod = importlib.import_module(f'dwave.cloud.client.{modname}')
|
|
66
|
+
return getattr(mod, 'Client')
|
|
67
|
+
|
|
68
|
+
raise AttributeError(f"module '{self.__name__}' has no attribute '{name}'")
|
|
69
|
+
|
|
70
|
+
def __dir__(self):
|
|
71
|
+
self.__getattr__('Client') # force submodule import
|
|
72
|
+
yield from dir(sys.modules[f'dwave.cloud.client.{self.__name__}'])
|
|
73
|
+
|
|
74
|
+
for name in ('qpu', 'sw', 'hybrid'):
|
|
75
|
+
globals()[name] = sys.modules[f'dwave.cloud.{name}'] = _submod(name)
|
|
76
|
+
|
|
77
|
+
# TODO: remove in 0.14.0
|
|
78
|
+
_alias_old_client_submodules()
|
|
@@ -14,20 +14,29 @@
|
|
|
14
14
|
|
|
15
15
|
from __future__ import annotations
|
|
16
16
|
|
|
17
|
+
import io
|
|
18
|
+
import hashlib
|
|
17
19
|
import logging
|
|
20
|
+
import numbers
|
|
21
|
+
import os
|
|
22
|
+
import warnings
|
|
18
23
|
from collections import deque, namedtuple
|
|
19
|
-
from typing import Optional, Union
|
|
24
|
+
from typing import Callable, Mapping, Optional, Tuple, TypedDict, Union, TYPE_CHECKING
|
|
20
25
|
|
|
26
|
+
import orjson
|
|
21
27
|
import requests
|
|
22
28
|
import urllib3
|
|
29
|
+
import werkzeug
|
|
23
30
|
from packaging.specifiers import SpecifierSet
|
|
24
|
-
from werkzeug.http import parse_options_header, dump_options_header
|
|
25
31
|
|
|
32
|
+
import dwave.cloud.config # don't use `from` to break circular import (config <> api.constants)
|
|
26
33
|
from dwave.cloud.api import constants, exceptions
|
|
27
|
-
from dwave.cloud.
|
|
28
|
-
from dwave.cloud.
|
|
29
|
-
from dwave.cloud.utils import
|
|
30
|
-
|
|
34
|
+
from dwave.cloud.utils.exception import is_caused_by
|
|
35
|
+
from dwave.cloud.utils.http import PretimedHTTPAdapter, BaseUrlSession, default_user_agent
|
|
36
|
+
from dwave.cloud.utils.time import epochnow
|
|
37
|
+
|
|
38
|
+
if TYPE_CHECKING:
|
|
39
|
+
from dwave.cloud.config.models import ClientConfig
|
|
31
40
|
|
|
32
41
|
__all__ = ['DWaveAPIClient', 'SolverAPIClient', 'MetadataAPIClient', 'LeapAPIClient']
|
|
33
42
|
|
|
@@ -171,7 +180,7 @@ class VersionedAPISession(LoggingSession):
|
|
|
171
180
|
"""Validate response's `Content-Type` matches the expected media type
|
|
172
181
|
and version range.
|
|
173
182
|
"""
|
|
174
|
-
if self._media_type is None or not response.
|
|
183
|
+
if self._media_type is None or not 200 <= response.status_code < 300:
|
|
175
184
|
return
|
|
176
185
|
|
|
177
186
|
content_type = response.headers.get('Content-Type')
|
|
@@ -183,7 +192,7 @@ class VersionedAPISession(LoggingSession):
|
|
|
183
192
|
else:
|
|
184
193
|
return
|
|
185
194
|
|
|
186
|
-
media_type, params = parse_options_header(content_type)
|
|
195
|
+
media_type, params = werkzeug.http.parse_options_header(content_type)
|
|
187
196
|
|
|
188
197
|
if media_type != self._media_type:
|
|
189
198
|
raise exceptions.ResourceBadResponseError(
|
|
@@ -214,7 +223,7 @@ class VersionedAPISession(LoggingSession):
|
|
|
214
223
|
params['version'] = self._ask_version
|
|
215
224
|
|
|
216
225
|
headers = {} if headers is None else headers.copy()
|
|
217
|
-
headers['Accept'] = dump_options_header(self._media_type, params)
|
|
226
|
+
headers['Accept'] = werkzeug.http.dump_options_header(self._media_type, params)
|
|
218
227
|
|
|
219
228
|
response = super().request(*args, headers=headers, **kwargs)
|
|
220
229
|
|
|
@@ -226,6 +235,243 @@ class VersionedAPISession(LoggingSession):
|
|
|
226
235
|
return response
|
|
227
236
|
|
|
228
237
|
|
|
238
|
+
def _create_default_cache_store(**kwargs) -> Mapping:
|
|
239
|
+
# TODO: de-dup vs `dwave.cloud.utils.decorators.cached`?
|
|
240
|
+
|
|
241
|
+
# defer to break circular imports
|
|
242
|
+
from dwave.cloud.config import get_cache_dir
|
|
243
|
+
|
|
244
|
+
directory = kwargs.pop('directory', os.path.join(get_cache_dir(), 'api'))
|
|
245
|
+
|
|
246
|
+
# defer import and construction until needed
|
|
247
|
+
import diskcache
|
|
248
|
+
return diskcache.Cache(directory=directory)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
class CachingSession(VersionedAPISession):
|
|
252
|
+
"""A `requests.Session` subclass (technically, further specialized
|
|
253
|
+
:class:`.VersionedAPISession`) that caches responses and uses conditional
|
|
254
|
+
requests for smart cache updates.
|
|
255
|
+
|
|
256
|
+
Args:
|
|
257
|
+
cache (dict):
|
|
258
|
+
Cache configuration in a dict with keys:
|
|
259
|
+
|
|
260
|
+
* ``enabled`` (bool):
|
|
261
|
+
Enable request caching.
|
|
262
|
+
|
|
263
|
+
* ``maxage`` (float):
|
|
264
|
+
Default response maxage, in case server response
|
|
265
|
+
doesn't specify ``Cache-Control``.
|
|
266
|
+
|
|
267
|
+
* ``store`` (mapping, callable):
|
|
268
|
+
Define cache storage (with a Mapping interface). Default to
|
|
269
|
+
``diskcache.Cache`` with pickle serialization.
|
|
270
|
+
|
|
271
|
+
:meth:`CachingSession.request` accepts the following keyword arguments,
|
|
272
|
+
in addition to the base class method:
|
|
273
|
+
|
|
274
|
+
* ``maxage_`` (float):
|
|
275
|
+
Suggested maxage for heuristic caching, overriding the default value
|
|
276
|
+
from cache config.
|
|
277
|
+
|
|
278
|
+
* ``no_cache_`` (bool):
|
|
279
|
+
Skip cache.
|
|
280
|
+
|
|
281
|
+
* ``refresh_`` (bool):
|
|
282
|
+
Force cache update, skipping time-based or etag-based validation.
|
|
283
|
+
"""
|
|
284
|
+
|
|
285
|
+
_cache_enabled = False
|
|
286
|
+
_maxage = None
|
|
287
|
+
_store = None
|
|
288
|
+
|
|
289
|
+
class CacheConfig(TypedDict, total=False):
|
|
290
|
+
enabled: bool
|
|
291
|
+
maxage: float
|
|
292
|
+
store: Union[Mapping, Callable[[], Mapping]]
|
|
293
|
+
|
|
294
|
+
# default cache config
|
|
295
|
+
_default_cache_config = CacheConfig(enabled=True,
|
|
296
|
+
maxage=0,
|
|
297
|
+
store=_create_default_cache_store)
|
|
298
|
+
|
|
299
|
+
def __init__(self, cache: Union[CacheConfig, bool, None] = None, **kwargs):
|
|
300
|
+
if cache is None:
|
|
301
|
+
cache = self._default_cache_config
|
|
302
|
+
|
|
303
|
+
if not isinstance(cache, dict):
|
|
304
|
+
enabled = bool(cache)
|
|
305
|
+
cache = self._default_cache_config
|
|
306
|
+
cache.update(enabled=enabled)
|
|
307
|
+
|
|
308
|
+
self.configure_cache(cache)
|
|
309
|
+
|
|
310
|
+
super().__init__(**kwargs)
|
|
311
|
+
|
|
312
|
+
def configure_cache(self, cache: CacheConfig) -> None:
|
|
313
|
+
config = {opt: cache.get(opt, default)
|
|
314
|
+
for opt, default in self._default_cache_config.items()}
|
|
315
|
+
|
|
316
|
+
self._cache_enabled = enabled = config['enabled']
|
|
317
|
+
if not enabled:
|
|
318
|
+
logger.debug("[%s] cache disabled.", type(self).__name__)
|
|
319
|
+
return
|
|
320
|
+
|
|
321
|
+
_maxage = config.get('maxage')
|
|
322
|
+
if not isinstance(_maxage, numbers.Real) or _maxage < 0:
|
|
323
|
+
raise ValueError("A non-negative real value required for 'maxage'.")
|
|
324
|
+
self._maxage = _maxage
|
|
325
|
+
|
|
326
|
+
self._store = config['store']
|
|
327
|
+
if callable(self._store):
|
|
328
|
+
self._store = self._store()
|
|
329
|
+
|
|
330
|
+
logger.debug("[%s] configured cache: (enabled=%r, maxage=%r, store=%r)",
|
|
331
|
+
type(self).__name__, self._cache_enabled, self._maxage, self._store)
|
|
332
|
+
|
|
333
|
+
if hasattr(self._store, 'directory'):
|
|
334
|
+
logger.debug("cache.store.directory=%r", self._store.directory)
|
|
335
|
+
|
|
336
|
+
def _parse_cache_control(
|
|
337
|
+
self,
|
|
338
|
+
cache_control: Optional[str] = None,
|
|
339
|
+
) -> Tuple[bool, Optional[int]]:
|
|
340
|
+
# parse Cache-Control header field (if present) and derive a suitable max-age value
|
|
341
|
+
# returns: (cache?, maxage)
|
|
342
|
+
|
|
343
|
+
# note:
|
|
344
|
+
# - we always revalidate after expiry, so we can ignore `must-revalidate`
|
|
345
|
+
# - and we never transform the response, so safe to ignore `no-transform`
|
|
346
|
+
# - our cache is private (for a single user), so we can ignore `private`,
|
|
347
|
+
# `public` and `s-maxage` directives
|
|
348
|
+
|
|
349
|
+
cc = werkzeug.http.parse_cache_control_header(
|
|
350
|
+
cache_control, cls=werkzeug.datastructures.ResponseCacheControl)
|
|
351
|
+
|
|
352
|
+
if cc.no_cache:
|
|
353
|
+
# cache, but always validate
|
|
354
|
+
return (True, 0)
|
|
355
|
+
|
|
356
|
+
if cc.no_store:
|
|
357
|
+
# skip cache
|
|
358
|
+
return (False, 0)
|
|
359
|
+
|
|
360
|
+
# cache for up to max_age
|
|
361
|
+
return (True, cc.max_age)
|
|
362
|
+
|
|
363
|
+
def _update_cache(
|
|
364
|
+
self,
|
|
365
|
+
response: requests.Response,
|
|
366
|
+
key_meta: str,
|
|
367
|
+
key_data: Optional[str] = None,
|
|
368
|
+
only_meta: bool = False
|
|
369
|
+
) -> bool:
|
|
370
|
+
# update cache from response according to cache-control
|
|
371
|
+
# returns: updated?
|
|
372
|
+
|
|
373
|
+
# etag and cache-control are present in 304 if they're in 200 response
|
|
374
|
+
# see: https://datatracker.ietf.org/doc/html/rfc9110#name-304-not-modified
|
|
375
|
+
etag = response.headers.get('ETag')
|
|
376
|
+
cache_control = response.headers.get('Cache-Control')
|
|
377
|
+
|
|
378
|
+
use_cache, maxage = self._parse_cache_control(cache_control)
|
|
379
|
+
if use_cache:
|
|
380
|
+
meta = dict(created=epochnow(), maxage=maxage, etag=etag)
|
|
381
|
+
self._store[key_meta] = meta
|
|
382
|
+
if not only_meta:
|
|
383
|
+
self._store[key_data] = response.content
|
|
384
|
+
|
|
385
|
+
logger.debug("response cached for maxage=%r", maxage)
|
|
386
|
+
return True
|
|
387
|
+
|
|
388
|
+
else:
|
|
389
|
+
if key_meta in self._store:
|
|
390
|
+
del self._store[key_meta]
|
|
391
|
+
if key_data in self._store:
|
|
392
|
+
del self._store[key_data]
|
|
393
|
+
|
|
394
|
+
logger.debug("response caching skipped at server's request")
|
|
395
|
+
return False
|
|
396
|
+
|
|
397
|
+
def request(self, method, url, *,
|
|
398
|
+
params: Optional[dict] = None,
|
|
399
|
+
headers: Optional[dict] = None,
|
|
400
|
+
**kwargs
|
|
401
|
+
) -> requests.Response:
|
|
402
|
+
|
|
403
|
+
# read CachingSession-specific params
|
|
404
|
+
refresh = kwargs.pop('refresh_', False)
|
|
405
|
+
no_cache = kwargs.pop('no_cache_', False)
|
|
406
|
+
default_maxage = kwargs.pop('maxage_', None)
|
|
407
|
+
if default_maxage is None:
|
|
408
|
+
default_maxage = self._maxage
|
|
409
|
+
elif not isinstance(default_maxage, numbers.Real) or default_maxage < 0:
|
|
410
|
+
warnings.warn(
|
|
411
|
+
f"non-negative real value required for 'maxage_'; ignoring {default_maxage}",
|
|
412
|
+
UserWarning, stacklevel=2)
|
|
413
|
+
default_maxage = self._maxage
|
|
414
|
+
|
|
415
|
+
if not self._cache_enabled or no_cache or method.lower() != 'get':
|
|
416
|
+
# completely bypass cache lookup and validation
|
|
417
|
+
return super().request(method, url, params=params, headers=headers, **kwargs)
|
|
418
|
+
|
|
419
|
+
key = (method,
|
|
420
|
+
self.base_url, url,
|
|
421
|
+
self.params, params,
|
|
422
|
+
self.headers, headers)
|
|
423
|
+
|
|
424
|
+
# note: metadata split from data for faster metadata-only updates
|
|
425
|
+
key_data = hashlib.sha256(repr(key).encode('utf8')).hexdigest()
|
|
426
|
+
key_meta = f"{key_data}:meta"
|
|
427
|
+
|
|
428
|
+
def make_response(content):
|
|
429
|
+
res = requests.Response()
|
|
430
|
+
res.status_code = 200
|
|
431
|
+
res.raw = io.BytesIO(content)
|
|
432
|
+
return res
|
|
433
|
+
|
|
434
|
+
if not refresh and (meta := self._store.get(key_meta)):
|
|
435
|
+
# respect max-age from response cache-control
|
|
436
|
+
maxage = meta.get('maxage')
|
|
437
|
+
if maxage is None:
|
|
438
|
+
# but if cache-control was absent, client gets do decide
|
|
439
|
+
maxage = default_maxage
|
|
440
|
+
|
|
441
|
+
# note: by deferring this lookup, we could save a few ms in case
|
|
442
|
+
# when upstream content was modified (but that doesn't happen often)
|
|
443
|
+
content = self._store.get(key_data)
|
|
444
|
+
|
|
445
|
+
if epochnow() - meta['created'] < maxage:
|
|
446
|
+
logger.debug('cache hit within maxage')
|
|
447
|
+
return make_response(content)
|
|
448
|
+
|
|
449
|
+
# validate with conditional request if possible
|
|
450
|
+
if etag := meta.get('etag'):
|
|
451
|
+
headers = {} if headers is None else headers.copy()
|
|
452
|
+
headers['If-None-Match'] = etag
|
|
453
|
+
|
|
454
|
+
res = super().request(method, url, params=params, headers=headers, **kwargs)
|
|
455
|
+
|
|
456
|
+
if res.status_code == requests.codes['not_modified']:
|
|
457
|
+
# see 4.3.4. in rfc9111 (http caching)
|
|
458
|
+
# we know SAPI only uses weak validators
|
|
459
|
+
logger.debug('resource "not modified", using cached value')
|
|
460
|
+
self._update_cache(res, key_meta=key_meta, only_meta=True)
|
|
461
|
+
return make_response(content)
|
|
462
|
+
|
|
463
|
+
else:
|
|
464
|
+
logger.debug('resource modified, updating cache')
|
|
465
|
+
self._update_cache(res, key_meta=key_meta, key_data=key_data)
|
|
466
|
+
return res
|
|
467
|
+
|
|
468
|
+
else:
|
|
469
|
+
logger.debug('cache miss, updating cache')
|
|
470
|
+
res = super().request(method, url, params=params, headers=headers, **kwargs)
|
|
471
|
+
self._update_cache(res, key_meta=key_meta, key_data=key_data)
|
|
472
|
+
return res
|
|
473
|
+
|
|
474
|
+
|
|
229
475
|
class DWaveAPIClient:
|
|
230
476
|
"""Low-level client for D-Wave APIs. A thin wrapper around
|
|
231
477
|
`requests.Session` that handles API specifics such as authentication,
|
|
@@ -269,10 +515,13 @@ class DWaveAPIClient:
|
|
|
269
515
|
'history_size': 0,
|
|
270
516
|
|
|
271
517
|
# response version strict mode validation, see :class:`VersionedAPISession`
|
|
272
|
-
'version_strict_mode': True
|
|
518
|
+
'version_strict_mode': True,
|
|
519
|
+
|
|
520
|
+
# enable conditional requests and response caching, see :class:`CachingSession`
|
|
521
|
+
'cache': dict(enabled=False), # type: CachingSession.CacheConfig
|
|
273
522
|
}
|
|
274
523
|
|
|
275
|
-
# client instance config, populated on init from kwargs
|
|
524
|
+
# client instance config, populated on init from kwargs overriding DEFAULTS
|
|
276
525
|
config = None
|
|
277
526
|
|
|
278
527
|
def __init__(self, **config):
|
|
@@ -326,8 +575,8 @@ class DWaveAPIClient:
|
|
|
326
575
|
logger.trace(f"{cls.__name__}.from_config_file("
|
|
327
576
|
f"config_file={config_file!r}, profile={profile!r}, **{kwargs!r})")
|
|
328
577
|
|
|
329
|
-
options = load_config(config_file=config_file, profile=profile, **kwargs)
|
|
330
|
-
config = validate_config_v1(options)
|
|
578
|
+
options = dwave.cloud.config.load_config(config_file=config_file, profile=profile, **kwargs)
|
|
579
|
+
config = dwave.cloud.config.validate_config_v1(options)
|
|
331
580
|
return cls.from_config_model(config)
|
|
332
581
|
|
|
333
582
|
@classmethod
|
|
@@ -346,7 +595,7 @@ class DWaveAPIClient:
|
|
|
346
595
|
"""
|
|
347
596
|
logger.trace(f"{cls.__name__}.from_config(config={config!r}, **{kwargs!r}")
|
|
348
597
|
|
|
349
|
-
if isinstance(config, ClientConfig):
|
|
598
|
+
if isinstance(config, dwave.cloud.config.ClientConfig):
|
|
350
599
|
return cls.from_config_model(config, **kwargs)
|
|
351
600
|
|
|
352
601
|
kwargs['config_file'] = config
|
|
@@ -392,10 +641,12 @@ class DWaveAPIClient:
|
|
|
392
641
|
endpoint += '/'
|
|
393
642
|
|
|
394
643
|
# configure request timeout and retries
|
|
395
|
-
session =
|
|
644
|
+
session = CachingSession(
|
|
396
645
|
base_url=endpoint,
|
|
397
646
|
history_size=config['history_size'],
|
|
398
|
-
strict_mode=config['version_strict_mode']
|
|
647
|
+
strict_mode=config['version_strict_mode'],
|
|
648
|
+
cache=config['cache'],
|
|
649
|
+
)
|
|
399
650
|
timeout = config['timeout']
|
|
400
651
|
retry = config['retry']
|
|
401
652
|
session.mount('http://', PretimedHTTPAdapter(
|
|
@@ -443,7 +694,7 @@ class DWaveAPIClient:
|
|
|
443
694
|
# error -> body can be json or plain text error message
|
|
444
695
|
if not response.ok:
|
|
445
696
|
try:
|
|
446
|
-
msg = response.
|
|
697
|
+
msg = orjson.loads(response.content)
|
|
447
698
|
error_msg = msg['error_msg']
|
|
448
699
|
error_code = msg['error_code']
|
|
449
700
|
except:
|
|
@@ -16,18 +16,44 @@ from datetime import datetime
|
|
|
16
16
|
from typing import List, Union, Optional, Dict, Any
|
|
17
17
|
from typing_extensions import Annotated # backport for py37, py38
|
|
18
18
|
|
|
19
|
-
from pydantic import BaseModel, RootModel,
|
|
19
|
+
from pydantic import BaseModel, RootModel, ConfigDict
|
|
20
20
|
from pydantic.functional_validators import AfterValidator
|
|
21
21
|
|
|
22
22
|
from dwave.cloud.api import constants
|
|
23
|
-
from dwave.cloud.utils import coerce_numpy_to_python
|
|
23
|
+
from dwave.cloud.utils.coders import coerce_numpy_to_python
|
|
24
24
|
|
|
25
25
|
|
|
26
26
|
# coerce common numpy types to python types on validation (parsing)
|
|
27
27
|
AnyIncludingNumpy = Annotated[Any, AfterValidator(coerce_numpy_to_python)]
|
|
28
28
|
|
|
29
29
|
|
|
30
|
-
class
|
|
30
|
+
class _RootGetterMixin:
|
|
31
|
+
"""Proxy getter calls to root model."""
|
|
32
|
+
|
|
33
|
+
def __getattr__(self, item):
|
|
34
|
+
return getattr(self.root, item)
|
|
35
|
+
|
|
36
|
+
def __getitem__(self, name):
|
|
37
|
+
return getattr(self.root, name)
|
|
38
|
+
|
|
39
|
+
def get(self, key, default=None):
|
|
40
|
+
try:
|
|
41
|
+
return self[key]
|
|
42
|
+
except AttributeError:
|
|
43
|
+
return default
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class _RootSetterMixin:
|
|
47
|
+
"""Proxy setter calls to root model."""
|
|
48
|
+
|
|
49
|
+
def __setattr__(self, name, value):
|
|
50
|
+
return setattr(self.root, name, value)
|
|
51
|
+
|
|
52
|
+
def __setitem__(self, name, value):
|
|
53
|
+
return setattr(self.root, name, value)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class SolverCompleteConfiguration(BaseModel):
|
|
31
57
|
id: str
|
|
32
58
|
status: str
|
|
33
59
|
description: str
|
|
@@ -35,6 +61,18 @@ class SolverConfiguration(BaseModel):
|
|
|
35
61
|
avg_load: float
|
|
36
62
|
|
|
37
63
|
|
|
64
|
+
class SolverFilteredConfiguration(BaseModel):
|
|
65
|
+
# no required fields, and no ignored fields
|
|
66
|
+
model_config = ConfigDict(extra='allow')
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
# NOTE: we implement getitem interface so that `SolverConfiguration` can be
|
|
70
|
+
# used as a drop-in replacement for data dict in `Solver(..., data=...)`
|
|
71
|
+
# TODO: break `Solver()` backwards compat and require pydantic model
|
|
72
|
+
class SolverConfiguration(_RootGetterMixin, _RootSetterMixin, RootModel):
|
|
73
|
+
root: Union[SolverCompleteConfiguration, SolverFilteredConfiguration]
|
|
74
|
+
|
|
75
|
+
|
|
38
76
|
class ProblemInitialStatus(BaseModel):
|
|
39
77
|
id: str
|
|
40
78
|
type: constants.ProblemType
|
|
@@ -71,14 +109,11 @@ class UnstructuredProblemAnswerBinaryRef(BaseModel):
|
|
|
71
109
|
shape: dict
|
|
72
110
|
|
|
73
111
|
|
|
74
|
-
class ProblemAnswer(RootModel):
|
|
112
|
+
class ProblemAnswer(_RootGetterMixin, RootModel):
|
|
75
113
|
root: Union[StructuredProblemAnswer,
|
|
76
114
|
UnstructuredProblemAnswer,
|
|
77
115
|
UnstructuredProblemAnswerBinaryRef]
|
|
78
116
|
|
|
79
|
-
def __getattr__(self, item):
|
|
80
|
-
return getattr(self.root, item)
|
|
81
|
-
|
|
82
117
|
|
|
83
118
|
class ProblemStatusWithAnswer(ProblemStatus):
|
|
84
119
|
answer: ProblemAnswer
|
|
@@ -100,12 +135,9 @@ class UnstructuredProblemData(BaseModel):
|
|
|
100
135
|
data: str
|
|
101
136
|
|
|
102
137
|
|
|
103
|
-
class ProblemData(RootModel):
|
|
138
|
+
class ProblemData(_RootGetterMixin, RootModel):
|
|
104
139
|
root: Union[StructuredProblemData, UnstructuredProblemData]
|
|
105
140
|
|
|
106
|
-
def __getattr__(self, item):
|
|
107
|
-
return getattr(self.root, item)
|
|
108
|
-
|
|
109
141
|
|
|
110
142
|
class ProblemMetadata(BaseModel):
|
|
111
143
|
solver: str
|