dwave-cloud-client 0.11.3__tar.gz → 0.12.0.dev0__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 (48) hide show
  1. {dwave-cloud-client-0.11.3/dwave_cloud_client.egg-info → dwave-cloud-client-0.12.0.dev0}/PKG-INFO +2 -1
  2. dwave-cloud-client-0.12.0.dev0/dwave/cloud/__init__.py +174 -0
  3. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/api/client.py +5 -11
  4. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/api/constants.py +6 -0
  5. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/api/models.py +12 -2
  6. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/api/resources.py +19 -1
  7. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/auth/flows.py +61 -1
  8. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/cli.py +32 -3
  9. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/client/base.py +53 -3
  10. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/client/hybrid.py +1 -1
  11. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/client/qpu.py +1 -1
  12. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/client/sw.py +1 -1
  13. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/coders.py +24 -2
  14. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/computation.py +29 -9
  15. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/package_info.py +1 -1
  16. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/solver.py +200 -35
  17. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/testing/mocks.py +14 -1
  18. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/utils.py +1 -0
  19. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0/dwave_cloud_client.egg-info}/PKG-INFO +2 -1
  20. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave_cloud_client.egg-info/requires.txt +13 -8
  21. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/setup.py +8 -4
  22. dwave-cloud-client-0.11.3/dwave/cloud/__init__.py +0 -91
  23. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/LICENSE +0 -0
  24. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/README.rst +0 -0
  25. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave/__init__.py +0 -0
  26. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/api/__init__.py +0 -0
  27. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/api/exceptions.py +0 -0
  28. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/auth/__init__.py +0 -0
  29. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/auth/_creds.py +0 -0
  30. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/auth/config.py +0 -0
  31. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/auth/creds.py +0 -0
  32. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/auth/server.py +0 -0
  33. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/client/__init__.py +0 -0
  34. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/concurrency.py +0 -0
  35. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/config/__init__.py +0 -0
  36. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/config/loaders.py +0 -0
  37. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/config/models.py +0 -0
  38. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/events.py +0 -0
  39. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/exceptions.py +0 -0
  40. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/regions.py +0 -0
  41. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/testing/__init__.py +0 -0
  42. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave/cloud/upload.py +0 -0
  43. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave_cloud_client.egg-info/SOURCES.txt +0 -0
  44. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave_cloud_client.egg-info/dependency_links.txt +0 -0
  45. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave_cloud_client.egg-info/entry_points.txt +0 -0
  46. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave_cloud_client.egg-info/not-zip-safe +0 -0
  47. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/dwave_cloud_client.egg-info/top_level.txt +0 -0
  48. {dwave-cloud-client-0.11.3 → dwave-cloud-client-0.12.0.dev0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: dwave-cloud-client
3
- Version: 0.11.3
3
+ Version: 0.12.0.dev0
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.
@@ -20,6 +20,7 @@ Provides-Extra: bqm-legacy
20
20
  Provides-Extra: dqm
21
21
  Provides-Extra: dqm-legacy
22
22
  Provides-Extra: cqm
23
+ Provides-Extra: nlm
23
24
  Provides-Extra: mocks
24
25
  License-File: LICENSE
25
26
 
@@ -0,0 +1,174 @@
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 io
16
+ import os
17
+ import re
18
+ import sys
19
+ import json
20
+ import logging
21
+ import datetime
22
+ import importlib
23
+ import typing
24
+
25
+ from dwave.cloud.client import Client
26
+ from dwave.cloud.solver import Solver
27
+ from dwave.cloud.computation import Future
28
+ from dwave.cloud.utils import parse_loglevel
29
+
30
+ __all__ = ['Client', 'Solver', 'Future']
31
+
32
+
33
+ # prevent log output (from library) when logging not configured by user/app
34
+ logger = logging.getLogger(__name__)
35
+ logger.addHandler(logging.NullHandler())
36
+
37
+ # add TRACE log level and Logger.trace() method
38
+ logging.TRACE = 5
39
+ logging.addLevelName(logging.TRACE, "TRACE")
40
+
41
+ def _trace(logger, message, *args, **kwargs):
42
+ logger.log(logging.TRACE, message, *args, **kwargs)
43
+
44
+ logging.Logger.trace = _trace
45
+
46
+
47
+ class ISOFormatter(logging.Formatter):
48
+ # target timezone, e.g. `datetime.timezone.utc`, or `None` for naive timestamp
49
+ as_tz: typing.Optional[datetime.timezone] = None
50
+
51
+ def __init__(self, *args, as_tz: typing.Optional[datetime.timezone] = None, **kwargs):
52
+ self.as_tz = as_tz
53
+ super().__init__(*args, **kwargs)
54
+
55
+ def formatTime(self, record: logging.LogRecord, datefmt: typing.Optional[str] = None) -> str:
56
+ return datetime.datetime.fromtimestamp(record.created, tz=self.as_tz).isoformat()
57
+
58
+
59
+ class FilteredSecretsFormatter(logging.Formatter):
60
+ """Logging formatter that filters out secrets (like Solver API tokens).
61
+
62
+ Note: we assume, for easier disambiguation, a secret/token is prefixed with
63
+ a short alphanumeric string, and comprises 40 or more hex digits.
64
+ """
65
+
66
+ # prefixed 160-bit+ hex tokens (sapi token format: `A{2,4}-X{40,}`)
67
+ _SAPI_TOKEN_PATTERN = re.compile(
68
+ r'\b([0-9A-Za-z]{2,4}-[0-9A-Fa-f]{3})([0-9A-Fa-f]{34,})([0-9A-Fa-f]{3})\b')
69
+ # 128-bit+ hex tokens (`X{32,}`)
70
+ _HEX_TOKEN_PATTERN = re.compile(
71
+ r'\b([0-9A-Fa-f]{3})([0-9A-Fa-f]{26,})([0-9A-Fa-f]{3})\b')
72
+ # 128-bit uuid tokens (`X{8}-X{4}-X{4}-X{4}-X{12}`)
73
+ _UUID_TOKEN_PATTERN = re.compile(
74
+ r'\b([0-9A-Fa-f]{3})([0-9A-Fa-f]{5}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{9})([0-9A-Fa-f]{3})\b')
75
+
76
+ def format(self, record: logging.LogRecord) -> str:
77
+ output = super().format(record)
78
+ output = re.sub(self._SAPI_TOKEN_PATTERN, r'\1...\3', output)
79
+ output = re.sub(self._HEX_TOKEN_PATTERN, r'\1...\3', output)
80
+ output = re.sub(self._UUID_TOKEN_PATTERN, r'\1...\3', output)
81
+ return output
82
+
83
+
84
+ class JSONFormatter(ISOFormatter):
85
+ def format(self, record: logging.LogRecord) -> str:
86
+ super().format(record)
87
+ # filter out message template and potentially unserializable args
88
+ rec = record.__dict__.copy()
89
+ del rec['args']
90
+ del rec['msg']
91
+ return json.dumps(rec)
92
+
93
+
94
+ def configure_logging(logger: typing.Optional[logging.Logger] = None,
95
+ *,
96
+ level: int = logging.WARNING,
97
+ filter_secrets: bool = True,
98
+ output_stream: typing.Optional[io.IOBase] = None,
99
+ in_utc: bool = False,
100
+ structured_output: bool = False,
101
+ handler_level: typing.Optional[int] = None,
102
+ additive: bool = False,
103
+ ) -> logging.Logger:
104
+ """Configure cloud-client's `dwave.cloud` base logger.
105
+
106
+ Logging output from the cloud-client is suppressed by default. This utility
107
+ function can be used to quickly setup basic logging from the library.
108
+
109
+ .. note::
110
+ This function is currently intended for internal/private use only.
111
+
112
+ .. versionadded:: 0.12.0
113
+ Explicit optional logging configuration. Previously, logger was minimally
114
+ configured by default.
115
+ """
116
+
117
+ if logger is None:
118
+ logger = logging.getLogger(__name__)
119
+ if output_stream is None:
120
+ output_stream = sys.stderr
121
+ if handler_level is None:
122
+ handler_level = level
123
+
124
+ format = dict(
125
+ fmt='%(asctime)s %(name)s %(levelname)s %(threadName)s [%(funcName)s] %(message)s',
126
+ as_tz=datetime.timezone.utc if in_utc else None,
127
+ )
128
+
129
+ if structured_output:
130
+ formatter_base = JSONFormatter
131
+ else:
132
+ formatter_base = ISOFormatter
133
+
134
+ if filter_secrets:
135
+ class Formatter(FilteredSecretsFormatter, formatter_base):
136
+ pass
137
+ else:
138
+ Formatter = formatter_base
139
+
140
+ if not additive:
141
+ # make sure handlers are not accumulated
142
+ while len(logger.handlers):
143
+ logger.removeHandler(logger.handlers[-1])
144
+
145
+ formatter = Formatter(**format)
146
+ handler = logging.StreamHandler(stream=output_stream)
147
+ handler.setFormatter(formatter)
148
+ handler.setLevel(handler_level)
149
+
150
+ logger.addHandler(handler)
151
+ logger.setLevel(level)
152
+
153
+ return logger
154
+
155
+
156
+ # configure logger if DWAVE_LOG_LEVEL present in environment
157
+ def _apply_loglevel_from_env(logger):
158
+ if log_level := os.getenv('DWAVE_LOG_LEVEL', os.getenv('dwave_log_level')):
159
+ level = parse_loglevel(log_level)
160
+ log_format = os.getenv('DWAVE_LOG_FORMAT', os.getenv('dwave_log_format', ''))
161
+ structured = log_format.strip().lower() == 'json'
162
+ configure_logging(logger, level=level, structured_output=structured)
163
+
164
+ _apply_loglevel_from_env(logger)
165
+
166
+
167
+ # alias dwave.cloud.client.{qpu,sw,hybrid} as dwave.cloud.*
168
+ def _alias_old_client_submodules():
169
+ for name in ('qpu', 'sw', 'hybrid'):
170
+ # note: create both module and local attribute
171
+ globals()[name] = sys.modules['dwave.cloud.{}'.format(name)] = \
172
+ importlib.import_module('dwave.cloud.client.{}'.format(name))
173
+
174
+ _alias_old_client_submodules()
@@ -66,7 +66,7 @@ class LoggingSession(BaseUrlSession):
66
66
  RequestRecord = namedtuple('RequestRecord',
67
67
  ('request', 'response', 'exception'))
68
68
 
69
- def send(self, request: requests.PreparedRequest, **kwargs):
69
+ def send(self, request: requests.PreparedRequest, **kwargs) -> requests.Response:
70
70
  callee = type(self).__name__
71
71
  if logger.getEffectiveLevel() >= logging.DEBUG:
72
72
  logger.debug(f"[{callee!s}] send(method={request.method!r}, url={request.url!r}, ...)")
@@ -95,13 +95,13 @@ class LoggingSession(BaseUrlSession):
95
95
  logger.debug("[%s] request failed with %r", callee, exc)
96
96
 
97
97
  req = getattr(exc, 'request', None)
98
- if req:
98
+ if req is not None:
99
99
  logger.trace("[%s] failing request=%r", callee,
100
100
  dict(method=req.method, url=req.url,
101
101
  headers=req.headers, body=req.body))
102
102
 
103
103
  res = getattr(exc, 'response', None)
104
- if res:
104
+ if res is not None:
105
105
  logger.trace("[%s] failing response=%r", callee,
106
106
  dict(status_code=res.status_code,
107
107
  headers=res.headers, text=res.text))
@@ -439,15 +439,9 @@ class DWaveAPIClient:
439
439
  # failure. However, that is currently not the case. We need to work
440
440
  # around this until it's fixed.
441
441
 
442
- # no error -> body is json
442
+ # no error -> content type verified by `VersionedAPISession ` @accepts
443
443
  # error -> body can be json or plain text error message
444
- if response.ok:
445
- try:
446
- response.json()
447
- except:
448
- raise exceptions.ResourceBadResponseError("JSON response expected")
449
-
450
- else:
444
+ if not response.ok:
451
445
  try:
452
446
  msg = response.json()
453
447
  error_msg = msg['error_msg']
@@ -58,6 +58,11 @@ class ProblemEncodingFormat(str, enum.Enum):
58
58
  class AnswerEncodingFormat(str, enum.Enum):
59
59
  QP = "qp"
60
60
  BQ = "bq" # dimod (de-)serialization-based
61
+ BINARY_REF = "binary-ref"
62
+
63
+
64
+ class BinaryRefAuthMethod(str, enum.Enum):
65
+ SAPI_TOKEN = "sapi-token"
61
66
 
62
67
 
63
68
  class ProblemType(str, enum.Enum):
@@ -66,3 +71,4 @@ class ProblemType(str, enum.Enum):
66
71
  BQM = "bqm"
67
72
  CQM = "cqm"
68
73
  DQM = "dqm"
74
+ NL = "nl"
@@ -16,7 +16,7 @@ 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, Field
20
20
  from pydantic.functional_validators import AfterValidator
21
21
 
22
22
  from dwave.cloud.api import constants
@@ -63,8 +63,18 @@ class UnstructuredProblemAnswer(BaseModel):
63
63
  data: dict
64
64
 
65
65
 
66
+ class UnstructuredProblemAnswerBinaryRef(BaseModel):
67
+ format: constants.AnswerEncodingFormat = constants.AnswerEncodingFormat.BINARY_REF
68
+ auth_method: constants.BinaryRefAuthMethod = constants.BinaryRefAuthMethod.SAPI_TOKEN
69
+ url: str
70
+ timing: dict
71
+ shape: dict
72
+
73
+
66
74
  class ProblemAnswer(RootModel):
67
- root: Union[StructuredProblemAnswer, UnstructuredProblemAnswer]
75
+ root: Union[StructuredProblemAnswer,
76
+ UnstructuredProblemAnswer,
77
+ UnstructuredProblemAnswerBinaryRef]
68
78
 
69
79
  def __getattr__(self, item):
70
80
  return getattr(self.root, item)
@@ -12,6 +12,7 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
 
15
+ import io
15
16
  import json
16
17
  from typing import List, Union, Optional, Callable, get_type_hints
17
18
  from functools import wraps
@@ -60,7 +61,7 @@ class ResourceBase:
60
61
  client_class: DWaveAPIClient = DWaveAPIClient
61
62
 
62
63
  # endpoint path prefix (base path) specific to all methods on the resource
63
- resource_path: str = None
64
+ resource_path: Optional[str] = None
64
65
 
65
66
  def __init__(self, client: Optional[DWaveAPIClient] = None, **config):
66
67
  if isinstance(client, DWaveAPIClient):
@@ -217,6 +218,23 @@ class Problems(ResourceBase):
217
218
  answer = response.json()['answer']
218
219
  return models.ProblemAnswer.model_validate(answer)
219
220
 
221
+ @accepts(media_type='application/octet-stream')
222
+ def get_answer_data(self, answer: models.UnstructuredProblemAnswerBinaryRef,
223
+ output: Optional[io.IOBase] = None) -> io.IOBase:
224
+ """Retrieve binary-ref answer data."""
225
+ if answer.auth_method != constants.BinaryRefAuthMethod.SAPI_TOKEN:
226
+ raise ValueError(f"Authentication method {answer.auth_method!r} not supported.")
227
+
228
+ if output is None:
229
+ output = io.BytesIO()
230
+
231
+ for chunk in self.session.get(answer.url, stream=True).iter_content(chunk_size=8192):
232
+ output.write(chunk)
233
+
234
+ output.seek(0)
235
+
236
+ return output
237
+
220
238
  @accepts(media_type='application/vnd.dwave.sapi.problem-message+json', version='>=2.1,<3')
221
239
  def get_problem_messages(self, problem_id: str) -> List[dict]:
222
240
  """Retrieve list of problem messages."""
@@ -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
@@ -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,20 @@ class AuthFlow:
96
103
  authorization_endpoint=authorization_endpoint,
97
104
  token_endpoint=token_endpoint)
