dwave-cloud-client 0.11.2__tar.gz → 0.11.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 (47) hide show
  1. {dwave-cloud-client-0.11.2/dwave_cloud_client.egg-info → dwave-cloud-client-0.11.4}/PKG-INFO +1 -1
  2. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave/cloud/api/client.py +2 -26
  3. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave/cloud/auth/flows.py +61 -6
  4. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave/cloud/cli.py +28 -2
  5. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave/cloud/client/base.py +2 -18
  6. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave/cloud/computation.py +57 -36
  7. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave/cloud/package_info.py +1 -1
  8. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave/cloud/utils.py +37 -8
  9. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4/dwave_cloud_client.egg-info}/PKG-INFO +1 -1
  10. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave_cloud_client.egg-info/requires.txt +9 -8
  11. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/setup.py +5 -4
  12. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/LICENSE +0 -0
  13. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/README.rst +0 -0
  14. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave/__init__.py +0 -0
  15. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave/cloud/__init__.py +0 -0
  16. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave/cloud/api/__init__.py +0 -0
  17. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave/cloud/api/constants.py +0 -0
  18. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave/cloud/api/exceptions.py +0 -0
  19. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave/cloud/api/models.py +0 -0
  20. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave/cloud/api/resources.py +0 -0
  21. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave/cloud/auth/__init__.py +0 -0
  22. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave/cloud/auth/_creds.py +0 -0
  23. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave/cloud/auth/config.py +0 -0
  24. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave/cloud/auth/creds.py +0 -0
  25. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave/cloud/auth/server.py +0 -0
  26. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave/cloud/client/__init__.py +0 -0
  27. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave/cloud/client/hybrid.py +0 -0
  28. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave/cloud/client/qpu.py +0 -0
  29. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave/cloud/client/sw.py +0 -0
  30. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave/cloud/coders.py +0 -0
  31. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave/cloud/concurrency.py +0 -0
  32. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave/cloud/config/__init__.py +0 -0
  33. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave/cloud/config/loaders.py +0 -0
  34. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave/cloud/config/models.py +0 -0
  35. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave/cloud/events.py +0 -0
  36. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave/cloud/exceptions.py +0 -0
  37. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave/cloud/regions.py +0 -0
  38. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave/cloud/solver.py +0 -0
  39. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave/cloud/testing/__init__.py +0 -0
  40. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave/cloud/testing/mocks.py +0 -0
  41. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave/cloud/upload.py +0 -0
  42. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave_cloud_client.egg-info/SOURCES.txt +0 -0
  43. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave_cloud_client.egg-info/dependency_links.txt +0 -0
  44. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave_cloud_client.egg-info/entry_points.txt +0 -0
  45. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave_cloud_client.egg-info/not-zip-safe +0 -0
  46. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/dwave_cloud_client.egg-info/top_level.txt +0 -0
  47. {dwave-cloud-client-0.11.2 → dwave-cloud-client-0.11.4}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: dwave-cloud-client
3
- Version: 0.11.2
3
+ Version: 0.11.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.
@@ -26,32 +26,14 @@ from werkzeug.http import parse_options_header, dump_options_header
26
26
  from dwave.cloud.api import constants, exceptions
27
27
  from dwave.cloud.config import load_config, validate_config_v1, update_config
28
28
  from dwave.cloud.config.models import ClientConfig
29
- from dwave.cloud.package_info import __packagename__, __version__
30
29
  from dwave.cloud.utils import (
31
- PretimedHTTPAdapter, BaseUrlSession, user_agent, is_caused_by)
30
+ PretimedHTTPAdapter, BaseUrlSession, default_user_agent, is_caused_by)
32
31
 
33
32
  __all__ = ['DWaveAPIClient', 'SolverAPIClient', 'MetadataAPIClient', 'LeapAPIClient']
34
33
 
35
34
  logger = logging.getLogger(__name__)
36
35
 
37
36
 
