dwave-cloud-client 0.13.2__tar.gz → 0.13.4__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.
Files changed (75) hide show
  1. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/PKG-INFO +25 -16
  2. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/README.rst +14 -15
  3. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/api/client.py +130 -10
  4. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/api/models.py +8 -0
  5. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/api/resources.py +43 -12
  6. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/client/base.py +61 -35
  7. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/config/models.py +3 -1
  8. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/exceptions.py +4 -0
  9. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/package_info.py +1 -1
  10. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/solver.py +22 -6
  11. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/utils/logging.py +39 -22
  12. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave_cloud_client.egg-info/PKG-INFO +25 -16
  13. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/tests/test_client.py +27 -3
  14. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/tests/test_mock_solver_loading.py +10 -0
  15. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/tests/test_mock_submission.py +125 -1
  16. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/tests/test_utils.py +25 -2
  17. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/LICENSE +0 -0
  18. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/__init__.py +0 -0
  19. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/__init__.py +0 -0
  20. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/api/__init__.py +0 -0
  21. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/api/constants.py +0 -0
  22. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/api/exceptions.py +0 -0
  23. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/auth/__init__.py +0 -0
  24. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/auth/_creds.py +0 -0
  25. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/auth/config.py +0 -0
  26. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/auth/creds.py +0 -0
  27. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/auth/flows.py +0 -0
  28. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/auth/server.py +0 -0
  29. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/cli.py +0 -0
  30. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/client/__init__.py +0 -0
  31. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/client/hybrid.py +0 -0
  32. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/client/qpu.py +0 -0
  33. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/client/sw.py +0 -0
  34. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/coders.py +0 -0
  35. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/computation.py +0 -0
  36. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/concurrency.py +0 -0
  37. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/config/__init__.py +0 -0
  38. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/config/constants.py +0 -0
  39. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/config/exceptions.py +0 -0
  40. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/config/loaders.py +0 -0
  41. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/events.py +0 -0
  42. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/regions.py +0 -0
  43. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/testing/__init__.py +0 -0
  44. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/testing/mocks.py +0 -0
  45. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/upload.py +0 -0
  46. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/utils/__init__.py +0 -0
  47. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/utils/cli.py +0 -0
  48. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/utils/coders.py +0 -0
  49. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/utils/decorators.py +0 -0
  50. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/utils/dist.py +0 -0
  51. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/utils/exception.py +0 -0
  52. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/utils/http.py +0 -0
  53. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/utils/qubo.py +0 -0
  54. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave/cloud/utils/time.py +0 -0
  55. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave_cloud_client.egg-info/SOURCES.txt +0 -0
  56. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave_cloud_client.egg-info/dependency_links.txt +0 -0
  57. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave_cloud_client.egg-info/entry_points.txt +0 -0
  58. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave_cloud_client.egg-info/not-zip-safe +0 -0
  59. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave_cloud_client.egg-info/requires.txt +0 -0
  60. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/dwave_cloud_client.egg-info/top_level.txt +0 -0
  61. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/pyproject.toml +0 -0
  62. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/setup.cfg +0 -0
  63. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/setup.py +0 -0
  64. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/tests/test_cli.py +0 -0
  65. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/tests/test_coders.py +0 -0
  66. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/tests/test_concurrency.py +0 -0
  67. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/tests/test_config.py +0 -0
  68. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/tests/test_events.py +0 -0
  69. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/tests/test_exceptions.py +0 -0
  70. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/tests/test_mock_unstructured_submission.py +0 -0
  71. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/tests/test_regions.py +0 -0
  72. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/tests/test_solver.py +0 -0
  73. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/tests/test_solver_utils.py +0 -0
  74. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/tests/test_testing.py +0 -0
  75. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.4}/tests/test_upload.py +0 -0
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.4
2
2
  Name: dwave-cloud-client
3
- Version: 0.13.2
3
+ Version: 0.13.4
4
4
  Summary: A minimal client for interacting with D-Wave cloud resources.
5
5
  Home-page: https://github.com/dwavesystems/dwave-cloud-client
6
6
  Author: D-Wave Systems Inc.
@@ -48,6 +48,16 @@ Requires-Dist: dwave-optimization<0.5,>=0.1.0; extra == "nlm"
48
48
  Requires-Dist: numpy>=1.20.0; extra == "nlm"
49
49
  Provides-Extra: mocks