98
105
 
106
+ # setup response logging
107
+ def log_response(response, **kwargs):
108
+ callee = type(self.session).__name__
109
+
110
+ req = getattr(response, 'request', None)
111
+ if req is not None:
112
+ logger.trace("[%s] request=%r", callee,
113
+ dict(method=req.method, url=req.url,
114
+ headers=req.headers, body=req.body))
115
+
116
+ logger.trace("[%s] request(...) = (code=%r, body=%r, headers=%r, %r)",
117
+ callee, response.status_code, response.text, response.headers, kwargs)
118
+ self.session.hooks["response"].append(log_response)
119
+
99
120
  # set default headers (overwritten by ``session_config['headers']``)
100
121
  self.session.headers.update({'User-Agent': default_user_agent()})
101
122
 
@@ -205,6 +226,39 @@ class AuthFlow:
205
226
  self._save_token_to_creds(token)
206
227
  return token
207
228
 
229
+ def revoke_token(self, *,
230
+ token: Optional[str] = None,
231
+ token_type_hint: Optional[
232
+ Literal['access_token', 'refresh_token']] = None
233
+ ) -> bool:
234
+ """Revoke OAuth 2.0 token.
235
+
236
+ Args:
237
+ token:
238
+ OAuth 2.0 access or refresh token to be revoked. If refresh token
239
+ is specified, the authorization server should also revoke the
240
+ corresponding access tokens. If ``token`` is not specified, then
241
+ current refresh token is revoked.
242
+ token_type_hint:
243
+ Type of the token to be revoked.
244
+
245
+ Returns:
246
+ Token revocation status. True if revocation was successful, or token
247
+ was invalid already. False in case of an error.
248
+
249
+ Note:
250
+ Token revocation requires that a ``revocation_endpoint`` is defined
251
+ in :class:`~dwave.cloud.auth.flows.AuthFlow` construction.
252
+ """
253
+ if self.revocation_endpoint is None:
254
+ raise TypeError("Revocation endpoint undefined.")
255
+
256
+ response: requests.Response = self.session.revoke_token(
257
+ url=self.revocation_endpoint, token=token,
258
+ token_type_hint=token_type_hint)
259
+
260
+ return response.ok
261
+
208
262
  def ensure_active_token(self):