38
- class LazyUserAgentClassProperty:
39
- # roughly equivalent to ``classmethod(property(cached_user_agent))``, but it
40
- # doesn't require chained decorators support available in py39+
41
- _user_agent = None
42
-
43
- def __get__(self, obj, objtype=None):
44
- # Note: The only tags that might change are platform tags, as returned
45
- # by `dwave.common.platform.tags` entry points, and `platform.platform()`
46
- # (like linux kernel version). Assuming OS/machine won't change during
47
- # client's lifespan, and typical platform tags defined via entry points
48
- # depend on process environment variables (which rarely change), it's
49
- # pretty safe to cache the user-agent per-class (or even globally).
50
- if self._user_agent is None:
51
- self._user_agent = user_agent(__packagename__, __version__)
52
- return self._user_agent
53
-
54
-
55
37
  class LoggingSession(BaseUrlSession):
56
38
  """:class:`.BaseUrlSession` extended to unify timeout exceptions and to log
57
39
  all requests (and responses).
@@ -293,12 +275,6 @@ class DWaveAPIClient:
293
275
  # client instance config, populated on init from kwargs overridding DEFAULTS
294
276
  config = None
295
277
 
296
- # User-Agent string used in API requests, as returned by
297
- # :meth:`~dwave.cloud.utils.user_agent`, computed on first access and
298
- # cached for the lifespan of the class.
299
- # TODO: consider exposing "user_agent" config parameter
300
- user_agent = LazyUserAgentClassProperty()
301
-
302
278
  def __init__(self, **config):
303
279
  self.config = {}
304
280
  for opt, default in self.DEFAULTS.items():
@@ -428,7 +404,7 @@ class DWaveAPIClient:
428
404
  timeout=timeout, max_retries=cls._retry_config(**retry)))
429
405
 
430
406
  # configure headers
431
- session.headers.update({'User-Agent': cls.user_agent})
407
+ session.headers.update({'User-Agent': default_user_agent()})
432
408
  if config['headers']:
433
409
  session.headers.update(config['headers'])
434
410
 
@@ -18,10 +18,11 @@ import logging
18
18
  import time
19
19
  import webbrowser
20
20
  from operator import sub
21
- from typing import Any, Callable, Dict, Optional, Union, Sequence
21
+ from typing import Any, Callable, Dict, Optional, Union, Sequence, Literal
22
22
  from urllib.parse import urljoin
23
23
 
24
24
  import click
25
+ import requests
25
26
  from authlib.integrations.requests_client import OAuth2Session, OAuthError
26
27
  from authlib.oauth2.rfc6749 import OAuth2Token
27
28
  from authlib.common.security import generate_token
@@ -32,7 +33,7 @@ from dwave.cloud.auth.creds import Credentials
32
33
  from dwave.cloud.auth.server import SingleRequestAppServer, RequestCaptureAndRedirectApp
33
34
  from dwave.cloud.config.models import ClientConfig
34
35
  from dwave.cloud.regions import resolve_endpoints
35
- from dwave.cloud.utils import pretty_argvalues
36
+ from dwave.cloud.utils import pretty_argvalues, default_user_agent
36
37
 
37
38
  __all__ = ['AuthFlow', 'LeapAuthFlow', 'OAuthError']
38
39
 
@@ -55,6 +56,8 @@ class AuthFlow:
55
56
  URL of the authorization server's authorization endpoint.
56
57
  token_endpoint:
57
58
  URL of the authorization server's token endpoint.
59
+ revocation_endpoint:
60
+ URL of the authorization server's OAuth 2.0 revocation endpoint.
58
61
  session_config:
59
62
  Configuration options for the low-level ``requests.Session`` used
60
63
  for all OAuth 2 requests. Supported options are: ``cert``,
@@ -78,6 +81,7 @@ class AuthFlow:
78
81
  redirect_uri: str,
79
82
  authorization_endpoint: str,
80
83
  token_endpoint: str,
84
+ revocation_endpoint: Optional[str] = None,
81
85
  session_config: Optional[Dict[str, Any]] = None,
82
86
  leap_api_endpoint: Optional[str] = None,
83
87
  creds: Optional[Credentials] = None
@@ -86,9 +90,12 @@ class AuthFlow:
86
90
  self.scopes = ' '.join(scopes)
87
91
  self.authorization_endpoint = authorization_endpoint
88
92
  self.token_endpoint = token_endpoint
93
+ self.revocation_endpoint = revocation_endpoint
89
94
  self.leap_api_endpoint = leap_api_endpoint
90
95
  self.creds = creds
91
96
 
97
+ # TODO: verify authorization/token/revocation endpoints are https
98
+
92
99
  self.session = OAuth2Session(
93
100
  client_id=client_id, scope=scopes, redirect_uri=redirect_uri,
94
101
  code_challenge_method='S256',
@@ -96,6 +103,9 @@ class AuthFlow:
96
103
  authorization_endpoint=authorization_endpoint,
97
104
  token_endpoint=token_endpoint)
98
105
 
106
+ # set default headers (overwritten by ``session_config['headers']``)
107
+ self.session.headers.update({'User-Agent': default_user_agent()})
108
+
99
109
  if session_config is not None:
100
110
  self.update_session(session_config)
101
111
 
@@ -189,6 +199,7 @@ class AuthFlow:
189
199
  url=self.token_endpoint,
190
200
  grant_type='authorization_code',
191
201
  code=code,
202
+ code_verifier=self.code_verifier,
192
203
  **kwargs)
193
204
 
194
205
  logger.debug(f"{type(self).__name__}.fetch_token() = {token!r}")
@@ -201,6 +212,39 @@ class AuthFlow:
201
212
  self._save_token_to_creds(token)
202
213
  return token
203
214
 
215
+ def revoke_token(self, *,
216
+ token: Optional[str] = None,
217
+ token_type_hint: Optional[
218
+ Literal['access_token', 'refresh_token']] = None
219
+ ) -> bool:
220
+ """Revoke OAuth 2.0 token.
221
+
222
+ Args:
223
+ token:
224
+ OAuth 2.0 access or refresh token to be revoked. If refresh token
225
+ is specified, the authorization server should also revoke the
226
+ corresponding access tokens. If ``token`` is not specified, then
227
+ current refresh token is revoked.
228
+ token_type_hint:
229
+ Type of the token to be revoked.
230
+
231
+ Returns:
232
+ Token revocation status. True if revocation was successful, or token
233
+ was invalid already. False in case of an error.
234
+
235
+ Note:
236
+ Token revocation requires that a ``revocation_endpoint`` is defined
237
+ in :class:`~dwave.cloud.auth.flows.AuthFlow` construction.
238
+ """
239
+ if self.revocation_endpoint is None:
240
+ raise TypeError("Revocation endpoint undefined.")
241
+
242
+ response: requests.Response = self.session.revoke_token(
243
+ url=self.revocation_endpoint, token=token,
244
+ token_type_hint=token_type_hint)
245
+
246
+ return response.ok
247
+
204
248
  def ensure_active_token(self):
205
249
  if not self.token:
206
250
  return False
@@ -255,13 +299,17 @@ class LeapAuthFlow(AuthFlow):
255
299
  def _infer_token_endpoint(leap_api_endpoint: str) -> str:
256
300
  return urljoin(leap_api_endpoint, '/leap/openid/token')
257
301
 
302
+ @staticmethod
303
+ def _infer_revocation_endpoint(leap_api_endpoint: str) -> str:
304
+ return urljoin(leap_api_endpoint, '/leap/openid/revoke_token/')
305
+
258
306
  @staticmethod
259
307
  def _infer_leap_success_uri(leap_api_endpoint: str) -> str:
260
- return urljoin(leap_api_endpoint, '/leap/openid/success')
308
+ return urljoin(leap_api_endpoint, '/leap/openid/success/')
261
309
 
262
310
  @staticmethod
263
311
  def _infer_leap_error_uri(leap_api_endpoint: str) -> str:
264
- return urljoin(leap_api_endpoint, '/leap/openid/error')
312
+ return urljoin(leap_api_endpoint, '/leap/openid/error/')
265
313
 
266
314
  @classmethod
267
315
  def from_config_model(cls, config: ClientConfig, **kwargs) -> LeapAuthFlow:
@@ -286,6 +334,7 @@ class LeapAuthFlow(AuthFlow):
286
334
 
287
335
  authorization_endpoint = cls._infer_auth_endpoint(config.leap_api_endpoint)
288
336
  token_endpoint = cls._infer_token_endpoint(config.leap_api_endpoint)
337
+ revocation_endpoint = cls._infer_revocation_endpoint(config.leap_api_endpoint)
289
338
 
290
339
  # note: possible to de-dup via `DWaveAPIClient.from_config_model`, but
291
340
  # currently not worth the extra complexity (indirection layer).
@@ -302,6 +351,7 @@ class LeapAuthFlow(AuthFlow):
302
351
  redirect_uri=kwargs.pop('redirect_uri', cls._OOB_REDIRECT_URI),
303
352
  authorization_endpoint=authorization_endpoint,
304
353
  token_endpoint=token_endpoint,
354
+ revocation_endpoint=revocation_endpoint,
305
355
  session_config=session_config,
306
356
  leap_api_endpoint=config.leap_api_endpoint,
307
357
  creds=creds)
@@ -377,7 +427,12 @@ class LeapAuthFlow(AuthFlow):
377
427
 
378
428
  # when code received, exchange it for token
379
429
  try:
380
- self.fetch_token(code=app.query.get('code'), state=app.query.get('state'))
430
+ # verify state (Cross-Site Request Forgery protection)
431
+ state = app.query.get('state')
432
+ if state != self.state:
433
+ raise ValueError('State mismatch')
434
+
435
+ self.fetch_token(code=app.query.get('code'), state=state)
381
436
 
382
437
  except OAuthError as exc:
383
438
  # store for main thread
@@ -398,7 +453,7 @@ class LeapAuthFlow(AuthFlow):
398
453
  return add_params_to_uri(error_uri, query)
399
454
 
400
455
  # redirect to leap success page
401
- return add_params_to_uri(success_uri, app.query)
456
+ return success_uri
402
457
 
403
458
  app = RequestCaptureAndRedirectApp(
404
459
  message=self._REDIRECT_DONE_MSG,
@@ -1009,11 +1009,11 @@ def get(*, config_file, profile, token_type, json_output, output):
1009
1009
  flow = LeapAuthFlow.from_config_model(config)
1010
1010
 
1011
1011
  token_key = token_type.replace('-', '_')
1012
- if not flow.token or not (token_value := flow.token.get(token_key)):
1012
+ if not flow.token or not token_key in flow.token:
1013
1013
  raise CLIError('Token not found. Please run "dwave auth login".', code=100)
1014
1014
 
1015
1015
  token_pretty = token_type.replace('-', ' ').capitalize()
1016
- output(f"{token_pretty}: {{%s}}" % token_key , **{token_key: token_value})
1016
+ output(f"{token_pretty}: {{%s}}" % token_key, **{token_key: flow.token[token_key]})
1017
1017
 
1018
1018
  if token_type == 'access-token':
1019
1019
  expires_at = flow.token.get('expires_at')
@@ -1051,6 +1051,32 @@ def refresh(*, config_file, profile, output):
1051
1051
  'You can now use "dwave auth get" to view them.')
1052
1052
 
1053
1053
 
1054
+ @auth.command()
1055
+ @config_file_options()
1056
+ @click.argument('token_type', default='access-token',
1057
+ type=click.Choice(['access-token', 'refresh-token']))
1058
+ @json_output
1059
+ @standardized_output
1060
+ def revoke(*, config_file, profile, token_type, json_output, output):
1061
+ """Revoke access and/or refresh token(s) for Leap API."""
1062
+
1063
+ config = validate_config_v1(load_config(config_file=config_file, profile=profile))
1064
+ flow = LeapAuthFlow.from_config_model(config)
1065
+
1066
+ token_key = token_type.replace('-', '_')
1067
+ token_pretty = token_type.replace('-', ' ').capitalize()
1068
+ if not flow.token or not token_key in flow.token:
1069
+ raise CLIError('Token not found. Please run "dwave auth login".', code=100)
1070
+
1071
+ # revoke
1072
+ revoked = flow.revoke_token(token=flow.token[token_key], token_type_hint=token_key)
1073
+
1074
+ if not revoked:
1075
+ raise CLIError(f'{token_pretty} revocation failed.', code=102)
1076
+
1077
+ output(f'{token_pretty} successfully revoked.')
1078
+
1079
+
1054
1080
  @cli.group()
1055
1081
  def leap():
1056
1082
  """Interact with Leap API."""
@@ -72,7 +72,7 @@ from dwave.cloud.regions import get_regions, resolve_endpoints
72
72
  from dwave.cloud.upload import ChunkedData
73
73
  from dwave.cloud.events import dispatches_events
74
74
  from dwave.cloud.utils import (
75
- PretimedHTTPAdapter, BaseUrlSession, user_agent,
75
+ PretimedHTTPAdapter, BaseUrlSession, default_user_agent,
76
76
  datetime_to_timestamp, utcnow, cached, retried, is_caused_by)
77
77
 
78
78
  __all__ = ['Client']
@@ -536,22 +536,6 @@ class Client(object):
536
536
  self._encode_problem_executor = \
537
537
  ThreadPoolExecutor(self._ENCODE_PROBLEM_THREAD_COUNT)
538
538
 
539
- @cached_property
540
- def _user_agent(self):
541
- """User-Agent string for this client instance, as returned by
542
- :meth:`~dwave.cloud.utils.user_agent`, computed on first access and
543
- cached for the lifespan of the client.
544
-
545
- Note:
546
- The only tags that might change are platform tags, as returned by
547
- ``dwave.common.platform.tags`` entry points, and `platform.platform()`
548
- (like linux kernel version). Assuming OS/machine won't change during
549
- client's lifespan, and typical platform tags defined via entry points
550
- depend on process environments (which rarely change), it's pretty safe
551
- to always use the per-instance cached user agent.
552
- """
553
- return user_agent(__packagename__, __version__)
554
-
555
539
  def create_session(self):
556
540
  """Create a new requests session based on client's (self) params.