50
50
  Requires-Dist: dwave-networkx>=0.8.10; extra == "mocks"
51
+ Dynamic: author
52
+ Dynamic: classifier
53
+ Dynamic: description
54
+ Dynamic: home-page
55
+ Dynamic: license
56
+ Dynamic: license-file
57
+ Dynamic: provides-extra
58
+ Dynamic: requires-dist
59
+ Dynamic: requires-python
60
+ Dynamic: summary
51
61
 
52
62
  .. image:: https://badge.fury.io/py/dwave-cloud-client.svg
53
63
  :target: https://badge.fury.io/py/dwave-cloud-client
@@ -67,6 +77,8 @@ Requires-Dist: dwave-networkx>=0.8.10; extra == "mocks"
67
77
  dwave-cloud-client
68
78
  ==================
69
79
 
80
+ .. start_cloud_about
81
+
70
82
  D-Wave Cloud Client is a minimal implementation of the REST interface used to
71
83
  communicate with D-Wave Sampler API (SAPI) servers.
72
84
 
@@ -75,9 +87,9 @@ and scheduling for quantum annealing resources at D-Wave Systems.
75
87
  This package provides a minimal Python interface to that layer without
76
88
  compromising the quality of interactions and workflow.
77
89
 
78
- The example below instantiates a D-Wave Cloud Client and solver based on the local
79
- system's auto-detected default configuration file and samples a random Ising problem
80
- tailored to fit the solver's graph.
90
+ The example below instantiates a D-Wave Cloud Client and solver based on the
91
+ local system's auto-detected default configuration file and samples a random
92
+ Ising problem tailored to fit the solver's graph.
81
93
 
82
94
  .. code-block:: python
83
95
 
@@ -100,13 +112,11 @@ tailored to fit the solver's graph.
100
112
  # Print the first sample out of a hundred
101
113
  print(computation.samples[0])
102
114
 
103
- .. index-end-marker
115
+ .. end_cloud_about
104
116
 
105
117
 
106
118
  Installation
107
- ------------
108
-
109
- .. installation-start-marker
119
+ ============
110
120
 
111
121
  Requires Python 3.8+:
112
122
 
@@ -114,7 +124,8 @@ Requires Python 3.8+:
114
124
 
115
125
  pip install dwave-cloud-client
116
126
 
117
- To install from source (available on GitHub in `dwavesystems/dwave-cloud-client`_ repo):
127
+ To install from source (available on GitHub in
128
+ `dwavesystems/dwave-cloud-client`_ repo):
118
129
 
119
130
  .. code-block:: bash
120
131
 