209
263
  if not self.token:
210
264
  return False
@@ -259,6 +313,10 @@ class LeapAuthFlow(AuthFlow):
259
313
  def _infer_token_endpoint(leap_api_endpoint: str) -> str:
260
314
  return urljoin(leap_api_endpoint, '/leap/openid/token')
261
315
 
316
+ @staticmethod
317
+ def _infer_revocation_endpoint(leap_api_endpoint: str) -> str:
318
+ return urljoin(leap_api_endpoint, '/leap/openid/revoke_token/')
319
+
262
320
  @staticmethod
263
321
  def _infer_leap_success_uri(leap_api_endpoint: str) -> str:
264
322
  return urljoin(leap_api_endpoint, '/leap/openid/success/')
@@ -290,6 +348,7 @@ class LeapAuthFlow(AuthFlow):
290
348
 
291
349
  authorization_endpoint = cls._infer_auth_endpoint(config.leap_api_endpoint)
292
350
  token_endpoint = cls._infer_token_endpoint(config.leap_api_endpoint)
351
+ revocation_endpoint = cls._infer_revocation_endpoint(config.leap_api_endpoint)
293
352
 
294
353
  # note: possible to de-dup via `DWaveAPIClient.from_config_model`, but
295
354
  # currently not worth the extra complexity (indirection layer).