557
541
 
@@ -572,7 +556,7 @@ class Client(object):
572
556
  timeout=self.config.request_timeout,
573
557
  max_retries=self.config.request_retry.to_urllib3_retry()))
574
558
 
575
- session.headers.update({'User-Agent': self._user_agent})
559
+ session.headers.update({'User-Agent': default_user_agent()})
576
560
  if self.config.headers:
577
561
  session.headers.update(self.config.headers)
578
562
  if self.config.token:
@@ -24,12 +24,12 @@ computation---sampling on a QPU or software solver---executed remotely, monitori
24
24
  waiting for and retrieving results, cancelling enqueued jobs, etc.
25
25
 
26
26
  Some :class:`Future` methods are blocking.
27
-
28
27
  """
29
28
 
30
29
  import time
31
30
  import threading
32
31
  import functools
32
+ import weakref
33
33
 
34
34
  from operator import itemgetter
35
35
  from dateutil.parser import parse
@@ -157,6 +157,9 @@ class Future(object):
157
157
  # XXX: energy offset carried via Future, until implemented in SAPI
158
158
  self._offset = 0
159
159
 
160
+ # weakref to resolved (already constructed) sampleset
161
+ self._sampleset = None
162
+
160
163
  # make Future ordered
161
164
 
162
165
  def __lt__(self, other):
@@ -631,11 +634,12 @@ class Future(object):
631
634
  """