@@ -123,23 +134,21 @@ To install from source (available on GitHub in `dwavesystems/dwave-cloud-client`
123
134
 
124
135
  .. _`dwavesystems/dwave-cloud-client`: https://github.com/dwavesystems/dwave-cloud-client
125
136
 
126
- .. installation-end-marker
127
-
128
137
 
129
138
  License
130
- -------
139
+ =======
131
140
 
132
141
  Released under the Apache License 2.0. See `<LICENSE>`_ file.
133
142
 
134
143
 
135
144
  Contributing
136
- ------------
145
+ ============
137
146
 
138
- Ocean's `contributing guide <https://docs.ocean.dwavesys.com/en/stable/contributing.html>`_
147
+ Ocean's `contributing guide <https://docs.dwavequantum.com/en/latest/ocean/contribute.html>`_
139
148
  has guidelines for contributing to Ocean packages.
140
149
 
141
150
  Release Notes
142
- ~~~~~~~~~~~~~
151
+ -------------
143
152
 
144
153
  D-Wave Cloud Client uses `reno <https://docs.openstack.org/reno/>`_ to manage
145
154
  its release notes.
@@ -16,6 +16,8 @@
16
16
  dwave-cloud-client
17
17
  ==================
18
18
 
19
+ .. start_cloud_about
20
+
19
21
  D-Wave Cloud Client is a minimal implementation of the REST interface used to
20
22
  communicate with D-Wave Sampler API (SAPI) servers.
21
23
 
@@ -24,9 +26,9 @@ and scheduling for quantum annealing resources at D-Wave Systems.
24
26
  This package provides a minimal Python interface to that layer without
25
27
  compromising the quality of interactions and workflow.
26
28
 
27
- The example below instantiates a D-Wave Cloud Client and solver based on the local
28
- system's auto-detected default configuration file and samples a random Ising problem
29
- tailored to fit the solver's graph.
29
+ The example below instantiates a D-Wave Cloud Client and solver based on the
30
+ local system's auto-detected default configuration file and samples a random
31
+ Ising problem tailored to fit the solver's graph.
30
32
 
31
33
  .. code-block:: python
32
34
 
@@ -49,13 +51,11 @@ tailored to fit the solver's graph.
49
51
  # Print the first sample out of a hundred
50
52
  print(computation.samples[0])
51
53
 
52
- .. index-end-marker
54
+ .. end_cloud_about
53
55
 
54
56
 
55
57
  Installation
56
- ------------
57
-
58
- .. installation-start-marker
58
+ ============
59
59
 
60
60
  Requires Python 3.8+:
61
61
 
@@ -63,7 +63,8 @@ Requires Python 3.8+:
63
63
 
64
64
  pip install dwave-cloud-client
65
65
 
66
- To install from source (available on GitHub in `dwavesystems/dwave-cloud-client`_ repo):
66
+ To install from source (available on GitHub in
67
+ `dwavesystems/dwave-cloud-client`_ repo):
67
68
 
68
69
  .. code-block:: bash
69
70
 
@@ -72,23 +73,21 @@ To install from source (available on GitHub in `dwavesystems/dwave-cloud-client`
72
73
 
73
74
  .. _`dwavesystems/dwave-cloud-client`: https://github.com/dwavesystems/dwave-cloud-client
74
75
 
75
- .. installation-end-marker
76
-
77
76
 
78
77
  License
79
- -------
78
+ =======
80
79
 
81
80
  Released under the Apache License 2.0. See `<LICENSE>`_ file.
82
81
 
83
82
 
84
83
  Contributing
85
- ------------
84
+ ============
86
85
 
87
- Ocean's `contributing guide <https://docs.ocean.dwavesys.com/en/stable/contributing.html>`_
86
+ Ocean's `contributing guide <https://docs.dwavequantum.com/en/latest/ocean/contribute.html>`_
88
87
  has guidelines for contributing to Ocean packages.
89
88
 
90
89
  Release Notes
91
- ~~~~~~~~~~~~~
90
+ -------------
92
91
 
93
92
  D-Wave Cloud Client uses `reno <https://docs.openstack.org/reno/>`_ to manage
94
93
  its release notes.
@@ -105,4 +104,4 @@ Remove any sections not relevant to your changes.
105
104
  Commit the file along with your changes.
106
105
 
107
106
  See reno's `user guide <https://docs.openstack.org/reno/latest/user/usage.html>`_
108
- for details.
107
+ for details.
@@ -20,8 +20,10 @@ import logging
20
20
  import numbers
21
21
  import os
22
22
  import warnings
23
+ import zlib
23
24
  from collections import deque, namedtuple, abc
24
- from typing import Optional, TypedDict, Union, TYPE_CHECKING
25
+ from collections.abc import Iterable
26
+ from typing import IO, Optional, TypedDict, TYPE_CHECKING, Union
25
27
 
26
28
  import orjson
27
29
  import requests
@@ -131,13 +133,113 @@ class LoggingSession(BaseUrlSession):
131
133
  return response
132
134
 
133
135
 
134
- class VersionedAPISession(LoggingSession):
135
- """A `requests.Session` subclass (technically, further specialized
136
- :class:`.LoggingSession`) that enforces conformance of API response
136
+ class PayloadCompressingSession(LoggingSession):
137
+ """A :class:`requests.Session` subclass (technically, a further specialized
138
+ :class:`.LoggingSession`) that adds support for payload compression on the
139
+ fly.
140
+
141
+ Args:
142
+ compress (bool, default=False):
143
+ Preemptively compress HTTP request body. When compression is enabled,
144
+ the payload is always compressed in 32KiB chunks and streamed to
145
+ minimize memory overhead.
146
+
147
+ .. note::
148
+ With compression enabled, the request body is transferred using chunked
149
+ encoding (``Transfer-Encoding: chunked``) and content is compressed using
150
+ the `DEFLATE <https://www.rfc-editor.org/rfc/rfc1951.txt>`_ compression
151
+ algorithm (``Content-Encoding: deflate``).
152
+
153
+ .. versionadded:: 0.13.3
154
+ Preemptive payload compression support added to :class:`.DWaveAPIClient`.
155
+
156
+ """
157
+
158
+ _compress: bool = False
159
+
160
+ def __init__(self, compress: bool = False, **kwargs):
161
+ self._compress = compress
162
+ super().__init__(**kwargs)
163
+
164
+ def set_payload_compress(self, compress: bool = True) -> bool:
165
+ """Modify payload compression on upload for current session.
166
+
167
+ Args:
168
+ compress (bool, default=True):
169
+ Enable request body compression with DEFLATE on upload requests.
170
+ Make sure the server supports compression on inbound requests,
171
+ as most servers don't.
172
+
173
+ Returns:
174
+ bool:
175
+ Previous compression setting.
176
+ """
177
+ previous = self._compress
178
+ self._compress = compress
179
+ return previous
180
+
181
+ @staticmethod
182
+ def _iter_compressed(data: Union[bytes, IO, Iterable[bytes]],
183
+ chunk_size: Optional[int] = None):
184
+ if chunk_size is None:
185
+ # match zlib window size
186
+ chunk_size = 2**15
187
+
188
+ if isinstance(data, bytes):
189
+ data = io.BytesIO(data)
190
+
191
+ if hasattr(data, 'read'):
192
+ def get_chunks(f, chunk_size):
193
+ while chunk := f.read(chunk_size):
194
+ yield chunk
195
+ chunks = get_chunks(data, chunk_size)
196
+
197
+ else:
198
+ # assume data is iterable
199
+ chunks = data
200
+
201
+ zbuf = zlib.compressobj()
202
+
203
+ for chunk in chunks:
204
+ if isinstance(chunk, str):
205
+ chunk = chunk.encode("utf-8")
206
+ if c := zbuf.compress(chunk):
207
+ yield c
208
+
209
+ yield zbuf.flush()
210
+
211
+ def request(self, *args, **kwargs):
212
+ compress = kwargs.pop('compress', self._compress)
213
+
214
+ # set compression for current request (assumes Session is not thread-safe)
215
+ old = self._compress
216
+ try:
217
+ self._compress = compress
218
+ return super().request(*args, **kwargs)
219
+ finally:
220
+ self._compress = old
221
+
222
+ def send(self, request: requests.PreparedRequest, **kwargs) -> requests.Response:
223
+ # Note: compress body on `send()` (rather than on `request()`) as by now
224
+ # json, form, and multipart data are all converted to bytes. We only need
225
+ # to handle bytes, files and iterators at this point.
226
+ if self._compress and request.body:
227
+ request.body = self._iter_compressed(request.body)
228
+ # update the prepared request for chunked upload
229
+ request.headers['Content-Encoding'] = 'deflate'
230
+ request.headers['Transfer-Encoding'] = 'chunked'
231
+ request.headers.pop('Content-Length', None)
232
+
233
+ return super().send(request, **kwargs)
234
+
235
+
236
+ class VersionedAPISession(PayloadCompressingSession):
237
+ """A :class:`requests.Session` subclass (technically, further specialized
238
+ :class:`.PayloadCompressingSession`) that enforces conformance of API response
137
239
  version with supported version range(s).
138
240
 
139
- Response format version is requested via `Accept` header field, and
140
- format/version of the response is checked via `Content-Type`.
241
+ Response format version is requested via ``Accept`` header field, and
242
+ format/version of the response is checked via ``Content-Type``.
141
243
 
142
244
  Args:
143
245
  strict_mode:
@@ -249,7 +351,7 @@ def _create_default_cache_store(**kwargs) -> abc.Mapping:
249
351
 
250
352
 
251
353
  class CachingSession(VersionedAPISession):
252
- """A `requests.Session` subclass (technically, further specialized
354
+ """A :class:`requests.Session` subclass (technically, further specialized
253
355
  :class:`.VersionedAPISession`) that caches responses and uses conditional
254
356
  requests for smart cache updates.
255
357
 
@@ -375,8 +477,11 @@ class CachingSession(VersionedAPISession):
375
477
  if use_cache:
376
478
  meta = dict(created=epochnow(), maxage=maxage, etag=etag)
377
479
  self._store[key_meta] = meta
480
+ logger.debug("cache_write (meta): %r = %r", key_meta, meta)
378
481
  if not only_meta:
379
- self._store[key_data] = response.content
482
+ content = self._store[key_data] = response.content
483
+ logger.debug("cache_write (data): %r <- (%d bytes)",
484
+ key_data, len(content))
380
485
 
381
486
  logger.debug("response cached for maxage=%r", maxage)
382
487
  return True
@@ -429,6 +534,7 @@ class CachingSession(VersionedAPISession):
429
534
  return res
430
535
 
431
536
  if not refresh and (meta := self._store.get(key_meta)):
537
+ logger.debug("cache_read (meta): %r = %r", key_meta, meta)
432
538
  # respect max-age from response cache-control
433
539
  maxage = meta.get('maxage')
434
540
  if maxage is None:
@@ -438,6 +544,7 @@ class CachingSession(VersionedAPISession):
438
544
  # note: by deferring this lookup, we could save a few ms in case
439
545
  # when upstream content was modified (but that doesn't happen often)
440
546
  content = self._store.get(key_data)
547
+ logger.debug("cache_read (data): %r -> (%d bytes)", key_data, len(content))
441
548
 
442
549
  if epochnow() - meta['created'] < maxage:
443
550
  logger.debug('cache hit within maxage')
@@ -484,8 +591,9 @@ class DWaveAPIClient:
484
591
  on demand, in each thread.
485
592
 
486
593
  Example:
487
- with DWaveAPIClient(endpoint='...', timeout=(5, 600)) as client:
488
- client.session.get('...')
594
+ >>> with DWaveAPIClient(endpoint='...', timeout=(5, 600)) as client: # doctest: +SKIP
595
+ >>> client.session.get('...')
596
+
489
597
  """
490
598
 
491
599
  DEFAULTS = {
@@ -511,6 +619,9 @@ class DWaveAPIClient:
511
619
  # number of most recent request records to keep in :attr:`.session.history`
512
620
  'history_size': 0,
513
621
 
622
+ # preemptive payload compression on upload requests, see :class:`PayloadCompressingSession`
623
+ 'compress': False,
624
+
514
625
  # response version strict mode validation, see :class:`VersionedAPISession`
515
626
  'version_strict_mode': True,
516
627
 
@@ -641,6 +752,7 @@ class DWaveAPIClient:
641
752
  session = CachingSession(
642
753
  base_url=endpoint,
643
754
  history_size=config['history_size'],
755
+ compress=config['compress'],
644
756
  strict_mode=config['version_strict_mode'],
645
757
  cache=config['cache'],
646
758
  )
@@ -728,8 +840,16 @@ class SolverAPIClient(DWaveAPIClient):
728
840
  self.DEFAULTS = super().DEFAULTS.copy()
729
841
  self.DEFAULTS.update(endpoint=dwave.cloud.config.constants.DEFAULT_SOLVER_API_ENDPOINT)
730
842
 
843
+ # add qpu data compression option
844
+ self.DEFAULTS.update(compress_qpu_problem_data=False)
845
+
731
846
  super().__init__(**config)
732
847
 
848
+ @classmethod
849
+ def from_config_model(cls, config: ClientConfig, **kwargs):
850
+ kwargs.setdefault('compress_qpu_problem_data', config.compress_qpu_problem_data)
851
+ return super().from_config_model(config, **kwargs)
852
+
733
853
 
734
854
  class MetadataAPIClient(DWaveAPIClient):
735
855
  """Client for D-Wave's Metadata API."""
@@ -164,6 +164,14 @@ class ProblemJob(BaseModel):
164
164
  type: constants.ProblemType
165
165
  label: Optional[str] = None
166
166
 
167
+ @classmethod
168
+ def from_info(cls, info: ProblemInfo):
169
+ return cls(data=info.data,
170
+ params=info.params,
171
+ solver=info.metadata.solver,
172
+ type=info.metadata.type,
173
+ label=info.metadata.label)
174
+
167
175
 
168
176
  class BatchItemError(BaseModel):
169
177
  error_code: int
@@ -17,7 +17,7 @@ from __future__ import annotations
17
17
  import io
18
18
  import orjson
19
19
  from collections import abc
20
- from typing import Union, Optional, get_type_hints, TYPE_CHECKING
20
+ from typing import Callable, Union, Optional, get_type_hints, TYPE_CHECKING
21
21
  from functools import wraps
22
22
 
23
23
  from pydantic import TypeAdapter
@@ -58,6 +58,31 @@ class accepts:
58
58
  return wrapper
59
59
 
60
60
 
61
+ class compress_if:
62
+ """Decorate :class:`ResourceBase` methods to enable compression on outbound
63
+ requests if predicate evaluates to truthy.
64
+ """
65
+
66
+ def __init__(self, compress: Union[bool, Callable] = True, **kwargs):
67
+ if not callable(compress):
68
+ compress = lambda *args, **kwargs: compress
69
+ self.compress = compress
70
+
71
+ def __call__(self, fn: abc.Callable):
72
+ @wraps(fn)
73
+ def wrapper(obj: 'ResourceBase', *args, **kwargs):
74
+ restore_to = False
75
+ try:
76
+ compress = self.compress(obj, *args, **kwargs)
77
+ restore_to = obj.session.set_payload_compress(compress=compress)
78
+ return fn(obj, *args, **kwargs)
79
+
80
+ finally:
81
+ obj.session.set_payload_compress(compress=restore_to)
82
+
83
+ return wrapper
84
+
85
+
61
86
  class ResourceBase:
62
87
  """A class for interacting with a Leap resource."""
63
88
 
@@ -268,36 +293,42 @@ class Problems(ResourceBase):
268
293
  return orjson.loads(response.content)
269
294
 
270
295
  @accepts(media_type='application/vnd.dwave.sapi.problems+json', version='>=2.1,<3')
271
- def submit_problem(self, *,
272
- data: models.ProblemData,
273
- params: dict,
274
- solver: str,
275
- type: constants.ProblemType,
296
+ @compress_if(lambda obj, *_, **__: obj.client.config.get('compress_qpu_problem_data'))
297
+ def submit_problem(self,
298
+ problem: Optional[models.ProblemJob] = None,
299
+ *,
300
+ data: Optional[models.ProblemData] = None,
301
+ params: Optional[dict] = None,
302
+ solver: Optional[str] = None,
303
+ type: Optional[constants.ProblemType] = None,
276
304
  label: Optional[str] = None) -> \
277
305
  Union[models.ProblemStatusMaybeWithAnswer, models.ProblemSubmitError]:
278
306
  """Blocking problem submit with timeout, returning final status and
279
307
  answer, if problem is solved within the (undisclosed) time limit.
280
308
  """
281
309
  path = ''
310
+ job_dict = problem.model_dump() if problem is not None else {}
311
+ updates = dict(data=data.model_dump() if data is not None else None,
312
+ params=params, solver=solver, type=type, label=label)
313
+ job_dict.update((k, v) for k, v in updates.items() if v is not None)
282
314
  # note: orjson.dumps(model.model_dump()) is about 6-7x faster then
283
315
  # model.model_dump_json() - 45us vs 300us (including model construction)
284
- job_dict = dict(data=data.model_dump(), params=params, solver=solver,
285
- type=type, label=label)
286
316
  data = orjson.dumps(job_dict, option=orjson.OPT_SERIALIZE_NUMPY)
287
- response = self.session.post(
288
- path, data=data, headers={'Content-Type': 'application/json'})
317
+ headers = {'Content-Type': 'application/json'}
318
+ response = self.session.post(path, data=data, headers=headers)
289
319
  rtype = get_type_hints(self.submit_problem)['return']
290
320
  return TypeAdapter(rtype).validate_python(orjson.loads(response.content))
291
321
 
292
322
  @accepts(media_type='application/vnd.dwave.sapi.problems+json', version='>=2.1,<3')
323
+ @compress_if(lambda obj, *_, **__: obj.client.config.get('compress_qpu_problem_data'))
293
324
  def submit_problems(self, problems: list[models.ProblemJob]) -> \
294
325
  list[Union[models.ProblemInitialStatus, models.ProblemSubmitError]]:
295
326
  """Asynchronous multi-problem submit, returning initial statuses."""
296
327
  path = ''
297
328
  # note: TypeAdapter().dump_json() is 2ms vs 50us by orjson.dumps(model.model_dump())
298
329
  data = orjson.dumps([job.model_dump() for job in problems])
299
- response = self.session.post(
300
- path, data=data, headers={'Content-Type': 'application/json'})
330
+ headers = {'Content-Type': 'application/json'}
331
+ response = self.session.post(path, data=data, headers=headers)
301
332
  rtype = get_type_hints(self.submit_problems)['return']
302
333
  return TypeAdapter(rtype).validate_python(orjson.loads(response.content))
303
334