@@ -306,6 +365,7 @@ class LeapAuthFlow(AuthFlow):
306
365
  redirect_uri=kwargs.pop('redirect_uri', cls._OOB_REDIRECT_URI),
307
366
  authorization_endpoint=authorization_endpoint,
308
367
  token_endpoint=token_endpoint,
368
+ revocation_endpoint=revocation_endpoint,
309
369
  session_config=session_config,
310
370
  leap_api_endpoint=config.leap_api_endpoint,
311
371
  creds=creds)
@@ -28,7 +28,7 @@ import click
28
28
  import requests.exceptions
29
29
 
30
30
  import dwave.cloud
31
- from dwave.cloud import Client
31
+ from dwave.cloud import Client, configure_logging
32
32
  from dwave.cloud import api
33
33
  from dwave.cloud.solver import StructuredSolver, BaseUnstructuredSolver
34
34
  from dwave.cloud.utils import (
@@ -55,10 +55,12 @@ click.option = partial(click.option, show_default=True)
55
55
 
56
56
  def enable_logging(ctx, param, value):
57
57
  if value and not ctx.resilient_parsing:
58
+ configure_logging()
58
59
  set_loglevel(dwave.cloud.logger, param.name)
59
60
 
60
61
  def enable_loglevel(ctx, param, value):
61
62
  if value and not ctx.resilient_parsing:
63
+ configure_logging()
62
64
  set_loglevel(dwave.cloud.logger, value)
63
65
 
64
66
  def show_platform(ctx, param, value):
@@ -543,6 +545,7 @@ def solvers(config_file, profile, endpoint, region, client_type, solver_def,
543
545
  client_type = 'base'
544
546
  solver_def = '{}'
545
547
 
548
+ # TODO: handle exceptions like in `_get_client_solver` and `standardized_output`
546
549
  with Client.from_config(
547
550
  config_file=config_file, profile=profile,
548
551
  endpoint=endpoint, region=region,
@@ -1009,11 +1012,11 @@ def get(*, config_file, profile, token_type, json_output, output):
1009
1012
  flow = LeapAuthFlow.from_config_model(config)
1010
1013
 
1011
1014
  token_key = token_type.replace('-', '_')
1012
- if not flow.token or not (token_value := flow.token.get(token_key)):
1015
+ if not flow.token or not token_key in flow.token:
1013
1016
  raise CLIError('Token not found. Please run "dwave auth login".', code=100)
1014
1017
 
1015
1018
  token_pretty = token_type.replace('-', ' ').capitalize()
1016
- output(f"{token_pretty}: {{%s}}" % token_key , **{token_key: token_value})
1019
+ output(f"{token_pretty}: {{%s}}" % token_key, **{token_key: flow.token[token_key]})
1017
1020
 
1018
1021
  if token_type == 'access-token':
1019
1022
  expires_at = flow.token.get('expires_at')
@@ -1051,6 +1054,32 @@ def refresh(*, config_file, profile, output):
1051
1054
  'You can now use "dwave auth get" to view them.')
1052
1055
 
1053
1056
 
1057
+ @auth.command()
1058
+ @config_file_options()
1059
+ @click.argument('token_type', default='access-token',
1060
+ type=click.Choice(['access-token', 'refresh-token']))
1061
+ @json_output
1062
+ @standardized_output
1063
+ def revoke(*, config_file, profile, token_type, json_output, output):
1064
+ """Revoke access and/or refresh token(s) for Leap API."""
1065
+
1066
+ config = validate_config_v1(load_config(config_file=config_file, profile=profile))
1067
+ flow = LeapAuthFlow.from_config_model(config)
1068
+
1069
+ token_key = token_type.replace('-', '_')
1070
+ token_pretty = token_type.replace('-', ' ').capitalize()
1071
+ if not flow.token or not token_key in flow.token:
1072
+ raise CLIError('Token not found. Please run "dwave auth login".', code=100)
1073
+
1074
+ # revoke
1075
+ revoked = flow.revoke_token(token=flow.token[token_key], token_type_hint=token_key)
1076
+
1077
+ if not revoked:
1078
+ raise CLIError(f'{token_pretty} revocation failed.', code=102)
1079
+
1080
+ output(f'{token_pretty} successfully revoked.')
1081
+
1082
+
1054
1083
  @cli.group()
1055
1084
  def leap():
1056
1085
  """Interact with Leap API."""
@@ -34,6 +34,7 @@ Examples:
34
34
 
35
35
  """
36
36
 
37
+ import io
37
38
  import re
38
39
  import time
39
40
  import copy
@@ -50,10 +51,10 @@ import codecs
50
51
  import concurrent.futures
51
52
 
52
53
  from itertools import chain, zip_longest
53
- from functools import partial, wraps, cached_property
54
+ from functools import partial, wraps
54
55
  from collections import namedtuple
55
56
  from concurrent.futures import ThreadPoolExecutor
56
- from typing import Dict
57
+ from typing import Dict, Optional, Union
57
58
 
58
59
  import requests
59
60
  import urllib3
@@ -350,6 +351,9 @@ class Client(object):
350
351
  _UPLOAD_REQUEST_RETRIES = 2
351
352
  _UPLOAD_RETRIES_BACKOFF = lambda retry: 2 ** retry
352
353
 
354
+ # Binary-ref answer download parameters
355
+ _DOWNLOAD_ANSWER_THREAD_COUNT = 2
356
+
353
357
  @staticmethod
354
358
  def _legacy_config_property_proxy(self, legacy_property, config_path):
355
359
  warnings.warn(
@@ -536,6 +540,10 @@ class Client(object):
536
540
  self._encode_problem_executor = \
537
541
  ThreadPoolExecutor(self._ENCODE_PROBLEM_THREAD_COUNT)
538
542
 
543
+ # Setup binary-ref answer download executors
544
+ self._download_answer_executor = \
545
+ ThreadPoolExecutor(self._DOWNLOAD_ANSWER_THREAD_COUNT)
546
+
539
547
  def create_session(self):
540
548
  """Create a new requests session based on client's (self) params.
541
549
 
@@ -613,6 +621,9 @@ class Client(object):
613
621
  logger.debug("Shutting down problem encoder executor")
614
622
  self._encode_problem_executor.shutdown()
615
623
 
624
+ logger.debug("Shutting down answer download executor")
625
+ self._download_answer_executor.shutdown()
626
+
616
627
  # Send kill-task to all worker threads
617
628
  # Note: threads can't be 'killed' in Python, they have to die by
618
629
  # natural causes
@@ -1602,7 +1613,46 @@ class Client(object):
1602
1613
  finally:
1603
1614
  session.close()
1604
1615
 
1605
- def upload_problem_encoded(self, problem, problem_id=None):
1616
+ def _download_answer_binary_ref(self, *, auth_method: str, url: str,
1617
+ output: Optional[io.IOBase] = None) -> concurrent.futures.Future:
1618
+ """Initiate binary-ref answer download, returning the binary data in
1619
+ :class:`~concurrent.futures.Future`.
1620
+
1621
+ Args:
1622
+ auth_method:
1623
+ Authentication method used to access data at ``url``.
1624
+
1625
+ url:
1626
+ Answer binary data.
1627
+
1628
+ Returns:
1629
+ :class:`concurrent.futures.Future`[bytes | io.IOBase]:
1630
+ Answer data in a Future.
1631
+ """
1632
+ return self._download_answer_executor.submit(
1633
+ self._download_answer_worker, auth_method=auth_method, url=url, output=output)
1634
+
1635
+ def _download_answer_worker(self, *, auth_method: str, url: str,
1636
+ output: Optional[io.IOBase] = None) -> io.IOBase:
1637
+ if auth_method != api.constants.BinaryRefAuthMethod.SAPI_TOKEN:
1638
+ raise ValueError(f"Authentication method {auth_method!r} not supported.")
1639
+ if output is None:
1640
+ output = io.BytesIO()
1641
+
1642
+ logger.debug("Downloading binary-ref answer from %r using %r method.",
1643
+ url, auth_method)
1644
+
1645
+ with self.create_session() as session:
1646
+ size = 0
1647
+ for chunk in session.get(url, stream=True).iter_content(chunk_size=8192):
1648
+ size += output.write(chunk)
1649
+ output.seek(0)
1650
+
1651
+ logger.debug("Answer data downloaded from %r. Written %r bytes.", url, size)
1652
+
1653
+ return output
1654
+
1655
+ def upload_problem_encoded(self, problem, problem_id=None, **kwargs):
1606
1656
  """Initiate multipart problem upload, returning the Problem ID in a
1607
1657
  :class:`~concurrent.futures.Future`.
1608
1658
 
@@ -12,7 +12,7 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
 
15
- """
15
+ r"""
16
16
  Interface to hybrid :term:`sampler`\ s available through the D-Wave Solver API
17
17
  (SAPI).
18
18
  """
@@ -12,7 +12,7 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
 
15
- """
15
+ r"""
16
16
  An implementation of the REST client for D-Wave Solver API (SAPI) service.
17
17
 
18
18
  SAPI servers provide authentication, queuing, and scheduling services,
@@ -12,7 +12,7 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
 
15
- """
15
+ r"""
16
16
  Interface to software :term:`sampler`\ s available through the D-Wave Solver
17
17
  API (SAPI).
18
18