632
635
 
633
636
  # return energies from sampleset, if already constructed
634
- result = self.result()
635
- if 'sampleset' in result:
636
- return result['sampleset'].record.energy
637
+ sampleset = self._sampleset() if self._sampleset else None
638
+ if sampleset is not None:
639
+ return sampleset.record.energy
637
640
 
638
641
  # fallback to energies from response
642
+ result = self.result()
639
643
  return result['energies']
640
644
 
641
645
  @property
@@ -672,25 +676,28 @@ class Future(object):
672
676
  (0, 1)
673
677
  """
674
678
  # return samples from sampleset, if already constructed
675
- result = self.result()
676
- if 'sampleset' in result:
677
- return result['sampleset'].record.sample
679
+ sampleset = self._sampleset() if self._sampleset else None
680
+ if sampleset is not None:
681
+ return sampleset.record.sample
678
682
 
679
683
  # fallback to samples from response
684
+ result = self.result()
680
685
  return result['solutions']
681
686
 
682
687
  @property
683
688
  def variables(self):
684
689
  """List of active variables in response/answer."""
685
690
 
686
- result = self.result()
691
+ # return variables from sampleset if available
692
+ sampleset = self._sampleset() if self._sampleset else None
693
+ if sampleset is not None:
694
+ return sampleset.variables
687
695
 
696
+ # fallback to variables from SAPI response
697
+ result = self.result()
688
698
  if 'active_variables' in result:
689
699
  return result['active_variables']
690
700
 
691
- if 'sampleset' in result:
692
- return result['sampleset'].variables
693
-
694
701
  raise InvalidAPIResponseError("Active variables not present in the response")
695
702
 
696
703
  @property
@@ -735,12 +742,13 @@ class Future(object):
735
742
  """
736
743
 
737
744
  # return num_occurrences from sampleset, if already constructed
738
- result = self.result()
739
- if 'sampleset' in result:
740
- return result['sampleset'].record.num_occurrences
745
+ sampleset = self._sampleset() if self._sampleset else None
746
+ if sampleset is not None:
747
+ return sampleset.record.num_occurrences
741
748
 
742
749
  # fallback to num_occurrences from response
743
750
  # (but `occurrences` data is not present if `answer_mode` was set to "raw")
751
+ result = self.result()
744
752
  if 'num_occurrences' in result:
745
753
  return result['num_occurrences']
746
754
  elif self.return_matrix:
@@ -751,18 +759,12 @@ class Future(object):
751
759
  def wait_sampleset(self):
752
760
  """Blocking sampleset getter."""
753
761
 
754
- # blocking result get
755
- result = self._load_result()
756
-
757
- # common problem info: id/label
758
- problem_info = dict(problem_id=self.id)
759
- if self.label is not None:
760
- problem_info.update(problem_label=self.label)
762
+ # resolve response
763
+ self._load_result()
761
764
 
762
- # sapi returned sampleset directly
763
- if 'sampleset' in result:
764
- sampleset = result['sampleset']
765
- sampleset.info.update(problem_info)
765
+ # check if sampleset already resolved (e.g. returned in response)
766
+ sampleset = self._sampleset() if self._sampleset else None
767
+ if sampleset is not None:
766
768
  return sampleset
767
769
 
768
770
  # construct sampleset from available data
@@ -783,7 +785,8 @@ class Future(object):
783
785
 
784
786
  # for QPU jobs, info field is blank; add timing info
785
787
  info = dict(timing=self.timing)
786
- info.update(problem_info)
788
+ # also extend info with problem metadata like id and label
789
+ info.update(self._get_problem_info())
787
790
 
788
791
  sampleset = dimod.SampleSet.from_samples(
789
792
  (samples, variables), vartype=vartype,
@@ -794,9 +797,9 @@ class Future(object):
794
797
  # the samplesets constructed .from_future, we add the method as well
795
798
  sampleset.wait_id = self.wait_id
796
799
 
797
- # this means that samplesets retrieved BEFORE this function are called
798
- # are not the same object as after, but it is a simpler implementation
799
- self._result['sampleset'] = self._sampleset = sampleset
800
+ # cache the constructed sampleset on computation, but don't prevent the
801
+ # gc from collecting it if unused in parent closure
802
+ self._sampleset = weakref.ref(sampleset)
800
803
 
801
804
  return sampleset
802
805
 
@@ -808,19 +811,18 @@ class Future(object):
808
811
  resolved.
809
812
  """
810
813
 
811
- try:
812
- return self._sampleset
813
- except AttributeError:
814
- pass
815
-
816
814
  try:
817
815
  import dimod
818
816
  except ImportError:
819
817
  raise RuntimeError("Can't construct SampleSet without dimod. "
820
818
  "Re-install the library with 'bqm' support.")
821
819
 
822
- self._sampleset = sampleset = dimod.SampleSet.from_future(
823
- self, lambda f: f.wait_sampleset())
820
+ # check if sampleset already resolved
821
+ sampleset = self._sampleset() if self._sampleset else None
822
+ if sampleset is not None:
823
+ return sampleset
824
+
825
+ sampleset = dimod.SampleSet.from_future(self, lambda f: f.wait_sampleset())
824
826
 
825
827
  # propagate id to sampleset as well
826
828
  # note: this requires dimod>=0.8.21 (before that version SampleSet
@@ -900,8 +902,27 @@ class Future(object):
900
902
  self._decode()
901
903
  self._alias_result()
902
904
 
905
+ # create a direct reference to sampleset if already available in response
906
+ # NB: in this case we don't actually need a weakref (strong ref is fine),
907
+ # but we use it for consistency
908
+ if 'sampleset' in self._result:
909
+ # add common problem info
910
+ sampleset = self._result['sampleset']
911
+ sampleset.info.update(self._get_problem_info())
912
+
913
+ self._sampleset = weakref.ref(sampleset)
914
+
903
915
  return self._result
904
916
 
917
+ def _get_problem_info(self):
918
+ """Return problem metadata (id, label) to be included in `sampleset.info`."""
919
+ problem_info = {}
920
+ if self.id is not None:
921
+ problem_info.update(problem_id=self.id)
922
+ if self.label is not None:
923
+ problem_info.update(problem_label=self.label)
924
+ return problem_info
925
+
905
926
  def _patch_offset(self):
906
927
  # XXX: This is a temporary fix, until SAPI starts returning the offset
907
928
  # in answer (for structured solvers only).
@@ -14,7 +14,7 @@
14
14
 
15
15
  __packagename__ = 'dwave-cloud-client'
16
16
  __title__ = 'D-Wave Cloud Client'
17
- __version__ = '0.11.2'
17
+ __version__ = '0.11.4'
18
18
  __author__ = 'D-Wave Systems Inc.'
19
19
  __description__ = 'A minimal client for interacting with D-Wave cloud resources.'
20
20
  __url__ = 'https://github.com/dwavesystems/dwave-cloud-client'
@@ -39,6 +39,8 @@ import diskcache
39
39
  from importlib_metadata import entry_points
40
40
  from packaging.requirements import Requirement
41
41
 
42
+ from dwave.cloud.package_info import __packagename__, __version__
43
+
42
44
  # Use numpy if available for fast decoding
43
45
  try:
44
46
  import numpy
@@ -214,13 +216,13 @@ def datetime_to_timestamp(dt):
214
216
  Note: similar to `datetime.timestamp()` in Python 3.3+.
215
217
  """
216
218
 
217
- epoch = datetime.utcfromtimestamp(0).replace(tzinfo=UTC)
219
+ epoch = datetime.fromtimestamp(0, tz=UTC)
218
220
  return (dt - epoch).total_seconds()
219
221
 
220
222
 
221
223
  def utcnow():
222
224
  """Returns tz-aware now in UTC."""
223
- return datetime.utcnow().replace(tzinfo=UTC)
225
+ return datetime.now(tz=UTC)
224
226
 
225
227
 
226
228
  def epochnow() -> float:
@@ -417,18 +419,37 @@ def is_caused_by(exception, exception_types):
417
419
  return hasinstance(exception_chain(exception), exception_types)
418
420
 
419
421
 
420
- def user_agent(name=None, version=None):
421
- """Return User-Agent ~ "name/version language/version interpreter/version os/version"."""
422
+ def user_agent(name: Optional[str] = None,
423
+ version: Optional[str] = None,
424
+ *,
425
+ include_platform_tags: bool = True) -> str:
426
+ """Return User-Agent ~ "name/version language/version interpreter/version os/version".
427
+
428
+ Args:
429
+ name:
430
+ Package name, primary UA component name.
431
+ version:
432
+ Package version, primary UA component version.
433
+ include_platform_tags:
434
+ Look for, query and include externally-contributed platform tags
435
+ (via ``dwave.common.platform.tags`` entrypoint).
436
+ See :func:`dwave.cloud.utils.get_platform_tags`.
437
+
438
+ Return:
439
+ User-Agent string composed of "key/value" pairs (joined with a space
440
+ character), for following components: package, language, interpreter,
441
+ machine, system and platform.
442
+ """
422
443
 
423
444
  def _interpreter():
424
445
  name = platform.python_implementation()
425
446
  version = platform.python_version()
426
- bitness = platform.architecture()[0]
427
447
  if name == 'PyPy':
428
448
  version = '.'.join(map(str, sys.pypy_version_info[:3]))
429
449
  full_version = [version]
430
- if bitness:
431
- full_version.append(bitness)
450
+ is_64bits = sys.maxsize > 2**32
451
+ if is_64bits:
452
+ full_version.append('64bit')
432
453
  return name, "-".join(full_version)
433
454
 
434
455
  tags = []
@@ -445,11 +466,19 @@ def user_agent(name=None, version=None):
445
466
  ])
446
467
 
447
468
  # add platform-specific tags
448
- tags.extend(get_platform_tags())
469
+ if include_platform_tags:
470
+ tags.extend(get_platform_tags())
449
471
 
450
472
  return ' '.join("{}/{}".format(name, version) for name, version in tags)
451
473
 
452
474
 
475
+ # defined as a function rather than constant because env might change during runtime
476
+ def default_user_agent() -> str:
477
+ """Default user agent string to be used consistently across client(s)."""
478
+ return user_agent(
479
+ name=__packagename__, version=__version__, include_platform_tags=False)
480
+
481
+
453
482
  class CLIError(Exception):
454
483
  """CLI command error that includes the error code in addition to the
455
484
  standard error message."""
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: dwave-cloud-client
3
- Version: 0.11.2
3
+ Version: 0.11.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.
@@ -1,13 +1,14 @@
1
- requests[socks]>=2.18
1
+ requests[socks]<3,>=2.25
2
+ urllib3<3,>=1.26
2
3
  pydantic<3,>=2
3
- homebase>=1.0
4
- click>=7.0
5
- python-dateutil>=2.7
6
- plucky>=0.4.3
7
- diskcache>=5.2.1
4
+ homebase<2,>=1.0
5
+ click<9,>=7.0
6
+ python-dateutil<3,>=2.7
7
+ plucky<0.5,>=0.4.3
8
+ diskcache<6,>=5.2.1
8
9
  packaging>=19
9
- werkzeug>=2.2
10
- typing-extensions>=4.5.0
10
+ werkzeug<4,>=2.2
11
+ typing-extensions<5,>=4.5.0
11
12
  authlib<2,>=1.2
12
13
  importlib_metadata>=5.0.0
13
14
 
@@ -13,10 +13,11 @@ with open(package_info_path, encoding='utf-8') as f:
13
13
  python_requires = '>=3.8'
14
14
 
15
15
  # Package requirements, minimal pinning
16
- install_requires = ['requests[socks]>=2.18', 'pydantic>=2,<3', 'homebase>=1.0',
17
- 'click>=7.0', 'python-dateutil>=2.7', 'plucky>=0.4.3',
18
- 'diskcache>=5.2.1', 'packaging>=19', 'werkzeug>=2.2',
19
- 'typing-extensions>=4.5.0', 'authlib>=1.2,<2',
16
+ install_requires = ['requests[socks]>=2.25,<3', 'urllib3>=1.26,<3',
17
+ 'pydantic>=2,<3', 'homebase>=1.0,<2',
18
+ 'click>=7.0,<9', 'python-dateutil>=2.7,<3', 'plucky>=0.4.3,<0.5',
19
+ 'diskcache>=5.2.1,<6', 'packaging>=19', 'werkzeug>=2.2,<4',
20
+ 'typing-extensions>=4.5.0,<5', 'authlib>=1.2,<2',
20
21
  'importlib_metadata>=5.0.0', # can be dropped in py312+
21
22
  ]
22
23